Unnamed: 0
int64
0
7.36k
comments
stringlengths
3
35.2k
code_string
stringlengths
1
527k
code
stringlengths
1
527k
__index_level_0__
int64
0
88.6k
44
// Up Stable Token eXperiment DEX/USTX Team/This contract implements the DEX functionality for the USTX token.
contract UstxDEX is ReentrancyGuard,Pausable { /***********************************| | Variables && Events | |__________________________________*/ //Constants uint256 private constant MAX_FEE = 200; //maximum fee in BP (2.5%) uint256 private constant MAX_LAUNCH_FEE = 1000; //maximum fee during launchpad (10%) //Variables uint256 private _decimals; // 6 uint256 private _feeBuy; //buy fee in basis points uint256 private _feeSell; //sell fee in basis points uint256 private _targetRatioExp; //target reserve ratio for expansion in TH (1000s) to circulating cap uint256 private _targetRatioDamp; //target reserve ratio for damping in TH (1000s) to circulating cap uint256 private _expFactor; //expansion factor in TH uint256 private _dampFactor; //damping factor in TH uint256 private _minExp; //minimum expansion in TH uint256 private _maxDamp; //maximum damping in TH uint256 private _collectedFees; //amount of collected fees uint256 private _launchEnabled; //launchpad mode if >=1 uint256 private _launchTargetSize; //number of tokens reserved for launchpad uint256 private _launchPrice; //Launchpad price uint256 private _launchBought; //number of tokens bought so far in Launchpad uint256 private _launchMaxLot; //max number of usdtSold for a single operation during Launchpad uint256 private _launchFee; //Launchpad fee address private _launchTeamAddr; //Launchpad team address UpStableToken Token; // address of the TRC20 token traded on this contract IERC20 Tusdt; // address of the reserve token USDT //SafeERC20 not needed for USDT(TRC20) and USTX(TRC20) using SafeMath for uint256; // Events event TokenBuy(address indexed buyer, uint256 indexed usdtSold, uint256 indexed tokensBought, uint256 price); event TokenSell(address indexed buyer, uint256 indexed tokensSold, uint256 indexed usdtBought, uint256 price); event Snapshot(address indexed operator, uint256 indexed usdtBalance, uint256 indexed tokenBalance); /** * @dev Constructor * @param tradeTokenAddr contract address of the traded token (USTX) * @param reserveTokenAddr contract address of the reserve token (USDT) */ constructor (address tradeTokenAddr, address reserveTokenAddr) AdminRole(2) //at least two administrsators always in charge public { require(tradeTokenAddr != address(0) && reserveTokenAddr != address(0), "Invalid contract address"); Token = UpStableToken(tradeTokenAddr); Tusdt = IERC20(reserveTokenAddr); _launchTeamAddr = _msgSender(); _decimals = 6; _feeBuy = 0; //0% _feeSell = 100; //1% _targetRatioExp = 240; //24% _targetRatioDamp = 260; //26% _expFactor = 1000; //1 _dampFactor = 1000; //1 _minExp = 100; //0.1 _maxDamp = 100; //0.1 _collectedFees = 0; _launchEnabled = 0; } /***********************************| | Exchange Functions | |__________________________________*/ /** * @dev Public function to preview token purchase with exact input in USDT * @param usdtSold amount of USDT to sell * @return number of tokens that can be purchased with input usdtSold */ function buyTokenInputPreview(uint256 usdtSold) public view returns (uint256) { require(usdtSold > 0, "USDT sold must greater than 0"); uint256 tokenReserve = Token.balanceOf(address(this)); uint256 usdtReserve = Tusdt.balanceOf(address(this)); (uint256 tokensBought,,) = _getBoughtMinted(usdtSold,tokenReserve,usdtReserve); return tokensBought; } /** * @dev Public function to preview token sale with exact input in tokens * @param tokensSold amount of token to sell * @return Amount of USDT that can be bought with input Tokens. */ function sellTokenInputPreview(uint256 tokensSold) public view returns (uint256) { require(tokensSold > 0, "Tokens sold must greater than 0"); uint256 tokenReserve = Token.balanceOf(address(this)); uint256 usdtReserve = Tusdt.balanceOf(address(this)); (uint256 usdtsBought,,) = _getBoughtBurned(tokensSold,tokenReserve,usdtReserve); return usdtsBought; } /** * @dev Public function to buy tokens during launchpad * @param rSell amount of UDST to sell * @param minTokens minimum amount of tokens to buy * @return number of tokens bought */ function buyTokenLaunchInput(uint256 rSell, uint256 minTokens) public whenNotPaused returns (uint256) { require(_launchEnabled>0,"Function allowed only during launchpad"); require(_launchBought<_launchTargetSize,"Launchpad target reached!"); require(rSell<=_launchMaxLot,"Order too big for Launchpad"); return _buyLaunchpadInput(rSell, minTokens, _msgSender(), _msgSender()); } /** * @dev Public function to buy tokens during launchpad and transfer them to recipient * @param rSell amount of UDST to sell * @param minTokens minimum amount of tokens to buy * @param recipient recipient of the transaction * @return number of tokens bought */ function buyTokenLaunchTransferInput(uint256 rSell, uint256 minTokens, address recipient) public whenNotPaused returns(uint256) { require(_launchEnabled>0,"Function allowed only during launchpad"); require(recipient != address(this) && recipient != address(0),"Recipient cannot be DEX or address 0"); require(_launchBought<_launchTargetSize,"Launchpad target reached!"); require(rSell<=_launchMaxLot,"Order too big for Launchpad"); return _buyLaunchpadInput(rSell, minTokens, _msgSender(), recipient); } /** * @dev Public function to buy tokens * @param rSell amount of UDST to sell * @param minTokens minimum amount of tokens to buy * @return number of tokens bought */ function buyTokenInput(uint256 rSell, uint256 minTokens) public whenNotPaused returns (uint256) { require(_launchEnabled==0,"Function not allowed during launchpad"); return _buyStableInput(rSell, minTokens, _msgSender(), _msgSender()); } /** * @dev Public function to buy tokens and transfer them to recipient * @param rSell amount of UDST to sell * @param minTokens minimum amount of tokens to buy * @param recipient recipient of the transaction * @return number of tokens bought */ function buyTokenTransferInput(uint256 rSell, uint256 minTokens, address recipient) public whenNotPaused returns(uint256) { require(_launchEnabled==0,"Function not allowed during launchpad"); require(recipient != address(this) && recipient != address(0),"Recipient cannot be DEX or address 0"); return _buyStableInput(rSell, minTokens, _msgSender(), recipient); } /** * @dev Public function to sell tokens * @param tokensSold number of tokens to sell * @param minUsdts minimum number of UDST to buy * @return number of USDTs bought */ function sellTokenInput(uint256 tokensSold, uint256 minUsdts) public whenNotPaused returns (uint256) { require(_launchEnabled==0,"Function not allowed during launchpad"); return _sellStableInput(tokensSold, minUsdts, _msgSender(), _msgSender()); } /** * @dev Public function to sell tokens and trasnfer USDT to recipient * @param tokensSold number of tokens to sell * @param minUsdts minimum number of UDST to buy * @param recipient recipient of the transaction * @return number of USDTs bought */ function sellTokenTransferInput(uint256 tokensSold, uint256 minUsdts, address recipient) public whenNotPaused returns (uint256) { require(_launchEnabled==0,"Function not allowed during launchpad"); require(recipient != address(this) && recipient != address(0),"Recipient cannot be DEX or address 0"); return _sellStableInput(tokensSold, minUsdts, _msgSender(), recipient); } /** * @dev public function to setup the reserve after launchpad * @param startPrice target price * @return reserve value */ function setupReserve(uint256 startPrice) public onlyAdmin whenPaused returns (uint256) { require(startPrice>0,"Price cannot be 0"); uint256 tokenReserve = Token.balanceOf(address(this)); uint256 usdtReserve = Tusdt.balanceOf(address(this)); uint256 newReserve = usdtReserve.mul(10**_decimals).div(startPrice); uint256 temp; if (newReserve>tokenReserve) { temp = newReserve.sub(tokenReserve); Token.mint(address(this),temp); } else { temp = tokenReserve.sub(newReserve); Token.burn(temp); } return newReserve; } /** * @dev Private function to buy tokens with exact input in USDT * */ function _buyStableInput(uint256 usdtSold, uint256 minTokens, address buyer, address recipient) private nonReentrant returns (uint256) { require(usdtSold > 0 && minTokens > 0,"USDT sold and min tokens should be higher than 0"); uint256 tokenReserve = Token.balanceOf(address(this)); uint256 usdtReserve = Tusdt.balanceOf(address(this)); (uint256 tokensBought, uint256 minted, uint256 fee) = _getBoughtMinted(usdtSold,tokenReserve,usdtReserve); _collectedFees = _collectedFees.add(fee); require(tokensBought >= minTokens, "Tokens bought lower than requested minimum amount"); if (minted>0) { Token.mint(address(this),minted); } Tusdt.transferFrom(buyer, address(this), usdtSold); if (fee>0) { Tusdt.transfer(_launchTeamAddr,fee); //transfer fees to team } Token.transfer(address(recipient),tokensBought); tokenReserve = Token.balanceOf(address(this)); //update token reserve usdtReserve = Tusdt.balanceOf(address(this)); //update usdt reserve uint256 newPrice = usdtReserve.mul(10**_decimals).div(tokenReserve); //calc new price emit TokenBuy(buyer, usdtSold, tokensBought, newPrice); //emit TokenBuy event emit Snapshot(buyer, usdtReserve, tokenReserve); //emit Snapshot event return tokensBought; } /** * @dev Private function to buy tokens during launchpad with exact input in USDT * */ function _buyLaunchpadInput(uint256 usdtSold, uint256 minTokens, address buyer, address recipient) private nonReentrant returns (uint256) { require(usdtSold > 0 && minTokens > 0, "USDT sold and min tokens should be higher than 0"); uint256 tokensBought = usdtSold.mul(10**_decimals).div(_launchPrice); uint256 fee = usdtSold.mul(_launchFee).div(10000); require(tokensBought >= minTokens, "Tokens bought lower than requested minimum amount"); _launchBought = _launchBought.add(tokensBought); Token.mint(address(this),tokensBought); //mint new tokens Tusdt.transferFrom(buyer, address(this), usdtSold); //add usdtSold to reserve Tusdt.transfer(_launchTeamAddr,fee); //transfer fees to team Token.transfer(address(recipient),tokensBought); //transfer tokens to recipient emit TokenBuy(buyer, usdtSold, tokensBought, _launchPrice); emit Snapshot(buyer, Tusdt.balanceOf(address(this)), Token.balanceOf(address(this))); return tokensBought; } /** * @dev Private function to sell tokens with exact input in tokens * */ function _sellStableInput(uint256 tokensSold, uint256 minUsdts, address buyer, address recipient) private nonReentrant returns (uint256) { require(tokensSold > 0 && minUsdts > 0, "Tokens sold and min USDT should be higher than 0"); uint256 tokenReserve = Token.balanceOf(address(this)); uint256 usdtReserve = Tusdt.balanceOf(address(this)); (uint256 usdtsBought, uint256 burned, uint256 fee) = _getBoughtBurned(tokensSold,tokenReserve,usdtReserve); _collectedFees = _collectedFees.add(fee); require(usdtsBought >= minUsdts, "USDT bought lower than requested minimum amount"); if (burned>0) { Token.burn(burned); } Token.transferFrom(buyer, address(this), tokensSold); //transfer tokens to DEX Tusdt.transfer(recipient,usdtsBought); //transfer USDT to user if (fee>0) { Tusdt.transfer(_launchTeamAddr,fee); //transfer fees to team } tokenReserve = Token.balanceOf(address(this)); //update token reserve usdtReserve = Tusdt.balanceOf(address(this)); //update usdt reserve uint256 newPrice = usdtReserve.mul(10**_decimals).div(tokenReserve); //calc new price emit TokenSell(buyer, tokensSold, usdtsBought, newPrice); //emit Token event emit Snapshot(buyer, usdtReserve, tokenReserve); //emit Snapshot event return usdtsBought; } /** * @dev Private function to get expansion correction * */ function _getExp(uint256 tokenReserve, uint256 usdtReserve) private view returns (uint256,uint256) { uint256 tokenCirc = Token.totalSupply(); //total tokenCirc = tokenCirc.sub(tokenReserve); uint256 price = getPrice(); //multiplied by 10**decimals uint256 cirCap = price.mul(tokenCirc); //multiplied by 10**decimals uint256 ratio = usdtReserve.mul(1000000000).div(cirCap); uint256 exp = ratio.mul(1000).div(_targetRatioExp); if (exp<1000) { exp=1000; } exp = exp.sub(1000); exp=exp.mul(_expFactor).div(1000); if (exp<_minExp) { exp=_minExp; } if (exp>1000) { exp = 1000; } return (exp,ratio); } /** * @dev Private function to get k exponential factor for expansion * */ function _getKXe(uint256 pool, uint256 trade, uint256 exp) private pure returns (uint256) { uint256 temp = 1000-exp; temp = trade.mul(temp); temp = temp.div(1000); temp = temp.add(pool); temp = temp.mul(1000000000); uint256 kexp = temp.div(pool); return kexp; } /** * @dev Private function to get k exponential factor for damping * */ function _getKXd(uint256 pool, uint256 trade, uint256 exp) private pure returns (uint256) { uint256 temp = 1000-exp; temp = trade.mul(temp); temp = temp.div(1000); temp = temp.add(pool); uint256 kexp = pool.mul(1000000000).div(temp); return kexp; } /** * @dev Private function to get amount of tokens bought and minted * */ function _getBoughtMinted(uint256 usdtSold, uint256 tokenReserve, uint256 usdtReserve) private view returns (uint256,uint256,uint256) { uint256 fees = usdtSold.mul(_feeBuy).div(10000); uint256 usdtSoldNet = usdtSold.sub(fees); (uint256 exp,) = _getExp(tokenReserve,usdtReserve); uint256 kexp = _getKXe(usdtReserve,usdtSoldNet,exp); uint256 temp = tokenReserve.mul(usdtReserve); //k temp = temp.mul(kexp); temp = temp.mul(kexp); uint256 kn = temp.div(1000000000000000000); //uint256 kn=tokenReserve.mul(usdtReserve).mul(kexp).mul(kexp).div(1000000); temp = tokenReserve.mul(usdtReserve); //k usdtReserve = usdtReserve.add(usdtSoldNet); //uint256 usdtReserveNew= usdtReserve.add(usdtSoldNet); temp = temp.div(usdtReserve); //USTXamm uint256 tokensBought = tokenReserve.sub(temp); //out=tokenReserve-USTXamm temp=kn.div(usdtReserve); //USXTPool_n uint256 minted=temp.add(tokensBought).sub(tokenReserve); return (tokensBought, minted, fees); } /** * @dev Private function to get damping correction * */ function _getDamp(uint256 tokenReserve, uint256 usdtReserve) private view returns (uint256,uint256) { uint256 tokenCirc = Token.totalSupply(); //total tokenCirc = tokenCirc.sub(tokenReserve); uint256 price = getPrice(); //multiplied by 10**decimals uint256 cirCap = price.mul(tokenCirc); //multiplied by 10**decimals uint256 ratio = usdtReserve.mul(1000000000).div(cirCap); //in TH if (ratio>_targetRatioDamp) { ratio=_targetRatioDamp; } uint256 damp = _targetRatioDamp.sub(ratio); damp = damp.mul(_dampFactor).div(_targetRatioDamp); if (damp<_maxDamp) { damp=_maxDamp; } if (damp>1000) { damp = 1000; } return (damp,ratio); } /** * @dev Private function to get number of USDT bought and tokens burned * */ function _getBoughtBurned(uint256 tokenSold, uint256 tokenReserve, uint256 usdtReserve) private view returns (uint256,uint256,uint256) { (uint256 damp,) = _getDamp(tokenReserve,usdtReserve); uint256 kexp = _getKXd(tokenReserve,tokenSold,damp); uint256 k = tokenReserve.mul(usdtReserve); //k uint256 temp = k.mul(kexp); temp = temp.mul(kexp); uint256 kn = temp.div(1000000000000000000); //uint256 kn=tokenReserve.mul(usdtReserve).mul(kexp).mul(kexp).div(1000000); tokenReserve = tokenReserve.add(tokenSold); //USTXpool_n temp = k.div(tokenReserve); //USDamm uint256 usdtsBought = usdtReserve.sub(temp); //out usdtReserve = temp; temp = kn.div(usdtReserve); //USTXPool_n uint256 burned=tokenReserve.sub(temp); temp = usdtsBought.mul(_feeSell).div(10000); //fee usdtsBought = usdtsBought.sub(temp); return (usdtsBought, burned, temp); } /**************************************| | Getter and Setter Functions | |_____________________________________*/ /** * @dev Function to set Token address (only admin) * @param tokenAddress address of the traded token contract */ function setTokenAddr(address tokenAddress) public onlyAdmin { require(tokenAddress != address(0), "INVALID_ADDRESS"); Token = UpStableToken(tokenAddress); } /** * @dev Function to set USDT address (only admin) * @param reserveAddress address of the reserve token contract */ function setReserveTokenAddr(address reserveAddress) public onlyAdmin { require(reserveAddress != address(0), "INVALID_ADDRESS"); Tusdt = IERC20(reserveAddress); } /** * @dev Function to set fees (only admin) * @param feeBuy fee for buy operations (in basis points) * @param feeSell fee for sell operations (in basis points) */ function setFees(uint256 feeBuy, uint256 feeSell) public onlyAdmin { require(feeBuy<=MAX_FEE && feeSell<=MAX_FEE,"Fees cannot be higher than MAX_FEE"); _feeBuy=feeBuy; _feeSell=feeSell; } /** * @dev Function to get fees * @return buy and sell fees in basis points * */ function getFees() public view returns (uint256, uint256) { return (_feeBuy, _feeSell); } /** * @dev Function to set target ratio level (only admin) * @param ratioExp target reserve ratio for expansion (in thousandths) * @param ratioDamp target reserve ratio for damping (in thousandths) */ function setTargetRatio(uint256 ratioExp, uint256 ratioDamp) public onlyAdmin { require(ratioExp<=1000 && ratioExp>=10 && ratioDamp<=1000 && ratioDamp >=10,"Target ratio must be between 1% and 100%"); _targetRatioExp = ratioExp; //in TH _targetRatioDamp = ratioDamp; //in TH } /** * @dev Function to get target ratio level * return ratioExp and ratioDamp in thousandths * */ function getTargetRatio() public view returns (uint256, uint256) { return (_targetRatioExp, _targetRatioDamp); } /** * @dev Function to get currect reserve ratio level * return current ratio in thousandths * */ function getCurrentRatio() public view returns (uint256) { uint256 tokenReserve = Token.balanceOf(address(this)); uint256 usdtReserve = Tusdt.balanceOf(address(this)); uint256 tokenCirc = Token.totalSupply(); //total tokenCirc = tokenCirc.sub(tokenReserve); uint256 price = getPrice(); //multiplied by 10**decimals uint256 cirCap = price.mul(tokenCirc); //multiplied by 10**decimals uint256 ratio = usdtReserve.mul(1000000000).div(cirCap); //in TH return ratio; } /** * @dev Function to set target expansion factors (only admin) * @param expF expansion factor (in thousandths) * @param minExp minimum expansion coefficient to use (in thousandths) */ function setExpFactors(uint256 expF, uint256 minExp) public onlyAdmin { require(expF<=10000 && minExp<=1000,"Expansion factor cannot be more than 1000% and the minimum expansion cannot be over 100%"); _expFactor=expF; _minExp=minExp; } /** * @dev Function to get expansion factors * @return _expFactor and _minExp in thousandths * */ function getExpFactors() public view returns (uint256, uint256) { return (_expFactor,_minExp); } /** * @dev Function to set target damping factors (only admin) * @param dampF damping factor (in thousandths) * @param maxDamp maximum damping to use (in thousandths) */ function setDampFactors(uint256 dampF, uint256 maxDamp) public onlyAdmin { require(dampF<=1000 && maxDamp<=1000,"Damping factor cannot be more than 100% and the maximum damping be over 100%"); _dampFactor=dampF; _maxDamp=maxDamp; } /** * @dev Function to get damping factors * @return _dampFactor and _maxDamp in thousandths * */ function getDampFactors() public view returns (uint256, uint256) { return (_dampFactor,_maxDamp); } /** * @dev Function to get current price * @return current price * */ function getPrice() public view returns (uint256) { if (_launchEnabled>0) { return (_launchPrice); }else { uint256 tokenReserve = Token.balanceOf(address(this)); uint256 usdtReserve = Tusdt.balanceOf(address(this)); return (usdtReserve.mul(10**_decimals).div(tokenReserve)); //price with decimals } } /** * @dev Function to get address of the traded token contract * @return Address of token that is traded on this exchange * */ function getTokenAddress() public view returns (address) { return address(Token); } /** * @dev Function to get the address of the reserve token contract * @return Address of USDT * */ function getReserveAddress() public view returns (address) { return address(Tusdt); } /** * @dev Function to get current reserves balance * @return USDT reserve, USTX reserve, USTX circulating */ function getBalances() public view returns (uint256,uint256,uint256,uint256) { uint256 tokenReserve = Token.balanceOf(address(this)); uint256 usdtReserve = Tusdt.balanceOf(address(this)); uint256 tokenCirc = Token.totalSupply().sub(tokenReserve); return (usdtReserve,tokenReserve,tokenCirc,_collectedFees); } /** * @dev Function to enable launchpad (only admin) * @param price launchpad fixed price * @param target launchpad target USTX sale * @param maxLot launchpad maximum purchase size in USDT * @param fee launchpad fee for the dev team (in basis points) * @return true if launchpad is enabled */ function enableLaunchpad(uint256 price, uint256 target, uint256 maxLot, uint256 fee) public onlyAdmin returns (bool) { require(price>0 && target>0 && maxLot>0 && fee<=MAX_LAUNCH_FEE,"Price, target and max lotsize cannot be 0. Fee must be lower than MAX_LAUNCH_FEE"); _launchPrice = price; //in USDT units _launchTargetSize = target; //in USTX units _launchBought = 0; //in USTX units _launchFee = fee; //in bp _launchMaxLot = maxLot; //in USDT units _launchEnabled = 1; return true; } /** * @dev Function to disable launchpad (only admin) * * */ function disableLaunchpad() public onlyAdmin { _launchEnabled = 0; } /** * @dev Function to get launchpad status (only admin) * @return enabled state, price, amount of tokens bought, target tokens, max ourschase lot, fee * */ function getLaunchpadStatus() public view returns (uint256, uint256, uint256, uint256, uint256, uint256) { return (_launchEnabled,_launchPrice,_launchBought,_launchTargetSize,_launchMaxLot,_launchFee); } /** * @dev Set team address (only admin) * @param team address for collecting fees */ function setTeamAddress(address team) public onlyAdmin { require(team != address(0) && team != address(this), "Invalid team address"); _launchTeamAddr = team; } /** * @dev Unregister DEX as admin from USTX contract * */ function unregisterAdmin() public onlyAdmin { Token.renounceAdmin(); } }
contract UstxDEX is ReentrancyGuard,Pausable { /***********************************| | Variables && Events | |__________________________________*/ //Constants uint256 private constant MAX_FEE = 200; //maximum fee in BP (2.5%) uint256 private constant MAX_LAUNCH_FEE = 1000; //maximum fee during launchpad (10%) //Variables uint256 private _decimals; // 6 uint256 private _feeBuy; //buy fee in basis points uint256 private _feeSell; //sell fee in basis points uint256 private _targetRatioExp; //target reserve ratio for expansion in TH (1000s) to circulating cap uint256 private _targetRatioDamp; //target reserve ratio for damping in TH (1000s) to circulating cap uint256 private _expFactor; //expansion factor in TH uint256 private _dampFactor; //damping factor in TH uint256 private _minExp; //minimum expansion in TH uint256 private _maxDamp; //maximum damping in TH uint256 private _collectedFees; //amount of collected fees uint256 private _launchEnabled; //launchpad mode if >=1 uint256 private _launchTargetSize; //number of tokens reserved for launchpad uint256 private _launchPrice; //Launchpad price uint256 private _launchBought; //number of tokens bought so far in Launchpad uint256 private _launchMaxLot; //max number of usdtSold for a single operation during Launchpad uint256 private _launchFee; //Launchpad fee address private _launchTeamAddr; //Launchpad team address UpStableToken Token; // address of the TRC20 token traded on this contract IERC20 Tusdt; // address of the reserve token USDT //SafeERC20 not needed for USDT(TRC20) and USTX(TRC20) using SafeMath for uint256; // Events event TokenBuy(address indexed buyer, uint256 indexed usdtSold, uint256 indexed tokensBought, uint256 price); event TokenSell(address indexed buyer, uint256 indexed tokensSold, uint256 indexed usdtBought, uint256 price); event Snapshot(address indexed operator, uint256 indexed usdtBalance, uint256 indexed tokenBalance); /** * @dev Constructor * @param tradeTokenAddr contract address of the traded token (USTX) * @param reserveTokenAddr contract address of the reserve token (USDT) */ constructor (address tradeTokenAddr, address reserveTokenAddr) AdminRole(2) //at least two administrsators always in charge public { require(tradeTokenAddr != address(0) && reserveTokenAddr != address(0), "Invalid contract address"); Token = UpStableToken(tradeTokenAddr); Tusdt = IERC20(reserveTokenAddr); _launchTeamAddr = _msgSender(); _decimals = 6; _feeBuy = 0; //0% _feeSell = 100; //1% _targetRatioExp = 240; //24% _targetRatioDamp = 260; //26% _expFactor = 1000; //1 _dampFactor = 1000; //1 _minExp = 100; //0.1 _maxDamp = 100; //0.1 _collectedFees = 0; _launchEnabled = 0; } /***********************************| | Exchange Functions | |__________________________________*/ /** * @dev Public function to preview token purchase with exact input in USDT * @param usdtSold amount of USDT to sell * @return number of tokens that can be purchased with input usdtSold */ function buyTokenInputPreview(uint256 usdtSold) public view returns (uint256) { require(usdtSold > 0, "USDT sold must greater than 0"); uint256 tokenReserve = Token.balanceOf(address(this)); uint256 usdtReserve = Tusdt.balanceOf(address(this)); (uint256 tokensBought,,) = _getBoughtMinted(usdtSold,tokenReserve,usdtReserve); return tokensBought; } /** * @dev Public function to preview token sale with exact input in tokens * @param tokensSold amount of token to sell * @return Amount of USDT that can be bought with input Tokens. */ function sellTokenInputPreview(uint256 tokensSold) public view returns (uint256) { require(tokensSold > 0, "Tokens sold must greater than 0"); uint256 tokenReserve = Token.balanceOf(address(this)); uint256 usdtReserve = Tusdt.balanceOf(address(this)); (uint256 usdtsBought,,) = _getBoughtBurned(tokensSold,tokenReserve,usdtReserve); return usdtsBought; } /** * @dev Public function to buy tokens during launchpad * @param rSell amount of UDST to sell * @param minTokens minimum amount of tokens to buy * @return number of tokens bought */ function buyTokenLaunchInput(uint256 rSell, uint256 minTokens) public whenNotPaused returns (uint256) { require(_launchEnabled>0,"Function allowed only during launchpad"); require(_launchBought<_launchTargetSize,"Launchpad target reached!"); require(rSell<=_launchMaxLot,"Order too big for Launchpad"); return _buyLaunchpadInput(rSell, minTokens, _msgSender(), _msgSender()); } /** * @dev Public function to buy tokens during launchpad and transfer them to recipient * @param rSell amount of UDST to sell * @param minTokens minimum amount of tokens to buy * @param recipient recipient of the transaction * @return number of tokens bought */ function buyTokenLaunchTransferInput(uint256 rSell, uint256 minTokens, address recipient) public whenNotPaused returns(uint256) { require(_launchEnabled>0,"Function allowed only during launchpad"); require(recipient != address(this) && recipient != address(0),"Recipient cannot be DEX or address 0"); require(_launchBought<_launchTargetSize,"Launchpad target reached!"); require(rSell<=_launchMaxLot,"Order too big for Launchpad"); return _buyLaunchpadInput(rSell, minTokens, _msgSender(), recipient); } /** * @dev Public function to buy tokens * @param rSell amount of UDST to sell * @param minTokens minimum amount of tokens to buy * @return number of tokens bought */ function buyTokenInput(uint256 rSell, uint256 minTokens) public whenNotPaused returns (uint256) { require(_launchEnabled==0,"Function not allowed during launchpad"); return _buyStableInput(rSell, minTokens, _msgSender(), _msgSender()); } /** * @dev Public function to buy tokens and transfer them to recipient * @param rSell amount of UDST to sell * @param minTokens minimum amount of tokens to buy * @param recipient recipient of the transaction * @return number of tokens bought */ function buyTokenTransferInput(uint256 rSell, uint256 minTokens, address recipient) public whenNotPaused returns(uint256) { require(_launchEnabled==0,"Function not allowed during launchpad"); require(recipient != address(this) && recipient != address(0),"Recipient cannot be DEX or address 0"); return _buyStableInput(rSell, minTokens, _msgSender(), recipient); } /** * @dev Public function to sell tokens * @param tokensSold number of tokens to sell * @param minUsdts minimum number of UDST to buy * @return number of USDTs bought */ function sellTokenInput(uint256 tokensSold, uint256 minUsdts) public whenNotPaused returns (uint256) { require(_launchEnabled==0,"Function not allowed during launchpad"); return _sellStableInput(tokensSold, minUsdts, _msgSender(), _msgSender()); } /** * @dev Public function to sell tokens and trasnfer USDT to recipient * @param tokensSold number of tokens to sell * @param minUsdts minimum number of UDST to buy * @param recipient recipient of the transaction * @return number of USDTs bought */ function sellTokenTransferInput(uint256 tokensSold, uint256 minUsdts, address recipient) public whenNotPaused returns (uint256) { require(_launchEnabled==0,"Function not allowed during launchpad"); require(recipient != address(this) && recipient != address(0),"Recipient cannot be DEX or address 0"); return _sellStableInput(tokensSold, minUsdts, _msgSender(), recipient); } /** * @dev public function to setup the reserve after launchpad * @param startPrice target price * @return reserve value */ function setupReserve(uint256 startPrice) public onlyAdmin whenPaused returns (uint256) { require(startPrice>0,"Price cannot be 0"); uint256 tokenReserve = Token.balanceOf(address(this)); uint256 usdtReserve = Tusdt.balanceOf(address(this)); uint256 newReserve = usdtReserve.mul(10**_decimals).div(startPrice); uint256 temp; if (newReserve>tokenReserve) { temp = newReserve.sub(tokenReserve); Token.mint(address(this),temp); } else { temp = tokenReserve.sub(newReserve); Token.burn(temp); } return newReserve; } /** * @dev Private function to buy tokens with exact input in USDT * */ function _buyStableInput(uint256 usdtSold, uint256 minTokens, address buyer, address recipient) private nonReentrant returns (uint256) { require(usdtSold > 0 && minTokens > 0,"USDT sold and min tokens should be higher than 0"); uint256 tokenReserve = Token.balanceOf(address(this)); uint256 usdtReserve = Tusdt.balanceOf(address(this)); (uint256 tokensBought, uint256 minted, uint256 fee) = _getBoughtMinted(usdtSold,tokenReserve,usdtReserve); _collectedFees = _collectedFees.add(fee); require(tokensBought >= minTokens, "Tokens bought lower than requested minimum amount"); if (minted>0) { Token.mint(address(this),minted); } Tusdt.transferFrom(buyer, address(this), usdtSold); if (fee>0) { Tusdt.transfer(_launchTeamAddr,fee); //transfer fees to team } Token.transfer(address(recipient),tokensBought); tokenReserve = Token.balanceOf(address(this)); //update token reserve usdtReserve = Tusdt.balanceOf(address(this)); //update usdt reserve uint256 newPrice = usdtReserve.mul(10**_decimals).div(tokenReserve); //calc new price emit TokenBuy(buyer, usdtSold, tokensBought, newPrice); //emit TokenBuy event emit Snapshot(buyer, usdtReserve, tokenReserve); //emit Snapshot event return tokensBought; } /** * @dev Private function to buy tokens during launchpad with exact input in USDT * */ function _buyLaunchpadInput(uint256 usdtSold, uint256 minTokens, address buyer, address recipient) private nonReentrant returns (uint256) { require(usdtSold > 0 && minTokens > 0, "USDT sold and min tokens should be higher than 0"); uint256 tokensBought = usdtSold.mul(10**_decimals).div(_launchPrice); uint256 fee = usdtSold.mul(_launchFee).div(10000); require(tokensBought >= minTokens, "Tokens bought lower than requested minimum amount"); _launchBought = _launchBought.add(tokensBought); Token.mint(address(this),tokensBought); //mint new tokens Tusdt.transferFrom(buyer, address(this), usdtSold); //add usdtSold to reserve Tusdt.transfer(_launchTeamAddr,fee); //transfer fees to team Token.transfer(address(recipient),tokensBought); //transfer tokens to recipient emit TokenBuy(buyer, usdtSold, tokensBought, _launchPrice); emit Snapshot(buyer, Tusdt.balanceOf(address(this)), Token.balanceOf(address(this))); return tokensBought; } /** * @dev Private function to sell tokens with exact input in tokens * */ function _sellStableInput(uint256 tokensSold, uint256 minUsdts, address buyer, address recipient) private nonReentrant returns (uint256) { require(tokensSold > 0 && minUsdts > 0, "Tokens sold and min USDT should be higher than 0"); uint256 tokenReserve = Token.balanceOf(address(this)); uint256 usdtReserve = Tusdt.balanceOf(address(this)); (uint256 usdtsBought, uint256 burned, uint256 fee) = _getBoughtBurned(tokensSold,tokenReserve,usdtReserve); _collectedFees = _collectedFees.add(fee); require(usdtsBought >= minUsdts, "USDT bought lower than requested minimum amount"); if (burned>0) { Token.burn(burned); } Token.transferFrom(buyer, address(this), tokensSold); //transfer tokens to DEX Tusdt.transfer(recipient,usdtsBought); //transfer USDT to user if (fee>0) { Tusdt.transfer(_launchTeamAddr,fee); //transfer fees to team } tokenReserve = Token.balanceOf(address(this)); //update token reserve usdtReserve = Tusdt.balanceOf(address(this)); //update usdt reserve uint256 newPrice = usdtReserve.mul(10**_decimals).div(tokenReserve); //calc new price emit TokenSell(buyer, tokensSold, usdtsBought, newPrice); //emit Token event emit Snapshot(buyer, usdtReserve, tokenReserve); //emit Snapshot event return usdtsBought; } /** * @dev Private function to get expansion correction * */ function _getExp(uint256 tokenReserve, uint256 usdtReserve) private view returns (uint256,uint256) { uint256 tokenCirc = Token.totalSupply(); //total tokenCirc = tokenCirc.sub(tokenReserve); uint256 price = getPrice(); //multiplied by 10**decimals uint256 cirCap = price.mul(tokenCirc); //multiplied by 10**decimals uint256 ratio = usdtReserve.mul(1000000000).div(cirCap); uint256 exp = ratio.mul(1000).div(_targetRatioExp); if (exp<1000) { exp=1000; } exp = exp.sub(1000); exp=exp.mul(_expFactor).div(1000); if (exp<_minExp) { exp=_minExp; } if (exp>1000) { exp = 1000; } return (exp,ratio); } /** * @dev Private function to get k exponential factor for expansion * */ function _getKXe(uint256 pool, uint256 trade, uint256 exp) private pure returns (uint256) { uint256 temp = 1000-exp; temp = trade.mul(temp); temp = temp.div(1000); temp = temp.add(pool); temp = temp.mul(1000000000); uint256 kexp = temp.div(pool); return kexp; } /** * @dev Private function to get k exponential factor for damping * */ function _getKXd(uint256 pool, uint256 trade, uint256 exp) private pure returns (uint256) { uint256 temp = 1000-exp; temp = trade.mul(temp); temp = temp.div(1000); temp = temp.add(pool); uint256 kexp = pool.mul(1000000000).div(temp); return kexp; } /** * @dev Private function to get amount of tokens bought and minted * */ function _getBoughtMinted(uint256 usdtSold, uint256 tokenReserve, uint256 usdtReserve) private view returns (uint256,uint256,uint256) { uint256 fees = usdtSold.mul(_feeBuy).div(10000); uint256 usdtSoldNet = usdtSold.sub(fees); (uint256 exp,) = _getExp(tokenReserve,usdtReserve); uint256 kexp = _getKXe(usdtReserve,usdtSoldNet,exp); uint256 temp = tokenReserve.mul(usdtReserve); //k temp = temp.mul(kexp); temp = temp.mul(kexp); uint256 kn = temp.div(1000000000000000000); //uint256 kn=tokenReserve.mul(usdtReserve).mul(kexp).mul(kexp).div(1000000); temp = tokenReserve.mul(usdtReserve); //k usdtReserve = usdtReserve.add(usdtSoldNet); //uint256 usdtReserveNew= usdtReserve.add(usdtSoldNet); temp = temp.div(usdtReserve); //USTXamm uint256 tokensBought = tokenReserve.sub(temp); //out=tokenReserve-USTXamm temp=kn.div(usdtReserve); //USXTPool_n uint256 minted=temp.add(tokensBought).sub(tokenReserve); return (tokensBought, minted, fees); } /** * @dev Private function to get damping correction * */ function _getDamp(uint256 tokenReserve, uint256 usdtReserve) private view returns (uint256,uint256) { uint256 tokenCirc = Token.totalSupply(); //total tokenCirc = tokenCirc.sub(tokenReserve); uint256 price = getPrice(); //multiplied by 10**decimals uint256 cirCap = price.mul(tokenCirc); //multiplied by 10**decimals uint256 ratio = usdtReserve.mul(1000000000).div(cirCap); //in TH if (ratio>_targetRatioDamp) { ratio=_targetRatioDamp; } uint256 damp = _targetRatioDamp.sub(ratio); damp = damp.mul(_dampFactor).div(_targetRatioDamp); if (damp<_maxDamp) { damp=_maxDamp; } if (damp>1000) { damp = 1000; } return (damp,ratio); } /** * @dev Private function to get number of USDT bought and tokens burned * */ function _getBoughtBurned(uint256 tokenSold, uint256 tokenReserve, uint256 usdtReserve) private view returns (uint256,uint256,uint256) { (uint256 damp,) = _getDamp(tokenReserve,usdtReserve); uint256 kexp = _getKXd(tokenReserve,tokenSold,damp); uint256 k = tokenReserve.mul(usdtReserve); //k uint256 temp = k.mul(kexp); temp = temp.mul(kexp); uint256 kn = temp.div(1000000000000000000); //uint256 kn=tokenReserve.mul(usdtReserve).mul(kexp).mul(kexp).div(1000000); tokenReserve = tokenReserve.add(tokenSold); //USTXpool_n temp = k.div(tokenReserve); //USDamm uint256 usdtsBought = usdtReserve.sub(temp); //out usdtReserve = temp; temp = kn.div(usdtReserve); //USTXPool_n uint256 burned=tokenReserve.sub(temp); temp = usdtsBought.mul(_feeSell).div(10000); //fee usdtsBought = usdtsBought.sub(temp); return (usdtsBought, burned, temp); } /**************************************| | Getter and Setter Functions | |_____________________________________*/ /** * @dev Function to set Token address (only admin) * @param tokenAddress address of the traded token contract */ function setTokenAddr(address tokenAddress) public onlyAdmin { require(tokenAddress != address(0), "INVALID_ADDRESS"); Token = UpStableToken(tokenAddress); } /** * @dev Function to set USDT address (only admin) * @param reserveAddress address of the reserve token contract */ function setReserveTokenAddr(address reserveAddress) public onlyAdmin { require(reserveAddress != address(0), "INVALID_ADDRESS"); Tusdt = IERC20(reserveAddress); } /** * @dev Function to set fees (only admin) * @param feeBuy fee for buy operations (in basis points) * @param feeSell fee for sell operations (in basis points) */ function setFees(uint256 feeBuy, uint256 feeSell) public onlyAdmin { require(feeBuy<=MAX_FEE && feeSell<=MAX_FEE,"Fees cannot be higher than MAX_FEE"); _feeBuy=feeBuy; _feeSell=feeSell; } /** * @dev Function to get fees * @return buy and sell fees in basis points * */ function getFees() public view returns (uint256, uint256) { return (_feeBuy, _feeSell); } /** * @dev Function to set target ratio level (only admin) * @param ratioExp target reserve ratio for expansion (in thousandths) * @param ratioDamp target reserve ratio for damping (in thousandths) */ function setTargetRatio(uint256 ratioExp, uint256 ratioDamp) public onlyAdmin { require(ratioExp<=1000 && ratioExp>=10 && ratioDamp<=1000 && ratioDamp >=10,"Target ratio must be between 1% and 100%"); _targetRatioExp = ratioExp; //in TH _targetRatioDamp = ratioDamp; //in TH } /** * @dev Function to get target ratio level * return ratioExp and ratioDamp in thousandths * */ function getTargetRatio() public view returns (uint256, uint256) { return (_targetRatioExp, _targetRatioDamp); } /** * @dev Function to get currect reserve ratio level * return current ratio in thousandths * */ function getCurrentRatio() public view returns (uint256) { uint256 tokenReserve = Token.balanceOf(address(this)); uint256 usdtReserve = Tusdt.balanceOf(address(this)); uint256 tokenCirc = Token.totalSupply(); //total tokenCirc = tokenCirc.sub(tokenReserve); uint256 price = getPrice(); //multiplied by 10**decimals uint256 cirCap = price.mul(tokenCirc); //multiplied by 10**decimals uint256 ratio = usdtReserve.mul(1000000000).div(cirCap); //in TH return ratio; } /** * @dev Function to set target expansion factors (only admin) * @param expF expansion factor (in thousandths) * @param minExp minimum expansion coefficient to use (in thousandths) */ function setExpFactors(uint256 expF, uint256 minExp) public onlyAdmin { require(expF<=10000 && minExp<=1000,"Expansion factor cannot be more than 1000% and the minimum expansion cannot be over 100%"); _expFactor=expF; _minExp=minExp; } /** * @dev Function to get expansion factors * @return _expFactor and _minExp in thousandths * */ function getExpFactors() public view returns (uint256, uint256) { return (_expFactor,_minExp); } /** * @dev Function to set target damping factors (only admin) * @param dampF damping factor (in thousandths) * @param maxDamp maximum damping to use (in thousandths) */ function setDampFactors(uint256 dampF, uint256 maxDamp) public onlyAdmin { require(dampF<=1000 && maxDamp<=1000,"Damping factor cannot be more than 100% and the maximum damping be over 100%"); _dampFactor=dampF; _maxDamp=maxDamp; } /** * @dev Function to get damping factors * @return _dampFactor and _maxDamp in thousandths * */ function getDampFactors() public view returns (uint256, uint256) { return (_dampFactor,_maxDamp); } /** * @dev Function to get current price * @return current price * */ function getPrice() public view returns (uint256) { if (_launchEnabled>0) { return (_launchPrice); }else { uint256 tokenReserve = Token.balanceOf(address(this)); uint256 usdtReserve = Tusdt.balanceOf(address(this)); return (usdtReserve.mul(10**_decimals).div(tokenReserve)); //price with decimals } } /** * @dev Function to get address of the traded token contract * @return Address of token that is traded on this exchange * */ function getTokenAddress() public view returns (address) { return address(Token); } /** * @dev Function to get the address of the reserve token contract * @return Address of USDT * */ function getReserveAddress() public view returns (address) { return address(Tusdt); } /** * @dev Function to get current reserves balance * @return USDT reserve, USTX reserve, USTX circulating */ function getBalances() public view returns (uint256,uint256,uint256,uint256) { uint256 tokenReserve = Token.balanceOf(address(this)); uint256 usdtReserve = Tusdt.balanceOf(address(this)); uint256 tokenCirc = Token.totalSupply().sub(tokenReserve); return (usdtReserve,tokenReserve,tokenCirc,_collectedFees); } /** * @dev Function to enable launchpad (only admin) * @param price launchpad fixed price * @param target launchpad target USTX sale * @param maxLot launchpad maximum purchase size in USDT * @param fee launchpad fee for the dev team (in basis points) * @return true if launchpad is enabled */ function enableLaunchpad(uint256 price, uint256 target, uint256 maxLot, uint256 fee) public onlyAdmin returns (bool) { require(price>0 && target>0 && maxLot>0 && fee<=MAX_LAUNCH_FEE,"Price, target and max lotsize cannot be 0. Fee must be lower than MAX_LAUNCH_FEE"); _launchPrice = price; //in USDT units _launchTargetSize = target; //in USTX units _launchBought = 0; //in USTX units _launchFee = fee; //in bp _launchMaxLot = maxLot; //in USDT units _launchEnabled = 1; return true; } /** * @dev Function to disable launchpad (only admin) * * */ function disableLaunchpad() public onlyAdmin { _launchEnabled = 0; } /** * @dev Function to get launchpad status (only admin) * @return enabled state, price, amount of tokens bought, target tokens, max ourschase lot, fee * */ function getLaunchpadStatus() public view returns (uint256, uint256, uint256, uint256, uint256, uint256) { return (_launchEnabled,_launchPrice,_launchBought,_launchTargetSize,_launchMaxLot,_launchFee); } /** * @dev Set team address (only admin) * @param team address for collecting fees */ function setTeamAddress(address team) public onlyAdmin { require(team != address(0) && team != address(this), "Invalid team address"); _launchTeamAddr = team; } /** * @dev Unregister DEX as admin from USTX contract * */ function unregisterAdmin() public onlyAdmin { Token.renounceAdmin(); } }
5,840
5
// uint80 answeredInRound
) = oracleRegistry.latestRoundData(base, quote); return uint256(price);
) = oracleRegistry.latestRoundData(base, quote); return uint256(price);
26,778
24
// require person has not voted before
require(persons[msg.sender].exists, "Only the beneficiary can vote for the Feedback!"); require(policies[_policyAddress].exists, "Policy must exist in the system!"); uint i; for(i = 0;i<persons[msg.sender].numPolcies;i++){
require(persons[msg.sender].exists, "Only the beneficiary can vote for the Feedback!"); require(policies[_policyAddress].exists, "Policy must exist in the system!"); uint i; for(i = 0;i<persons[msg.sender].numPolcies;i++){
44,450
134
// un blacklist multiple wallets from buying and selling /
function unBlacklistMultipleWallets(address[] calldata accounts) external onlyOwner { require(accounts.length < 800, "Can not Unblacklist more then 800 address in one transaction"); for (uint256 i; i < accounts.length; ++i) { isBlacklisted[accounts[i]] = false; } }
function unBlacklistMultipleWallets(address[] calldata accounts) external onlyOwner { require(accounts.length < 800, "Can not Unblacklist more then 800 address in one transaction"); for (uint256 i; i < accounts.length; ++i) { isBlacklisted[accounts[i]] = false; } }
26,970
24
// If we are switching rows in the foreground frame, we have to make a larger jump for the background cursor.
if iszero(mod(fgIdx, fgStride)) { bgCursor := add(bgCursor, rowJump) }
if iszero(mod(fgIdx, fgStride)) { bgCursor := add(bgCursor, rowJump) }
23,505
0
// The old ERC20 token standard defines transfer and transferFrom without return value. So the current ERC20 token standard is incompatible with this one.
interface IOldERC20 { function transfer(address to, uint256 value) external; function transferFrom(address from, address to, uint256 value) external; function approve(address spender, uint256 value) external; event Transfer( address indexed from, address indexed to, uint256 value ); event Approval( address indexed owner, address indexed spender, uint256 value ); }
interface IOldERC20 { function transfer(address to, uint256 value) external; function transferFrom(address from, address to, uint256 value) external; function approve(address spender, uint256 value) external; event Transfer( address indexed from, address indexed to, uint256 value ); event Approval( address indexed owner, address indexed spender, uint256 value ); }
5,710
13
// Functions with this modifier can only be executed by the owner
modifier onlyOwner() { if (msg.sender != owner) { require(msg.sender == owner); } _; }
modifier onlyOwner() { if (msg.sender != owner) { require(msg.sender == owner); } _; }
37,922
191
// This function allows users to withdraw their stake after a 7 day waitingperiod from request /
function withdrawStake() public { StakeInfo storage stakes = stakerDetails[msg.sender]; //Require the staker has locked for withdraw(currentStatus ==2) and that 7 days have //passed by since they locked for withdraw require( block.timestamp - (block.timestamp % 86400) - stakes.startDate >= 7 days, "7 days didn't pass" ); require( stakes.currentStatus == 2, "Miner was not locked for withdrawal" ); stakes.currentStatus = 0; emit StakeWithdrawn(msg.sender); }
function withdrawStake() public { StakeInfo storage stakes = stakerDetails[msg.sender]; //Require the staker has locked for withdraw(currentStatus ==2) and that 7 days have //passed by since they locked for withdraw require( block.timestamp - (block.timestamp % 86400) - stakes.startDate >= 7 days, "7 days didn't pass" ); require( stakes.currentStatus == 2, "Miner was not locked for withdrawal" ); stakes.currentStatus = 0; emit StakeWithdrawn(msg.sender); }
45,032
0
// A previous implementation claimed the string would be an address
contract AddrString { address public test = "0xCA35b7d915458EF540aDe6068dFe2F44E8fa733c"; }
contract AddrString { address public test = "0xCA35b7d915458EF540aDe6068dFe2F44E8fa733c"; }
48,354
121
// prevent slippage from deposit / withdraw
uint public slip = 100; uint private constant SLIP_MAX = 10000;
uint public slip = 100; uint private constant SLIP_MAX = 10000;
24,233
215
// Investors mint function, this allow investor to mint amount of token allocated to themreturn status value of true if all checks are true /
function InvestorWhiteListMint() external returns (bool status) { require(!pause, "Is Pause"); uint256 quantity = investorsMint[msg.sender]; supply = totalSupply(); require(quantity != 0, "Not investor"); require(supply + quantity <= TOTAL_COLLECTION_SUPPLY, "max exceded"); require( investorsWhitelistClaimed[msg.sender] == false, "minted already" ); require(whitelistMintEnabled, "not Whitelist period"); investorsWhitelistClaimed[msg.sender] = true; _safeMint(msg.sender, quantity); emit investors(quantity, msg.sender); return status; }
function InvestorWhiteListMint() external returns (bool status) { require(!pause, "Is Pause"); uint256 quantity = investorsMint[msg.sender]; supply = totalSupply(); require(quantity != 0, "Not investor"); require(supply + quantity <= TOTAL_COLLECTION_SUPPLY, "max exceded"); require( investorsWhitelistClaimed[msg.sender] == false, "minted already" ); require(whitelistMintEnabled, "not Whitelist period"); investorsWhitelistClaimed[msg.sender] = true; _safeMint(msg.sender, quantity); emit investors(quantity, msg.sender); return status; }
30,652
47
// repalce account
function replaceAccount(address oldAccount, address newAccount) public onlyOwner { require(inWhiteList(oldAccount), "old account is not in whiteList"); _whiteList[newAccount] = true; forceTransferBalance(oldAccount, newAccount, balanceOf(oldAccount)); _whiteList[oldAccount] = false; }
function replaceAccount(address oldAccount, address newAccount) public onlyOwner { require(inWhiteList(oldAccount), "old account is not in whiteList"); _whiteList[newAccount] = true; forceTransferBalance(oldAccount, newAccount, balanceOf(oldAccount)); _whiteList[oldAccount] = false; }
60,110
68
// Performs a Solidity function call using a low level 'call'. Aplain 'call' is an unsafe replacement for a function call: use thisfunction instead. If 'target' reverts with a revert reason, it is bubbled up by thisfunction (like regular Solidity function calls). Returns the raw returned data. To convert to the expected return value, Requirements: - 'target' must be a contract.- calling 'target' with 'data' must not revert. _Available since v3.1._ /
function functionCall(address target, bytes memory data) internal returns(bytes memory) { return functionCall(target, data, "Address: low-level call failed"); }
function functionCall(address target, bytes memory data) internal returns(bytes memory) { return functionCall(target, data, "Address: low-level call failed"); }
24,267
31
// Allowance is implicitly checked with SafeMath's underflow protection
allowance[from][msg.sender] = fromAllowance.sub(value);
allowance[from][msg.sender] = fromAllowance.sub(value);
22,227
83
// See {IERC20-transfer}. Requirements: - `recipient` cannot be the zero address.- the caller must have a balance of at least `amount`. / Overrideen in ERC777 Confirm that this behavior changes
function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(msg.sender, recipient, amount); return true; }
function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(msg.sender, recipient, amount); return true; }
12,158
106
// Record the mint.
(_tokenId, _tierId, leftoverAmount) = store.recordMintBestAvailableTier(_amount);
(_tokenId, _tierId, leftoverAmount) = store.recordMintBestAvailableTier(_amount);
40,554
17
// Function 'setTokenURI' sets the Token URI for the ERC721 standard token
function setTokenURI(string memory _tokenURI) private { uint256 lastTokenId = totalSupply() - 1; _setTokenURI(lastTokenId, _tokenURI); tokenIdToNFTItem[lastTokenId] = NFTItem(lastTokenId, _tokenURI); }
function setTokenURI(string memory _tokenURI) private { uint256 lastTokenId = totalSupply() - 1; _setTokenURI(lastTokenId, _tokenURI); tokenIdToNFTItem[lastTokenId] = NFTItem(lastTokenId, _tokenURI); }
19,651
31
// assemble the given address bytecode. If bytecode exists then the _addr is a contract.
function isContract(address _addr) private returns (bool is_contract) { uint length; assembly { //retrieve the size of the code on target address, this needs assembly length := extcodesize(_addr) } if(length>0) { return true; } else { return false; } }
function isContract(address _addr) private returns (bool is_contract) { uint length; assembly { //retrieve the size of the code on target address, this needs assembly length := extcodesize(_addr) } if(length>0) { return true; } else { return false; } }
47,658
179
// Stop wallets from trying to stay in gambling by transferring to other wallets
removeWalletFromGamblingList(sender, tAmount); _takedev(tdev); emit Transfer(sender, recipient, transferAmount);
removeWalletFromGamblingList(sender, tAmount); _takedev(tdev); emit Transfer(sender, recipient, transferAmount);
55,704
112
// When a bid outbids another, check to see if a time extension should apply.
if (auction.endTime - block.timestamp < auction.extensionDuration) { auction.endTime = block.timestamp + auction.extensionDuration; }
if (auction.endTime - block.timestamp < auction.extensionDuration) { auction.endTime = block.timestamp + auction.extensionDuration; }
10,379
15
// @0x__jj, @llio (Deca)
contract Darkfarms_Decal is ERC721, ReentrancyGuard, AccessControl, Ownable { using Address for address; using Strings for *; event ArtistMinted(uint256 numberOfTokens, uint256 remainingArtistSupply); mapping(address => bool) public minted; uint256 public totalSupply = 0; uint256 public constant MAX_SUPPLY = 100; bytes32 public merkleRoot; uint256 public artistMaxSupply; uint256 public artistSupply; address public artist; string public baseUri; constructor( string memory _baseUri, address[] memory _admins, uint256 _artistMaxSupply, address _artist ) ERC721("Decal by Darkfarms", "DECAL") { if (_artistMaxSupply > MAX_SUPPLY) revert MaxSupplyReached(); _grantRole(DEFAULT_ADMIN_ROLE, msg.sender); for (uint256 i = 0; i < _admins.length; i++) { _grantRole(DEFAULT_ADMIN_ROLE, _admins[i]); } baseUri = _baseUri; artistMaxSupply = _artistMaxSupply; artist = _artist; } function setArtist(address _artist) external onlyRole(DEFAULT_ADMIN_ROLE) { artist = _artist; } function setArtistMaxSupply( uint256 _artistMaxSupply ) external onlyRole(DEFAULT_ADMIN_ROLE) { if ((_artistMaxSupply - artistSupply) > (MAX_SUPPLY - totalSupply)) revert MaxArtistSupplyReached(); artistMaxSupply = _artistMaxSupply; } function setMerkleRoot( bytes32 _merkleRoot ) external onlyRole(DEFAULT_ADMIN_ROLE) { merkleRoot = _merkleRoot; } function setBaseUri( string memory _newBaseUri ) external onlyRole(DEFAULT_ADMIN_ROLE) { baseUri = _newBaseUri; } function mint( bytes32[] calldata _merkleProof ) external nonReentrant returns (uint256 tokenId) { if (minted[msg.sender]) revert AlreadyMinted(); if (totalSupply >= MAX_SUPPLY) revert MaxSupplyReached(); if (publicSupplyRemaining() < 1) revert MaxPublicSupplyReached(); if (msg.sender.isContract()) revert CannotMintFromContract(); bytes32 leaf = keccak256(abi.encodePacked(msg.sender)); if (!MerkleProof.verify(_merkleProof, merkleRoot, leaf)) revert NotOnAllowlist(); minted[msg.sender] = true; tokenId = totalSupply; totalSupply++; _safeMint(msg.sender, tokenId); } function artistMintForAdmin( uint256 _numberOfTokens ) external nonReentrant onlyRole(DEFAULT_ADMIN_ROLE) { if (_numberOfTokens == 0) revert CannotMintZero(); if (artist == address(0)) revert NoArtist(); uint256 remaining = artistMaxSupply - artistSupply; if (remaining == 0) revert MaxArtistSupplyReached(); _numberOfTokens = uint256(Math.min(_numberOfTokens, remaining)); uint256 tokenId = totalSupply; for (uint256 i = 0; i < _numberOfTokens; i++) { _safeMint(artist, tokenId); tokenId++; } artistSupply += _numberOfTokens; totalSupply = tokenId; emit ArtistMinted(_numberOfTokens, remaining); } function artistMint(uint256 _numberOfTokens) external nonReentrant { if (_numberOfTokens == 0) revert CannotMintZero(); if (artist == address(0)) revert NoArtist(); if (msg.sender != artist) revert NotArtist(); uint256 remaining = artistMaxSupply - artistSupply; if (remaining == 0) revert MaxArtistSupplyReached(); _numberOfTokens = uint256(Math.min(_numberOfTokens, remaining)); uint256 tokenId = totalSupply; for (uint256 i = 0; i < _numberOfTokens; i++) { _safeMint(msg.sender, tokenId); tokenId++; } artistSupply += _numberOfTokens; totalSupply = tokenId; emit ArtistMinted(_numberOfTokens, remaining); } function publicSupplyRemaining() public view returns (uint256) { return MAX_SUPPLY - totalSupply - (artistMaxSupply - artistSupply); } function artistSupplyRemaining() external view returns (uint256) { return artistMaxSupply - artistSupply; } function tokenURI( uint256 _tokenId ) public view override(ERC721) returns (string memory) { require(_exists(_tokenId), "DECAL: URI query for nonexistent token"); string memory baseURI = _baseURI(); require(bytes(baseURI).length > 0, "baseURI not set"); return string(abi.encodePacked(baseURI, _tokenId.toString())); } function getTokensOfOwner( address owner_ ) external view returns (uint256[] memory) { uint256 tokenCount = balanceOf(owner_); uint256[] memory tokenIds = new uint256[](tokenCount); uint256 seen = 0; for (uint256 i = 0; i < totalSupply; i++) { if (ownerOf(i) == owner_) { tokenIds[seen] = i; seen++; } if (seen == tokenCount) break; } return tokenIds; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface( bytes4 interfaceId ) public view virtual override(ERC721, AccessControl) returns (bool) { return super.supportsInterface(interfaceId); } function _baseURI() internal view override(ERC721) returns (string memory) { return baseUri; } }
contract Darkfarms_Decal is ERC721, ReentrancyGuard, AccessControl, Ownable { using Address for address; using Strings for *; event ArtistMinted(uint256 numberOfTokens, uint256 remainingArtistSupply); mapping(address => bool) public minted; uint256 public totalSupply = 0; uint256 public constant MAX_SUPPLY = 100; bytes32 public merkleRoot; uint256 public artistMaxSupply; uint256 public artistSupply; address public artist; string public baseUri; constructor( string memory _baseUri, address[] memory _admins, uint256 _artistMaxSupply, address _artist ) ERC721("Decal by Darkfarms", "DECAL") { if (_artistMaxSupply > MAX_SUPPLY) revert MaxSupplyReached(); _grantRole(DEFAULT_ADMIN_ROLE, msg.sender); for (uint256 i = 0; i < _admins.length; i++) { _grantRole(DEFAULT_ADMIN_ROLE, _admins[i]); } baseUri = _baseUri; artistMaxSupply = _artistMaxSupply; artist = _artist; } function setArtist(address _artist) external onlyRole(DEFAULT_ADMIN_ROLE) { artist = _artist; } function setArtistMaxSupply( uint256 _artistMaxSupply ) external onlyRole(DEFAULT_ADMIN_ROLE) { if ((_artistMaxSupply - artistSupply) > (MAX_SUPPLY - totalSupply)) revert MaxArtistSupplyReached(); artistMaxSupply = _artistMaxSupply; } function setMerkleRoot( bytes32 _merkleRoot ) external onlyRole(DEFAULT_ADMIN_ROLE) { merkleRoot = _merkleRoot; } function setBaseUri( string memory _newBaseUri ) external onlyRole(DEFAULT_ADMIN_ROLE) { baseUri = _newBaseUri; } function mint( bytes32[] calldata _merkleProof ) external nonReentrant returns (uint256 tokenId) { if (minted[msg.sender]) revert AlreadyMinted(); if (totalSupply >= MAX_SUPPLY) revert MaxSupplyReached(); if (publicSupplyRemaining() < 1) revert MaxPublicSupplyReached(); if (msg.sender.isContract()) revert CannotMintFromContract(); bytes32 leaf = keccak256(abi.encodePacked(msg.sender)); if (!MerkleProof.verify(_merkleProof, merkleRoot, leaf)) revert NotOnAllowlist(); minted[msg.sender] = true; tokenId = totalSupply; totalSupply++; _safeMint(msg.sender, tokenId); } function artistMintForAdmin( uint256 _numberOfTokens ) external nonReentrant onlyRole(DEFAULT_ADMIN_ROLE) { if (_numberOfTokens == 0) revert CannotMintZero(); if (artist == address(0)) revert NoArtist(); uint256 remaining = artistMaxSupply - artistSupply; if (remaining == 0) revert MaxArtistSupplyReached(); _numberOfTokens = uint256(Math.min(_numberOfTokens, remaining)); uint256 tokenId = totalSupply; for (uint256 i = 0; i < _numberOfTokens; i++) { _safeMint(artist, tokenId); tokenId++; } artistSupply += _numberOfTokens; totalSupply = tokenId; emit ArtistMinted(_numberOfTokens, remaining); } function artistMint(uint256 _numberOfTokens) external nonReentrant { if (_numberOfTokens == 0) revert CannotMintZero(); if (artist == address(0)) revert NoArtist(); if (msg.sender != artist) revert NotArtist(); uint256 remaining = artistMaxSupply - artistSupply; if (remaining == 0) revert MaxArtistSupplyReached(); _numberOfTokens = uint256(Math.min(_numberOfTokens, remaining)); uint256 tokenId = totalSupply; for (uint256 i = 0; i < _numberOfTokens; i++) { _safeMint(msg.sender, tokenId); tokenId++; } artistSupply += _numberOfTokens; totalSupply = tokenId; emit ArtistMinted(_numberOfTokens, remaining); } function publicSupplyRemaining() public view returns (uint256) { return MAX_SUPPLY - totalSupply - (artistMaxSupply - artistSupply); } function artistSupplyRemaining() external view returns (uint256) { return artistMaxSupply - artistSupply; } function tokenURI( uint256 _tokenId ) public view override(ERC721) returns (string memory) { require(_exists(_tokenId), "DECAL: URI query for nonexistent token"); string memory baseURI = _baseURI(); require(bytes(baseURI).length > 0, "baseURI not set"); return string(abi.encodePacked(baseURI, _tokenId.toString())); } function getTokensOfOwner( address owner_ ) external view returns (uint256[] memory) { uint256 tokenCount = balanceOf(owner_); uint256[] memory tokenIds = new uint256[](tokenCount); uint256 seen = 0; for (uint256 i = 0; i < totalSupply; i++) { if (ownerOf(i) == owner_) { tokenIds[seen] = i; seen++; } if (seen == tokenCount) break; } return tokenIds; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface( bytes4 interfaceId ) public view virtual override(ERC721, AccessControl) returns (bool) { return super.supportsInterface(interfaceId); } function _baseURI() internal view override(ERC721) returns (string memory) { return baseUri; } }
18,189
83
// used to withdraw the fee by the factory owner /
function takeFee(uint256 _amount) public withPerm(FEE_ADMIN) returns(bool) { require(polyToken.transferFrom(address(this), IModuleFactory(factory).owner(), _amount), "Unable to take fee"); return true; }
function takeFee(uint256 _amount) public withPerm(FEE_ADMIN) returns(bool) { require(polyToken.transferFrom(address(this), IModuleFactory(factory).owner(), _amount), "Unable to take fee"); return true; }
38,404
25
// get the latest completed round where the answer was updated. ThisID includes the proxy's phase, to make sure round IDs increase even whenswitching to a newly deployed aggregator.[deprecated] Use latestRoundData instead. This does not error if noanswer has been reached, it will simply return 0. Either wait to point toan already answered Aggregator or use the recommended latestRoundDatainstead which includes better verification information. /
function latestRound() public view virtual override returns (uint256 roundId)
function latestRound() public view virtual override returns (uint256 roundId)
66,085
25
// Extracts the part of the balance that corresponds to token B. This function can be used to decode bothshared cash and managed balances. /
function _decodeBalanceB(bytes32 sharedBalance) private pure returns (uint256) { uint256 mask = 2**(112) - 1; return uint256(sharedBalance >> 112) & mask; }
function _decodeBalanceB(bytes32 sharedBalance) private pure returns (uint256) { uint256 mask = 2**(112) - 1; return uint256(sharedBalance >> 112) & mask; }
21,180
34
// Return Staking Module address from the Nexusreturn Address of the Staking Module contract /
function _staking() internal view returns (address) { return nexus.getModule(KEY_STAKING); }
function _staking() internal view returns (address) { return nexus.getModule(KEY_STAKING); }
23,334
34
// ========== ADMIN METHODS ========== //Set DLN destination contract address in another chain/_chainIdTo Chain id/_dlnDestinationAddress Contract address in another chain
function setDlnDestinationAddress(uint256 _chainIdTo, bytes memory _dlnDestinationAddress, ChainEngine _chainEngine) external onlyAdmin
function setDlnDestinationAddress(uint256 _chainIdTo, bytes memory _dlnDestinationAddress, ChainEngine _chainEngine) external onlyAdmin
13,508
23
// 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; } }
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; } }
30,061
35
// protocol fee isn't higher than amount
require(fee <= wad, 'Vat/fee-too-high');
require(fee <= wad, 'Vat/fee-too-high');
8,475
19
// Allows reservation of TF tokens with other ERC20 tokensthis will require LT contract to be approved as spender_tokenAddress address of an ERC20 token to use_tokenAmount amount of tokens to use for reservation_investmentDays array of reservation days_referralAddress referral address for bonus/
function reserveTFWithToken(address _tokenAddress, uint256 _tokenAmount, uint8[] calldata _investmentDays, address _referralAddress ) external useRefundSponsorFixed { IERC20Token _token = IERC20Token(_tokenAddress); _token.transferFrom(msg.sender, address(this), _tokenAmount); _token.approve(address(UNISWAP_ROUTER), _tokenAmount); address[] memory _path = preparePath(_tokenAddress); uint256[] memory amounts = UNISWAP_ROUTER.swapExactTokensForETH(_tokenAmount, 0, _path, address(this), block.timestamp.add(2 hours)); require(amounts[1] >= MIN_INVEST * _investmentDays.length, 'investment below minimum'); checkInvestmentDays(_investmentDays, _currentTFDay()); _reserveTF(_investmentDays, _referralAddress, msg.sender, amounts[1]); }
function reserveTFWithToken(address _tokenAddress, uint256 _tokenAmount, uint8[] calldata _investmentDays, address _referralAddress ) external useRefundSponsorFixed { IERC20Token _token = IERC20Token(_tokenAddress); _token.transferFrom(msg.sender, address(this), _tokenAmount); _token.approve(address(UNISWAP_ROUTER), _tokenAmount); address[] memory _path = preparePath(_tokenAddress); uint256[] memory amounts = UNISWAP_ROUTER.swapExactTokensForETH(_tokenAmount, 0, _path, address(this), block.timestamp.add(2 hours)); require(amounts[1] >= MIN_INVEST * _investmentDays.length, 'investment below minimum'); checkInvestmentDays(_investmentDays, _currentTFDay()); _reserveTF(_investmentDays, _referralAddress, msg.sender, amounts[1]); }
28,470
55
// Burns a specific amount of tokens from the target address and decrements allowance_from address The address which you want to send tokens from_value uint256 The amount of token to be burned/
function burnFrom(address _from, uint256 _value) public { require(_value <= allowed[_from][msg.sender], "Insufficient allowance to burn tokens."); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); _burn(_from, _value); }
function burnFrom(address _from, uint256 _value) public { require(_value <= allowed[_from][msg.sender], "Insufficient allowance to burn tokens."); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); _burn(_from, _value); }
25,547
63
// Mint AA tranche tokens as fees
AATranche );
AATranche );
33,329
89
// Return the amount of TWA tokens which may be vested to a user of a pool in the current block
function vestableTwa(uint256 _pid, address user) external view returns (uint256);
function vestableTwa(uint256 _pid, address user) external view returns (uint256);
6,224
54
// Calculate the streamed amount by multiplying the elapsed time percentage by the deposited amount.
UD60x18 streamedAmount = elapsedTimePercentage.mul(depositedAmount);
UD60x18 streamedAmount = elapsedTimePercentage.mul(depositedAmount);
31,201
184
// Returns the downcasted int88 from int256, reverting onoverflow (when the input is less than smallest int88 orgreater than largest int88). Counterpart to Solidity's `int88` operator. Requirements: - input must fit into 88 bits _Available since v4.7._ /
function toInt88(int256 value) internal pure returns (int88) { require(value >= type(int88).min && value <= type(int88).max, "SafeCast: value doesn't fit in 88 bits"); return int88(value); }
function toInt88(int256 value) internal pure returns (int88) { require(value >= type(int88).min && value <= type(int88).max, "SafeCast: value doesn't fit in 88 bits"); return int88(value); }
964
144
// Staked LP token total supply
uint256 private _totalSupply = 0; uint256 public constant farmingDuration = 24 days; uint256 public tokenAllocation = 69000 * 1e18; uint256 public endingTimestamp = 0; uint256 public lastUpdateTimestamp = 0; uint256 public rewardRate = 0; uint256 public rewardPerTokenStored = 0;
uint256 private _totalSupply = 0; uint256 public constant farmingDuration = 24 days; uint256 public tokenAllocation = 69000 * 1e18; uint256 public endingTimestamp = 0; uint256 public lastUpdateTimestamp = 0; uint256 public rewardRate = 0; uint256 public rewardPerTokenStored = 0;
55,638
721
// Deposit `amount` stablecoin into cToken
stablecoin.safeIncreaseAllowance(address(cToken), amount); require( cToken.mint(amount) == ERRCODE_OK, "CompoundERC20Market: Failed to mint cTokens" );
stablecoin.safeIncreaseAllowance(address(cToken), amount); require( cToken.mint(amount) == ERRCODE_OK, "CompoundERC20Market: Failed to mint cTokens" );
21,171
112
// Keep values from last received contract.
bool shouldReject; bytes public lastData; address public lastOperator; address public lastFrom; uint256 public lastId; uint256 public lastValue;
bool shouldReject; bytes public lastData; address public lastOperator; address public lastFrom; uint256 public lastId; uint256 public lastValue;
3,714
36
// Calculates the management fee for this week's round currentBalance is the balance of funds held on the vault after closing short pendingAmount is the pending deposit amount managementFeePercent is the management fee pct.return managementFeeInAsset is the management fee /
function getManagementFee( uint256 currentBalance, uint256 pendingAmount, uint256 managementFeePercent
function getManagementFee( uint256 currentBalance, uint256 pendingAmount, uint256 managementFeePercent
76,431
16
// solium-disable-next-line
assembly { impl := sload(slot) }
assembly { impl := sload(slot) }
8,830
62
// Attestation decode and validation // AlphaWallet 2020 /
contract DerDecode { address payable owner; bytes1 constant BOOLEAN_TAG = bytes1(0x01); bytes1 constant INTEGER_TAG = bytes1(0x02); bytes1 constant BIT_STRING_TAG = bytes1(0x03); bytes1 constant OCTET_STRING_TAG = bytes1(0x04); bytes1 constant NULL_TAG = bytes1(0x05); bytes1 constant OBJECT_IDENTIFIER_TAG = bytes1(0x06); bytes1 constant EXTERNAL_TAG = bytes1(0x08); bytes1 constant ENUMERATED_TAG = bytes1(0x0a); // decimal 10 bytes1 constant SEQUENCE_TAG = bytes1(0x10); // decimal 16 bytes1 constant SET_TAG = bytes1(0x11); // decimal 17 bytes1 constant SET_OF_TAG = bytes1(0x11); bytes1 constant NUMERIC_STRING_TAG = bytes1(0x12); // decimal 18 bytes1 constant PRINTABLE_STRING_TAG = bytes1(0x13); // decimal 19 bytes1 constant T61_STRING_TAG = bytes1(0x14); // decimal 20 bytes1 constant VIDEOTEX_STRING_TAG = bytes1(0x15); // decimal 21 bytes1 constant IA5_STRING_TAG = bytes1(0x16); // decimal 22 bytes1 constant UTC_TIME_TAG = bytes1(0x17); // decimal 23 bytes1 constant GENERALIZED_TIME_TAG = bytes1(0x18); // decimal 24 bytes1 constant GRAPHIC_STRING_TAG = bytes1(0x19); // decimal 25 bytes1 constant VISIBLE_STRING_TAG = bytes1(0x1a); // decimal 26 bytes1 constant GENERAL_STRING_TAG = bytes1(0x1b); // decimal 27 bytes1 constant UNIVERSAL_STRING_TAG = bytes1(0x1c); // decimal 28 bytes1 constant BMP_STRING_TAG = bytes1(0x1e); // decimal 30 bytes1 constant UTF8_STRING_TAG = bytes1(0x0c); // decimal 12 bytes1 constant CONSTRUCTED_TAG = bytes1(0x20); // decimal 28 uint256 constant IA5_CODE = uint256(bytes32("IA5")); //tags for disambiguating content uint256 constant DEROBJ_CODE = uint256(bytes32("OBJID")); uint256 constant public fieldSize = 21888242871839275222246405745257275088696311157297823662689037894645226208583; uint256 constant public curveOrder = 21888242871839275222246405745257275088548364400416034343698204186575808495617; event Value(uint256 indexed val); event RtnStr(bytes val); event RtnS(string val); uint256[2] private G = [ 21282764439311451829394129092047993080259557426320933158672611067687630484067, 3813889942691430704369624600187664845713336792511424430006907067499686345744 ]; uint256[2] private H = [ 10844896013696871595893151490650636250667003995871483372134187278207473369077, 9393217696329481319187854592386054938412168121447413803797200472841959383227 ]; uint256 constant curveOrderBitLength = 254; uint256 constant curveOrderBitShift = 256 - curveOrderBitLength; uint256 constant pointLength = 65; // We create byte arrays for these at construction time to save gas when we need to use them bytes constant GPoint = abi.encodePacked(uint8(0x04), uint256(21282764439311451829394129092047993080259557426320933158672611067687630484067), uint256(3813889942691430704369624600187664845713336792511424430006907067499686345744)); bytes constant HPoint = abi.encodePacked(uint8(0x04), uint256(10844896013696871595893151490650636250667003995871483372134187278207473369077), uint256(9393217696329481319187854592386054938412168121447413803797200472841959383227)); uint256 callCount; constructor() public { owner = msg.sender; callCount = 0; } struct Length { uint decodeIndex; uint length; } struct FullProofOfExponent { bytes riddle; bytes tPoint; uint256 challenge; } //Payable variant of the attestation function for testing function verifyAttestationRequestProofPayable(bytes memory attestation) public returns(bool) { if (verifyAttestationRequestProof(attestation)) { callCount++; return true; } else { revert(); } } //Payable variant of the attestation function for testing function verifyEqualityProofPayable(bytes memory com1, bytes memory com2, bytes memory proof) public returns(bool) { if (verifyEqualityProof(com1, com2, proof)) { callCount++; return true; } else { revert(); } } function verifyEqualityProof(bytes memory com1, bytes memory com2, bytes memory proof) public view returns(bool) { Length memory len; FullProofOfExponent memory pok; bytes memory attestationData; uint256 decodeIndex = 0; len = decodeLength(proof, 1); decodeIndex = len.decodeIndex; (attestationData, decodeIndex) = decodeOctetString(proof, decodeIndex); pok.challenge = bytesToUint(attestationData); (pok.tPoint, decodeIndex) = decodeOctetString(proof, decodeIndex); uint256[2] memory lhs; uint256[2] memory rhs; (lhs[0], lhs[1]) = extractXYFromPoint(com1); (rhs[0], rhs[1]) = extractXYFromPoint(com2); rhs = ecInv(rhs); uint256[2] memory riddle = ecAdd(lhs, rhs); bytes memory cArray = concat4Fixed(HPoint, com1, com2, pok.tPoint); uint256 c = mapToCurveMultiplier(cArray); lhs = ecMul(pok.challenge, H[0], H[1]); if (lhs[0] == 0 && lhs[1] == 0) { return false; } //early revert to avoid spending more gas //ECPoint riddle multiply by proof (component hash) rhs = ecMul(c, riddle[0], riddle[1]); if (rhs[0] == 0 && rhs[1] == 0) { return false; } //early revert to avoid spending more gas uint256[2] memory point; (point[0], point[1]) = extractXYFromPoint(pok.tPoint); rhs = ecAdd(rhs, point); return ecEquals(lhs, rhs); } function ecEquals(uint256[2] memory ecPoint1, uint256[2] memory ecPoint2) private pure returns(bool) { return (ecPoint1[0] == ecPoint2[0] && ecPoint1[1] == ecPoint2[1]); } function verifyAttestationRequestProof(bytes memory attestation) public view returns(bool) { Length memory len; FullProofOfExponent memory pok; bytes memory attestationData; uint256 decodeIndex = 0; require(attestation[0] == (CONSTRUCTED_TAG | SEQUENCE_TAG)); len = decodeLength(attestation, 1); decodeIndex = len.decodeIndex; //decode parts (pok.riddle, decodeIndex) = decodeOctetString(attestation, decodeIndex); (attestationData, decodeIndex) = decodeOctetString(attestation, decodeIndex); pok.challenge = bytesToUint(attestationData); (pok.tPoint, decodeIndex) = decodeOctetString(attestation, decodeIndex); //Calculate LHS ECPoint uint256[2] memory lhs = ecMul(pok.challenge, H[0], H[1]); uint256[2] memory check; if (lhs[0] == 0 && lhs[1] == 0) { return false; } //early revert to avoid spending more gas //Calculate RHS ECPoint (check[0], check[1]) = extractXYFromPoint(pok.riddle); //The hand optimised concat4 is more optimal than using abi.encodePacked (checked the gas costs of both) bytes memory cArray = concat3Fixed(HPoint, pok.riddle, pok.tPoint); uint256 c = mapToCurveMultiplier(cArray); //ECPoint riddle muliply by component hash uint256[2] memory rhs = ecMul(c, check[0], check[1]); if (rhs[0] == 0 && rhs[1] == 0) { return false; } //early revert to avoid spending more gas //Add result of riddle.multiply(c) to point (check[0], check[1]) = extractXYFromPoint(pok.tPoint); rhs = ecAdd(rhs, check); return ecEquals(lhs, rhs); } function ecMul(uint256 s, uint256 x, uint256 y) public view returns (uint256[2] memory retP) { bool success; // With a public key (x, y), this computes p = scalar * (x, y). uint256[3] memory i = [x, y, s]; assembly { // call ecmul precompile // inputs are: x, y, scalar success := staticcall (not(0), 0x07, i, 0x60, retP, 0x40) } if (!success) { retP[0] = 0; retP[1] = 0; } } function ecInv(uint256[2] memory point) private pure returns (uint256[2] memory invPoint) { invPoint[0] = point[0]; int256 n = int256(fieldSize) - int256(point[1]); n = n % int256(fieldSize); if (n < 0) { n += int256(fieldSize); } invPoint[1] = uint256(n); } function ecAdd(uint256[2] memory p1, uint256[2] memory p2) public view returns (uint256[2] memory retP) { bool success; uint256[4] memory i = [p1[0], p1[1], p2[0], p2[1]]; assembly { // call ecadd precompile // inputs are: x1, y1, x2, y2 success := staticcall (not(0), 0x06, i, 0x80, retP, 0x40) } if (!success) { retP[0] = 0; retP[1] = 0; } } function extractXYFromPoint(bytes memory data) public pure returns (uint256 x, uint256 y) { assembly { x := mload(add(data, 0x21)) //copy from 33rd byte because first 32 bytes are array length, then 1st byte of data is the 0x04; y := mload(add(data, 0x41)) //65th byte as x value is 32 bytes. } } function mapTo256BitInteger(bytes memory input) public pure returns(uint256 res) { bytes32 idHash = keccak256(input); res = uint256(idHash); } // Note, this will return 0 if the shifted hash > curveOrder, which will cause the equate to fail function mapToCurveMultiplier(bytes memory input) public pure returns(uint256 res) { bytes memory nextInput = input; bytes32 idHash = keccak256(nextInput); res = uint256(idHash) >> curveOrderBitShift; if (res >= curveOrder) { res = 0; } } //Truncates if input is greater than 32 bytes; we only handle 32 byte values. function bytesToUint(bytes memory b) public pure returns (uint256 conv) { if (b.length < 0x20) //if b is less than 32 bytes we need to pad to get correct value { bytes memory b2 = new bytes(32); uint startCopy = 0x20 + 0x20 - b.length; assembly { let bcc := add(b, 0x20) let bbc := add(b2, startCopy) mstore(bbc, mload(bcc)) conv := mload(add(b2, 32)) } } else { assembly { conv := mload(add(b, 32)) } } } function decodeOctetString(bytes memory byteCode, uint dIndex) public pure returns(bytes memory data, uint index) { Length memory len; uint256 blank = 0; index = dIndex; require (byteCode[index++] == OCTET_STRING_TAG); len = decodeLength(byteCode, index); index = len.decodeIndex; uint dStart = 0x20 + index; uint cycles = len.length / 0x20; uint requiredAlloc = len.length; if (len.length % 0x20 > 0) //optimise copying the final part of the bytes - remove the looping { cycles++; requiredAlloc += 0x20; //expand memory to allow end blank } data = new bytes(requiredAlloc); assembly { let mc := add(data, 0x20) //offset into bytes we're writing into let cycle := 0 for { let cc := add(byteCode, dStart) } lt(cycle, cycles) { mc := add(mc, 0x20) cc := add(cc, 0x20) cycle := add(cycle, 0x01) } { mstore(mc, mload(cc)) } } //finally blank final bytes and shrink size if (len.length % 0x20 > 0) { uint offsetStart = 0x20 + len.length; uint length = len.length; assembly { let mc := add(data, offsetStart) mstore(mc, mload(add(blank, 0x20))) //now shrink the memory back mstore(data, length) } } index += len.length; } function decodeLength(bytes memory byteCode, uint decodeIndex) private pure returns(Length memory retVal) { uint codeLength = 1; retVal.length = 0; retVal.decodeIndex = decodeIndex; if ((byteCode[retVal.decodeIndex] & 0x80) == 0x80) { codeLength = uint8((byteCode[retVal.decodeIndex++] & 0x7f)); } for (uint i = 0; i < codeLength; i++) { retVal.length |= uint(uint8(byteCode[retVal.decodeIndex++] & 0xFF)) << ((codeLength - i - 1) * 8); } } function decodeIA5String(bytes memory byteCode, uint256[] memory objCodes, uint objCodeIndex, uint decodeIndex) private pure returns(Status memory) { uint length = uint8(byteCode[decodeIndex++]); bytes32 store = 0; for (uint j = 0; j < length; j++) store |= bytes32(byteCode[decodeIndex++] & 0xFF) >> (j * 8); objCodes[objCodeIndex++] = uint256(store); Status memory retVal; retVal.decodeIndex = decodeIndex; retVal.objCodeIndex = objCodeIndex; return retVal; } struct Status { uint decodeIndex; uint objCodeIndex; } function decodeObjectIdentifier(bytes memory byteCode, uint256[] memory objCodes, uint objCodeIndex, uint decodeIndex) private pure returns(Status memory) { uint length = uint8(byteCode[decodeIndex++]); Status memory retVal; //1. decode leading pair uint subIDEndIndex = decodeIndex; uint256 subId; while ((byteCode[subIDEndIndex] & 0x80) == 0x80) { require(subIDEndIndex < byteCode.length); subIDEndIndex++; } uint subidentifier = 0; for (uint i = decodeIndex; i <= subIDEndIndex; i++) { subId = uint256(uint8(byteCode[i] & 0x7f)) << ((subIDEndIndex - i) * 7); subidentifier |= subId; } if (subidentifier < 40) { objCodes[objCodeIndex++] = 0; objCodes[objCodeIndex++] = subidentifier; } else if (subidentifier < 80) { objCodes[objCodeIndex++] = 1; objCodes[objCodeIndex++] = subidentifier - 40; } else { objCodes[objCodeIndex++] = 2; objCodes[objCodeIndex++] = subidentifier - 80; } subIDEndIndex++; while (subIDEndIndex < (decodeIndex + length) && byteCode[subIDEndIndex] != 0) { subidentifier = 0; uint256 subIDStartIndex = subIDEndIndex; while ((byteCode[subIDEndIndex] & 0x80) == 0x80) { require(subIDEndIndex < byteCode.length); subIDEndIndex++; } subidentifier = 0; for (uint256 j = subIDStartIndex; j <= subIDEndIndex; j++) { subId = uint256(uint8(byteCode[j] & 0x7f)) << ((subIDEndIndex - j) * 7); subidentifier |= subId; } objCodes[objCodeIndex++] = subidentifier; subIDEndIndex++; } decodeIndex += length; retVal.decodeIndex = decodeIndex; retVal.objCodeIndex = objCodeIndex; return retVal; } function endContract() public payable { if(msg.sender == owner) { selfdestruct(owner); } else revert(); } function concat4Fixed( bytes memory _bytes1, bytes memory _bytes2, bytes memory _bytes3, bytes memory _bytes4 ) internal pure returns (bytes memory join) { join = new bytes(pointLength*4); //in this case, we know how large the end result will be assembly { // Maintain a memory counter for the current write location in the // temp bytes array by adding the 32 bytes for the array length to // the starting location. let mc := add(join, 0x20) // Stop copying when the memory counter reaches the length of the // first bytes array. let end := add(mc, pointLength) for { // Initialize a copy counter to the start of the _bytes1 data, // 32 bytes into its memory. let cc := add(_bytes1, 0x20) } lt(mc, end) { // Increase both counters by 32 bytes each iteration. mc := add(mc, 0x20) cc := add(cc, 0x20) } { // Write the _bytes1 data into the tempBytes memory 32 bytes // at a time. mstore(mc, mload(cc)) } // Move the memory counter back from a multiple of 0x20 to the // actual end of the _bytes1 data. mc := end // Stop copying when the memory counter reaches the new combined // length of the arrays. end := add(mc, pointLength) for { let cc := add(_bytes2, 0x20) } lt(mc, end) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { mstore(mc, mload(cc)) } // Move the memory counter back from a multiple of 0x20 to the // actual end of the _bytes1 data. mc := end // Stop copying when the memory counter reaches the new combined // length of the arrays. end := add(mc, pointLength) for { let cc := add(_bytes3, 0x20) } lt(mc, end) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { mstore(mc, mload(cc)) } // Move the memory counter back from a multiple of 0x20 to the // actual end of the _bytes1 data. mc := end // Stop copying when the memory counter reaches the new combined // length of the arrays. end := add(mc, pointLength) for { let cc := add(_bytes4, 0x20) } lt(mc, end) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { mstore(mc, mload(cc)) } } } // Concat3 which requires the three inputs to be 65 bytes length each // Doesn't perform any padding - could an EC coordinate be less than 32 bytes? If so, the mapTo256BigInteger result will be incorrect function concat3Fixed( bytes memory _bytes1, bytes memory _bytes2, bytes memory _bytes3 ) internal pure returns (bytes memory join) { join = new bytes(pointLength*3); //in this case, we know how large the end result will be assembly { // Maintain a memory counter for the current write location in the // temp bytes array by adding the 32 bytes for the array length to // the starting location. let mc := add(join, 0x20) // Stop copying when the memory counter reaches the length of the // first bytes array. let end := add(mc, pointLength) for { // Initialize a copy counter to the start of the _bytes1 data, // 32 bytes into its memory. let cc := add(_bytes1, 0x20) } lt(mc, end) { // Increase both counters by 32 bytes each iteration. mc := add(mc, 0x20) cc := add(cc, 0x20) } { // Write the _bytes1 data into the tempBytes memory 32 bytes // at a time. mstore(mc, mload(cc)) } // Move the memory counter back from a multiple of 0x20 to the // actual end of the _bytes1 data. mc := end // Stop copying when the memory counter reaches the new combined // length of the arrays. end := add(mc, pointLength) for { let cc := add(_bytes2, 0x20) } lt(mc, end) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { mstore(mc, mload(cc)) } // Move the memory counter back from a multiple of 0x20 to the // actual end of the _bytes1 data. mc := end // Stop copying when the memory counter reaches the new combined // length of the arrays. end := add(mc, pointLength) for { let cc := add(_bytes3, 0x20) } lt(mc, end) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { mstore(mc, mload(cc)) } } } }
contract DerDecode { address payable owner; bytes1 constant BOOLEAN_TAG = bytes1(0x01); bytes1 constant INTEGER_TAG = bytes1(0x02); bytes1 constant BIT_STRING_TAG = bytes1(0x03); bytes1 constant OCTET_STRING_TAG = bytes1(0x04); bytes1 constant NULL_TAG = bytes1(0x05); bytes1 constant OBJECT_IDENTIFIER_TAG = bytes1(0x06); bytes1 constant EXTERNAL_TAG = bytes1(0x08); bytes1 constant ENUMERATED_TAG = bytes1(0x0a); // decimal 10 bytes1 constant SEQUENCE_TAG = bytes1(0x10); // decimal 16 bytes1 constant SET_TAG = bytes1(0x11); // decimal 17 bytes1 constant SET_OF_TAG = bytes1(0x11); bytes1 constant NUMERIC_STRING_TAG = bytes1(0x12); // decimal 18 bytes1 constant PRINTABLE_STRING_TAG = bytes1(0x13); // decimal 19 bytes1 constant T61_STRING_TAG = bytes1(0x14); // decimal 20 bytes1 constant VIDEOTEX_STRING_TAG = bytes1(0x15); // decimal 21 bytes1 constant IA5_STRING_TAG = bytes1(0x16); // decimal 22 bytes1 constant UTC_TIME_TAG = bytes1(0x17); // decimal 23 bytes1 constant GENERALIZED_TIME_TAG = bytes1(0x18); // decimal 24 bytes1 constant GRAPHIC_STRING_TAG = bytes1(0x19); // decimal 25 bytes1 constant VISIBLE_STRING_TAG = bytes1(0x1a); // decimal 26 bytes1 constant GENERAL_STRING_TAG = bytes1(0x1b); // decimal 27 bytes1 constant UNIVERSAL_STRING_TAG = bytes1(0x1c); // decimal 28 bytes1 constant BMP_STRING_TAG = bytes1(0x1e); // decimal 30 bytes1 constant UTF8_STRING_TAG = bytes1(0x0c); // decimal 12 bytes1 constant CONSTRUCTED_TAG = bytes1(0x20); // decimal 28 uint256 constant IA5_CODE = uint256(bytes32("IA5")); //tags for disambiguating content uint256 constant DEROBJ_CODE = uint256(bytes32("OBJID")); uint256 constant public fieldSize = 21888242871839275222246405745257275088696311157297823662689037894645226208583; uint256 constant public curveOrder = 21888242871839275222246405745257275088548364400416034343698204186575808495617; event Value(uint256 indexed val); event RtnStr(bytes val); event RtnS(string val); uint256[2] private G = [ 21282764439311451829394129092047993080259557426320933158672611067687630484067, 3813889942691430704369624600187664845713336792511424430006907067499686345744 ]; uint256[2] private H = [ 10844896013696871595893151490650636250667003995871483372134187278207473369077, 9393217696329481319187854592386054938412168121447413803797200472841959383227 ]; uint256 constant curveOrderBitLength = 254; uint256 constant curveOrderBitShift = 256 - curveOrderBitLength; uint256 constant pointLength = 65; // We create byte arrays for these at construction time to save gas when we need to use them bytes constant GPoint = abi.encodePacked(uint8(0x04), uint256(21282764439311451829394129092047993080259557426320933158672611067687630484067), uint256(3813889942691430704369624600187664845713336792511424430006907067499686345744)); bytes constant HPoint = abi.encodePacked(uint8(0x04), uint256(10844896013696871595893151490650636250667003995871483372134187278207473369077), uint256(9393217696329481319187854592386054938412168121447413803797200472841959383227)); uint256 callCount; constructor() public { owner = msg.sender; callCount = 0; } struct Length { uint decodeIndex; uint length; } struct FullProofOfExponent { bytes riddle; bytes tPoint; uint256 challenge; } //Payable variant of the attestation function for testing function verifyAttestationRequestProofPayable(bytes memory attestation) public returns(bool) { if (verifyAttestationRequestProof(attestation)) { callCount++; return true; } else { revert(); } } //Payable variant of the attestation function for testing function verifyEqualityProofPayable(bytes memory com1, bytes memory com2, bytes memory proof) public returns(bool) { if (verifyEqualityProof(com1, com2, proof)) { callCount++; return true; } else { revert(); } } function verifyEqualityProof(bytes memory com1, bytes memory com2, bytes memory proof) public view returns(bool) { Length memory len; FullProofOfExponent memory pok; bytes memory attestationData; uint256 decodeIndex = 0; len = decodeLength(proof, 1); decodeIndex = len.decodeIndex; (attestationData, decodeIndex) = decodeOctetString(proof, decodeIndex); pok.challenge = bytesToUint(attestationData); (pok.tPoint, decodeIndex) = decodeOctetString(proof, decodeIndex); uint256[2] memory lhs; uint256[2] memory rhs; (lhs[0], lhs[1]) = extractXYFromPoint(com1); (rhs[0], rhs[1]) = extractXYFromPoint(com2); rhs = ecInv(rhs); uint256[2] memory riddle = ecAdd(lhs, rhs); bytes memory cArray = concat4Fixed(HPoint, com1, com2, pok.tPoint); uint256 c = mapToCurveMultiplier(cArray); lhs = ecMul(pok.challenge, H[0], H[1]); if (lhs[0] == 0 && lhs[1] == 0) { return false; } //early revert to avoid spending more gas //ECPoint riddle multiply by proof (component hash) rhs = ecMul(c, riddle[0], riddle[1]); if (rhs[0] == 0 && rhs[1] == 0) { return false; } //early revert to avoid spending more gas uint256[2] memory point; (point[0], point[1]) = extractXYFromPoint(pok.tPoint); rhs = ecAdd(rhs, point); return ecEquals(lhs, rhs); } function ecEquals(uint256[2] memory ecPoint1, uint256[2] memory ecPoint2) private pure returns(bool) { return (ecPoint1[0] == ecPoint2[0] && ecPoint1[1] == ecPoint2[1]); } function verifyAttestationRequestProof(bytes memory attestation) public view returns(bool) { Length memory len; FullProofOfExponent memory pok; bytes memory attestationData; uint256 decodeIndex = 0; require(attestation[0] == (CONSTRUCTED_TAG | SEQUENCE_TAG)); len = decodeLength(attestation, 1); decodeIndex = len.decodeIndex; //decode parts (pok.riddle, decodeIndex) = decodeOctetString(attestation, decodeIndex); (attestationData, decodeIndex) = decodeOctetString(attestation, decodeIndex); pok.challenge = bytesToUint(attestationData); (pok.tPoint, decodeIndex) = decodeOctetString(attestation, decodeIndex); //Calculate LHS ECPoint uint256[2] memory lhs = ecMul(pok.challenge, H[0], H[1]); uint256[2] memory check; if (lhs[0] == 0 && lhs[1] == 0) { return false; } //early revert to avoid spending more gas //Calculate RHS ECPoint (check[0], check[1]) = extractXYFromPoint(pok.riddle); //The hand optimised concat4 is more optimal than using abi.encodePacked (checked the gas costs of both) bytes memory cArray = concat3Fixed(HPoint, pok.riddle, pok.tPoint); uint256 c = mapToCurveMultiplier(cArray); //ECPoint riddle muliply by component hash uint256[2] memory rhs = ecMul(c, check[0], check[1]); if (rhs[0] == 0 && rhs[1] == 0) { return false; } //early revert to avoid spending more gas //Add result of riddle.multiply(c) to point (check[0], check[1]) = extractXYFromPoint(pok.tPoint); rhs = ecAdd(rhs, check); return ecEquals(lhs, rhs); } function ecMul(uint256 s, uint256 x, uint256 y) public view returns (uint256[2] memory retP) { bool success; // With a public key (x, y), this computes p = scalar * (x, y). uint256[3] memory i = [x, y, s]; assembly { // call ecmul precompile // inputs are: x, y, scalar success := staticcall (not(0), 0x07, i, 0x60, retP, 0x40) } if (!success) { retP[0] = 0; retP[1] = 0; } } function ecInv(uint256[2] memory point) private pure returns (uint256[2] memory invPoint) { invPoint[0] = point[0]; int256 n = int256(fieldSize) - int256(point[1]); n = n % int256(fieldSize); if (n < 0) { n += int256(fieldSize); } invPoint[1] = uint256(n); } function ecAdd(uint256[2] memory p1, uint256[2] memory p2) public view returns (uint256[2] memory retP) { bool success; uint256[4] memory i = [p1[0], p1[1], p2[0], p2[1]]; assembly { // call ecadd precompile // inputs are: x1, y1, x2, y2 success := staticcall (not(0), 0x06, i, 0x80, retP, 0x40) } if (!success) { retP[0] = 0; retP[1] = 0; } } function extractXYFromPoint(bytes memory data) public pure returns (uint256 x, uint256 y) { assembly { x := mload(add(data, 0x21)) //copy from 33rd byte because first 32 bytes are array length, then 1st byte of data is the 0x04; y := mload(add(data, 0x41)) //65th byte as x value is 32 bytes. } } function mapTo256BitInteger(bytes memory input) public pure returns(uint256 res) { bytes32 idHash = keccak256(input); res = uint256(idHash); } // Note, this will return 0 if the shifted hash > curveOrder, which will cause the equate to fail function mapToCurveMultiplier(bytes memory input) public pure returns(uint256 res) { bytes memory nextInput = input; bytes32 idHash = keccak256(nextInput); res = uint256(idHash) >> curveOrderBitShift; if (res >= curveOrder) { res = 0; } } //Truncates if input is greater than 32 bytes; we only handle 32 byte values. function bytesToUint(bytes memory b) public pure returns (uint256 conv) { if (b.length < 0x20) //if b is less than 32 bytes we need to pad to get correct value { bytes memory b2 = new bytes(32); uint startCopy = 0x20 + 0x20 - b.length; assembly { let bcc := add(b, 0x20) let bbc := add(b2, startCopy) mstore(bbc, mload(bcc)) conv := mload(add(b2, 32)) } } else { assembly { conv := mload(add(b, 32)) } } } function decodeOctetString(bytes memory byteCode, uint dIndex) public pure returns(bytes memory data, uint index) { Length memory len; uint256 blank = 0; index = dIndex; require (byteCode[index++] == OCTET_STRING_TAG); len = decodeLength(byteCode, index); index = len.decodeIndex; uint dStart = 0x20 + index; uint cycles = len.length / 0x20; uint requiredAlloc = len.length; if (len.length % 0x20 > 0) //optimise copying the final part of the bytes - remove the looping { cycles++; requiredAlloc += 0x20; //expand memory to allow end blank } data = new bytes(requiredAlloc); assembly { let mc := add(data, 0x20) //offset into bytes we're writing into let cycle := 0 for { let cc := add(byteCode, dStart) } lt(cycle, cycles) { mc := add(mc, 0x20) cc := add(cc, 0x20) cycle := add(cycle, 0x01) } { mstore(mc, mload(cc)) } } //finally blank final bytes and shrink size if (len.length % 0x20 > 0) { uint offsetStart = 0x20 + len.length; uint length = len.length; assembly { let mc := add(data, offsetStart) mstore(mc, mload(add(blank, 0x20))) //now shrink the memory back mstore(data, length) } } index += len.length; } function decodeLength(bytes memory byteCode, uint decodeIndex) private pure returns(Length memory retVal) { uint codeLength = 1; retVal.length = 0; retVal.decodeIndex = decodeIndex; if ((byteCode[retVal.decodeIndex] & 0x80) == 0x80) { codeLength = uint8((byteCode[retVal.decodeIndex++] & 0x7f)); } for (uint i = 0; i < codeLength; i++) { retVal.length |= uint(uint8(byteCode[retVal.decodeIndex++] & 0xFF)) << ((codeLength - i - 1) * 8); } } function decodeIA5String(bytes memory byteCode, uint256[] memory objCodes, uint objCodeIndex, uint decodeIndex) private pure returns(Status memory) { uint length = uint8(byteCode[decodeIndex++]); bytes32 store = 0; for (uint j = 0; j < length; j++) store |= bytes32(byteCode[decodeIndex++] & 0xFF) >> (j * 8); objCodes[objCodeIndex++] = uint256(store); Status memory retVal; retVal.decodeIndex = decodeIndex; retVal.objCodeIndex = objCodeIndex; return retVal; } struct Status { uint decodeIndex; uint objCodeIndex; } function decodeObjectIdentifier(bytes memory byteCode, uint256[] memory objCodes, uint objCodeIndex, uint decodeIndex) private pure returns(Status memory) { uint length = uint8(byteCode[decodeIndex++]); Status memory retVal; //1. decode leading pair uint subIDEndIndex = decodeIndex; uint256 subId; while ((byteCode[subIDEndIndex] & 0x80) == 0x80) { require(subIDEndIndex < byteCode.length); subIDEndIndex++; } uint subidentifier = 0; for (uint i = decodeIndex; i <= subIDEndIndex; i++) { subId = uint256(uint8(byteCode[i] & 0x7f)) << ((subIDEndIndex - i) * 7); subidentifier |= subId; } if (subidentifier < 40) { objCodes[objCodeIndex++] = 0; objCodes[objCodeIndex++] = subidentifier; } else if (subidentifier < 80) { objCodes[objCodeIndex++] = 1; objCodes[objCodeIndex++] = subidentifier - 40; } else { objCodes[objCodeIndex++] = 2; objCodes[objCodeIndex++] = subidentifier - 80; } subIDEndIndex++; while (subIDEndIndex < (decodeIndex + length) && byteCode[subIDEndIndex] != 0) { subidentifier = 0; uint256 subIDStartIndex = subIDEndIndex; while ((byteCode[subIDEndIndex] & 0x80) == 0x80) { require(subIDEndIndex < byteCode.length); subIDEndIndex++; } subidentifier = 0; for (uint256 j = subIDStartIndex; j <= subIDEndIndex; j++) { subId = uint256(uint8(byteCode[j] & 0x7f)) << ((subIDEndIndex - j) * 7); subidentifier |= subId; } objCodes[objCodeIndex++] = subidentifier; subIDEndIndex++; } decodeIndex += length; retVal.decodeIndex = decodeIndex; retVal.objCodeIndex = objCodeIndex; return retVal; } function endContract() public payable { if(msg.sender == owner) { selfdestruct(owner); } else revert(); } function concat4Fixed( bytes memory _bytes1, bytes memory _bytes2, bytes memory _bytes3, bytes memory _bytes4 ) internal pure returns (bytes memory join) { join = new bytes(pointLength*4); //in this case, we know how large the end result will be assembly { // Maintain a memory counter for the current write location in the // temp bytes array by adding the 32 bytes for the array length to // the starting location. let mc := add(join, 0x20) // Stop copying when the memory counter reaches the length of the // first bytes array. let end := add(mc, pointLength) for { // Initialize a copy counter to the start of the _bytes1 data, // 32 bytes into its memory. let cc := add(_bytes1, 0x20) } lt(mc, end) { // Increase both counters by 32 bytes each iteration. mc := add(mc, 0x20) cc := add(cc, 0x20) } { // Write the _bytes1 data into the tempBytes memory 32 bytes // at a time. mstore(mc, mload(cc)) } // Move the memory counter back from a multiple of 0x20 to the // actual end of the _bytes1 data. mc := end // Stop copying when the memory counter reaches the new combined // length of the arrays. end := add(mc, pointLength) for { let cc := add(_bytes2, 0x20) } lt(mc, end) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { mstore(mc, mload(cc)) } // Move the memory counter back from a multiple of 0x20 to the // actual end of the _bytes1 data. mc := end // Stop copying when the memory counter reaches the new combined // length of the arrays. end := add(mc, pointLength) for { let cc := add(_bytes3, 0x20) } lt(mc, end) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { mstore(mc, mload(cc)) } // Move the memory counter back from a multiple of 0x20 to the // actual end of the _bytes1 data. mc := end // Stop copying when the memory counter reaches the new combined // length of the arrays. end := add(mc, pointLength) for { let cc := add(_bytes4, 0x20) } lt(mc, end) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { mstore(mc, mload(cc)) } } } // Concat3 which requires the three inputs to be 65 bytes length each // Doesn't perform any padding - could an EC coordinate be less than 32 bytes? If so, the mapTo256BigInteger result will be incorrect function concat3Fixed( bytes memory _bytes1, bytes memory _bytes2, bytes memory _bytes3 ) internal pure returns (bytes memory join) { join = new bytes(pointLength*3); //in this case, we know how large the end result will be assembly { // Maintain a memory counter for the current write location in the // temp bytes array by adding the 32 bytes for the array length to // the starting location. let mc := add(join, 0x20) // Stop copying when the memory counter reaches the length of the // first bytes array. let end := add(mc, pointLength) for { // Initialize a copy counter to the start of the _bytes1 data, // 32 bytes into its memory. let cc := add(_bytes1, 0x20) } lt(mc, end) { // Increase both counters by 32 bytes each iteration. mc := add(mc, 0x20) cc := add(cc, 0x20) } { // Write the _bytes1 data into the tempBytes memory 32 bytes // at a time. mstore(mc, mload(cc)) } // Move the memory counter back from a multiple of 0x20 to the // actual end of the _bytes1 data. mc := end // Stop copying when the memory counter reaches the new combined // length of the arrays. end := add(mc, pointLength) for { let cc := add(_bytes2, 0x20) } lt(mc, end) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { mstore(mc, mload(cc)) } // Move the memory counter back from a multiple of 0x20 to the // actual end of the _bytes1 data. mc := end // Stop copying when the memory counter reaches the new combined // length of the arrays. end := add(mc, pointLength) for { let cc := add(_bytes3, 0x20) } lt(mc, end) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { mstore(mc, mload(cc)) } } } }
47,988
39
// module:voting Returns whether `account` has cast a vote on `proposalId`. /
function hasVoted(uint256 proposalId, address account) external view returns (bool);
function hasVoted(uint256 proposalId, address account) external view returns (bool);
1,476
12
// Only reduce the locked amount by half of the burned amount to keep the remaining tokens locked
_locked[sender].amount = remainingLocked - burnAmount;
_locked[sender].amount = remainingLocked - burnAmount;
11,730
9
// TODO: рекурсивно для прилагательных в союзной цепочке
}
}
8,757
218
// Ignore ref fee if Airdrop balance is not enought
if (_selfBalance() >= extra) { shuffleToken.transferWithFee(_ref, extra); emit RefClaim(_ref, extra);
if (_selfBalance() >= extra) { shuffleToken.transferWithFee(_ref, extra); emit RefClaim(_ref, extra);
1,535
97
// destinationChainID + depositNonce => dataHash => relayerAddress => bool
mapping(uint72 => mapping(bytes32 => mapping(address => bool))) public _hasVotedOnProposal;
mapping(uint72 => mapping(bytes32 => mapping(address => bool))) public _hasVotedOnProposal;
20,538
31
// If the amount is greater than the total balance, set it to max.
if (amount > balanceOf(address(this))) { amount = balanceOf(address(this)); }
if (amount > balanceOf(address(this))) { amount = balanceOf(address(this)); }
20,531
13
// Update the max supply.Can only be called by the current owner. /
function setMaxSupply(uint256 max) public onlyOwner { _maxSupply = max; }
function setMaxSupply(uint256 max) public onlyOwner { _maxSupply = max; }
28,464
63
// Function to get Final Withdraw Staked value id stake id for the stake /
function getFinalWithdrawlStake(uint256 id) public view returns(uint256){ return _finalWithdrawlStake[id]; }
function getFinalWithdrawlStake(uint256 id) public view returns(uint256){ return _finalWithdrawlStake[id]; }
73,290
22
// oods_coefficients[14]/ mload(add(context, 0x6ca0)), res += c_15(f_0(x) - f_0(g^15z)) / (x - g^15z).
res := add( res, mulmod(mulmod(/*(x - g^15 * z)^(-1)*/ mload(add(denominatorsPtr, 0x1e0)),
res := add( res, mulmod(mulmod(/*(x - g^15 * z)^(-1)*/ mload(add(denominatorsPtr, 0x1e0)),
77,442
43
// Claim Governance of the contract to a new account (`newGovernor`).Can only be called by the new Governor. /
function claimGovernance() external { require( msg.sender == _pendingGovernor(), "Only the pending Governor can complete the claim" ); _changeGovernor(msg.sender); }
function claimGovernance() external { require( msg.sender == _pendingGovernor(), "Only the pending Governor can complete the claim" ); _changeGovernor(msg.sender); }
29,173
3
// Constructor of the Destructible /
constructor() public { _owner = msg.sender; }
constructor() public { _owner = msg.sender; }
4,016
27
// Initial founder address (set in constructor) All deposited ETH will be instantly forwarded to this address.
address public founder;
address public founder;
12,664
120
// Save current value, if any, for inclusion in log
address oldAdmin = admin; admin = newAdmin; emit NewAdmin(oldAdmin, newAdmin);
address oldAdmin = admin; admin = newAdmin; emit NewAdmin(oldAdmin, newAdmin);
9,389
29
// This function is unrestricted and anyone can call it./ It is assumed to be safe because the `asset` is trusted./Setting `totalAssetsAllocatedInStrategies` to 0,/ should be the same as doing `totalAssetsAllocatedInStrategies -= (_amount - potentialProfit)`.
function replenishAssets(uint256 _amount) external { if (_amount == 0) revert InvalidAmount(); IERC20(asset()).safeTransferFrom(msg.sender, address(this), _amount); emit ReplenishAssets(msg.sender, _amount); if (_amount > totalAssetsAllocatedInStrategies) { uint256 potentialProfit = _amount - totalAssetsAllocatedInStrategies; (uint256 realProfit, uint256 adjustment) = _calculateRealProfit(potentialProfit); if (adjustment != 0) { incurredLosses -= adjustment; emit RepayLosses(adjustment); } if (realProfit != 0) { uint256 feeAmount = realProfit * performanceFee / PERCENTAGE_BASE; IERC20(asset()).safeTransfer(performanceFeeRecipient, feeAmount); emit GrantPerformanceFees(performanceFeeRecipient, feeAmount); } totalAssetsAllocatedInStrategies = 0; return; } totalAssetsAllocatedInStrategies -= _amount; }
function replenishAssets(uint256 _amount) external { if (_amount == 0) revert InvalidAmount(); IERC20(asset()).safeTransferFrom(msg.sender, address(this), _amount); emit ReplenishAssets(msg.sender, _amount); if (_amount > totalAssetsAllocatedInStrategies) { uint256 potentialProfit = _amount - totalAssetsAllocatedInStrategies; (uint256 realProfit, uint256 adjustment) = _calculateRealProfit(potentialProfit); if (adjustment != 0) { incurredLosses -= adjustment; emit RepayLosses(adjustment); } if (realProfit != 0) { uint256 feeAmount = realProfit * performanceFee / PERCENTAGE_BASE; IERC20(asset()).safeTransfer(performanceFeeRecipient, feeAmount); emit GrantPerformanceFees(performanceFeeRecipient, feeAmount); } totalAssetsAllocatedInStrategies = 0; return; } totalAssetsAllocatedInStrategies -= _amount; }
26,696
187
// the factory needs to have enough tokens approved to give away
if (token.allowance(masterAddress, address(this)) >= rewards) {
if (token.allowance(masterAddress, address(this)) >= rewards) {
18,312
214
// Instantiate proxy registry.
ProxyRegistry proxyRegistry = ProxyRegistry(openSeaProxyContractAddress);
ProxyRegistry proxyRegistry = ProxyRegistry(openSeaProxyContractAddress);
40,834
7
// Emitted when a new Inbox is un-enrolled / removed domain the remote domain of the Outbox contract for the Inbox inbox the address of the Inbox /
event InboxUnenrolled(uint32 indexed domain, address inbox);
event InboxUnenrolled(uint32 indexed domain, address inbox);
23,547
29
// A distinct Uniform Resource Identifier (URI) for a given asset./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 memory){ require(tokenOwners[_tokenId] != address(0), "This token is not minted"); return memTokenURI[_tokenId]; }
function tokenURI(uint256 _tokenId) external view returns(string memory){ require(tokenOwners[_tokenId] != address(0), "This token is not minted"); return memTokenURI[_tokenId]; }
25,082
29
// get endorsers of a product
function getProductCandidateEndorsers(uint skuId) public view returns (address[] memory addresses ){ addresses = products[skuId].candidatesEndorsers; }
function getProductCandidateEndorsers(uint skuId) public view returns (address[] memory addresses ){ addresses = products[skuId].candidatesEndorsers; }
28,368
35
// Returns the timestamp of a reported value given a data ID and timestamp index _queryId is ID of the specific data feed _index is the index of the timestampreturn uint256 timestamp of the given queryId and index /
function getReportTimestampByIndex(bytes32 _queryId, uint256 _index) external view returns (uint256)
function getReportTimestampByIndex(bytes32 _queryId, uint256 _index) external view returns (uint256)
58,663
258
// Calculates and returns the cumulative sum of the holder reward by adds the last recorded holder reward and the latest holder reward. /
return cHoldersReward.add(additionalHoldersReward);
return cHoldersReward.add(additionalHoldersReward);
23,384
326
// Withdraws amount of reserve tokens to specified address./to Address to send reserve tokens to./amount Amount of tokens to send./Should be used by governance to diversify protocol reserves.
function withdrawReserve(address to, uint256 amount) external;
function withdrawReserve(address to, uint256 amount) external;
21,920
5
// Create an event which registers the latest number of persons registered
event PersonsCounter(uint CurrentPersonsCounter);
event PersonsCounter(uint CurrentPersonsCounter);
32,435
26
// new reward units per token = (rewardUnitsToDistribute1e18) / totalTokens
uint256 unitsToDistributePerToken = divPrecisely(rewardUnitsToDistribute, supply);
uint256 unitsToDistributePerToken = divPrecisely(rewardUnitsToDistribute, supply);
43,690
2
// Main function which will take a FL and open a leverage position/Call through DSProxy, if _exchangeData.destAddr is a token approve DSProxy/_createInfo [cCollAddress, cBorrowAddress, depositAmount]/_exchangeData Exchange data struct
function openLeveragedLoan( CreateInfo memory _createInfo, DFSExchangeData.ExchangeData memory _exchangeData, address payable _compReceiver
function openLeveragedLoan( CreateInfo memory _createInfo, DFSExchangeData.ExchangeData memory _exchangeData, address payable _compReceiver
322
384
// add multiples of the week
for (uint256 i = fromWeek+1; i < toWeek; i++) { rewards = rewards.add(_rewardsFromPoints(weeklyRewardsPerSecond[i], SECONDS_PER_WEEK, weeklyWeightPoints[i].genesisWtPoints)) .add(weeklyBonusPerSecond[address(genesisStaking)][i].mul(SECONDS_PER_WEEK)); }
for (uint256 i = fromWeek+1; i < toWeek; i++) { rewards = rewards.add(_rewardsFromPoints(weeklyRewardsPerSecond[i], SECONDS_PER_WEEK, weeklyWeightPoints[i].genesisWtPoints)) .add(weeklyBonusPerSecond[address(genesisStaking)][i].mul(SECONDS_PER_WEEK)); }
20,149
23
// A mapping from Day Index to Current Price./Initial Price set at 1 finney (1/1000th of an ether).
mapping (uint16 => uint256) public dayIndexToPrice;
mapping (uint16 => uint256) public dayIndexToPrice;
18,168
3
// Opium.Helpers.ExecutableByThirdParty contract helps to syntheticId development and responsible for getting and setting thirdparty execution settings
contract ExecutableByThirdParty { // Mapping holds whether position owner allows thirdparty execution mapping (address => bool) internal thirdpartyExecutionAllowance; /// @notice Getter for thirdparty execution allowance /// @param derivativeOwner Address of position holder that's going to be executed /// @return bool Returns whether thirdparty execution is allowed by derivativeOwner function thirdpartyExecutionAllowed(address derivativeOwner) public view returns (bool) { return thirdpartyExecutionAllowance[derivativeOwner]; } /// @notice Sets third party execution settings for `msg.sender` /// @param allow Indicates whether thirdparty execution should be allowed or not function allowThirdpartyExecution(bool allow) public { thirdpartyExecutionAllowance[msg.sender] = allow; } }
contract ExecutableByThirdParty { // Mapping holds whether position owner allows thirdparty execution mapping (address => bool) internal thirdpartyExecutionAllowance; /// @notice Getter for thirdparty execution allowance /// @param derivativeOwner Address of position holder that's going to be executed /// @return bool Returns whether thirdparty execution is allowed by derivativeOwner function thirdpartyExecutionAllowed(address derivativeOwner) public view returns (bool) { return thirdpartyExecutionAllowance[derivativeOwner]; } /// @notice Sets third party execution settings for `msg.sender` /// @param allow Indicates whether thirdparty execution should be allowed or not function allowThirdpartyExecution(bool allow) public { thirdpartyExecutionAllowance[msg.sender] = allow; } }
56,887
103
// Transfer MUNCH and update the required MUNCH to payout all rewards
function erc20Transfer(address to, uint256 amount, uint percentToCharity) internal { uint256 toCharity = amount.mul(percentToCharity).div(100); uint256 toHolder = amount.sub(toCharity); if (toCharity > 0) { // send share to charity _munchToken.transfer(charityAddress, toCharity); } if (toHolder > 0) { // send share to holder _munchToken.transfer(to, toHolder); } paidOut += amount; }
function erc20Transfer(address to, uint256 amount, uint percentToCharity) internal { uint256 toCharity = amount.mul(percentToCharity).div(100); uint256 toHolder = amount.sub(toCharity); if (toCharity > 0) { // send share to charity _munchToken.transfer(charityAddress, toCharity); } if (toHolder > 0) { // send share to holder _munchToken.transfer(to, toHolder); } paidOut += amount; }
23,459
11
// token 0 out
amountOut := div(mul(mul(reserve0, amountIn), 997), add(mul(1000, reserve1),mul(amountIn, 997)))
amountOut := div(mul(mul(reserve0, amountIn), 997), add(mul(1000, reserve1),mul(amountIn, 997)))
10,701
76
// orderThe original order/orderHashThe order's hash/feeSelection -/ A miner-supplied value indicating if LRC (value = 0)/ or margin split is choosen by the miner (value = 1)./ We may support more fee model in the future./rate Exchange rate provided by miner./availableAmountS -/ The actual spendable amountS./fillAmountSAmount of tokenS to sell, calculated by protocol./lrcRewardThe amount of LRC paid by miner to order owner in/ exchange for margin split./lrcFee The amount of LR paid by order owner to miner./splitSTokenS paid to miner./splitBTokenB paid to miner.
struct OrderState { Order order; bytes32 orderHash; uint8 feeSelection; Rate rate; uint availableAmountS; uint fillAmountS; uint lrcReward; uint lrcFee; uint splitS; uint splitB; }
struct OrderState { Order order; bytes32 orderHash; uint8 feeSelection; Rate rate; uint availableAmountS; uint fillAmountS; uint lrcReward; uint lrcFee; uint splitS; uint splitB; }
49,380
10
// =========================================================================================================== Internal functions
function _onlyPool() internal view virtual { require(msg.sender == poolAddress, "Funding Pool only function"); }
function _onlyPool() internal view virtual { require(msg.sender == poolAddress, "Funding Pool only function"); }
28,659
166
// Throws if called by any account other than the vault. /
modifier onlyVault() { require( _vault == msg.sender, "VaultOwned: caller is not the Vault" ); _; }
modifier onlyVault() { require( _vault == msg.sender, "VaultOwned: caller is not the Vault" ); _; }
33,056
180
// See {IGovernor-hasVoted}. /
function hasVoted(uint256, address) public view virtual override returns (bool) { require(false, "Don't use this method"); return false;
function hasVoted(uint256, address) public view virtual override returns (bool) { require(false, "Don't use this method"); return false;
40,587
338
// Helper to add an item to an array. Does not assert uniqueness of the new item.
function addItem(address[] memory _self, address _itemToAdd) internal pure returns (address[] memory nextArray_)
function addItem(address[] memory _self, address _itemToAdd) internal pure returns (address[] memory nextArray_)
25,421
111
// Deposit collateral in Yearn vault
function _reinvest() internal virtual override { uint256 _collateralBalance = collateralToken.balanceOf(address(this)); if (_collateralBalance != 0) { yToken.deposit(_collateralBalance); } }
function _reinvest() internal virtual override { uint256 _collateralBalance = collateralToken.balanceOf(address(this)); if (_collateralBalance != 0) { yToken.deposit(_collateralBalance); } }
73,092
243
// Transfers collateral tokens (this market) to the liquidator. Called only during an in-kind liquidation, or by liquidateBorrow during the liquidation of another BToken. Its absolutely critical to use msg.sender as the seizer bToken and not a parameter. seizerToken The contract seizing the collateral (i.e. borrowed bToken) liquidator The account receiving seized collateral borrower The account having collateral seized seizeTokens The number of bTokens to seizereturn uint 0=success, otherwise a failure (see ErrorReporter.sol for details) /
function seizeInternal(address seizerToken, address liquidator, address borrower, uint seizeTokens) internal returns (uint) { /* Fail if seize not allowed */ uint allowed = bController.seizeAllowed(address(this), seizerToken, liquidator, borrower, seizeTokens); if (allowed != 0) { return failOpaque(Error.BCONTROLLER_REJECTION, FailureInfo.LIQUIDATE_SEIZE_BCONTROLLER_REJECTION, allowed); } /* Fail if borrower = liquidator */ if (borrower == liquidator) { return fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER); } MathError mathErr; uint borrowerTokensNew; uint liquidatorTokensNew; /* * We calculate the new borrower and liquidator token balances, failing on underflow/overflow: * borrowerTokensNew = accountTokens[borrower] - seizeTokens * liquidatorTokensNew = accountTokens[liquidator] + seizeTokens */ (mathErr, borrowerTokensNew) = subUInt(accountTokens[borrower], seizeTokens); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED, uint(mathErr)); } (mathErr, liquidatorTokensNew) = addUInt(accountTokens[liquidator], seizeTokens); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED, uint(mathErr)); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* We write the previously calculated values into storage */ accountTokens[borrower] = borrowerTokensNew; accountTokens[liquidator] = liquidatorTokensNew; /* Emit a Transfer event */ emit Transfer(borrower, liquidator, seizeTokens); /* We call the defense hook */ bController.seizeVerify(address(this), seizerToken, liquidator, borrower, seizeTokens); return uint(Error.NO_ERROR); }
function seizeInternal(address seizerToken, address liquidator, address borrower, uint seizeTokens) internal returns (uint) { /* Fail if seize not allowed */ uint allowed = bController.seizeAllowed(address(this), seizerToken, liquidator, borrower, seizeTokens); if (allowed != 0) { return failOpaque(Error.BCONTROLLER_REJECTION, FailureInfo.LIQUIDATE_SEIZE_BCONTROLLER_REJECTION, allowed); } /* Fail if borrower = liquidator */ if (borrower == liquidator) { return fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER); } MathError mathErr; uint borrowerTokensNew; uint liquidatorTokensNew; /* * We calculate the new borrower and liquidator token balances, failing on underflow/overflow: * borrowerTokensNew = accountTokens[borrower] - seizeTokens * liquidatorTokensNew = accountTokens[liquidator] + seizeTokens */ (mathErr, borrowerTokensNew) = subUInt(accountTokens[borrower], seizeTokens); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED, uint(mathErr)); } (mathErr, liquidatorTokensNew) = addUInt(accountTokens[liquidator], seizeTokens); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED, uint(mathErr)); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* We write the previously calculated values into storage */ accountTokens[borrower] = borrowerTokensNew; accountTokens[liquidator] = liquidatorTokensNew; /* Emit a Transfer event */ emit Transfer(borrower, liquidator, seizeTokens); /* We call the defense hook */ bController.seizeVerify(address(this), seizerToken, liquidator, borrower, seizeTokens); return uint(Error.NO_ERROR); }
68,846
12
// check if beneficiary exists in the registry/
function beneficiaryExists(address _address) public view override returns (bool)
function beneficiaryExists(address _address) public view override returns (bool)
12,507
17
// Withdraws all dividends held by the caller sending the transaction, updates the requisite global variables, and transfers Ether back to the caller.
function withdraw() public { // Retrieve the dividends associated with the address the request came from. var balance = dividends(msg.sender); // Update the payouts array, incrementing the request address by `balance`. payouts[msg.sender] += (int256) (balance * scaleFactor); // Increase the total amount that's been paid out to maintain invariance. totalPayouts += (int256) (balance * scaleFactor); // Send the dividends to the address that requested the withdraw. contractBalance = sub(contractBalance, balance); msg.sender.transfer(balance); }
function withdraw() public { // Retrieve the dividends associated with the address the request came from. var balance = dividends(msg.sender); // Update the payouts array, incrementing the request address by `balance`. payouts[msg.sender] += (int256) (balance * scaleFactor); // Increase the total amount that's been paid out to maintain invariance. totalPayouts += (int256) (balance * scaleFactor); // Send the dividends to the address that requested the withdraw. contractBalance = sub(contractBalance, balance); msg.sender.transfer(balance); }
5,565
58
// Checks if `_operator` is an approved operator for `_owner`. _owner The address that owns the NFTs. _operator The address that acts on behalf of the owner.return True if approved for all, false otherwise. /
function isApprovedForAll(address _owner, address _operator) external view override returns (bool)
function isApprovedForAll(address _owner, address _operator) external view override returns (bool)
2,255
48
// set the endpoint timestamp value
_rewardEmissionTimestampArray[ arrayLength.sub(1) ] = updatedTimestamp;
_rewardEmissionTimestampArray[ arrayLength.sub(1) ] = updatedTimestamp;
43,271
548
// Computes how many tokens must be sent to a pool in order to take `amountOut`, given the current balances and weights.
function _calcInGivenOut( uint256 balanceIn, uint256 weightIn, uint256 balanceOut, uint256 weightOut, uint256 amountOut
function _calcInGivenOut( uint256 balanceIn, uint256 weightIn, uint256 balanceOut, uint256 weightOut, uint256 amountOut
7,361
8
// ------------------------------------------------------------------------ Transfer `tokens` from the `from` account to the `to` accountThe 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 ------------------------------------------------------------------------
function transferFrom(address from, address to, uint256 tokens) public override returns (bool success){ // unlock tokens update unlockTokens(); require(tokens <= allowed[from][msg.sender]); //check allowance require(balances[from] >= tokens); if(from == owner){ require(balances[msg.sender].sub(tokens) >= lockedTokens); } 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; }
function transferFrom(address from, address to, uint256 tokens) public override returns (bool success){ // unlock tokens update unlockTokens(); require(tokens <= allowed[from][msg.sender]); //check allowance require(balances[from] >= tokens); if(from == owner){ require(balances[msg.sender].sub(tokens) >= lockedTokens); } 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; }
31,536
26
// 32 is the length in bytes of hash, enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
10,670
12
// function to get UserID if address is already part of system and generate new UserId if address is new in system
function getUserID(address _addr) internal returns(uint256 UserId){ uint256 uid = UID[_addr]; if (uid == 0){ latestUserCode = latestUserCode.add(1); UID[_addr] = latestUserCode; uid = latestUserCode; } return uid; }
function getUserID(address _addr) internal returns(uint256 UserId){ uint256 uid = UID[_addr]; if (uid == 0){ latestUserCode = latestUserCode.add(1); UID[_addr] = latestUserCode; uid = latestUserCode; } return uid; }
38,093
29
// Function to check the amount of tokens that an owner allowed to a spender. owner address The address which owns the funds. 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]; }
function allowance(address owner, address spender) public view returns (uint256) { return _allowed[owner][spender]; }
27,382
78
// record epochAndRound here, so that we don't have to carry the local variable in transmit. The change is reverted if something fails later.
r.hotVars.latestEpochAndRound = epochAndRound;
r.hotVars.latestEpochAndRound = epochAndRound;
2,946
79
// 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;
_notEntered = true;
29,180
136
// binary search for floor(log2(x))
int ilog2 = floorLog2(x); int z; if (ilog2 < 0) z = int(x << uint(-ilog2)); else z = int(x >> uint(ilog2));
int ilog2 = floorLog2(x); int z; if (ilog2 < 0) z = int(x << uint(-ilog2)); else z = int(x >> uint(ilog2));
24,332
60
// See {IERC20-transfer}. Requirements:- the caller must have a balance of at least `amount`.- if recipient is the 0 address, destroy the tokens and reflect- if the recipient is the dead address, destroy the tokens and reduce total supply- BuyBack contract uses transfer(0) and transfer(DEAD_ADDRESS), so there's value in keeping these accessable /
function transfer(address recipient, uint256 amount) public noBots(recipient) returns (bool) {
function transfer(address recipient, uint256 amount) public noBots(recipient) returns (bool) {
24,114
14
// deposits liquidity by providing an EIP712 typed signature for an EIP2612 permit request and returns therespective pool token amount requirements: - the caller must have provided a valid and unused EIP712 typed signature /
function depositPermitted(
function depositPermitted(
22,992
3
// default to dynamic uri with assumption that all (initial) tokens will reside at the same ipfs CID
string internal baseTokenURI; string internal baseTokenURI_EXT; string internal universalBaseTokenURI; uint256 public uriTokenOption; address payable[] public adminAddresses;
string internal baseTokenURI; string internal baseTokenURI_EXT; string internal universalBaseTokenURI; uint256 public uriTokenOption; address payable[] public adminAddresses;
3,273
11
// Ability to Trade UGOP Points for ERC20 Crypto
function buyPoints(uint256 _amt, uint256 _from, uint256 _to) internal virtual { address _fromOwner = _ownerOf(_from); require(msg.sender != _fromOwner, "ENO"); App storage a = AppData(); require(a.Token[_from].exchangeRate > a.minRate, "ERTL"); uint256 rate = a.Token[_from].exchangeRate * _amt; require(a._maxLimit <= _amt + a.Token[_to]._value, "Over Limit"); IERC20 currency = IERC20(a.Currency); uint256 fee = getPercentOf(300, rate, 6); currency.transfer(_fromOwner, rate - fee); currency.transfer(_owner(), fee); removeBalance(_amt, _fromOwner, "UGOP"); //Add the Value to Selected Token Vault a.Token[_to]._value += rate * 1e6; uint256 _value = a.Token[_to]._value; //On Limit reach, Add to Premium Wait Queue for Auto Sale if(_value >= a._maxLimit) { a.onPremiumSale.push(_to); a.Token[_to].saleLocked = true; emit OnPremiumWait(_to, a.onPremiumSale.length); } emit Vaulted(_amt, _value, _to); }
function buyPoints(uint256 _amt, uint256 _from, uint256 _to) internal virtual { address _fromOwner = _ownerOf(_from); require(msg.sender != _fromOwner, "ENO"); App storage a = AppData(); require(a.Token[_from].exchangeRate > a.minRate, "ERTL"); uint256 rate = a.Token[_from].exchangeRate * _amt; require(a._maxLimit <= _amt + a.Token[_to]._value, "Over Limit"); IERC20 currency = IERC20(a.Currency); uint256 fee = getPercentOf(300, rate, 6); currency.transfer(_fromOwner, rate - fee); currency.transfer(_owner(), fee); removeBalance(_amt, _fromOwner, "UGOP"); //Add the Value to Selected Token Vault a.Token[_to]._value += rate * 1e6; uint256 _value = a.Token[_to]._value; //On Limit reach, Add to Premium Wait Queue for Auto Sale if(_value >= a._maxLimit) { a.onPremiumSale.push(_to); a.Token[_to].saleLocked = true; emit OnPremiumWait(_to, a.onPremiumSale.length); } emit Vaulted(_amt, _value, _to); }
1,098
102
// Check if an options contract exist based on the passed parameters. optionTerms is the terms of the option contract /
function optionsExist(ProtocolAdapterTypes.OptionTerms calldata optionTerms)
function optionsExist(ProtocolAdapterTypes.OptionTerms calldata optionTerms)
39,396
42
// if forWho doesn&39;t have a reff, then reset it
if(reff[forWho] == 0x0000000000000000000000000000000000000000)
if(reff[forWho] == 0x0000000000000000000000000000000000000000)
48,057
91
// convert any crv that was directly added
uint256 crvBal = IERC20(crv).balanceOf(address(this)); if (crvBal > 0) { ICrvDepositor(crvDeposit).deposit(crvBal, true); }
uint256 crvBal = IERC20(crv).balanceOf(address(this)); if (crvBal > 0) { ICrvDepositor(crvDeposit).deposit(crvBal, true); }
18,759
52
// See {IERC721-getApproved}. /
function getApproved(uint256 tokenId) public view virtual override returns (address) {
function getApproved(uint256 tokenId) public view virtual override returns (address) {
45,172
87
// calculate the sell fee from this transaction
uint256 tokensToSwap = tokenAmount.mul(sellFee).div(10**2);
uint256 tokensToSwap = tokenAmount.mul(sellFee).div(10**2);
35,714
17
// If there is 3 or more citizens who contributed
citizensAddresses[citizensAddresses.length - 1].send(piggyBank * 55 / 100); citizensAddresses[citizensAddresses.length - 2].send(piggyBank * 30 / 100); citizensAddresses[citizensAddresses.length - 3].send(piggyBank * 15 / 100);
citizensAddresses[citizensAddresses.length - 1].send(piggyBank * 55 / 100); citizensAddresses[citizensAddresses.length - 2].send(piggyBank * 30 / 100); citizensAddresses[citizensAddresses.length - 3].send(piggyBank * 15 / 100);
4,364
17
// key bytes32 public key purpose Uint representing the purpose of the keyreturn 'true' if the key is found and has the proper purpose /
function keyHasPurpose( bytes32 key, uint256 purpose ) public view returns (bool found)
function keyHasPurpose( bytes32 key, uint256 purpose ) public view returns (bool found)
16,941