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 |
|---|---|---|---|---|
23 | // Update game information | games[gameIndex].gameTotalBacklog -= valueAfterTax;
games[gameIndex].gameTotalPaidOut += valueAfterTax;
| games[gameIndex].gameTotalBacklog -= valueAfterTax;
games[gameIndex].gameTotalPaidOut += valueAfterTax;
| 56,809 |
3 | // Emitted when the implementation is finalized. | event FinalizedImplementation(address indexed implementation);
using Addresses for address;
string public constant PROXY_VERSION = "3.0.1";
| event FinalizedImplementation(address indexed implementation);
using Addresses for address;
string public constant PROXY_VERSION = "3.0.1";
| 47,103 |
527 | // update collateral reserve | reserves[_collateralReserve].updateCumulativeIndexes();
| reserves[_collateralReserve].updateCumulativeIndexes();
| 35,112 |
355 | // structure RLP data as <offset> <length> <bytes> | mstore(ptr, 0x20)
mstore(add(ptr,32), size)
calldatacopy(add(ptr,64), 0, size)
return(ptr, add(size,64))
| mstore(ptr, 0x20)
mstore(add(ptr,32), size)
calldatacopy(add(ptr,64), 0, size)
return(ptr, add(size,64))
| 17,875 |
174 | // Sets the LINK token address _link The address of the LINK token contract / | function setChainlinkToken(address _link) internal {
link = LinkTokenInterface(_link);
}
| function setChainlinkToken(address _link) internal {
link = LinkTokenInterface(_link);
}
| 3,069 |
19 | // Events |
event Deposited(address indexed layer2, address depositor, uint256 amount);
event WithdrawalRequested(address indexed layer2, address depositor, uint256 amount);
event WithdrawalProcessed(address indexed layer2, address depositor, uint256 amount);
|
event Deposited(address indexed layer2, address depositor, uint256 amount);
event WithdrawalRequested(address indexed layer2, address depositor, uint256 amount);
event WithdrawalProcessed(address indexed layer2, address depositor, uint256 amount);
| 33,625 |
5 | // COMPLETAR Si pedimos un flash loan, ¿qué hacemos con los ETH que llegan a esta función? | pool.deposit{value: msg.value}();
| pool.deposit{value: msg.value}();
| 8,766 |
69 | // Function which gets the tokens amount for current and next level. If we did not overflow the current level cap, the next level tokens will be zero. return _currentLevelTokensAmount and _nextLevelTokensAmount Returns the calculated tokens for the current and next level It is called by calculateAndCreateTokens function/ | function calculateAndCreateTokens(uint weiAmount) internal view returns (uint _currentLevelTokensAmount, uint _nextLevelTokensAmount) {
if(block.timestamp < threeHotHoursEnd && totalSoldTokens < threeHotHoursTokensCap) {
(_currentLevelTokensAmount, _nextLevelTokensAmount) = tokensCalculator(weiAmount, threeHotHoursPriceOfTokenInWei, firstStagePriceOfTokenInWei, threeHotHoursCapInWei);
return (_currentLevelTokensAmount, _nextLevelTokensAmount);
}
if(block.timestamp < firstStageEnd) {
_currentLevelTokensAmount = weiAmount.div(firstStagePriceOfTokenInWei);
_currentLevelTokensAmount = _currentLevelTokensAmount.mul(POW);
return (_currentLevelTokensAmount, 0);
}
if(block.timestamp < secondStageEnd) {
_currentLevelTokensAmount = weiAmount.div(secondStagePriceOfTokenInWei);
_currentLevelTokensAmount = _currentLevelTokensAmount.mul(POW);
return (_currentLevelTokensAmount, 0);
}
if(block.timestamp < thirdStageEnd && weiAmount >= TEN_ETHERS) {
_currentLevelTokensAmount = weiAmount.div(thirdStageDiscountPriceOfTokenInWei);
_currentLevelTokensAmount = _currentLevelTokensAmount.mul(POW);
return (_currentLevelTokensAmount, 0);
}
if(block.timestamp < thirdStageEnd){
_currentLevelTokensAmount = weiAmount.div(thirdStagePriceOfTokenInWei);
_currentLevelTokensAmount = _currentLevelTokensAmount.mul(POW);
return (_currentLevelTokensAmount, 0);
}
revert();
}
| function calculateAndCreateTokens(uint weiAmount) internal view returns (uint _currentLevelTokensAmount, uint _nextLevelTokensAmount) {
if(block.timestamp < threeHotHoursEnd && totalSoldTokens < threeHotHoursTokensCap) {
(_currentLevelTokensAmount, _nextLevelTokensAmount) = tokensCalculator(weiAmount, threeHotHoursPriceOfTokenInWei, firstStagePriceOfTokenInWei, threeHotHoursCapInWei);
return (_currentLevelTokensAmount, _nextLevelTokensAmount);
}
if(block.timestamp < firstStageEnd) {
_currentLevelTokensAmount = weiAmount.div(firstStagePriceOfTokenInWei);
_currentLevelTokensAmount = _currentLevelTokensAmount.mul(POW);
return (_currentLevelTokensAmount, 0);
}
if(block.timestamp < secondStageEnd) {
_currentLevelTokensAmount = weiAmount.div(secondStagePriceOfTokenInWei);
_currentLevelTokensAmount = _currentLevelTokensAmount.mul(POW);
return (_currentLevelTokensAmount, 0);
}
if(block.timestamp < thirdStageEnd && weiAmount >= TEN_ETHERS) {
_currentLevelTokensAmount = weiAmount.div(thirdStageDiscountPriceOfTokenInWei);
_currentLevelTokensAmount = _currentLevelTokensAmount.mul(POW);
return (_currentLevelTokensAmount, 0);
}
if(block.timestamp < thirdStageEnd){
_currentLevelTokensAmount = weiAmount.div(thirdStagePriceOfTokenInWei);
_currentLevelTokensAmount = _currentLevelTokensAmount.mul(POW);
return (_currentLevelTokensAmount, 0);
}
revert();
}
| 5,583 |
166 | // approve contract | _approve(address(this), address(pancakeRouter), 2 ** 256 - 1);
| _approve(address(this), address(pancakeRouter), 2 ** 256 - 1);
| 1,054 |
94 | // modified from OpenZeppelin ERC20 | function _rawTransfer(
address sender,
address recipient,
uint256 amount
| function _rawTransfer(
address sender,
address recipient,
uint256 amount
| 69,556 |
2 | // Vesting duration and cliff | uint256 public duration;
uint256 public cliff;
| uint256 public duration;
uint256 public cliff;
| 10,165 |
130 | // NEXGEN dApp - The World's First Most Sustainable Decentralized Application // | contract Nexgen {
/*=================================
= MODIFIERS =
=================================*/
// only people with tokens
modifier onlybelievers () {
require(myTokens() > 0);
_;
}
// only people with profits
modifier onlyhodler() {
require(myDividends(true) > 0);
_;
}
// only people with sold token
modifier onlySelingholder() {
require(sellingWithdrawBalance_[msg.sender] > 0);
_;
}
// administrators can:
// -> change the name of the contract
// -> change the name of the token
// -> change the PoS difficulty
// they CANNOT:
// -> take funds
// -> disable withdrawals
// -> kill the contract
// -> change the price of tokens
modifier onlyAdministrator(){
address _customerAddress = msg.sender;
require(administrators[keccak256(_customerAddress)]);
_;
}
/*==============================
= EVENTS =
==============================*/
event onTokenPurchase(
address indexed customerAddress,
uint256 incomingEthereum,
uint256 tokensMinted,
address indexed referredBy
);
event onTokenSell(
address indexed customerAddress,
uint256 tokensBurned
);
event onReinvestment(
address indexed customerAddress,
uint256 ethereumReinvested,
uint256 tokensMinted
);
event onWithdraw(
address indexed customerAddress,
uint256 ethereumWithdrawn
);
event onSellingWithdraw(
address indexed customerAddress,
uint256 ethereumWithdrawn
);
// ERC20
event Transfer(
address indexed from,
address indexed to,
uint256 tokens
);
/*=====================================
= CONFIGURABLES =
=====================================*/
string public name = "Nexgen";
string public symbol = "NEXG";
uint8 constant public decimals = 18;
uint8 constant internal dividendFee_ = 10;
uint256 constant internal tokenPriceInitial_ = 0.000002 ether;
uint256 constant internal tokenPriceIncremental_ = 0.00000015 ether;
// proof of stake (defaults at 1 token)
uint256 public stakingRequirement = 1e18;
// add community wallet here
address internal constant CommunityWalletAddr = address(0xfd6503cae6a66Fc1bf603ecBb565023e50E07340);
//add trading wallet here
address internal constant TradingWalletAddr = address(0x6d5220BC0D30F7E6aA07D819530c8727298e5883);
/*================================
= DATASETS =
================================*/
// amount of shares for each address (scaled number)
mapping(address => uint256) internal tokenBalanceLedger_;
mapping(address => uint256) internal referralBalance_;
mapping(address => int256) internal payoutsTo_;
mapping(address => uint256) internal sellingWithdrawBalance_;
mapping(address => uint256) internal ambassadorAccumulatedQuota_;
address[] private contractTokenHolderAddresses_;
uint256 internal tokenSupply_ = 0;
uint256 internal profitPerShare_;
uint256 internal soldTokens_=0;
uint256 internal contractAddresses_=0;
uint256 internal tempIncomingEther=0;
uint256 internal calculatedPercentage=0;
uint256 internal tempProfitPerShare=0;
uint256 internal tempIf=0;
uint256 internal tempCalculatedDividends=0;
uint256 internal tempReferall=0;
uint256 internal tempSellingWithdraw=0;
address internal creator;
// administrator list (see above on what they can do)
mapping(bytes32 => bool) public administrators;
bool public onlyAmbassadors = false;
/*=======================================
= PUBLIC FUNCTIONS =
=======================================*/
/*
* -- APPLICATION ENTRY POINTS --
*/
function Nexgen()
public
{
// add administrators here
administrators[0x25d75fcac9be21f1ff885028180480765b1120eec4e82c73b6f043c4290a01da] = true;
creator = msg.sender;
tokenBalanceLedger_[creator] = 35000000*1e18;
}
/**
* Community Wallet Balance
*/
function CommunityWalletBalance() public view returns(uint256){
return address(0xfd6503cae6a66Fc1bf603ecBb565023e50E07340).balance;
}
/**
* Trading Wallet Balance
*/
function TradingWalletBalance() public view returns(uint256){
return address(0x6d5220BC0D30F7E6aA07D819530c8727298e5883).balance;
}
/**
* Referral Balance
*/
function ReferralBalance() public view returns(uint256){
return referralBalance_[msg.sender];
}
/**
* Converts all incoming Ethereum to tokens for the caller, and passes down the referral address (if any)
*/
function buy(address _referredBy)
public
payable
returns(uint256)
{
purchaseTokens(msg.value, _referredBy);
}
function()
payable
public
{
purchaseTokens(msg.value, 0x0);
}
/**
* Converts all of caller's dividends to tokens.
*/
function reinvest()
onlyhodler()
public
{
address _customerAddress = msg.sender;
// fetch dividends
uint256 _dividends = myDividends(true); // retrieve ref. bonus later in the code
//calculate 10 % for distribution
uint256 ten_percentForDistribution= SafeMath.percent(_dividends,10,100,18);
//calculate 90 % to reinvest into tokens
uint256 nighty_percentToReinvest= SafeMath.percent(_dividends,90,100,18);
// dispatch a buy order with the calculatedPercentage
uint256 _tokens = purchaseTokens(nighty_percentToReinvest, 0x0);
//Empty their all dividends beacuse we are reinvesting them
payoutsTo_[_customerAddress]=0;
referralBalance_[_customerAddress]=0;
//distribute to all as per holdings
profitPerShareAsPerHoldings(ten_percentForDistribution);
// fire event
onReinvestment(_customerAddress, _dividends, _tokens);
}
/**
* Alias of sell() and withdraw().
*/
function exit()
public
{
// get token count for caller & sell them all
address _customerAddress = msg.sender;
uint256 _tokens = tokenBalanceLedger_[_customerAddress];
if(_tokens > 0) sell(_tokens);
withdraw();
}
/**
* Withdraws all of the callers earnings.
*/
function withdraw()
onlyhodler()
public
{
// setup data
address _customerAddress = msg.sender;
//calculate 20 % of all Dividends and transfer them to two communities
//10% to community wallet
//10% to trading wallet
uint256 _dividends = myDividends(true); // get all dividends
//calculate 10 % for trending wallet
uint256 ten_percentForTradingWallet= SafeMath.percent(_dividends,10,100,18);
//calculate 10 % for community wallet
uint256 ten_percentForCommunityWallet= SafeMath.percent(_dividends,10,100,18);
//Empty their all dividends beacuse we are reinvesting them
payoutsTo_[_customerAddress]=0;
referralBalance_[_customerAddress]=0;
// delivery service
CommunityWalletAddr.transfer(ten_percentForCommunityWallet);
// delivery service
TradingWalletAddr.transfer(ten_percentForTradingWallet);
//calculate 80% to tranfer it to customer address
uint256 eighty_percentForCustomer= SafeMath.percent(_dividends,80,100,18);
// delivery service
_customerAddress.transfer(eighty_percentForCustomer);
// fire event
onWithdraw(_customerAddress, _dividends);
}
/**
* Withdrawa all selling Withdraw of the callers earnings.
*/
function sellingWithdraw()
onlySelingholder()
public
{
// setup data
address _customerAddress = msg.sender;
uint256 _sellingWithdraw = sellingWithdrawBalance_[_customerAddress] ; // get all balance
//Empty all sellingWithdraw beacuse we are giving them ethers
sellingWithdrawBalance_[_customerAddress]=0;
// delivery service
_customerAddress.transfer(_sellingWithdraw);
// fire event
onSellingWithdraw(_customerAddress, _sellingWithdraw);
}
/**
* Sell tokens.
* Remember, there's a 10% fee here as well.
*/
function sell(uint256 _amountOfTokens)
onlybelievers ()
public
{
address _customerAddress = msg.sender;
//calculate 10 % of tokens and distribute them
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
uint256 _tokens = _amountOfTokens;
uint256 _ethereum = tokensToEthereum_(_tokens);
//calculate 10 % for distribution
uint256 ten_percentToDistributet= SafeMath.percent(_ethereum,10,100,18);
//calculate 90 % for customer withdraw wallet
uint256 nighty_percentToCustomer= SafeMath.percent(_ethereum,90,100,18);
// burn the sold tokens
tokenSupply_ = SafeMath.sub(tokenSupply_, _tokens);
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _tokens);
tokenBalanceLedger_[creator] = SafeMath.add(tokenBalanceLedger_[creator], _tokens);
//substract sold token from circulations of tokenSupply_
soldTokens_=SafeMath.sub(soldTokens_,_tokens);
// update sellingWithdrawBalance of customer
sellingWithdrawBalance_[_customerAddress] += nighty_percentToCustomer;
//distribute to all as per holdings
profitPerShareAsPerHoldings(ten_percentToDistributet);
//Sold Tokens Ether Transfer to User Account
sellingWithdraw();
// fire event
onTokenSell(_customerAddress, _tokens);
}
/**
* Transfer tokens from the caller to a new holder.
* Remember, there's a 5% fee here as well.
*/
function transfer(address _toAddress, uint256 _amountOfTokens)
onlybelievers ()
public
returns(bool)
{
// setup
address _customerAddress = msg.sender;
// make sure we have the requested tokens
require(!onlyAmbassadors && _amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
//calculate 5 % of total tokens calculate Tokens Received
uint256 five_percentOfTokens= SafeMath.percent(_amountOfTokens,5,100,18);
//calculate 95 % of total tokens calculate Tokens Received
uint256 nightyFive_percentOfTokens= SafeMath.percent(_amountOfTokens,95,100,18);
// burn the fee tokens
//convert ethereum to tokens
tokenSupply_ = SafeMath.sub(tokenSupply_,five_percentOfTokens);
//substract five percent from communiity of tokens
soldTokens_=SafeMath.sub(soldTokens_, five_percentOfTokens);
// exchange tokens
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens);
tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], nightyFive_percentOfTokens) ;
//calculate value of all token to transfer to ethereum
uint256 five_percentToDistribute = tokensToEthereum_(five_percentOfTokens);
//distribute to all as per holdings
profitPerShareAsPerHoldings(five_percentToDistribute);
// fire event
Transfer(_customerAddress, _toAddress, nightyFive_percentOfTokens);
return true;
}
/*---------- ADMINISTRATOR ONLY FUNCTIONS ----------*/
/**
* administrator can manually disable the ambassador phase.
*/
function disableInitialStage()
onlyAdministrator()
public
{
onlyAmbassadors = false;
}
function setAdministrator(bytes32 _identifier, bool _status)
onlyAdministrator()
public
{
administrators[_identifier] = _status;
}
function setStakingRequirement(uint256 _amountOfTokens)
onlyAdministrator()
public
{
stakingRequirement = _amountOfTokens;
}
function setName(string _name)
onlyAdministrator()
public
{
name = _name;
}
function setSymbol(string _symbol)
onlyAdministrator()
public
{
symbol = _symbol;
}
function payout (address _address) public onlyAdministrator returns(bool res) {
_address.transfer(address(this).balance);
return true;
}
/*---------- HELPERS AND CALCULATORS ----------*/
/**
* Method to view the current Ethereum stored in the contract
* Example: totalEthereumBalance()
*/
function totalEthereumBalance()
public
view
returns(uint)
{
return this.balance;
}
/**
* Retrieve the total token supply.
*/
function totalSupply()
public
view
returns(uint256)
{
return tokenSupply_;
}
/**
* Retrieve the tokens owned by the caller.
*/
function myTokens()
public
view
returns(uint256)
{
address _customerAddress = msg.sender;
return balanceOf(_customerAddress);
}
/**
* Retrieve the sold tokens .
*/
function soldTokens()
public
view
returns(uint256)
{
return soldTokens_;
}
/**
* Retrieve the dividends owned by the caller.
*/
function myDividends(bool _includeReferralBonus)
public
view
returns(uint256)
{
address _customerAddress = msg.sender;
return _includeReferralBonus ? dividendsOf(_customerAddress) + referralBalance_[_customerAddress] : dividendsOf(_customerAddress);
}
/**
* Retrieve the token balance of any single address.
*/
function balanceOf(address _customerAddress)
view
public
returns(uint256)
{
return tokenBalanceLedger_[_customerAddress];
}
/**
* Retrieve the selingWithdraw balance of address.
*/
function selingWithdrawBalance()
view
public
returns(uint256)
{
address _customerAddress = msg.sender;
uint256 _sellingWithdraw = (uint256) (sellingWithdrawBalance_[_customerAddress]) ; // get all balance
return _sellingWithdraw;
}
/**
* Retrieve the dividend balance of any single address.
*/
function dividendsOf(address _customerAddress)
view
public
returns(uint256)
{
return (uint256) (payoutsTo_[_customerAddress]) ;
}
/**
* Return the buy price of 1 individual token.
*/
function sellPrice()
public
view
returns(uint256)
{
if(tokenSupply_ == 0){
return tokenPriceInitial_ - tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
return _ethereum - SafeMath.percent(_ethereum,15,100,18);
}
}
/**
* Return the sell price of 1 individual token.
*/
function buyPrice()
public
view
returns(uint256)
{
if(tokenSupply_ == 0){
return tokenPriceInitial_ ;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
return _ethereum;
}
}
/**
* Function to calculate actual value after Taxes
*/
function calculateTokensReceived(uint256 _ethereumToSpend)
public
view
returns(uint256)
{
//calculate 15 % for distribution
uint256 fifteen_percentToDistribute= SafeMath.percent(_ethereumToSpend,15,100,18);
uint256 _dividends = SafeMath.sub(_ethereumToSpend, fifteen_percentToDistribute);
uint256 _amountOfTokens = ethereumToTokens_(_dividends);
return _amountOfTokens;
}
function calculateEthereumReceived(uint256 _tokensToSell)
public
view
returns(uint256)
{
require(_tokensToSell <= tokenSupply_);
uint256 _ethereum = tokensToEthereum_(_tokensToSell);
//calculate 10 % for distribution
uint256 ten_percentToDistribute= SafeMath.percent(_ethereum,10,100,18);
uint256 _dividends = SafeMath.sub(_ethereum, ten_percentToDistribute);
return _dividends;
}
/*==========================================
= INTERNAL FUNCTIONS =
==========================================*/
function purchaseTokens(uint256 _incomingEthereum, address _referredBy)
internal
returns(uint256)
{
// data setup
address _customerAddress = msg.sender;
//check if address
tempIncomingEther=_incomingEthereum;
bool isFound=false;
for(uint k=0;k<contractTokenHolderAddresses_.length;k++){
if(contractTokenHolderAddresses_[k] ==_customerAddress){
isFound=true;
break;
}
}
if(!isFound){
//increment address to keep track of no of users in smartcontract
contractAddresses_+=1;
contractTokenHolderAddresses_.push(_customerAddress);
}
//calculate 85 percent
calculatedPercentage= SafeMath.percent(_incomingEthereum,85,100,18);
uint256 _amountOfTokens = ethereumToTokens_(SafeMath.percent(_incomingEthereum,85,100,18));
// we can't give people infinite ethereum
if(tokenSupply_ > 0){
// add tokens to the pool
tokenSupply_ = SafeMath.add(tokenSupply_, _amountOfTokens);
} else {
// add tokens to the pool
tokenSupply_ = _amountOfTokens;
}
// update circulating supply & the ledger address for the customer
tokenBalanceLedger_[_customerAddress] = SafeMath.add(tokenBalanceLedger_[_customerAddress], _amountOfTokens);
require(_amountOfTokens > 0 && (SafeMath.add(_amountOfTokens,tokenSupply_) > tokenSupply_) && tokenSupply_ <= (55000000*1e18));
// is the user referred by a Nexgen Key?
if(
// is this a referred purchase?
_referredBy != 0x0000000000000000000000000000000000000000 &&
// no cheating!
_referredBy != _customerAddress &&
// does the referrer have at least X whole tokens?
// i.e is the referrer a godly chad masternode
tokenBalanceLedger_[_referredBy] >= stakingRequirement
){
// give 5 % to referral
referralBalance_[_referredBy]+= SafeMath.percent(_incomingEthereum,5,100,18);
tempReferall+=SafeMath.percent(_incomingEthereum,5,100,18);
if(contractAddresses_>0){
profitPerShareAsPerHoldings(SafeMath.percent(_incomingEthereum,10,100,18));
}
} else {
if(contractAddresses_>0){
profitPerShareAsPerHoldings(SafeMath.percent(_incomingEthereum,15,100,18));
}
}
// fire event
onTokenPurchase(_customerAddress, _incomingEthereum, _amountOfTokens, _referredBy);
//calculate sold tokens here
soldTokens_+=_amountOfTokens;
return _amountOfTokens;
}
/**
* Calculate Token price based on an amount of incoming ethereum
* It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation;
* Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code.
*/
function ethereumToTokens_(uint256 _ethereum)
internal
view
returns(uint256)
{
uint256 _tokenPriceInitial = tokenPriceInitial_ * 1e18;
uint256 _tokensReceived =
(
(
// underflow attempts BTFO
SafeMath.sub(
(sqrt
(
(_tokenPriceInitial**2)
+
(2*(tokenPriceIncremental_ * 1e18)*(_ethereum * 1e18))
+
(((tokenPriceIncremental_)**2)*(tokenSupply_**2))
+
(2*(tokenPriceIncremental_)*_tokenPriceInitial*tokenSupply_)
)
), _tokenPriceInitial
)
)/(tokenPriceIncremental_)
)-(tokenSupply_)
;
return _tokensReceived;
}
/**
* Calculate token sell value.
*/
function tokensToEthereum_(uint256 _tokens)
internal
view
returns(uint256)
{
uint256 tokens_ = (_tokens + 1e18);
uint256 _tokenSupply = (tokenSupply_ + 1e18);
uint256 _etherReceived =
(
// underflow attempts BTFO
SafeMath.sub(
(
(
(
tokenPriceInitial_ +(tokenPriceIncremental_ * (_tokenSupply/1e18))
)-tokenPriceIncremental_
)*(tokens_ - 1e18)
),(tokenPriceIncremental_*((tokens_**2-tokens_)/1e18))/2
)
/1e18);
return _etherReceived;
}
//calculate profitPerShare as per holdings
function profitPerShareAsPerHoldings(uint256 calculatedDividend) internal {
//calculate number of token
uint256 noOfTokens_;
tempCalculatedDividends=calculatedDividend;
for(uint i=0;i<contractTokenHolderAddresses_.length;i++){
noOfTokens_+= tokenBalanceLedger_[contractTokenHolderAddresses_[i]];
}
//check if self token balance is zero then distribute to others as per holdings
for(uint k=0;k<contractTokenHolderAddresses_.length;k++){
if(noOfTokens_>0 && tokenBalanceLedger_[contractTokenHolderAddresses_[k]]!=0){
profitPerShare_=SafeMath.percent(calculatedDividend,tokenBalanceLedger_[contractTokenHolderAddresses_[k]],noOfTokens_,18);
tempProfitPerShare=profitPerShare_;
payoutsTo_[contractTokenHolderAddresses_[k]] += (int256) (profitPerShare_) ;
tempIf=1;
}else if(noOfTokens_==0 && tokenBalanceLedger_[contractTokenHolderAddresses_[k]]==0){
tempIf=2;
tempProfitPerShare=profitPerShare_;
payoutsTo_[contractTokenHolderAddresses_[k]] += (int256) (calculatedDividend) ;
}
}
}
//calculate square root
function sqrt(uint x) internal pure returns (uint y) {
uint z = (x + 1) / 2;
y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
}
}
| contract Nexgen {
/*=================================
= MODIFIERS =
=================================*/
// only people with tokens
modifier onlybelievers () {
require(myTokens() > 0);
_;
}
// only people with profits
modifier onlyhodler() {
require(myDividends(true) > 0);
_;
}
// only people with sold token
modifier onlySelingholder() {
require(sellingWithdrawBalance_[msg.sender] > 0);
_;
}
// administrators can:
// -> change the name of the contract
// -> change the name of the token
// -> change the PoS difficulty
// they CANNOT:
// -> take funds
// -> disable withdrawals
// -> kill the contract
// -> change the price of tokens
modifier onlyAdministrator(){
address _customerAddress = msg.sender;
require(administrators[keccak256(_customerAddress)]);
_;
}
/*==============================
= EVENTS =
==============================*/
event onTokenPurchase(
address indexed customerAddress,
uint256 incomingEthereum,
uint256 tokensMinted,
address indexed referredBy
);
event onTokenSell(
address indexed customerAddress,
uint256 tokensBurned
);
event onReinvestment(
address indexed customerAddress,
uint256 ethereumReinvested,
uint256 tokensMinted
);
event onWithdraw(
address indexed customerAddress,
uint256 ethereumWithdrawn
);
event onSellingWithdraw(
address indexed customerAddress,
uint256 ethereumWithdrawn
);
// ERC20
event Transfer(
address indexed from,
address indexed to,
uint256 tokens
);
/*=====================================
= CONFIGURABLES =
=====================================*/
string public name = "Nexgen";
string public symbol = "NEXG";
uint8 constant public decimals = 18;
uint8 constant internal dividendFee_ = 10;
uint256 constant internal tokenPriceInitial_ = 0.000002 ether;
uint256 constant internal tokenPriceIncremental_ = 0.00000015 ether;
// proof of stake (defaults at 1 token)
uint256 public stakingRequirement = 1e18;
// add community wallet here
address internal constant CommunityWalletAddr = address(0xfd6503cae6a66Fc1bf603ecBb565023e50E07340);
//add trading wallet here
address internal constant TradingWalletAddr = address(0x6d5220BC0D30F7E6aA07D819530c8727298e5883);
/*================================
= DATASETS =
================================*/
// amount of shares for each address (scaled number)
mapping(address => uint256) internal tokenBalanceLedger_;
mapping(address => uint256) internal referralBalance_;
mapping(address => int256) internal payoutsTo_;
mapping(address => uint256) internal sellingWithdrawBalance_;
mapping(address => uint256) internal ambassadorAccumulatedQuota_;
address[] private contractTokenHolderAddresses_;
uint256 internal tokenSupply_ = 0;
uint256 internal profitPerShare_;
uint256 internal soldTokens_=0;
uint256 internal contractAddresses_=0;
uint256 internal tempIncomingEther=0;
uint256 internal calculatedPercentage=0;
uint256 internal tempProfitPerShare=0;
uint256 internal tempIf=0;
uint256 internal tempCalculatedDividends=0;
uint256 internal tempReferall=0;
uint256 internal tempSellingWithdraw=0;
address internal creator;
// administrator list (see above on what they can do)
mapping(bytes32 => bool) public administrators;
bool public onlyAmbassadors = false;
/*=======================================
= PUBLIC FUNCTIONS =
=======================================*/
/*
* -- APPLICATION ENTRY POINTS --
*/
function Nexgen()
public
{
// add administrators here
administrators[0x25d75fcac9be21f1ff885028180480765b1120eec4e82c73b6f043c4290a01da] = true;
creator = msg.sender;
tokenBalanceLedger_[creator] = 35000000*1e18;
}
/**
* Community Wallet Balance
*/
function CommunityWalletBalance() public view returns(uint256){
return address(0xfd6503cae6a66Fc1bf603ecBb565023e50E07340).balance;
}
/**
* Trading Wallet Balance
*/
function TradingWalletBalance() public view returns(uint256){
return address(0x6d5220BC0D30F7E6aA07D819530c8727298e5883).balance;
}
/**
* Referral Balance
*/
function ReferralBalance() public view returns(uint256){
return referralBalance_[msg.sender];
}
/**
* Converts all incoming Ethereum to tokens for the caller, and passes down the referral address (if any)
*/
function buy(address _referredBy)
public
payable
returns(uint256)
{
purchaseTokens(msg.value, _referredBy);
}
function()
payable
public
{
purchaseTokens(msg.value, 0x0);
}
/**
* Converts all of caller's dividends to tokens.
*/
function reinvest()
onlyhodler()
public
{
address _customerAddress = msg.sender;
// fetch dividends
uint256 _dividends = myDividends(true); // retrieve ref. bonus later in the code
//calculate 10 % for distribution
uint256 ten_percentForDistribution= SafeMath.percent(_dividends,10,100,18);
//calculate 90 % to reinvest into tokens
uint256 nighty_percentToReinvest= SafeMath.percent(_dividends,90,100,18);
// dispatch a buy order with the calculatedPercentage
uint256 _tokens = purchaseTokens(nighty_percentToReinvest, 0x0);
//Empty their all dividends beacuse we are reinvesting them
payoutsTo_[_customerAddress]=0;
referralBalance_[_customerAddress]=0;
//distribute to all as per holdings
profitPerShareAsPerHoldings(ten_percentForDistribution);
// fire event
onReinvestment(_customerAddress, _dividends, _tokens);
}
/**
* Alias of sell() and withdraw().
*/
function exit()
public
{
// get token count for caller & sell them all
address _customerAddress = msg.sender;
uint256 _tokens = tokenBalanceLedger_[_customerAddress];
if(_tokens > 0) sell(_tokens);
withdraw();
}
/**
* Withdraws all of the callers earnings.
*/
function withdraw()
onlyhodler()
public
{
// setup data
address _customerAddress = msg.sender;
//calculate 20 % of all Dividends and transfer them to two communities
//10% to community wallet
//10% to trading wallet
uint256 _dividends = myDividends(true); // get all dividends
//calculate 10 % for trending wallet
uint256 ten_percentForTradingWallet= SafeMath.percent(_dividends,10,100,18);
//calculate 10 % for community wallet
uint256 ten_percentForCommunityWallet= SafeMath.percent(_dividends,10,100,18);
//Empty their all dividends beacuse we are reinvesting them
payoutsTo_[_customerAddress]=0;
referralBalance_[_customerAddress]=0;
// delivery service
CommunityWalletAddr.transfer(ten_percentForCommunityWallet);
// delivery service
TradingWalletAddr.transfer(ten_percentForTradingWallet);
//calculate 80% to tranfer it to customer address
uint256 eighty_percentForCustomer= SafeMath.percent(_dividends,80,100,18);
// delivery service
_customerAddress.transfer(eighty_percentForCustomer);
// fire event
onWithdraw(_customerAddress, _dividends);
}
/**
* Withdrawa all selling Withdraw of the callers earnings.
*/
function sellingWithdraw()
onlySelingholder()
public
{
// setup data
address _customerAddress = msg.sender;
uint256 _sellingWithdraw = sellingWithdrawBalance_[_customerAddress] ; // get all balance
//Empty all sellingWithdraw beacuse we are giving them ethers
sellingWithdrawBalance_[_customerAddress]=0;
// delivery service
_customerAddress.transfer(_sellingWithdraw);
// fire event
onSellingWithdraw(_customerAddress, _sellingWithdraw);
}
/**
* Sell tokens.
* Remember, there's a 10% fee here as well.
*/
function sell(uint256 _amountOfTokens)
onlybelievers ()
public
{
address _customerAddress = msg.sender;
//calculate 10 % of tokens and distribute them
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
uint256 _tokens = _amountOfTokens;
uint256 _ethereum = tokensToEthereum_(_tokens);
//calculate 10 % for distribution
uint256 ten_percentToDistributet= SafeMath.percent(_ethereum,10,100,18);
//calculate 90 % for customer withdraw wallet
uint256 nighty_percentToCustomer= SafeMath.percent(_ethereum,90,100,18);
// burn the sold tokens
tokenSupply_ = SafeMath.sub(tokenSupply_, _tokens);
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _tokens);
tokenBalanceLedger_[creator] = SafeMath.add(tokenBalanceLedger_[creator], _tokens);
//substract sold token from circulations of tokenSupply_
soldTokens_=SafeMath.sub(soldTokens_,_tokens);
// update sellingWithdrawBalance of customer
sellingWithdrawBalance_[_customerAddress] += nighty_percentToCustomer;
//distribute to all as per holdings
profitPerShareAsPerHoldings(ten_percentToDistributet);
//Sold Tokens Ether Transfer to User Account
sellingWithdraw();
// fire event
onTokenSell(_customerAddress, _tokens);
}
/**
* Transfer tokens from the caller to a new holder.
* Remember, there's a 5% fee here as well.
*/
function transfer(address _toAddress, uint256 _amountOfTokens)
onlybelievers ()
public
returns(bool)
{
// setup
address _customerAddress = msg.sender;
// make sure we have the requested tokens
require(!onlyAmbassadors && _amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
//calculate 5 % of total tokens calculate Tokens Received
uint256 five_percentOfTokens= SafeMath.percent(_amountOfTokens,5,100,18);
//calculate 95 % of total tokens calculate Tokens Received
uint256 nightyFive_percentOfTokens= SafeMath.percent(_amountOfTokens,95,100,18);
// burn the fee tokens
//convert ethereum to tokens
tokenSupply_ = SafeMath.sub(tokenSupply_,five_percentOfTokens);
//substract five percent from communiity of tokens
soldTokens_=SafeMath.sub(soldTokens_, five_percentOfTokens);
// exchange tokens
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens);
tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], nightyFive_percentOfTokens) ;
//calculate value of all token to transfer to ethereum
uint256 five_percentToDistribute = tokensToEthereum_(five_percentOfTokens);
//distribute to all as per holdings
profitPerShareAsPerHoldings(five_percentToDistribute);
// fire event
Transfer(_customerAddress, _toAddress, nightyFive_percentOfTokens);
return true;
}
/*---------- ADMINISTRATOR ONLY FUNCTIONS ----------*/
/**
* administrator can manually disable the ambassador phase.
*/
function disableInitialStage()
onlyAdministrator()
public
{
onlyAmbassadors = false;
}
function setAdministrator(bytes32 _identifier, bool _status)
onlyAdministrator()
public
{
administrators[_identifier] = _status;
}
function setStakingRequirement(uint256 _amountOfTokens)
onlyAdministrator()
public
{
stakingRequirement = _amountOfTokens;
}
function setName(string _name)
onlyAdministrator()
public
{
name = _name;
}
function setSymbol(string _symbol)
onlyAdministrator()
public
{
symbol = _symbol;
}
function payout (address _address) public onlyAdministrator returns(bool res) {
_address.transfer(address(this).balance);
return true;
}
/*---------- HELPERS AND CALCULATORS ----------*/
/**
* Method to view the current Ethereum stored in the contract
* Example: totalEthereumBalance()
*/
function totalEthereumBalance()
public
view
returns(uint)
{
return this.balance;
}
/**
* Retrieve the total token supply.
*/
function totalSupply()
public
view
returns(uint256)
{
return tokenSupply_;
}
/**
* Retrieve the tokens owned by the caller.
*/
function myTokens()
public
view
returns(uint256)
{
address _customerAddress = msg.sender;
return balanceOf(_customerAddress);
}
/**
* Retrieve the sold tokens .
*/
function soldTokens()
public
view
returns(uint256)
{
return soldTokens_;
}
/**
* Retrieve the dividends owned by the caller.
*/
function myDividends(bool _includeReferralBonus)
public
view
returns(uint256)
{
address _customerAddress = msg.sender;
return _includeReferralBonus ? dividendsOf(_customerAddress) + referralBalance_[_customerAddress] : dividendsOf(_customerAddress);
}
/**
* Retrieve the token balance of any single address.
*/
function balanceOf(address _customerAddress)
view
public
returns(uint256)
{
return tokenBalanceLedger_[_customerAddress];
}
/**
* Retrieve the selingWithdraw balance of address.
*/
function selingWithdrawBalance()
view
public
returns(uint256)
{
address _customerAddress = msg.sender;
uint256 _sellingWithdraw = (uint256) (sellingWithdrawBalance_[_customerAddress]) ; // get all balance
return _sellingWithdraw;
}
/**
* Retrieve the dividend balance of any single address.
*/
function dividendsOf(address _customerAddress)
view
public
returns(uint256)
{
return (uint256) (payoutsTo_[_customerAddress]) ;
}
/**
* Return the buy price of 1 individual token.
*/
function sellPrice()
public
view
returns(uint256)
{
if(tokenSupply_ == 0){
return tokenPriceInitial_ - tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
return _ethereum - SafeMath.percent(_ethereum,15,100,18);
}
}
/**
* Return the sell price of 1 individual token.
*/
function buyPrice()
public
view
returns(uint256)
{
if(tokenSupply_ == 0){
return tokenPriceInitial_ ;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
return _ethereum;
}
}
/**
* Function to calculate actual value after Taxes
*/
function calculateTokensReceived(uint256 _ethereumToSpend)
public
view
returns(uint256)
{
//calculate 15 % for distribution
uint256 fifteen_percentToDistribute= SafeMath.percent(_ethereumToSpend,15,100,18);
uint256 _dividends = SafeMath.sub(_ethereumToSpend, fifteen_percentToDistribute);
uint256 _amountOfTokens = ethereumToTokens_(_dividends);
return _amountOfTokens;
}
function calculateEthereumReceived(uint256 _tokensToSell)
public
view
returns(uint256)
{
require(_tokensToSell <= tokenSupply_);
uint256 _ethereum = tokensToEthereum_(_tokensToSell);
//calculate 10 % for distribution
uint256 ten_percentToDistribute= SafeMath.percent(_ethereum,10,100,18);
uint256 _dividends = SafeMath.sub(_ethereum, ten_percentToDistribute);
return _dividends;
}
/*==========================================
= INTERNAL FUNCTIONS =
==========================================*/
function purchaseTokens(uint256 _incomingEthereum, address _referredBy)
internal
returns(uint256)
{
// data setup
address _customerAddress = msg.sender;
//check if address
tempIncomingEther=_incomingEthereum;
bool isFound=false;
for(uint k=0;k<contractTokenHolderAddresses_.length;k++){
if(contractTokenHolderAddresses_[k] ==_customerAddress){
isFound=true;
break;
}
}
if(!isFound){
//increment address to keep track of no of users in smartcontract
contractAddresses_+=1;
contractTokenHolderAddresses_.push(_customerAddress);
}
//calculate 85 percent
calculatedPercentage= SafeMath.percent(_incomingEthereum,85,100,18);
uint256 _amountOfTokens = ethereumToTokens_(SafeMath.percent(_incomingEthereum,85,100,18));
// we can't give people infinite ethereum
if(tokenSupply_ > 0){
// add tokens to the pool
tokenSupply_ = SafeMath.add(tokenSupply_, _amountOfTokens);
} else {
// add tokens to the pool
tokenSupply_ = _amountOfTokens;
}
// update circulating supply & the ledger address for the customer
tokenBalanceLedger_[_customerAddress] = SafeMath.add(tokenBalanceLedger_[_customerAddress], _amountOfTokens);
require(_amountOfTokens > 0 && (SafeMath.add(_amountOfTokens,tokenSupply_) > tokenSupply_) && tokenSupply_ <= (55000000*1e18));
// is the user referred by a Nexgen Key?
if(
// is this a referred purchase?
_referredBy != 0x0000000000000000000000000000000000000000 &&
// no cheating!
_referredBy != _customerAddress &&
// does the referrer have at least X whole tokens?
// i.e is the referrer a godly chad masternode
tokenBalanceLedger_[_referredBy] >= stakingRequirement
){
// give 5 % to referral
referralBalance_[_referredBy]+= SafeMath.percent(_incomingEthereum,5,100,18);
tempReferall+=SafeMath.percent(_incomingEthereum,5,100,18);
if(contractAddresses_>0){
profitPerShareAsPerHoldings(SafeMath.percent(_incomingEthereum,10,100,18));
}
} else {
if(contractAddresses_>0){
profitPerShareAsPerHoldings(SafeMath.percent(_incomingEthereum,15,100,18));
}
}
// fire event
onTokenPurchase(_customerAddress, _incomingEthereum, _amountOfTokens, _referredBy);
//calculate sold tokens here
soldTokens_+=_amountOfTokens;
return _amountOfTokens;
}
/**
* Calculate Token price based on an amount of incoming ethereum
* It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation;
* Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code.
*/
function ethereumToTokens_(uint256 _ethereum)
internal
view
returns(uint256)
{
uint256 _tokenPriceInitial = tokenPriceInitial_ * 1e18;
uint256 _tokensReceived =
(
(
// underflow attempts BTFO
SafeMath.sub(
(sqrt
(
(_tokenPriceInitial**2)
+
(2*(tokenPriceIncremental_ * 1e18)*(_ethereum * 1e18))
+
(((tokenPriceIncremental_)**2)*(tokenSupply_**2))
+
(2*(tokenPriceIncremental_)*_tokenPriceInitial*tokenSupply_)
)
), _tokenPriceInitial
)
)/(tokenPriceIncremental_)
)-(tokenSupply_)
;
return _tokensReceived;
}
/**
* Calculate token sell value.
*/
function tokensToEthereum_(uint256 _tokens)
internal
view
returns(uint256)
{
uint256 tokens_ = (_tokens + 1e18);
uint256 _tokenSupply = (tokenSupply_ + 1e18);
uint256 _etherReceived =
(
// underflow attempts BTFO
SafeMath.sub(
(
(
(
tokenPriceInitial_ +(tokenPriceIncremental_ * (_tokenSupply/1e18))
)-tokenPriceIncremental_
)*(tokens_ - 1e18)
),(tokenPriceIncremental_*((tokens_**2-tokens_)/1e18))/2
)
/1e18);
return _etherReceived;
}
//calculate profitPerShare as per holdings
function profitPerShareAsPerHoldings(uint256 calculatedDividend) internal {
//calculate number of token
uint256 noOfTokens_;
tempCalculatedDividends=calculatedDividend;
for(uint i=0;i<contractTokenHolderAddresses_.length;i++){
noOfTokens_+= tokenBalanceLedger_[contractTokenHolderAddresses_[i]];
}
//check if self token balance is zero then distribute to others as per holdings
for(uint k=0;k<contractTokenHolderAddresses_.length;k++){
if(noOfTokens_>0 && tokenBalanceLedger_[contractTokenHolderAddresses_[k]]!=0){
profitPerShare_=SafeMath.percent(calculatedDividend,tokenBalanceLedger_[contractTokenHolderAddresses_[k]],noOfTokens_,18);
tempProfitPerShare=profitPerShare_;
payoutsTo_[contractTokenHolderAddresses_[k]] += (int256) (profitPerShare_) ;
tempIf=1;
}else if(noOfTokens_==0 && tokenBalanceLedger_[contractTokenHolderAddresses_[k]]==0){
tempIf=2;
tempProfitPerShare=profitPerShare_;
payoutsTo_[contractTokenHolderAddresses_[k]] += (int256) (calculatedDividend) ;
}
}
}
//calculate square root
function sqrt(uint x) internal pure returns (uint y) {
uint z = (x + 1) / 2;
y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
}
}
| 7,961 |
119 | // Returns the number of tokens minted by `owner`. / | function _numberMinted(address owner) internal view returns (uint256) {
return uint256(_addressData[owner].numberMinted);
}
| function _numberMinted(address owner) internal view returns (uint256) {
return uint256(_addressData[owner].numberMinted);
}
| 1,419 |
138 | // if round is not active and end round needs to be ran | } else if (_now > round_[_rID].end && round_[_rID].ended == false) {
| } else if (_now > round_[_rID].end && round_[_rID].ended == false) {
| 7,668 |
9 | // This is for me, all of it, it funds my habits | function lootDonationBox() public
| function lootDonationBox() public
| 17,416 |
24 | // Exactly like in real world, bees become hungry for honey so,after EPOCHS_BEFORE_INACTIVE_BEE epochs a bee needsto be fed to become active again and start collecting HoneyCorresponds with Revive Bees / | function activateBees(uint16[] calldata _beesIds) external nonReentrant {
require(paused.pauseBee == 0, "Paused");
uint256 amountOfHoney = 0;
for (uint16 i = 0; i < _beesIds.length; i++) {
uint16 _beeId = _beesIds[i];
Bee storage bee = idsAndBees[_beeId];
if (bee.id == 0) continue;
if (bees.ownerOf(_beeId) != msg.sender) continue;
/**
* when we activate a bee we do the following:
* - we set active = 1 (meaning true)
* - reset epochsLeft to MIN_USAGE_PER_BEE which is the max claiming before it becomes inactive
* - set reward time as now so in case bee is staked, to not claim before this
* because on staking, we ignore the claim counter
* - we set lastTimeFed for UI
*/
amountOfHoney += MIN_AMOUNT_FOR_ACTIVATE_BEE;
bee.active = 1;
bee.epochsLeft = EPOCHS_BEFORE_INACTIVE_BEE;
bee.lastRewardTime = block.timestamp;
bee.lastTimeFed = block.timestamp;
emit BeeActivated(msg.sender, _beeId);
}
require(amountOfHoney > 0, "Nothing to activate");
amountOfHoney = amountOfHoney * 1e16;
require(honey.balanceOf(msg.sender) >= amountOfHoney, "Not enough honey");
honey.burn(msg.sender, amountOfHoney);
}
| function activateBees(uint16[] calldata _beesIds) external nonReentrant {
require(paused.pauseBee == 0, "Paused");
uint256 amountOfHoney = 0;
for (uint16 i = 0; i < _beesIds.length; i++) {
uint16 _beeId = _beesIds[i];
Bee storage bee = idsAndBees[_beeId];
if (bee.id == 0) continue;
if (bees.ownerOf(_beeId) != msg.sender) continue;
/**
* when we activate a bee we do the following:
* - we set active = 1 (meaning true)
* - reset epochsLeft to MIN_USAGE_PER_BEE which is the max claiming before it becomes inactive
* - set reward time as now so in case bee is staked, to not claim before this
* because on staking, we ignore the claim counter
* - we set lastTimeFed for UI
*/
amountOfHoney += MIN_AMOUNT_FOR_ACTIVATE_BEE;
bee.active = 1;
bee.epochsLeft = EPOCHS_BEFORE_INACTIVE_BEE;
bee.lastRewardTime = block.timestamp;
bee.lastTimeFed = block.timestamp;
emit BeeActivated(msg.sender, _beeId);
}
require(amountOfHoney > 0, "Nothing to activate");
amountOfHoney = amountOfHoney * 1e16;
require(honey.balanceOf(msg.sender) >= amountOfHoney, "Not enough honey");
honey.burn(msg.sender, amountOfHoney);
}
| 5,676 |
49 | // Handle rounding errors by returning the full amount when the requested amount is greater | if (amount > lockedCollateral.quote) {
amount = lockedCollateral.quote;
}
| if (amount > lockedCollateral.quote) {
amount = lockedCollateral.quote;
}
| 9,674 |
31 | // Returns the contenthash associated with an ENS node. node The ENS node to query.return The associated contenthash. / | function contenthash(bytes32 node) external view returns (bytes memory) {
return hashes[node];
}
| function contenthash(bytes32 node) external view returns (bytes memory) {
return hashes[node];
}
| 11,930 |
29 | // if function does not exist then do nothing and return | require(_facetAddress == address(0), "LibDiamondCut: Remove facet address must be address(0)");
uint256 len = _functionSelectors.length;
for (uint256 selectorIndex; selectorIndex < len; ) {
bytes4 selector = _functionSelectors[selectorIndex];
require(selector != proposeSelector && selector != cutSelector, "LibDiamondCut: Cannot remove cut selectors");
address oldFacetAddress = ds.selectorToFacetAndPosition[selector].facetAddress;
removeFunction(ds, oldFacetAddress, selector);
unchecked {
++selectorIndex;
| require(_facetAddress == address(0), "LibDiamondCut: Remove facet address must be address(0)");
uint256 len = _functionSelectors.length;
for (uint256 selectorIndex; selectorIndex < len; ) {
bytes4 selector = _functionSelectors[selectorIndex];
require(selector != proposeSelector && selector != cutSelector, "LibDiamondCut: Cannot remove cut selectors");
address oldFacetAddress = ds.selectorToFacetAndPosition[selector].facetAddress;
removeFunction(ds, oldFacetAddress, selector);
unchecked {
++selectorIndex;
| 30,086 |
8 | // Check if passed amount is not zero Check for the pass of a non zero variable. amountnumber checked to be a non zero. / | modifier nonzeroAmount(uint256 amount) {
require(amount > 0, "STRFStaker: Amount cannot be 0");
_;
}
| modifier nonzeroAmount(uint256 amount) {
require(amount > 0, "STRFStaker: Amount cannot be 0");
_;
}
| 2,707 |
60 | // Gets the index of the account Returns -1 for missing accountsaddr The address of the account to get the index for return The index of the given account address / | function accountIndexOf(address addr)
external
view
| function accountIndexOf(address addr)
external
view
| 30,878 |
5 | // Draw collateral to repay the flash loan | drawCollateral(managerAddr, _saverData.safeId, _saverData.joinAddr, _saverData.flAmount, false);
logger.Log(address(this), msg.sender, "RAIFlashBoost", abi.encode(_saverData.safeId, user, _exchangeData.srcAmount, swapedAmount));
| drawCollateral(managerAddr, _saverData.safeId, _saverData.joinAddr, _saverData.flAmount, false);
logger.Log(address(this), msg.sender, "RAIFlashBoost", abi.encode(_saverData.safeId, user, _exchangeData.srcAmount, swapedAmount));
| 16,176 |
5 | // Get the underlying price of a jToken asset jToken The jToken to get the underlying price ofreturn The underlying asset price mantissa (scaled by 1e18). Zero means the price is unavailable. / | function getUnderlyingPrice(address jToken) external view returns (uint256);
| function getUnderlyingPrice(address jToken) external view returns (uint256);
| 25,024 |
55 | // Gets COIN balance of the handler in the safeEngine | uint coin = SAFEEngineLike(safeEngine).coinBalance(safeHandler);
| uint coin = SAFEEngineLike(safeEngine).coinBalance(safeHandler);
| 32,280 |
74 | // Modify the deviation from scale | function changeDeviationFromScale(uint256 num) public onlyOwner {
_deviationFromScale = num;
}
| function changeDeviationFromScale(uint256 num) public onlyOwner {
_deviationFromScale = num;
}
| 10,694 |
77 | // Query if a contract implements an interface _interfaceIDThe interface identifier, as specified in ERC-165return `true` if the contract implements `_interfaceID` and / | function supportsInterface(bytes4 _interfaceID)
external
view
returns (bool)
| function supportsInterface(bytes4 _interfaceID)
external
view
returns (bool)
| 28,745 |
140 | // transfer remaining tokens to the account | if (balanceOf(account, pool) > 0) {
_rescuePoints(account, pool);
}
| if (balanceOf(account, pool) > 0) {
_rescuePoints(account, pool);
}
| 66,191 |
125 | // remaining gu per total ethIn in the phrase | uint256 _gpe = (_remainGu.mul(1e18)) / phrase_[_phID].eth;
phrase_[_phID].mask = _gpe.add(phrase_[_phID].mask); // should only added once
| uint256 _gpe = (_remainGu.mul(1e18)) / phrase_[_phID].eth;
phrase_[_phID].mask = _gpe.add(phrase_[_phID].mask); // should only added once
| 8,563 |
154 | // Checks to see if request was made and if time elapsed | if(isAttached > 1 && block.timestamp - isAttached > detachmentTime) {
isAttached = 0;
} else if(isAttached > 1) {
| if(isAttached > 1 && block.timestamp - isAttached > detachmentTime) {
isAttached = 0;
} else if(isAttached > 1) {
| 50,875 |
21 | // Changes All Presale Roots / | function __ChangePresaleRootsAll (
uint SaleIndex,
bytes32 RootEligibilityFullSet,
bytes32 RootAmountsFullSet,
bytes32 RootEligibilityCitizen,
bytes32 RootAmountsCitizen
| function __ChangePresaleRootsAll (
uint SaleIndex,
bytes32 RootEligibilityFullSet,
bytes32 RootAmountsFullSet,
bytes32 RootEligibilityCitizen,
bytes32 RootAmountsCitizen
| 36,268 |
22 | // mint DSD | mintToAccount(msg.sender, amount);
addRedeemedThisExpansion(msg.sender, amount);
incrementTotalCDSDRedeemed(amount);
emit CDSDRedeemed(msg.sender, amount);
| mintToAccount(msg.sender, amount);
addRedeemedThisExpansion(msg.sender, amount);
incrementTotalCDSDRedeemed(amount);
emit CDSDRedeemed(msg.sender, amount);
| 168 |
20 | // footer functions | function transferAnyERC20Token(address tokenAddress, uint256 tokens) public returns (bool success) {
require(isOwner());
return IERC20(tokenAddress).transfer(owner(), tokens);
}
| function transferAnyERC20Token(address tokenAddress, uint256 tokens) public returns (bool success) {
require(isOwner());
return IERC20(tokenAddress).transfer(owner(), tokens);
}
| 7,723 |
291 | // Changes extra lock period for a cover, post its expiry. / | function _setLockTokenTimeAfterCoverExp(uint time) internal {
lockTokenTimeAfterCoverExp = time;
}
| function _setLockTokenTimeAfterCoverExp(uint time) internal {
lockTokenTimeAfterCoverExp = time;
}
| 28,555 |
10 | // For the quarter in which the stake was locked, we reduce the share amount to reflect the part of the quarter that has already passed. Note that this only happens when quarterIdx == currentQuarter. | if (quarterIdx == stake.lockQuarter) {
newShare = newShare * (nextQuarterStart - stake.lockTime) / QUARTER_LENGTH;
}
| if (quarterIdx == stake.lockQuarter) {
newShare = newShare * (nextQuarterStart - stake.lockTime) / QUARTER_LENGTH;
}
| 2,705 |
185 | // getter for recipients & their shares/ return recipients the recipients/ return shares their shares | function getSplit()
public
view
returns (address[] memory recipients, uint256[] memory shares)
| function getSplit()
public
view
returns (address[] memory recipients, uint256[] memory shares)
| 26,823 |
11 | // Add liquidity to pool position/manager must be approved for token A/B transfer/poolPosition PP to add liquidity to/recipient address where PoolPosition erc20 LP tokens are sent/desiredLpTokenAmount number of erc20 PP LP tokens to mint/minLpTokenAmount miniumum number of erc20 PP LP tokens to mint/addLimits struct of max token amounts, deadline and whether tostake new pool position in reward contract | function addLiquidityToPoolPosition(
IPoolPositionSlim poolPosition,
address recipient,
uint256 desiredLpTokenAmount,
uint256 minLpTokenAmount,
AddLimits calldata addLimits
) external payable returns (uint256 mintedPoolPositionTokenAmount, uint256 tokenAAmount, uint256 tokenBAmount);
| function addLiquidityToPoolPosition(
IPoolPositionSlim poolPosition,
address recipient,
uint256 desiredLpTokenAmount,
uint256 minLpTokenAmount,
AddLimits calldata addLimits
) external payable returns (uint256 mintedPoolPositionTokenAmount, uint256 tokenAAmount, uint256 tokenBAmount);
| 6,972 |
12 | // Add multiple itemsAll for same priceThis saves sending 10 tickets to create 10 items. | function AddMultipleItems(uint256 price, uint8 howmuch) public {
require(msg.sender == owner);
require(price != 0);
require(howmuch != 255); // this is to prevent an infinite for loop
uint8 i=0;
for (i; i<howmuch; i++){
AddItem(price);
}
}
| function AddMultipleItems(uint256 price, uint8 howmuch) public {
require(msg.sender == owner);
require(price != 0);
require(howmuch != 255); // this is to prevent an infinite for loop
uint8 i=0;
for (i; i<howmuch; i++){
AddItem(price);
}
}
| 23,149 |
54 | // Mapping from Nifty type to IPFS hash of canonical artifcat file. | mapping(uint256 => string) private _niftyTypeIPFSHashes;
| mapping(uint256 => string) private _niftyTypeIPFSHashes;
| 15,962 |
131 | // The contract which interfaces with the exchange | OptionsExchange public optionsExchange;
address public oracleAddress;
event OptionsContractCreated(address addr);
event AssetWhitelisted(address indexed asset);
| OptionsExchange public optionsExchange;
address public oracleAddress;
event OptionsContractCreated(address addr);
event AssetWhitelisted(address indexed asset);
| 51,269 |
18 | // chainId Chain's id/maxLength OneFork max length | function initialize(
mapping(bytes32 => Info) storage self,
uint256 chainId,
uint256 maxLength
| function initialize(
mapping(bytes32 => Info) storage self,
uint256 chainId,
uint256 maxLength
| 47,959 |
99 | // third term | work_point = proof.T3;
work_point.validateG1Point();
assembly {
scalar_multiplier := mulmod(scalar_multiplier, scalar_multiplier, p)
mstore(add(accumulator_ptr, 0x40), mload(work_point))
mstore(add(accumulator_ptr, 0x60), mload(add(work_point, 0x20)))
mstore(add(accumulator_ptr, 0x80), scalar_multiplier)
| work_point = proof.T3;
work_point.validateG1Point();
assembly {
scalar_multiplier := mulmod(scalar_multiplier, scalar_multiplier, p)
mstore(add(accumulator_ptr, 0x40), mload(work_point))
mstore(add(accumulator_ptr, 0x60), mload(add(work_point, 0x20)))
mstore(add(accumulator_ptr, 0x80), scalar_multiplier)
| 59,049 |
0 | // IFantomMintCore defines the interface of the Fantom fMint core contract. | interface IFantomMintBalanceGuard {
// rewardCanClaim checks if the account can claim accumulated rewards.
function rewardCanClaim(address _account) external view returns (bool);
// rewardIsEligible checks if the account is eligible to receive any reward.
function rewardIsEligible(address _account) external view returns (bool);
// collateralCanDecrease checks if the specified amount of collateral can be removed from account
// without breaking collateral to debt ratio rule.
function collateralCanDecrease(address _account, address _token, uint256 _amount) external view returns (bool);
// debtCanIncrease checks if the specified amount of debt can be added to the account
// without breaking collateral to debt ratio rule.
function debtCanIncrease(address _account, address _token, uint256 _amount) external view returns (bool);
}
| interface IFantomMintBalanceGuard {
// rewardCanClaim checks if the account can claim accumulated rewards.
function rewardCanClaim(address _account) external view returns (bool);
// rewardIsEligible checks if the account is eligible to receive any reward.
function rewardIsEligible(address _account) external view returns (bool);
// collateralCanDecrease checks if the specified amount of collateral can be removed from account
// without breaking collateral to debt ratio rule.
function collateralCanDecrease(address _account, address _token, uint256 _amount) external view returns (bool);
// debtCanIncrease checks if the specified amount of debt can be added to the account
// without breaking collateral to debt ratio rule.
function debtCanIncrease(address _account, address _token, uint256 _amount) external view returns (bool);
}
| 34,241 |
363 | // Admin Functions // Sets a new price oracle for the comptroller Admin function to set a new price oraclereturn uint 0=success, otherwise a failure (see ErrorReporter.sol for details) / | function _setPriceOracle(PriceOracle newOracle) public returns (uint256) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PRICE_ORACLE_OWNER_CHECK);
}
// Track the old oracle for the comptroller
PriceOracle oldOracle = oracle;
// Set comptroller's oracle to newOracle
oracle = newOracle;
// Emit NewPriceOracle(oldOracle, newOracle)
emit NewPriceOracle(oldOracle, newOracle);
return uint256(Error.NO_ERROR);
}
| function _setPriceOracle(PriceOracle newOracle) public returns (uint256) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PRICE_ORACLE_OWNER_CHECK);
}
// Track the old oracle for the comptroller
PriceOracle oldOracle = oracle;
// Set comptroller's oracle to newOracle
oracle = newOracle;
// Emit NewPriceOracle(oldOracle, newOracle)
emit NewPriceOracle(oldOracle, newOracle);
return uint256(Error.NO_ERROR);
}
| 71,951 |
549 | // fee related | uint256[] public feeLevel; // fixed length = 9 (unit without 10^18); [50,200,500,1000,2000,3500,6000,9000,11000]
uint256[] public discountTable; // fixed length = 9; [9,19,28,40,50,60,70,80,90]
uint256 public vaultFee; // divided by 10000
constructor(
IMintableERC20 _token,
IMintableERC20 _xtoken,
IVotingEscrow _votingEscrow,
address _governance,
address _sentinel,
| uint256[] public feeLevel; // fixed length = 9 (unit without 10^18); [50,200,500,1000,2000,3500,6000,9000,11000]
uint256[] public discountTable; // fixed length = 9; [9,19,28,40,50,60,70,80,90]
uint256 public vaultFee; // divided by 10000
constructor(
IMintableERC20 _token,
IMintableERC20 _xtoken,
IVotingEscrow _votingEscrow,
address _governance,
address _sentinel,
| 59,426 |
45 | // for managing the Raum Public and Private Sale / | contract RaumSale {
using SafeMath for uint256;
struct vault {
uint256 privateSalebalance;
uint256 privateSaleWithdrawDate;
uint256 publicSalebalance1;
uint256 publicSaleWithdrawDate1;
uint256 publicSalebalance2;
uint256 publicSaleWithdrawDate2;
}
mapping(address => vault) public saleBalances;
address payable admin;
address RNTokens;
uint256 rnTokenPerMatic;
bool isPublicSale1 = false;
bool isPublicSale2 = false;
event print(uint256 amount);
/**
* @dev Sets the values for {admin}, {RNTokens}, {startSaleBlock} and {price}.
*
*
*/
constructor(address _RNAddress,uint256 _rnTokenPerMatic) {
admin = payable(msg.sender);
RNTokens = _RNAddress;
rnTokenPerMatic = _rnTokenPerMatic;
}
/**
* @dev Set the Updated price for public and private sale.
*/
function setrnTokenPerMatic(uint256 _rnTokenPerMatic) public {
require ( msg.sender == admin, "Only admin callable function");
rnTokenPerMatic = _rnTokenPerMatic;
}
/**
* @dev Set the close the public sale 1
*/
function changePublicSale1(bool _start) public {
require ( msg.sender == admin, "Only admin callable function");
isPublicSale1 = _start;
}
/**
* @dev Set the close the public sale 2
*/
function changePublicSale2(bool _start) public {
require ( msg.sender == admin, "Only admin callable function");
isPublicSale2 = _start;
}
/**
* @dev Allows account to Book Tokens and lock them for 12 months
*/
function privateSale(uint256 rnTokens, address investor) public {
require ( msg.sender == admin, "Only admin callable function");
saleBalances[investor].privateSalebalance = saleBalances[msg.sender].privateSalebalance.add(rnTokens);
saleBalances[investor].privateSaleWithdrawDate = block.timestamp + 360 days;
}
/**
* @dev Allows account to Book Tokens and lock them for 8 months
*/
function publicSale1() public payable {
require( isPublicSale1==true, "Public Sale 1 is closed");
require( msg.value>=50*(10**18) && msg.value<=7500*(10**18), "You can buy a minimum of tokens worth 50 Matic and maximum of 7500 Matic" );
uint256 noOfTokens = rnTokenPerMatic*(msg.value);
saleBalances[msg.sender].publicSalebalance1 = saleBalances[msg.sender].publicSalebalance1.add(noOfTokens);
saleBalances[msg.sender].publicSaleWithdrawDate1 = block.timestamp + 240 days;
}
/**
* @dev Allows account to Book Tokens and lock them for 6 months
*/
function publicSale2() public payable {
require( isPublicSale2==true, "Public Sale 2 is closed");
require( msg.value>=50*(10**18) && msg.value<=7500*(10**18), "You can buy a minimum of tokens worth 50 Matic and maximum of 7500 Matic" );
uint256 noOfTokens = rnTokenPerMatic*(msg.value);
saleBalances[msg.sender].publicSalebalance2 = saleBalances[msg.sender].publicSalebalance2.add(noOfTokens);
saleBalances[msg.sender].publicSaleWithdrawDate2 = block.timestamp + 180 days;
}
/**
* @dev Allows account to withdraw the Public sale 1 tokens
*/
function withdrawPublicSale1() public {
require( block.timestamp >= saleBalances[msg.sender].publicSaleWithdrawDate1, "Yorn RN Tokens are still locked" );
IERC20(RNTokens).transfer(msg.sender, saleBalances[msg.sender].publicSalebalance1);
saleBalances[msg.sender].publicSalebalance1 = 0;
}
/**
* @dev Allows account to withdraw the Public sale 2 tokens
*/
function withdrawPublicSale2() public {
require( block.timestamp >= saleBalances[msg.sender].publicSaleWithdrawDate2, "Yorn RN Tokens are still locked" );
IERC20(RNTokens).transfer(msg.sender, saleBalances[msg.sender].publicSalebalance2);
saleBalances[msg.sender].publicSalebalance2 = 0;
}
/**
* @dev Allows account to withdraw the Private token sale
*/
function withdrawPrivateSale() public {
require( block.timestamp >= saleBalances[msg.sender].privateSaleWithdrawDate, "Yorn RN Tokens are still locked" );
IERC20(RNTokens).transfer(msg.sender, saleBalances[msg.sender].privateSalebalance);
saleBalances[msg.sender].privateSalebalance = 0;
}
/**
* @dev Returnnumber of RN Tokens in this contract
*/
function getRNBalance() public view returns (uint) {
return IERC20(RNTokens).balanceOf(address(this));
}
/**
* @dev Returnnumber of MATIC Tokens in this contract
*/
function getMaticBalance() public view returns (uint) {
return address(this).balance;
}
/**
* @dev allows admin to withdraw MATIC Tokens.
*/
function withdrawMatic() public {
require ( msg.sender == admin, "Only admin callable function");
admin.transfer(getMaticBalance());
}
/**
* @dev allows admin to withdraw RN Tokens.
*/
function withdrawRN() public {
require ( msg.sender == admin, "Only admin callable function");
IERC20(RNTokens).transfer(admin, getRNBalance());
}
}
| contract RaumSale {
using SafeMath for uint256;
struct vault {
uint256 privateSalebalance;
uint256 privateSaleWithdrawDate;
uint256 publicSalebalance1;
uint256 publicSaleWithdrawDate1;
uint256 publicSalebalance2;
uint256 publicSaleWithdrawDate2;
}
mapping(address => vault) public saleBalances;
address payable admin;
address RNTokens;
uint256 rnTokenPerMatic;
bool isPublicSale1 = false;
bool isPublicSale2 = false;
event print(uint256 amount);
/**
* @dev Sets the values for {admin}, {RNTokens}, {startSaleBlock} and {price}.
*
*
*/
constructor(address _RNAddress,uint256 _rnTokenPerMatic) {
admin = payable(msg.sender);
RNTokens = _RNAddress;
rnTokenPerMatic = _rnTokenPerMatic;
}
/**
* @dev Set the Updated price for public and private sale.
*/
function setrnTokenPerMatic(uint256 _rnTokenPerMatic) public {
require ( msg.sender == admin, "Only admin callable function");
rnTokenPerMatic = _rnTokenPerMatic;
}
/**
* @dev Set the close the public sale 1
*/
function changePublicSale1(bool _start) public {
require ( msg.sender == admin, "Only admin callable function");
isPublicSale1 = _start;
}
/**
* @dev Set the close the public sale 2
*/
function changePublicSale2(bool _start) public {
require ( msg.sender == admin, "Only admin callable function");
isPublicSale2 = _start;
}
/**
* @dev Allows account to Book Tokens and lock them for 12 months
*/
function privateSale(uint256 rnTokens, address investor) public {
require ( msg.sender == admin, "Only admin callable function");
saleBalances[investor].privateSalebalance = saleBalances[msg.sender].privateSalebalance.add(rnTokens);
saleBalances[investor].privateSaleWithdrawDate = block.timestamp + 360 days;
}
/**
* @dev Allows account to Book Tokens and lock them for 8 months
*/
function publicSale1() public payable {
require( isPublicSale1==true, "Public Sale 1 is closed");
require( msg.value>=50*(10**18) && msg.value<=7500*(10**18), "You can buy a minimum of tokens worth 50 Matic and maximum of 7500 Matic" );
uint256 noOfTokens = rnTokenPerMatic*(msg.value);
saleBalances[msg.sender].publicSalebalance1 = saleBalances[msg.sender].publicSalebalance1.add(noOfTokens);
saleBalances[msg.sender].publicSaleWithdrawDate1 = block.timestamp + 240 days;
}
/**
* @dev Allows account to Book Tokens and lock them for 6 months
*/
function publicSale2() public payable {
require( isPublicSale2==true, "Public Sale 2 is closed");
require( msg.value>=50*(10**18) && msg.value<=7500*(10**18), "You can buy a minimum of tokens worth 50 Matic and maximum of 7500 Matic" );
uint256 noOfTokens = rnTokenPerMatic*(msg.value);
saleBalances[msg.sender].publicSalebalance2 = saleBalances[msg.sender].publicSalebalance2.add(noOfTokens);
saleBalances[msg.sender].publicSaleWithdrawDate2 = block.timestamp + 180 days;
}
/**
* @dev Allows account to withdraw the Public sale 1 tokens
*/
function withdrawPublicSale1() public {
require( block.timestamp >= saleBalances[msg.sender].publicSaleWithdrawDate1, "Yorn RN Tokens are still locked" );
IERC20(RNTokens).transfer(msg.sender, saleBalances[msg.sender].publicSalebalance1);
saleBalances[msg.sender].publicSalebalance1 = 0;
}
/**
* @dev Allows account to withdraw the Public sale 2 tokens
*/
function withdrawPublicSale2() public {
require( block.timestamp >= saleBalances[msg.sender].publicSaleWithdrawDate2, "Yorn RN Tokens are still locked" );
IERC20(RNTokens).transfer(msg.sender, saleBalances[msg.sender].publicSalebalance2);
saleBalances[msg.sender].publicSalebalance2 = 0;
}
/**
* @dev Allows account to withdraw the Private token sale
*/
function withdrawPrivateSale() public {
require( block.timestamp >= saleBalances[msg.sender].privateSaleWithdrawDate, "Yorn RN Tokens are still locked" );
IERC20(RNTokens).transfer(msg.sender, saleBalances[msg.sender].privateSalebalance);
saleBalances[msg.sender].privateSalebalance = 0;
}
/**
* @dev Returnnumber of RN Tokens in this contract
*/
function getRNBalance() public view returns (uint) {
return IERC20(RNTokens).balanceOf(address(this));
}
/**
* @dev Returnnumber of MATIC Tokens in this contract
*/
function getMaticBalance() public view returns (uint) {
return address(this).balance;
}
/**
* @dev allows admin to withdraw MATIC Tokens.
*/
function withdrawMatic() public {
require ( msg.sender == admin, "Only admin callable function");
admin.transfer(getMaticBalance());
}
/**
* @dev allows admin to withdraw RN Tokens.
*/
function withdrawRN() public {
require ( msg.sender == admin, "Only admin callable function");
IERC20(RNTokens).transfer(admin, getRNBalance());
}
}
| 43,779 |
3 | // Transfer | function tokenTransfer(
address _sender,
address _receiver,
int64 _amount
| function tokenTransfer(
address _sender,
address _receiver,
int64 _amount
| 30,636 |
3,894 | // 1948 | entry "multiforked" : ENG_ADJECTIVE
| entry "multiforked" : ENG_ADJECTIVE
| 18,560 |
120 | // A. If number of users for this _bracket number is superior to 0 | if (
(_numberTicketsPerLotteryId[_lotteryId][transformedWinningNumber] - numberAddressesInPreviousBracket) !=
0
) {
| if (
(_numberTicketsPerLotteryId[_lotteryId][transformedWinningNumber] - numberAddressesInPreviousBracket) !=
0
) {
| 53,498 |
6 | // This error is thrown whenever a zero address is passed | error ZeroAddress();
| error ZeroAddress();
| 20,225 |
7 | // the last one is emitted if the required signatures change | event RequirementChanged(uint newRequirement);
| event RequirementChanged(uint newRequirement);
| 34,160 |
5 | // Return the DEX pool and the amount of LP tokens / | function getVaultInfo(uint256 _vaultId)
external
view
override
returns (IERC20, uint256)
| function getVaultInfo(uint256 _vaultId)
external
view
override
returns (IERC20, uint256)
| 18,271 |
48 | // ==== Token Binding Functions ==== // A public function for the tokenBinder entity to call. token_ The address of the token to bind to the pool. balance The quantity of the token to deposit into the pool. denorm The denormalized weight of the token in the pool. / | function bind(
address token_,
uint256 balance,
uint256 denorm
| function bind(
address token_,
uint256 balance,
uint256 denorm
| 40,093 |
17 | // Check that the code was actually deployed correctly. I'm not sure if you can ever actually fail this check. Should only happen if the contract creation from above runs out of gas but this parent execution thread does NOT run out of gas. Seems like we should be doing this check anyway though. | require(
_getAccountCodeHash(newImplementation) == keccak256(_code),
"L1ChugSplashProxy: code was not correctly deployed."
);
_setImplementation(newImplementation);
| require(
_getAccountCodeHash(newImplementation) == keccak256(_code),
"L1ChugSplashProxy: code was not correctly deployed."
);
_setImplementation(newImplementation);
| 28,773 |
77 | // check that the owner can pay interest before trying to pay | if (asset.allowance(getOwner(), address(this)) >= _interest && asset.balanceOf(getOwner()) >= _interest) {
require(asset.transferFrom(getOwner(), msg.sender, _interest));
} else {
| if (asset.allowance(getOwner(), address(this)) >= _interest && asset.balanceOf(getOwner()) >= _interest) {
require(asset.transferFrom(getOwner(), msg.sender, _interest));
} else {
| 13,668 |
15 | // ETH receive callback / | receive() external payable {}
/**
* @dev returns the burn reward percentage and its maximum amount
*/
function burnReward() external view returns (uint32, uint256) {
return (_burnReward, _maxBurnRewardAmount);
}
| receive() external payable {}
/**
* @dev returns the burn reward percentage and its maximum amount
*/
function burnReward() external view returns (uint32, uint256) {
return (_burnReward, _maxBurnRewardAmount);
}
| 22,280 |
189 | // Do nothing if we call this when there is no update plan | if (gradualUpdate.startBlock == 0) {
return;
}
| if (gradualUpdate.startBlock == 0) {
return;
}
| 40,310 |
68 | // pragma solidity 0.6.12; // pragma experimental ABIEncoderV2; // import "dss-exec-lib/DssExec.sol"; // import "dss-exec-lib/DssAction.sol"; / | contract DssSpellAction is DssAction {
uint256 constant MILLION = 10**6;
// Provides a descriptive tag for bot consumption
// This should be modified weekly to provide a summary of the actions
// Hash: seth keccak -- "$(wget https://raw.githubusercontent.com/makerdao/community/287beee2bb76636b8b9e02c7e698fa639cb6b859/governance/votes/Executive%20vote%20-%20October%2022%2C%202021.md -q -O - 2>/dev/null)"
string public constant override description =
"2021-10-22 MakerDAO Executive Spell | Hash: 0x1980e67884fc3b449708d14f67d095b612118e9fb183de4b107f37c0bc8499aa";
// Many of the settings that change weekly rely on the rate accumulator
// described at https://docs.makerdao.com/smart-contract-modules/rates-module
// To check this yourself, use the following rate calculation (example 8%):
//
// $ bc -l <<< 'scale=27; e( l(1.08)/(60 * 60 * 24 * 365) )'
//
// A table of rates can be found at
// https://ipfs.io/ipfs/QmefQMseb3AiTapiAKKexdKHig8wroKuZbmLtPLv4u2YwW
//
uint256 constant FOUR_PCT_RATE = 1000000001243680656318820312;
address public constant STETH_GEM = 0xae7ab96520DE3A18E5e111B5EaAb095312D7fE84;
address public constant WSTETH_GEM = 0x7f39C581F595B53c5cb19bD0b3f8dA6c935E2Ca0;
address public constant MCD_JOIN_WSTETH_A = 0x10CD5fbe1b404B7E19Ef964B63939907bdaf42E2;
address public constant MCD_CLIP_WSTETH_A = 0x49A33A28C4C7D9576ab28898F4C9ac7e52EA457A;
address public constant MCD_CLIP_CALC_WSTETH_A = 0x15282b886675cc1Ce04590148f456428E87eaf13;
address public constant PIP_WSTETH = 0xFe7a2aC0B945f12089aEEB6eCebf4F384D9f043F;
function actions() public override {
// Increase the GUNIV3DAIUSDC1-A Debt Ceiling - October 11, 2021
// https://vote.makerdao.com/polling/QmU6fTQx?network=mainnet#poll-detail
DssExecLib.setIlkAutoLineParameters("GUNIV3DAIUSDC1-A", 50 * MILLION, 10 * MILLION, 8 hours);
// Parameter Changes Proposal - MakerDAO Open Market Committee - October 18, 2021
// https://vote.makerdao.com/polling/QmP6GPeK?network=mainnet#poll-detail
DssExecLib.setIlkAutoLineParameters("ETH-A", 15_000 * MILLION, 150 * MILLION, 6 hours);
DssExecLib.setIlkAutoLineParameters("ETH-B", 500 * MILLION, 20 * MILLION, 6 hours);
DssExecLib.setIlkAutoLineParameters("WBTC-A", 1_500 * MILLION, 60 * MILLION, 6 hours);
// Add stETH (Lido Staked ETH) as a new Vault Type - October 11, 2021
// https://vote.makerdao.com/polling/QmXXHpYi?network=mainnet#poll-detail
// https://forum.makerdao.com/t/steth-collateral-onboarding-risk-evaluation/9061
CollateralOpts memory WSTETH_A = CollateralOpts({
ilk: "WSTETH-A",
gem: WSTETH_GEM,
join: MCD_JOIN_WSTETH_A,
clip: MCD_CLIP_WSTETH_A,
calc: MCD_CLIP_CALC_WSTETH_A,
pip: PIP_WSTETH,
isLiquidatable: true,
isOSM: true,
whitelistOSM: true,
ilkDebtCeiling: 3 * MILLION, // Start at 3mm, DCIAM sets to 5mm
minVaultAmount: 10000,
maxLiquidationAmount: 3 * MILLION,
liquidationPenalty: 1300, // 13% penalty fee
ilkStabilityFee: FOUR_PCT_RATE,
startingPriceFactor: 13000, // Auction price begins at 130% of oracle
breakerTolerance: 5000, // Allows for a 50% hourly price drop before disabling liquidations
auctionDuration: 140 minutes,
permittedDrop: 4000, // 40% price drop before reset
liquidationRatio: 16000, // 160% collateralization
kprFlatReward: 300, // 300 Dai
kprPctReward: 10 // 0.1%
});
DssExecLib.addNewCollateral(WSTETH_A);
DssExecLib.setStairstepExponentialDecrease(MCD_CLIP_CALC_WSTETH_A, 90 seconds, 9900);
DssExecLib.setIlkAutoLineParameters("WSTETH-A", 5 * MILLION, 3 * MILLION, 8 hours);
DssExecLib.setChangelogAddress("STETH", STETH_GEM);
DssExecLib.setChangelogAddress("WSTETH", WSTETH_GEM);
DssExecLib.setChangelogAddress("PIP_WSTETH", PIP_WSTETH);
DssExecLib.setChangelogAddress("MCD_JOIN_WSTETH_A", MCD_JOIN_WSTETH_A);
DssExecLib.setChangelogAddress("MCD_CLIP_WSTETH_A", MCD_CLIP_WSTETH_A);
DssExecLib.setChangelogAddress("MCD_CLIP_CALC_WSTETH_A", MCD_CLIP_CALC_WSTETH_A);
// bump changelog version
DssExecLib.setChangelogVersion("1.9.8");
}
}
| contract DssSpellAction is DssAction {
uint256 constant MILLION = 10**6;
// Provides a descriptive tag for bot consumption
// This should be modified weekly to provide a summary of the actions
// Hash: seth keccak -- "$(wget https://raw.githubusercontent.com/makerdao/community/287beee2bb76636b8b9e02c7e698fa639cb6b859/governance/votes/Executive%20vote%20-%20October%2022%2C%202021.md -q -O - 2>/dev/null)"
string public constant override description =
"2021-10-22 MakerDAO Executive Spell | Hash: 0x1980e67884fc3b449708d14f67d095b612118e9fb183de4b107f37c0bc8499aa";
// Many of the settings that change weekly rely on the rate accumulator
// described at https://docs.makerdao.com/smart-contract-modules/rates-module
// To check this yourself, use the following rate calculation (example 8%):
//
// $ bc -l <<< 'scale=27; e( l(1.08)/(60 * 60 * 24 * 365) )'
//
// A table of rates can be found at
// https://ipfs.io/ipfs/QmefQMseb3AiTapiAKKexdKHig8wroKuZbmLtPLv4u2YwW
//
uint256 constant FOUR_PCT_RATE = 1000000001243680656318820312;
address public constant STETH_GEM = 0xae7ab96520DE3A18E5e111B5EaAb095312D7fE84;
address public constant WSTETH_GEM = 0x7f39C581F595B53c5cb19bD0b3f8dA6c935E2Ca0;
address public constant MCD_JOIN_WSTETH_A = 0x10CD5fbe1b404B7E19Ef964B63939907bdaf42E2;
address public constant MCD_CLIP_WSTETH_A = 0x49A33A28C4C7D9576ab28898F4C9ac7e52EA457A;
address public constant MCD_CLIP_CALC_WSTETH_A = 0x15282b886675cc1Ce04590148f456428E87eaf13;
address public constant PIP_WSTETH = 0xFe7a2aC0B945f12089aEEB6eCebf4F384D9f043F;
function actions() public override {
// Increase the GUNIV3DAIUSDC1-A Debt Ceiling - October 11, 2021
// https://vote.makerdao.com/polling/QmU6fTQx?network=mainnet#poll-detail
DssExecLib.setIlkAutoLineParameters("GUNIV3DAIUSDC1-A", 50 * MILLION, 10 * MILLION, 8 hours);
// Parameter Changes Proposal - MakerDAO Open Market Committee - October 18, 2021
// https://vote.makerdao.com/polling/QmP6GPeK?network=mainnet#poll-detail
DssExecLib.setIlkAutoLineParameters("ETH-A", 15_000 * MILLION, 150 * MILLION, 6 hours);
DssExecLib.setIlkAutoLineParameters("ETH-B", 500 * MILLION, 20 * MILLION, 6 hours);
DssExecLib.setIlkAutoLineParameters("WBTC-A", 1_500 * MILLION, 60 * MILLION, 6 hours);
// Add stETH (Lido Staked ETH) as a new Vault Type - October 11, 2021
// https://vote.makerdao.com/polling/QmXXHpYi?network=mainnet#poll-detail
// https://forum.makerdao.com/t/steth-collateral-onboarding-risk-evaluation/9061
CollateralOpts memory WSTETH_A = CollateralOpts({
ilk: "WSTETH-A",
gem: WSTETH_GEM,
join: MCD_JOIN_WSTETH_A,
clip: MCD_CLIP_WSTETH_A,
calc: MCD_CLIP_CALC_WSTETH_A,
pip: PIP_WSTETH,
isLiquidatable: true,
isOSM: true,
whitelistOSM: true,
ilkDebtCeiling: 3 * MILLION, // Start at 3mm, DCIAM sets to 5mm
minVaultAmount: 10000,
maxLiquidationAmount: 3 * MILLION,
liquidationPenalty: 1300, // 13% penalty fee
ilkStabilityFee: FOUR_PCT_RATE,
startingPriceFactor: 13000, // Auction price begins at 130% of oracle
breakerTolerance: 5000, // Allows for a 50% hourly price drop before disabling liquidations
auctionDuration: 140 minutes,
permittedDrop: 4000, // 40% price drop before reset
liquidationRatio: 16000, // 160% collateralization
kprFlatReward: 300, // 300 Dai
kprPctReward: 10 // 0.1%
});
DssExecLib.addNewCollateral(WSTETH_A);
DssExecLib.setStairstepExponentialDecrease(MCD_CLIP_CALC_WSTETH_A, 90 seconds, 9900);
DssExecLib.setIlkAutoLineParameters("WSTETH-A", 5 * MILLION, 3 * MILLION, 8 hours);
DssExecLib.setChangelogAddress("STETH", STETH_GEM);
DssExecLib.setChangelogAddress("WSTETH", WSTETH_GEM);
DssExecLib.setChangelogAddress("PIP_WSTETH", PIP_WSTETH);
DssExecLib.setChangelogAddress("MCD_JOIN_WSTETH_A", MCD_JOIN_WSTETH_A);
DssExecLib.setChangelogAddress("MCD_CLIP_WSTETH_A", MCD_CLIP_WSTETH_A);
DssExecLib.setChangelogAddress("MCD_CLIP_CALC_WSTETH_A", MCD_CLIP_CALC_WSTETH_A);
// bump changelog version
DssExecLib.setChangelogVersion("1.9.8");
}
}
| 42,272 |
80 | // Throw an exception if called by any account other than the heir's. / | modifier onlyHeir() {
require(msg.sender == heir_);
_;
}
| modifier onlyHeir() {
require(msg.sender == heir_);
_;
}
| 4,537 |
216 | // State transitions for names: Open -> Auction (startAuction) Auction -> Reveal Reveal -> Owned Reveal -> Open (if nobody bid) Owned -> Open (releaseDeed or invalidateName) | function state(bytes32 _hash) public view returns (Mode) {
Entry storage entry = _entries[_hash];
if (!isAllowed(_hash, now)) {
return Mode.NotYetAvailable;
} else if (now < entry.registrationDate) {
if (now < entry.registrationDate - revealPeriod) {
return Mode.Auction;
} else {
return Mode.Reveal;
}
} else {
if (entry.highestBid == 0) {
return Mode.Open;
} else {
return Mode.Owned;
}
}
}
| function state(bytes32 _hash) public view returns (Mode) {
Entry storage entry = _entries[_hash];
if (!isAllowed(_hash, now)) {
return Mode.NotYetAvailable;
} else if (now < entry.registrationDate) {
if (now < entry.registrationDate - revealPeriod) {
return Mode.Auction;
} else {
return Mode.Reveal;
}
} else {
if (entry.highestBid == 0) {
return Mode.Open;
} else {
return Mode.Owned;
}
}
}
| 28,222 |
169 | // token1 is currency,use all | amount0Min = 0;
amount1Min = removeAmount1;
| amount0Min = 0;
amount1Min = removeAmount1;
| 13,897 |
224 | // get a reference to the collection where token goes to | uint32[] storage destination = collections[_to];
| uint32[] storage destination = collections[_to];
| 42,829 |
6 | // v.12.7 string date_last_filled; string date_last_filled_formatted; | // struct Utils {
// string date_prescribed_formatted;
// string date_last_filled_formatted;
// string date_next_fill;
// string date_next_fill_formatted;
// uint256 per_diem_max;
// string script_status;
// uint256 rxId;
// }
| // struct Utils {
// string date_prescribed_formatted;
// string date_last_filled_formatted;
// string date_next_fill;
// string date_next_fill_formatted;
// uint256 per_diem_max;
// string script_status;
// uint256 rxId;
// }
| 4,638 |
189 | // _settlementID A unique 64-bit settlement identifier./_settlementContract The address to use for settling matches./_brokerVerifierContract The decimals to use for verifying/broker signatures. | function registerSettlement(uint64 _settlementID, Settlement _settlementContract, BrokerVerifier _brokerVerifierContract) public onlyOwner {
bool alreadyRegistered = settlementDetails[_settlementID].registered;
settlementDetails[_settlementID] = SettlementDetails({
registered: true,
settlementContract: _settlementContract,
brokerVerifierContract: _brokerVerifierContract
});
if (alreadyRegistered) {
emit LogSettlementUpdated(_settlementID, _settlementContract, _brokerVerifierContract);
} else {
emit LogSettlementRegistered(_settlementID, _settlementContract, _brokerVerifierContract);
}
}
| function registerSettlement(uint64 _settlementID, Settlement _settlementContract, BrokerVerifier _brokerVerifierContract) public onlyOwner {
bool alreadyRegistered = settlementDetails[_settlementID].registered;
settlementDetails[_settlementID] = SettlementDetails({
registered: true,
settlementContract: _settlementContract,
brokerVerifierContract: _brokerVerifierContract
});
if (alreadyRegistered) {
emit LogSettlementUpdated(_settlementID, _settlementContract, _brokerVerifierContract);
} else {
emit LogSettlementRegistered(_settlementID, _settlementContract, _brokerVerifierContract);
}
}
| 23,031 |
120 | // Exercises the options contract. optionsAddress is the address of the options contract optionID is the ID of the option position in non fungible protocols like Hegic. amount is the amount of tokens or options contract to exercise. Only relevant for fungle protocols like Opyn account is the account that receives the exercised profits. This is needed since the adapter holds all the positions and the msg.sender is an instrument contract. / | function exercise(
address optionsAddress,
uint256 optionID,
uint256 amount,
address account
| function exercise(
address optionsAddress,
uint256 optionID,
uint256 amount,
address account
| 39,258 |
0 | // @inheritdoc IAlgebraLimitVirtualPool | bool public override isFinished;
| bool public override isFinished;
| 15,418 |
121 | // GoToken Uniform Price Dutch auction contract - distribution of a fixed/ number of tokens using second price auction, where everybody gets the same final/ price when the auction ends i.e. the ending bid becomes the finalized/ price per token for all participants. | contract GoTokenDutchAuction {
/*
---------------------------------------------------------------------------------------------
GoToken Uniform Price Dutch auction contract - distribution of a fixed
number of tokens using seconprice auction, where everybody gets the lowest
price when the auction ends i.e. the ending bid becomes the finalized
price per token. This is the mechanism for price discovery.
The uniform price Dutch auction is set up to discover a fair price for a
fixed amount of GOT tokens. It starts with a very high price which
continuously declines with every block over time, based on a predefined
formula. After the auction is started, participants can send in ETH to bid.
The auction ends once the price multiplied with the number of offered tokens
equals the total ETH amount sent to the auction. All participants receive
their tokens at the same final price.
The main goals of the auction are to enable everyone to participate while
offering certainty about the maximum total value of all tokens at the time
of the bid.
All token balances are transferable.
Token name, ticker symbol and decimals
1 token (GOT) = 1 indivisible unit * multiplier
multiplier set from token's number of decimals (i.e. 10 ** decimals)
---------------------------------------------------------------------------------------------
*/
/*
---------------------------------------------------------------------------------------------
Data structures for Storage
---------------------------------------------------------------------------------------------
*/
GoToken public token;
address public owner_address;
address public wallet_address;
address public whitelister_address;
address public distributor_address;
// Minimum bid value during the auction
uint256 constant public bid_threshold = 10 finney;
// Maximum contribution per ETH address during public sale
//uint256 constant public MAX_CONTRIBUTION_PUBLICSALE = 20 ether;
// token multiplied derived out of decimals
uint256 public token_multiplier;
// Total number of indivisible GoTokens (GOT * token_multiplier) that will be auctioned
uint256 public num_tokens_auctioned;
/*
---------------------------------------------------------------------------------------------
Price decay function parameters to be changed depending on the desired outcome
This is modeled based on composite exponentially decaying curve auction price model.
The price curves are mathematically modeled per the business needs. There are two
exponentially decaying curves for teh auction: curve 1 is for teh first eight days
and curve 2 is for the remaining days until the auction is finalized.
---------------------------------------------------------------------------------------------
*/
// Starting price in WEI; e.g. 2 * 10 ** 18
uint256 public price_start;
uint256 constant public CURVE_CUTOFF_DURATION = 8 days;
// Price constant for first eight days of the price curve; e.g. 1728
uint256 public price_constant1;
// Price exponent for first eight days of the price curve; e.g. 2
uint256 public price_exponent1;
// Price constant for eight plus days of the price curve; e.g. 1257
uint256 public price_constant2;
// Price exponent for eight plus days of the price curve; e.g. 2
uint256 public price_exponent2;
// For private sale start time (same as auction deployement time)
uint256 public privatesale_start_time;
// For calculating elapsed time for price auction
uint256 public auction_start_time;
uint256 public end_time;
uint256 public start_block;
// All ETH received from the bids
uint256 public received_wei;
uint256 public received_wei_with_bonus;
// Cumulative ETH funds for which the tokens have been claimed
uint256 public funds_claimed;
// Wei per token (GOT * token_multiplier)
uint256 public final_price;
struct Account {
uint256 accounted; // bid value including bonus
uint256 received; // the amount received, without bonus
}
// Address of the Bidder => bid value
mapping (address => Account) public bids;
// privatesalewhitelist for private ETH addresses
mapping (address => bool) public privatesalewhitelist;
// publicsalewhitelist for addresses that want to bid in public sale excluding private sale accounts
mapping (address => bool) public publicsalewhitelist;
/*
---------------------------------------------------------------------------------------------
Bonus tiers
---------------------------------------------------------------------------------------------
*/
// Maximum duration after sale begins that 15% bonus is active.
uint256 constant public BONUS_DAY1_DURATION = 24 hours; ///24 hours;
// Maximum duration after sale begins that 10% bonus is active.
uint256 constant public BONUS_DAY2_DURATION = 48 hours; ///48 hours;
// Maximum duration after sale begins that 5% bonus is active.
uint256 constant public BONUS_DAY3_DURATION = 72 hours; ///72 hours;
// The current percentage of bonus that contributors get.
uint256 public currentBonus = 0;
// Waiting time in days before a participant can claim tokens after the end of the auction
uint256 constant public TOKEN_CLAIM_WAIT_PERIOD = 0 days;
// Keep track of stages during the auction and contract deployment process
Stages public stage;
enum Stages {
AuctionDeployed,
AuctionSetUp,
AuctionStarted,
AuctionEnded,
TokensDistributed
}
/*
---------------------------------------------------------------------------------------------
Modifiers
---------------------------------------------------------------------------------------------
*/
// State of the auction
modifier atStage(Stages _stage) {
require(stage == _stage);
_;
}
// Only owner of the contract
modifier isOwner() {
require(msg.sender == owner_address);
_;
}
// Only who is allowed to whitelist the participant ETH addresses (specified
// during the contract deployment)
modifier isWhitelister() {
require(msg.sender == whitelister_address);
_;
}
// Only who is allowed to distribute the GOT to the participant ETH addresses (specified
// during the contract deployment)
modifier isDistributor() {
require(msg.sender == distributor_address);
_;
}
/*
---------------------------------------------------------------------------------------------
Events
---------------------------------------------------------------------------------------------
*/
event Deployed(uint256 indexed _price_start, uint256 _price_constant1, uint256 _price_exponent1, uint256 _price_constant2, uint256 _price_exponent2);
event Setup();
event AuctionStarted(uint256 indexed _auction_start_time, uint256 indexed _block_number);
event BidSubmission(address indexed _sender,uint256 _amount, uint256 _amount_with_bonus, uint256 _remaining_funds_to_end_auction);
event ClaimedTokens(address indexed _recipient, uint256 _sent_amount);
event AuctionEnded(uint256 _final_price);
event TokensDistributed();
/// whitelisting events for private sale and public sale ETH addresses
event PrivateSaleWhitelisted(address indexed who);
event RemovedFromPrivateSaleWhitelist(address indexed who);
event PublicSaleWhitelisted(address indexed who);
event RemovedFromPublicSaleWhitelist(address indexed who);
/*
---------------------------------------------------------------------------------------------
Public facing functions
---------------------------------------------------------------------------------------------
*/
/// @dev GoToken Contract constructor function sets the starting price,
/// price constant and price exponent for calculating the Dutch Auction price.
/// @param _wallet_address Wallet address to which all contributed ETH will be forwarded.
function GoTokenDutchAuction(
address _wallet_address,
address _whitelister_address,
address _distributor_address,
uint256 _price_start,
uint256 _price_constant1,
uint256 _price_exponent1,
uint256 _price_constant2,
uint256 _price_exponent2)
public
{
// Address shouldn't be null
require(_wallet_address != 0x0);
require(_whitelister_address != 0x0);
require(_distributor_address != 0x0);
wallet_address = _wallet_address;
whitelister_address = _whitelister_address;
distributor_address = _distributor_address;
owner_address = msg.sender;
stage = Stages.AuctionDeployed;
changePriceCurveSettings(_price_start, _price_constant1, _price_exponent1, _price_constant2, _price_exponent2);
Deployed(_price_start, _price_constant1, _price_exponent1, _price_constant2, _price_exponent2);
}
/// @dev Fallback function for the contract, which calls bid()
function () public payable {
bid();
}
/// @notice Set "_token_address" as the token address to be used in the auction.
/// @dev Setup function sets external contracts addresses.
/// @param _token_address Token address.
function setup(address _token_address) public isOwner atStage(Stages.AuctionDeployed) {
require(_token_address != 0x0);
token = GoToken(_token_address);
// Get number of GoToken indivisible tokens (GOT * token_multiplier)
// to be auctioned from token auction balance
num_tokens_auctioned = token.balanceOf(address(this));
// Set the number of the token multiplier for its decimals
token_multiplier = 10 ** (token.decimals());
// State is set to Auction Setup
stage = Stages.AuctionSetUp;
Setup();
}
/// @notice Set "_price_start", "_price_constant1" and "_price_exponent1"
/// "_price_constant2" and "_price_exponent2" as
/// the new starting price, price constant and price exponent for the auction price.
/// @dev Changes auction price function parameters before auction is started.
/// @param _price_start Updated start price.
/// @param _price_constant1 Updated price divisor constant.
/// @param _price_exponent1 Updated price divisor exponent.
/// @param _price_constant2 Updated price divisor constant.
/// @param _price_exponent2 Updated price divisor exponent.
function changePriceCurveSettings(
uint256 _price_start,
uint256 _price_constant1,
uint256 _price_exponent1,
uint256 _price_constant2,
uint256 _price_exponent2)
internal
{
// You can change the price curve settings only when either the auction is Deployed
// or the auction is setup. You can't change during the auction is running or ended.
require(stage == Stages.AuctionDeployed || stage == Stages.AuctionSetUp);
require(_price_start > 0);
require(_price_constant1 > 0);
require(_price_constant2 > 0);
price_start = _price_start;
price_constant1 = _price_constant1;
price_exponent1 = _price_exponent1;
price_constant2 = _price_constant2;
price_exponent2 = _price_exponent2;
}
/*
---------------------------------------------------------------------------------------------
Functions related to whitelisting of presale and public sale ETH addresses.
The Whitelister must add the participant's ETH address before they can bid.
---------------------------------------------------------------------------------------------
*/
// @notice Adds account addresses to public sale ETH whitelist.
// @dev Adds account addresses to public sale ETH whitelist.
// @param _bidder_addresses Array of addresses. Use double quoted array.
function addToPublicSaleWhitelist(address[] _bidder_addresses) public isWhitelister {
for (uint32 i = 0; i < _bidder_addresses.length; i++) {
require(!privatesalewhitelist[_bidder_addresses[i]]); //Can't be in public whitelist
publicsalewhitelist[_bidder_addresses[i]] = true;
PublicSaleWhitelisted(_bidder_addresses[i]);
}
}
// @notice Removes account addresses from public sale ETH whitelist.
// @dev Removes account addresses from public sale ETH whitelist.
// @param _bidder_addresses Array of addresses. Use double quoted array.
function removeFromPublicSaleWhitelist(address[] _bidder_addresses) public isWhitelister {
for (uint32 i = 0; i < _bidder_addresses.length; i++) {
publicsalewhitelist[_bidder_addresses[i]] = false;
RemovedFromPublicSaleWhitelist(_bidder_addresses[i]);
}
}
// Private sale contributors whitelist. Only Admin can add or remove
// @notice Adds presale account addresses to privatesalewhitelist.
// @ Admin Adds presale account addresses to privatesalewhitelist.
// @param _bidder_addresses Array of addresses.
function addToPrivateSaleWhitelist(address[] _bidder_addresses) public isOwner {
for (uint32 i = 0; i < _bidder_addresses.length; i++) {
privatesalewhitelist[_bidder_addresses[i]] = true;
PrivateSaleWhitelisted(_bidder_addresses[i]);
}
}
// @notice Removes presale account addresses from privatesalewhitelist.
// @ Admin Removes presale account addresses from privatesalewhitelist.
// @param _bidder_addresses Array of addresses.
function removeFromPrivateSaleWhitelist(address[] _bidder_addresses) public isOwner {
for (uint32 i = 0; i < _bidder_addresses.length; i++) {
privatesalewhitelist[_bidder_addresses[i]] = false;
RemovedFromPrivateSaleWhitelist(_bidder_addresses[i]);
}
}
// @notice Start the auction.
// @dev Starts auction and sets auction_start_time.
function startAuction() public isOwner atStage(Stages.AuctionSetUp) {
stage = Stages.AuctionStarted;
auction_start_time = now;
start_block = block.number;
AuctionStarted(auction_start_time, start_block);
}
/// @notice Send "msg.value" WEI to the auction from the "msg.sender" account.
/// @dev Allows to send a bid to the auction.
function bid() public payable
{
// Address shouldn't be null and the minimum bid amount of contribution is met.
// Private sale contributor can submit a bid at AuctionSetUp before AuctionStarted
// When AuctionStarted only private sale and public sale whitelisted ETH addresses can participate
require(stage == Stages.AuctionSetUp || stage == Stages.AuctionStarted);
require(privatesalewhitelist[msg.sender] || publicsalewhitelist[msg.sender]);
if (stage == Stages.AuctionSetUp){
require(privatesalewhitelist[msg.sender]);
}
require(msg.value > 0);
require(bids[msg.sender].received + msg.value >= bid_threshold);
assert(bids[msg.sender].received + msg.value >= msg.value);
// Maximum public sale contribution per ETH account
//if (stage == Stages.AuctionStarted && publicsalewhitelist[msg.sender]) {
// require (bids[msg.sender].received + msg.value <= MAX_CONTRIBUTION_PUBLICSALE);
//}
// Remaining funds without the current bid value to end the auction
uint256 remaining_funds_to_end_auction = remainingFundsToEndAuction();
// The bid value must be less than the funds remaining to end the auction
// at the current price.
require(msg.value <= remaining_funds_to_end_auction);
/*
---------------------------------------------------------------------------------------------
Bonus period settings
---------------------------------------------------------------------------------------------
*/
//Private sale bids before Auction starts
if (stage == Stages.AuctionSetUp){
require(privatesalewhitelist[msg.sender]);
currentBonus = 25; //private sale bonus before AuctionStarted
}
else if (stage == Stages.AuctionStarted) {
// private sale contributors bonus period settings
if (privatesalewhitelist[msg.sender] && now >= auction_start_time && now < auction_start_time + BONUS_DAY1_DURATION) {
currentBonus = 25; //private sale contributor Day 1 bonus
}
else if (privatesalewhitelist[msg.sender] && now >= auction_start_time + BONUS_DAY1_DURATION && now < auction_start_time + BONUS_DAY2_DURATION ) {
currentBonus = 25; //private sale contributor Day 2 bonus
}
else if (privatesalewhitelist[msg.sender] && now >= auction_start_time + BONUS_DAY2_DURATION && now < auction_start_time + BONUS_DAY3_DURATION) {
currentBonus = 25; //private sale contributor Day 3 bonus
}
else if (privatesalewhitelist[msg.sender] && now >= auction_start_time + BONUS_DAY3_DURATION) {
currentBonus = 25; //private sale contributor Day 4+ bonus
}
else if (publicsalewhitelist[msg.sender] && now >= auction_start_time && now < auction_start_time + BONUS_DAY1_DURATION) {
currentBonus = 15; //private sale contributor Day 1 bonus
}
else if (publicsalewhitelist[msg.sender] && now >= auction_start_time + BONUS_DAY1_DURATION && now < auction_start_time + BONUS_DAY2_DURATION ) {
currentBonus = 10; //private sale contributor Day 2 bonus
}
else if (publicsalewhitelist[msg.sender] && now >= auction_start_time + BONUS_DAY2_DURATION && now < auction_start_time + BONUS_DAY3_DURATION) {
currentBonus = 5; //private sale contributor Day 3 bonus
}
else if (publicsalewhitelist[msg.sender] && now >= auction_start_time + BONUS_DAY3_DURATION) {
currentBonus = 0; //private sale contributor Day 4+ bonus
}
else {
currentBonus = 0;
}
}
else {
currentBonus = 0;
}
// amount raised including bonus
uint256 accounted = msg.value + msg.value * (currentBonus) / 100;
// Save the bid amount received with and without bonus.
bids[msg.sender].accounted += accounted; //including bonus
bids[msg.sender].received += msg.value;
// keep track of total amount raised and with bonus
received_wei += msg.value;
received_wei_with_bonus += accounted;
// Send bid amount to wallet
wallet_address.transfer(msg.value);
//Log the bid
BidSubmission(msg.sender, msg.value, accounted, remaining_funds_to_end_auction);
assert(received_wei >= msg.value);
assert(received_wei_with_bonus >= accounted);
}
// @notice Finalize the auction - sets the final GoToken price and
// changes the auction stage after no bids are allowed. Only owner can finalize the auction.
// The owner can end the auction anytime after either the auction is deployed or started.
// @dev Finalize auction and set the final GOT token price.
function finalizeAuction() public isOwner
{
// The owner can end the auction anytime during the stages
// AuctionSetUp and AuctionStarted
require(stage == Stages.AuctionSetUp || stage == Stages.AuctionStarted);
// Calculate the final price = WEI / (GOT / token_multiplier)
final_price = token_multiplier * received_wei_with_bonus / num_tokens_auctioned;
// End the auction
end_time = now;
stage = Stages.AuctionEnded;
AuctionEnded(final_price);
assert(final_price > 0);
}
// @notice Distribute GoTokens for "receiver_address" after the auction has ended by the owner.
// @dev Distribute GoTokens for "receiver_address" after auction has ended by the owner.
// @param receiver_address GoTokens will be assigned to this address if eligible.
function distributeGoTokens(address receiver_address)
public isDistributor atStage(Stages.AuctionEnded) returns (bool)
{
// Waiting period in days after the end of the auction, before anyone can claim GoTokens.
// Ensures enough time to check if auction was finalized correctly
// before users start transacting tokens
require(now > end_time + TOKEN_CLAIM_WAIT_PERIOD);
require(receiver_address != 0x0);
require(bids[receiver_address].received > 0);
if (bids[receiver_address].received == 0 || bids[receiver_address].accounted == 0) {
return false;
}
// Number of GOT = bid_wei_with_bonus / (wei_per_GOT * token_multiplier)
// Includes the bonus
uint256 num = (token_multiplier * bids[receiver_address].accounted) / final_price;
// Due to final_price rounding, the number of assigned tokens may be higher
// than expected. Therefore, the number of remaining unassigned auction tokens
// may be smaller than the number of tokens needed for the last claimTokens call
uint256 auction_tokens_balance = token.balanceOf(address(this));
if (num > auction_tokens_balance) {
num = auction_tokens_balance;
}
// Update the total amount of funds for which tokens have been claimed
funds_claimed += bids[receiver_address].received;
// Set receiver bid to 0 before assigning tokens
bids[receiver_address].accounted = 0;
bids[receiver_address].received = 0;
// Send the GoTokens to the receiver address including the qualified bonus
require(token.transfer(receiver_address, num));
// Log the event for claimed GoTokens
ClaimedTokens(receiver_address, num);
// After the last tokens are claimed, change the auction stage
// Due to the above logic described, rounding errors will not be an issue here.
if (funds_claimed == received_wei) {
stage = Stages.TokensDistributed;
TokensDistributed();
}
assert(token.balanceOf(receiver_address) >= num);
assert(bids[receiver_address].accounted == 0);
assert(bids[receiver_address].received == 0);
return true;
}
/// @notice Get the GOT price in WEI during the auction, at the time of
/// calling this function. Returns 0 if auction has ended.
/// Returns "price_start" before auction has started.
/// @dev Calculates the current GOT token price in WEI.
/// @return Returns WEI per indivisible GOT (token_multiplier * GOT).
function price() public constant returns (uint256) {
if (stage == Stages.AuctionEnded ||
stage == Stages.TokensDistributed) {
return 0;
}
return calcTokenPrice();
}
/// @notice Get the remaining funds needed to end the auction, calculated at
/// the current GOT price in WEI.
/// @dev The remaining funds necessary to end the auction at the current GOT price in WEI.
/// @return Returns the remaining funds to end the auction in WEI.
function remainingFundsToEndAuction() constant public returns (uint256) {
// num_tokens_auctioned = total number of indivisible GOT (GOT * token_multiplier) that is auctioned
uint256 required_wei_at_price = num_tokens_auctioned * price() / token_multiplier;
if (required_wei_at_price <= received_wei) {
return 0;
}
return required_wei_at_price - received_wei;
}
/*
---------------------------------------------------------------------------------------------
Private function for calcuclating current token price
---------------------------------------------------------------------------------------------
*/
// @dev Calculates the token price (WEI / GOT) at the current timestamp
// during the auction; elapsed time = 0 before auction starts.
// This is a composite exponentially decaying curve (two curves combined).
// The curve 1 is for the first 8 days and the curve 2 is for the remaining days.
// They are of the form:
// current_price = price_start * (1 + elapsed) / (1 + elapsed + decay_rate);
// where, decay_rate = elapsed ** price_exponent / price_constant;
// Based on the provided parameters, the price does not change in the first
// price_constant^(1/price_exponent) seconds due to rounding.
// Rounding in `decay_rate` also produces values that increase instead of decrease
// in the beginning of the auction; these spikes decrease over time and are noticeable
// only in first hours. This should be calculated before usage.
// @return Returns the token price - WEI per GOT.
function calcTokenPrice() constant private returns (uint256) {
uint256 elapsed;
uint256 decay_rate1;
uint256 decay_rate2;
if (stage == Stages.AuctionDeployed || stage == Stages.AuctionSetUp){
return price_start;
}
if (stage == Stages.AuctionStarted) {
elapsed = now - auction_start_time;
// The first eight days auction price curve
if (now >= auction_start_time && now < auction_start_time + CURVE_CUTOFF_DURATION){
decay_rate1 = elapsed ** price_exponent1 / price_constant1;
return price_start * (1 + elapsed) / (1 + elapsed + decay_rate1);
}
// The remaining days auction price curve
else if (now >= auction_start_time && now >= auction_start_time + CURVE_CUTOFF_DURATION){
decay_rate2 = elapsed ** price_exponent2 / price_constant2;
return price_start * (1 + elapsed) / (1 + elapsed + decay_rate2);
}
else {
return price_start;
}
}
}
} | contract GoTokenDutchAuction {
/*
---------------------------------------------------------------------------------------------
GoToken Uniform Price Dutch auction contract - distribution of a fixed
number of tokens using seconprice auction, where everybody gets the lowest
price when the auction ends i.e. the ending bid becomes the finalized
price per token. This is the mechanism for price discovery.
The uniform price Dutch auction is set up to discover a fair price for a
fixed amount of GOT tokens. It starts with a very high price which
continuously declines with every block over time, based on a predefined
formula. After the auction is started, participants can send in ETH to bid.
The auction ends once the price multiplied with the number of offered tokens
equals the total ETH amount sent to the auction. All participants receive
their tokens at the same final price.
The main goals of the auction are to enable everyone to participate while
offering certainty about the maximum total value of all tokens at the time
of the bid.
All token balances are transferable.
Token name, ticker symbol and decimals
1 token (GOT) = 1 indivisible unit * multiplier
multiplier set from token's number of decimals (i.e. 10 ** decimals)
---------------------------------------------------------------------------------------------
*/
/*
---------------------------------------------------------------------------------------------
Data structures for Storage
---------------------------------------------------------------------------------------------
*/
GoToken public token;
address public owner_address;
address public wallet_address;
address public whitelister_address;
address public distributor_address;
// Minimum bid value during the auction
uint256 constant public bid_threshold = 10 finney;
// Maximum contribution per ETH address during public sale
//uint256 constant public MAX_CONTRIBUTION_PUBLICSALE = 20 ether;
// token multiplied derived out of decimals
uint256 public token_multiplier;
// Total number of indivisible GoTokens (GOT * token_multiplier) that will be auctioned
uint256 public num_tokens_auctioned;
/*
---------------------------------------------------------------------------------------------
Price decay function parameters to be changed depending on the desired outcome
This is modeled based on composite exponentially decaying curve auction price model.
The price curves are mathematically modeled per the business needs. There are two
exponentially decaying curves for teh auction: curve 1 is for teh first eight days
and curve 2 is for the remaining days until the auction is finalized.
---------------------------------------------------------------------------------------------
*/
// Starting price in WEI; e.g. 2 * 10 ** 18
uint256 public price_start;
uint256 constant public CURVE_CUTOFF_DURATION = 8 days;
// Price constant for first eight days of the price curve; e.g. 1728
uint256 public price_constant1;
// Price exponent for first eight days of the price curve; e.g. 2
uint256 public price_exponent1;
// Price constant for eight plus days of the price curve; e.g. 1257
uint256 public price_constant2;
// Price exponent for eight plus days of the price curve; e.g. 2
uint256 public price_exponent2;
// For private sale start time (same as auction deployement time)
uint256 public privatesale_start_time;
// For calculating elapsed time for price auction
uint256 public auction_start_time;
uint256 public end_time;
uint256 public start_block;
// All ETH received from the bids
uint256 public received_wei;
uint256 public received_wei_with_bonus;
// Cumulative ETH funds for which the tokens have been claimed
uint256 public funds_claimed;
// Wei per token (GOT * token_multiplier)
uint256 public final_price;
struct Account {
uint256 accounted; // bid value including bonus
uint256 received; // the amount received, without bonus
}
// Address of the Bidder => bid value
mapping (address => Account) public bids;
// privatesalewhitelist for private ETH addresses
mapping (address => bool) public privatesalewhitelist;
// publicsalewhitelist for addresses that want to bid in public sale excluding private sale accounts
mapping (address => bool) public publicsalewhitelist;
/*
---------------------------------------------------------------------------------------------
Bonus tiers
---------------------------------------------------------------------------------------------
*/
// Maximum duration after sale begins that 15% bonus is active.
uint256 constant public BONUS_DAY1_DURATION = 24 hours; ///24 hours;
// Maximum duration after sale begins that 10% bonus is active.
uint256 constant public BONUS_DAY2_DURATION = 48 hours; ///48 hours;
// Maximum duration after sale begins that 5% bonus is active.
uint256 constant public BONUS_DAY3_DURATION = 72 hours; ///72 hours;
// The current percentage of bonus that contributors get.
uint256 public currentBonus = 0;
// Waiting time in days before a participant can claim tokens after the end of the auction
uint256 constant public TOKEN_CLAIM_WAIT_PERIOD = 0 days;
// Keep track of stages during the auction and contract deployment process
Stages public stage;
enum Stages {
AuctionDeployed,
AuctionSetUp,
AuctionStarted,
AuctionEnded,
TokensDistributed
}
/*
---------------------------------------------------------------------------------------------
Modifiers
---------------------------------------------------------------------------------------------
*/
// State of the auction
modifier atStage(Stages _stage) {
require(stage == _stage);
_;
}
// Only owner of the contract
modifier isOwner() {
require(msg.sender == owner_address);
_;
}
// Only who is allowed to whitelist the participant ETH addresses (specified
// during the contract deployment)
modifier isWhitelister() {
require(msg.sender == whitelister_address);
_;
}
// Only who is allowed to distribute the GOT to the participant ETH addresses (specified
// during the contract deployment)
modifier isDistributor() {
require(msg.sender == distributor_address);
_;
}
/*
---------------------------------------------------------------------------------------------
Events
---------------------------------------------------------------------------------------------
*/
event Deployed(uint256 indexed _price_start, uint256 _price_constant1, uint256 _price_exponent1, uint256 _price_constant2, uint256 _price_exponent2);
event Setup();
event AuctionStarted(uint256 indexed _auction_start_time, uint256 indexed _block_number);
event BidSubmission(address indexed _sender,uint256 _amount, uint256 _amount_with_bonus, uint256 _remaining_funds_to_end_auction);
event ClaimedTokens(address indexed _recipient, uint256 _sent_amount);
event AuctionEnded(uint256 _final_price);
event TokensDistributed();
/// whitelisting events for private sale and public sale ETH addresses
event PrivateSaleWhitelisted(address indexed who);
event RemovedFromPrivateSaleWhitelist(address indexed who);
event PublicSaleWhitelisted(address indexed who);
event RemovedFromPublicSaleWhitelist(address indexed who);
/*
---------------------------------------------------------------------------------------------
Public facing functions
---------------------------------------------------------------------------------------------
*/
/// @dev GoToken Contract constructor function sets the starting price,
/// price constant and price exponent for calculating the Dutch Auction price.
/// @param _wallet_address Wallet address to which all contributed ETH will be forwarded.
function GoTokenDutchAuction(
address _wallet_address,
address _whitelister_address,
address _distributor_address,
uint256 _price_start,
uint256 _price_constant1,
uint256 _price_exponent1,
uint256 _price_constant2,
uint256 _price_exponent2)
public
{
// Address shouldn't be null
require(_wallet_address != 0x0);
require(_whitelister_address != 0x0);
require(_distributor_address != 0x0);
wallet_address = _wallet_address;
whitelister_address = _whitelister_address;
distributor_address = _distributor_address;
owner_address = msg.sender;
stage = Stages.AuctionDeployed;
changePriceCurveSettings(_price_start, _price_constant1, _price_exponent1, _price_constant2, _price_exponent2);
Deployed(_price_start, _price_constant1, _price_exponent1, _price_constant2, _price_exponent2);
}
/// @dev Fallback function for the contract, which calls bid()
function () public payable {
bid();
}
/// @notice Set "_token_address" as the token address to be used in the auction.
/// @dev Setup function sets external contracts addresses.
/// @param _token_address Token address.
function setup(address _token_address) public isOwner atStage(Stages.AuctionDeployed) {
require(_token_address != 0x0);
token = GoToken(_token_address);
// Get number of GoToken indivisible tokens (GOT * token_multiplier)
// to be auctioned from token auction balance
num_tokens_auctioned = token.balanceOf(address(this));
// Set the number of the token multiplier for its decimals
token_multiplier = 10 ** (token.decimals());
// State is set to Auction Setup
stage = Stages.AuctionSetUp;
Setup();
}
/// @notice Set "_price_start", "_price_constant1" and "_price_exponent1"
/// "_price_constant2" and "_price_exponent2" as
/// the new starting price, price constant and price exponent for the auction price.
/// @dev Changes auction price function parameters before auction is started.
/// @param _price_start Updated start price.
/// @param _price_constant1 Updated price divisor constant.
/// @param _price_exponent1 Updated price divisor exponent.
/// @param _price_constant2 Updated price divisor constant.
/// @param _price_exponent2 Updated price divisor exponent.
function changePriceCurveSettings(
uint256 _price_start,
uint256 _price_constant1,
uint256 _price_exponent1,
uint256 _price_constant2,
uint256 _price_exponent2)
internal
{
// You can change the price curve settings only when either the auction is Deployed
// or the auction is setup. You can't change during the auction is running or ended.
require(stage == Stages.AuctionDeployed || stage == Stages.AuctionSetUp);
require(_price_start > 0);
require(_price_constant1 > 0);
require(_price_constant2 > 0);
price_start = _price_start;
price_constant1 = _price_constant1;
price_exponent1 = _price_exponent1;
price_constant2 = _price_constant2;
price_exponent2 = _price_exponent2;
}
/*
---------------------------------------------------------------------------------------------
Functions related to whitelisting of presale and public sale ETH addresses.
The Whitelister must add the participant's ETH address before they can bid.
---------------------------------------------------------------------------------------------
*/
// @notice Adds account addresses to public sale ETH whitelist.
// @dev Adds account addresses to public sale ETH whitelist.
// @param _bidder_addresses Array of addresses. Use double quoted array.
function addToPublicSaleWhitelist(address[] _bidder_addresses) public isWhitelister {
for (uint32 i = 0; i < _bidder_addresses.length; i++) {
require(!privatesalewhitelist[_bidder_addresses[i]]); //Can't be in public whitelist
publicsalewhitelist[_bidder_addresses[i]] = true;
PublicSaleWhitelisted(_bidder_addresses[i]);
}
}
// @notice Removes account addresses from public sale ETH whitelist.
// @dev Removes account addresses from public sale ETH whitelist.
// @param _bidder_addresses Array of addresses. Use double quoted array.
function removeFromPublicSaleWhitelist(address[] _bidder_addresses) public isWhitelister {
for (uint32 i = 0; i < _bidder_addresses.length; i++) {
publicsalewhitelist[_bidder_addresses[i]] = false;
RemovedFromPublicSaleWhitelist(_bidder_addresses[i]);
}
}
// Private sale contributors whitelist. Only Admin can add or remove
// @notice Adds presale account addresses to privatesalewhitelist.
// @ Admin Adds presale account addresses to privatesalewhitelist.
// @param _bidder_addresses Array of addresses.
function addToPrivateSaleWhitelist(address[] _bidder_addresses) public isOwner {
for (uint32 i = 0; i < _bidder_addresses.length; i++) {
privatesalewhitelist[_bidder_addresses[i]] = true;
PrivateSaleWhitelisted(_bidder_addresses[i]);
}
}
// @notice Removes presale account addresses from privatesalewhitelist.
// @ Admin Removes presale account addresses from privatesalewhitelist.
// @param _bidder_addresses Array of addresses.
function removeFromPrivateSaleWhitelist(address[] _bidder_addresses) public isOwner {
for (uint32 i = 0; i < _bidder_addresses.length; i++) {
privatesalewhitelist[_bidder_addresses[i]] = false;
RemovedFromPrivateSaleWhitelist(_bidder_addresses[i]);
}
}
// @notice Start the auction.
// @dev Starts auction and sets auction_start_time.
function startAuction() public isOwner atStage(Stages.AuctionSetUp) {
stage = Stages.AuctionStarted;
auction_start_time = now;
start_block = block.number;
AuctionStarted(auction_start_time, start_block);
}
/// @notice Send "msg.value" WEI to the auction from the "msg.sender" account.
/// @dev Allows to send a bid to the auction.
function bid() public payable
{
// Address shouldn't be null and the minimum bid amount of contribution is met.
// Private sale contributor can submit a bid at AuctionSetUp before AuctionStarted
// When AuctionStarted only private sale and public sale whitelisted ETH addresses can participate
require(stage == Stages.AuctionSetUp || stage == Stages.AuctionStarted);
require(privatesalewhitelist[msg.sender] || publicsalewhitelist[msg.sender]);
if (stage == Stages.AuctionSetUp){
require(privatesalewhitelist[msg.sender]);
}
require(msg.value > 0);
require(bids[msg.sender].received + msg.value >= bid_threshold);
assert(bids[msg.sender].received + msg.value >= msg.value);
// Maximum public sale contribution per ETH account
//if (stage == Stages.AuctionStarted && publicsalewhitelist[msg.sender]) {
// require (bids[msg.sender].received + msg.value <= MAX_CONTRIBUTION_PUBLICSALE);
//}
// Remaining funds without the current bid value to end the auction
uint256 remaining_funds_to_end_auction = remainingFundsToEndAuction();
// The bid value must be less than the funds remaining to end the auction
// at the current price.
require(msg.value <= remaining_funds_to_end_auction);
/*
---------------------------------------------------------------------------------------------
Bonus period settings
---------------------------------------------------------------------------------------------
*/
//Private sale bids before Auction starts
if (stage == Stages.AuctionSetUp){
require(privatesalewhitelist[msg.sender]);
currentBonus = 25; //private sale bonus before AuctionStarted
}
else if (stage == Stages.AuctionStarted) {
// private sale contributors bonus period settings
if (privatesalewhitelist[msg.sender] && now >= auction_start_time && now < auction_start_time + BONUS_DAY1_DURATION) {
currentBonus = 25; //private sale contributor Day 1 bonus
}
else if (privatesalewhitelist[msg.sender] && now >= auction_start_time + BONUS_DAY1_DURATION && now < auction_start_time + BONUS_DAY2_DURATION ) {
currentBonus = 25; //private sale contributor Day 2 bonus
}
else if (privatesalewhitelist[msg.sender] && now >= auction_start_time + BONUS_DAY2_DURATION && now < auction_start_time + BONUS_DAY3_DURATION) {
currentBonus = 25; //private sale contributor Day 3 bonus
}
else if (privatesalewhitelist[msg.sender] && now >= auction_start_time + BONUS_DAY3_DURATION) {
currentBonus = 25; //private sale contributor Day 4+ bonus
}
else if (publicsalewhitelist[msg.sender] && now >= auction_start_time && now < auction_start_time + BONUS_DAY1_DURATION) {
currentBonus = 15; //private sale contributor Day 1 bonus
}
else if (publicsalewhitelist[msg.sender] && now >= auction_start_time + BONUS_DAY1_DURATION && now < auction_start_time + BONUS_DAY2_DURATION ) {
currentBonus = 10; //private sale contributor Day 2 bonus
}
else if (publicsalewhitelist[msg.sender] && now >= auction_start_time + BONUS_DAY2_DURATION && now < auction_start_time + BONUS_DAY3_DURATION) {
currentBonus = 5; //private sale contributor Day 3 bonus
}
else if (publicsalewhitelist[msg.sender] && now >= auction_start_time + BONUS_DAY3_DURATION) {
currentBonus = 0; //private sale contributor Day 4+ bonus
}
else {
currentBonus = 0;
}
}
else {
currentBonus = 0;
}
// amount raised including bonus
uint256 accounted = msg.value + msg.value * (currentBonus) / 100;
// Save the bid amount received with and without bonus.
bids[msg.sender].accounted += accounted; //including bonus
bids[msg.sender].received += msg.value;
// keep track of total amount raised and with bonus
received_wei += msg.value;
received_wei_with_bonus += accounted;
// Send bid amount to wallet
wallet_address.transfer(msg.value);
//Log the bid
BidSubmission(msg.sender, msg.value, accounted, remaining_funds_to_end_auction);
assert(received_wei >= msg.value);
assert(received_wei_with_bonus >= accounted);
}
// @notice Finalize the auction - sets the final GoToken price and
// changes the auction stage after no bids are allowed. Only owner can finalize the auction.
// The owner can end the auction anytime after either the auction is deployed or started.
// @dev Finalize auction and set the final GOT token price.
function finalizeAuction() public isOwner
{
// The owner can end the auction anytime during the stages
// AuctionSetUp and AuctionStarted
require(stage == Stages.AuctionSetUp || stage == Stages.AuctionStarted);
// Calculate the final price = WEI / (GOT / token_multiplier)
final_price = token_multiplier * received_wei_with_bonus / num_tokens_auctioned;
// End the auction
end_time = now;
stage = Stages.AuctionEnded;
AuctionEnded(final_price);
assert(final_price > 0);
}
// @notice Distribute GoTokens for "receiver_address" after the auction has ended by the owner.
// @dev Distribute GoTokens for "receiver_address" after auction has ended by the owner.
// @param receiver_address GoTokens will be assigned to this address if eligible.
function distributeGoTokens(address receiver_address)
public isDistributor atStage(Stages.AuctionEnded) returns (bool)
{
// Waiting period in days after the end of the auction, before anyone can claim GoTokens.
// Ensures enough time to check if auction was finalized correctly
// before users start transacting tokens
require(now > end_time + TOKEN_CLAIM_WAIT_PERIOD);
require(receiver_address != 0x0);
require(bids[receiver_address].received > 0);
if (bids[receiver_address].received == 0 || bids[receiver_address].accounted == 0) {
return false;
}
// Number of GOT = bid_wei_with_bonus / (wei_per_GOT * token_multiplier)
// Includes the bonus
uint256 num = (token_multiplier * bids[receiver_address].accounted) / final_price;
// Due to final_price rounding, the number of assigned tokens may be higher
// than expected. Therefore, the number of remaining unassigned auction tokens
// may be smaller than the number of tokens needed for the last claimTokens call
uint256 auction_tokens_balance = token.balanceOf(address(this));
if (num > auction_tokens_balance) {
num = auction_tokens_balance;
}
// Update the total amount of funds for which tokens have been claimed
funds_claimed += bids[receiver_address].received;
// Set receiver bid to 0 before assigning tokens
bids[receiver_address].accounted = 0;
bids[receiver_address].received = 0;
// Send the GoTokens to the receiver address including the qualified bonus
require(token.transfer(receiver_address, num));
// Log the event for claimed GoTokens
ClaimedTokens(receiver_address, num);
// After the last tokens are claimed, change the auction stage
// Due to the above logic described, rounding errors will not be an issue here.
if (funds_claimed == received_wei) {
stage = Stages.TokensDistributed;
TokensDistributed();
}
assert(token.balanceOf(receiver_address) >= num);
assert(bids[receiver_address].accounted == 0);
assert(bids[receiver_address].received == 0);
return true;
}
/// @notice Get the GOT price in WEI during the auction, at the time of
/// calling this function. Returns 0 if auction has ended.
/// Returns "price_start" before auction has started.
/// @dev Calculates the current GOT token price in WEI.
/// @return Returns WEI per indivisible GOT (token_multiplier * GOT).
function price() public constant returns (uint256) {
if (stage == Stages.AuctionEnded ||
stage == Stages.TokensDistributed) {
return 0;
}
return calcTokenPrice();
}
/// @notice Get the remaining funds needed to end the auction, calculated at
/// the current GOT price in WEI.
/// @dev The remaining funds necessary to end the auction at the current GOT price in WEI.
/// @return Returns the remaining funds to end the auction in WEI.
function remainingFundsToEndAuction() constant public returns (uint256) {
// num_tokens_auctioned = total number of indivisible GOT (GOT * token_multiplier) that is auctioned
uint256 required_wei_at_price = num_tokens_auctioned * price() / token_multiplier;
if (required_wei_at_price <= received_wei) {
return 0;
}
return required_wei_at_price - received_wei;
}
/*
---------------------------------------------------------------------------------------------
Private function for calcuclating current token price
---------------------------------------------------------------------------------------------
*/
// @dev Calculates the token price (WEI / GOT) at the current timestamp
// during the auction; elapsed time = 0 before auction starts.
// This is a composite exponentially decaying curve (two curves combined).
// The curve 1 is for the first 8 days and the curve 2 is for the remaining days.
// They are of the form:
// current_price = price_start * (1 + elapsed) / (1 + elapsed + decay_rate);
// where, decay_rate = elapsed ** price_exponent / price_constant;
// Based on the provided parameters, the price does not change in the first
// price_constant^(1/price_exponent) seconds due to rounding.
// Rounding in `decay_rate` also produces values that increase instead of decrease
// in the beginning of the auction; these spikes decrease over time and are noticeable
// only in first hours. This should be calculated before usage.
// @return Returns the token price - WEI per GOT.
function calcTokenPrice() constant private returns (uint256) {
uint256 elapsed;
uint256 decay_rate1;
uint256 decay_rate2;
if (stage == Stages.AuctionDeployed || stage == Stages.AuctionSetUp){
return price_start;
}
if (stage == Stages.AuctionStarted) {
elapsed = now - auction_start_time;
// The first eight days auction price curve
if (now >= auction_start_time && now < auction_start_time + CURVE_CUTOFF_DURATION){
decay_rate1 = elapsed ** price_exponent1 / price_constant1;
return price_start * (1 + elapsed) / (1 + elapsed + decay_rate1);
}
// The remaining days auction price curve
else if (now >= auction_start_time && now >= auction_start_time + CURVE_CUTOFF_DURATION){
decay_rate2 = elapsed ** price_exponent2 / price_constant2;
return price_start * (1 + elapsed) / (1 + elapsed + decay_rate2);
}
else {
return price_start;
}
}
}
} | 43,698 |
101 | // Returns the token generator tool. / | function generator() public pure returns (string memory) {
return _GENERATOR;
}
| function generator() public pure returns (string memory) {
return _GENERATOR;
}
| 8,201 |
4 | // these 2 lines have such effect: balance of the contract will be equal (original_balance + FEE) and the sender will get the change from MAX_TRANS_FEE | tvm.rawReserve(FEE, 4); // reserve original_balance + FEE.
| tvm.rawReserve(FEE, 4); // reserve original_balance + FEE.
| 17,943 |
4 | // add the seller to the payment structure the amount left is the amount that the seller will receive this can potentially be 0 | recipients[offset] = seller;
amounts[offset] = amountLeft;
offset++;
return (recipients, amounts);
| recipients[offset] = seller;
amounts[offset] = amountLeft;
offset++;
return (recipients, amounts);
| 18,389 |
23 | // collect presale contributions | function sendToPresale() public payable {
/// look up the sender's current contribution amount in the mapping
uint256 currentContribution = contribution[contributoor[msg.sender]].amount;
/// initialize a contribution index so we can keep track of this address' contributions
uint256 contributionIndex;
require(msg.value >= MIN_CONTRIBUTION, "Contribution too low");
/// check to see if contributions are allowed
require (allowContributions, "Contributions not allowed");
/// enforce per-wallet contribution limit
require (msg.value + currentContribution <= MAX_CONTRIBUTION, "Contribution exceeds per wallet limit");
/// enforce hard cap
require (msg.value + TOTAL_CONTRIBUTED <= HARD_CAP, "Contribution exceeds hard cap");
if (contributoor[msg.sender] != 0){
/// no need to increase the number of contributors since this person already added
contributionIndex = contributoor[msg.sender];
} else {
/// keep track of each new contributor with a unique index
contributionIndex = NUMBER_OF_CONTRIBUTOORS + 1;
NUMBER_OF_CONTRIBUTOORS++;
}
/// add the contribution to the amount contributed
TOTAL_CONTRIBUTED = TOTAL_CONTRIBUTED + msg.value;
/// keep track of the address' contributions so far
contributoor[msg.sender] = contributionIndex;
contribution[contributionIndex].addr = msg.sender;
contribution[contributionIndex].amount += msg.value;
}
| function sendToPresale() public payable {
/// look up the sender's current contribution amount in the mapping
uint256 currentContribution = contribution[contributoor[msg.sender]].amount;
/// initialize a contribution index so we can keep track of this address' contributions
uint256 contributionIndex;
require(msg.value >= MIN_CONTRIBUTION, "Contribution too low");
/// check to see if contributions are allowed
require (allowContributions, "Contributions not allowed");
/// enforce per-wallet contribution limit
require (msg.value + currentContribution <= MAX_CONTRIBUTION, "Contribution exceeds per wallet limit");
/// enforce hard cap
require (msg.value + TOTAL_CONTRIBUTED <= HARD_CAP, "Contribution exceeds hard cap");
if (contributoor[msg.sender] != 0){
/// no need to increase the number of contributors since this person already added
contributionIndex = contributoor[msg.sender];
} else {
/// keep track of each new contributor with a unique index
contributionIndex = NUMBER_OF_CONTRIBUTOORS + 1;
NUMBER_OF_CONTRIBUTOORS++;
}
/// add the contribution to the amount contributed
TOTAL_CONTRIBUTED = TOTAL_CONTRIBUTED + msg.value;
/// keep track of the address' contributions so far
contributoor[msg.sender] = contributionIndex;
contribution[contributionIndex].addr = msg.sender;
contribution[contributionIndex].amount += msg.value;
}
| 8,528 |
24 | // minimum amount which must stay in contract and can not be systemWithdrawn. Configurable by owner. | uint96 public systemWithdrawLimit;
| uint96 public systemWithdrawLimit;
| 10,769 |
0 | // The address where the router's default extension set is stored. | address public immutable defaultExtensions;
| address public immutable defaultExtensions;
| 27,356 |
4 | // ===============================Constructor============================ | constructor() public {
owner = msg.sender;
superMan = msg.sender;
}
| constructor() public {
owner = msg.sender;
superMan = msg.sender;
}
| 14,124 |
71 | // Safe to be unchecked as it's also overflow checked within the dToken.mint() below | dTokenBalance += _newDebt;
| dTokenBalance += _newDebt;
| 35,603 |
45 | // Minimum amount to invest | uint public constant MIN_INVEST_ETHER = 0.1 ether;
| uint public constant MIN_INVEST_ETHER = 0.1 ether;
| 19,278 |
75 | // tracks all current unbondings (time) | mapping(address => uint) public unbondings;
| mapping(address => uint) public unbondings;
| 49,721 |
20 | // Burn process is just a funtion to calculate burn amount depending on an amount of Tokens | function cutForBurn(uint256 a) public pure returns (uint256) {
uint256 c = a.div(20);
return c;
}
| function cutForBurn(uint256 a) public pure returns (uint256) {
uint256 c = a.div(20);
return c;
}
| 8,373 |
12 | // The unix timestamp that public minting begins / | uint80 public publicMintStart;
| uint80 public publicMintStart;
| 5,553 |
162 | // View function to see pending DOPs on frontend. | function pendingDop(uint256 _pid, address _user)
external
view
returns (uint256)
| function pendingDop(uint256 _pid, address _user)
external
view
returns (uint256)
| 27,713 |
132 | // ProxiableVaultLib Contract/Enzyme Council <[email protected]>/A contract that defines the upgrade behavior for VaultLib instances/The recommended implementation of the target of a proxy according to EIP-1822 and EIP-1967/ Code position in storage is `bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1)`,/ which is "0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc". | abstract contract ProxiableVaultLib {
/// @dev Updates the target of the proxy to be the contract at _nextVaultLib
function __updateCodeAddress(address _nextVaultLib) internal {
require(
bytes32(0x027b9570e9fedc1a80b937ae9a06861e5faef3992491af30b684a64b3fbec7a5) ==
ProxiableVaultLib(_nextVaultLib).proxiableUUID(),
"__updateCodeAddress: _nextVaultLib not compatible"
);
assembly {
// solium-disable-line
sstore(
0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc,
_nextVaultLib
)
}
}
/// @notice Returns a unique bytes32 hash for VaultLib instances
/// @return uuid_ The bytes32 hash representing the UUID
/// @dev The UUID is `bytes32(keccak256('mln.proxiable.vaultlib'))`
function proxiableUUID() public pure returns (bytes32 uuid_) {
return 0x027b9570e9fedc1a80b937ae9a06861e5faef3992491af30b684a64b3fbec7a5;
}
}
| abstract contract ProxiableVaultLib {
/// @dev Updates the target of the proxy to be the contract at _nextVaultLib
function __updateCodeAddress(address _nextVaultLib) internal {
require(
bytes32(0x027b9570e9fedc1a80b937ae9a06861e5faef3992491af30b684a64b3fbec7a5) ==
ProxiableVaultLib(_nextVaultLib).proxiableUUID(),
"__updateCodeAddress: _nextVaultLib not compatible"
);
assembly {
// solium-disable-line
sstore(
0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc,
_nextVaultLib
)
}
}
/// @notice Returns a unique bytes32 hash for VaultLib instances
/// @return uuid_ The bytes32 hash representing the UUID
/// @dev The UUID is `bytes32(keccak256('mln.proxiable.vaultlib'))`
function proxiableUUID() public pure returns (bytes32 uuid_) {
return 0x027b9570e9fedc1a80b937ae9a06861e5faef3992491af30b684a64b3fbec7a5;
}
}
| 16,878 |
3 | // initializing | OwnableUpgradeable.__Ownable_init();
ERC721HolderUpgradeable.__ERC721Holder_init();
| OwnableUpgradeable.__Ownable_init();
ERC721HolderUpgradeable.__ERC721Holder_init();
| 37,567 |
5 | // bookingIntents: roomId -> hash(date) -> possibleBooker -> bookingIntent | mapping (uint256 => mapping (bytes32 => mapping (address => BookingIntent))) internal bookingIntents;
mapping (uint256 => mapping (bytes32 => address[])) internal possibleBookers;
mapping (address => uint256) public accumulatedPayments;
Room[] public rooms;
uint256 public nextRoomId = 0;
| mapping (uint256 => mapping (bytes32 => mapping (address => BookingIntent))) internal bookingIntents;
mapping (uint256 => mapping (bytes32 => address[])) internal possibleBookers;
mapping (address => uint256) public accumulatedPayments;
Room[] public rooms;
uint256 public nextRoomId = 0;
| 11,580 |
146 | // View function to see pending WETH on frontend. | function pendingWeth(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accWETHPerShare = pool.accWETHPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 WethReward = multiplier.mul(WethPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accWETHPerShare = accWETHPerShare.add(WethReward.mul(1e12).div(lpSupply));
}
return user.amount.mul(accWETHPerShare).div(1e12).sub(user.rewardDebt);
}
| function pendingWeth(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accWETHPerShare = pool.accWETHPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 WethReward = multiplier.mul(WethPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accWETHPerShare = accWETHPerShare.add(WethReward.mul(1e12).div(lpSupply));
}
return user.amount.mul(accWETHPerShare).div(1e12).sub(user.rewardDebt);
}
| 39,511 |
175 | // _getPoolBalances external function that returns the current pool balance of token A and token B return totalTokenA balanceOf this contract of token Areturn totalTokenB balanceOf this contract of token B / | function _getPoolBalances() internal view returns (uint256 totalTokenA, uint256 totalTokenB) {
totalTokenA = IERC20(_tokenA).balanceOf(address(this));
totalTokenB = IERC20(_tokenB).balanceOf(address(this));
}
| function _getPoolBalances() internal view returns (uint256 totalTokenA, uint256 totalTokenB) {
totalTokenA = IERC20(_tokenA).balanceOf(address(this));
totalTokenB = IERC20(_tokenB).balanceOf(address(this));
}
| 18,775 |
17 | // The client funds a new iteration. | function newIteration(uint256 fundingAmount) external payable;
| function newIteration(uint256 fundingAmount) external payable;
| 31,010 |
5 | // Updates the maxVolatilityBps parameter of the pair.This can only be called by the Factory address. newMaxVolatilityBps The new value for maxVolatilityBps / | function setMaxVolatilityBps(uint16 newMaxVolatilityBps) external;
| function setMaxVolatilityBps(uint16 newMaxVolatilityBps) external;
| 41,312 |
13 | // check if payment is sufficient | require(listedNFT[tokenIds[0]].price <= payment, 'Payment is too low');
| require(listedNFT[tokenIds[0]].price <= payment, 'Payment is too low');
| 13,473 |
8 | // the memory keyword tells to store the strings in volatile memory | function addPost(string memory _content, string memory _ipfsHash, string memory _timeStamp) public onlyOwner{
//adds a Post variable to the mapping while incrementing the index
//storage keyword tells to save the mapping in account's persistent storage
//creating mappings in volatile memory is prohibited in this version of solidity
//p is a pointer to the Post variable, so you set its values after
Post storage p = posts[postsCount++];
p.content = _content;
p.ipfsHash = _ipfsHash;
p.timeStamp = _timeStamp;
}
| function addPost(string memory _content, string memory _ipfsHash, string memory _timeStamp) public onlyOwner{
//adds a Post variable to the mapping while incrementing the index
//storage keyword tells to save the mapping in account's persistent storage
//creating mappings in volatile memory is prohibited in this version of solidity
//p is a pointer to the Post variable, so you set its values after
Post storage p = posts[postsCount++];
p.content = _content;
p.ipfsHash = _ipfsHash;
p.timeStamp = _timeStamp;
}
| 1,761 |
49 | // final calculation for the remaining time period | time = endTime.sub(depositTime);
interest = time
.mul(amount)
.mul(rates[userIndex].newInterestRate)
.div(_lockduration.mul(10000)); //replace with (lockduration * 10000)
amount += interest;
| time = endTime.sub(depositTime);
interest = time
.mul(amount)
.mul(rates[userIndex].newInterestRate)
.div(_lockduration.mul(10000)); //replace with (lockduration * 10000)
amount += interest;
| 34,103 |
775 | // Copyright 2017 Loopring Technology Limited. | 19,922 | ||
412 | // hackingRewardAmount | uint256 claimRewardAmount =
totalSupply.mul(poolsRewards[_pid].rewardsLevels[_severity]);
claimRewards.hackerVestedReward =
claimRewardAmount.mul(poolsRewards[_pid].rewardsSplit.hackerVestedReward)
.div(REWARDS_LEVEL_DENOMINATOR*REWARDS_LEVEL_DENOMINATOR);
claimRewards.hackerReward =
claimRewardAmount.mul(poolsRewards[_pid].rewardsSplit.hackerReward)
.div(REWARDS_LEVEL_DENOMINATOR*REWARDS_LEVEL_DENOMINATOR);
claimRewards.committeeReward =
claimRewardAmount.mul(poolsRewards[_pid].rewardsSplit.committeeReward)
| uint256 claimRewardAmount =
totalSupply.mul(poolsRewards[_pid].rewardsLevels[_severity]);
claimRewards.hackerVestedReward =
claimRewardAmount.mul(poolsRewards[_pid].rewardsSplit.hackerVestedReward)
.div(REWARDS_LEVEL_DENOMINATOR*REWARDS_LEVEL_DENOMINATOR);
claimRewards.hackerReward =
claimRewardAmount.mul(poolsRewards[_pid].rewardsSplit.hackerReward)
.div(REWARDS_LEVEL_DENOMINATOR*REWARDS_LEVEL_DENOMINATOR);
claimRewards.committeeReward =
claimRewardAmount.mul(poolsRewards[_pid].rewardsSplit.committeeReward)
| 46,149 |
9 | // See {IERC721Listings-purchaseToken}.Must have a valid listingmsg.sender must not the owner of tokencontract balance must be at least sell price plus fees / | function purchaseToken(
address erc721Address,
uint256 tokenId,
uint256 value,
address buyer
) external payable {
require(
buyer == _msgSender() || isApprovedOperator(buyer, _msgSender()),
"sender not buyer or approved operator"
);
| function purchaseToken(
address erc721Address,
uint256 tokenId,
uint256 value,
address buyer
) external payable {
require(
buyer == _msgSender() || isApprovedOperator(buyer, _msgSender()),
"sender not buyer or approved operator"
);
| 20,301 |
5 | // Mapping of Chainlink aggregators (input currency => output currency => contract address) input & output currencies are the addresses of the ERC20 contracts OR the sha3("currency code") | mapping(address => mapping(address => address)) public allAggregators;
| mapping(address => mapping(address => address)) public allAggregators;
| 30,442 |
64 | // 10 Billion | uint256 public constant _totalSupply = 10000000000*(10**18);
| uint256 public constant _totalSupply = 10000000000*(10**18);
| 25,457 |
86 | // The liquidator liquidates the borrowers collateral. The collateral seized is transferred to the liquidator. borrower The borrower of this cToken to be liquidated liquidator The address repaying the borrow and seizing collateral cTokenCollateral The market in which to seize collateral from the borrower repayAmount The amount of the underlying borrowed asset to repayreturn (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. / | function liquidateBorrowFresh(address liquidator, address borrower, uint repayAmount, CTokenInterface cTokenCollateral) internal returns (uint, uint) {
/* Fail if liquidate not allowed */
uint allowed = comptroller.liquidateBorrowAllowed(address(this), address(cTokenCollateral), liquidator, borrower, repayAmount);
if (allowed != 0) {
return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.LIQUIDATE_COMPTROLLER_REJECTION, allowed), 0);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_FRESHNESS_CHECK), 0);
}
/* Verify cTokenCollateral market's block number equals current block number */
if (cTokenCollateral.accrualBlockNumber() != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_COLLATERAL_FRESHNESS_CHECK), 0);
}
/* Fail if borrower = liquidator */
if (borrower == liquidator) {
return (fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_LIQUIDATOR_IS_BORROWER), 0);
}
/* Fail if repayAmount = 0 */
if (repayAmount == 0) {
return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_ZERO), 0);
}
/* Fail if repayAmount = -1 */
if (repayAmount == uint(-1)) {
return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX), 0);
}
/* Fail if repayBorrow fails */
(uint repayBorrowError, uint actualRepayAmount) = repayBorrowFresh(liquidator, borrower, repayAmount);
if (repayBorrowError != uint(Error.NO_ERROR)) {
return (fail(Error(repayBorrowError), FailureInfo.LIQUIDATE_REPAY_BORROW_FRESH_FAILED), 0);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/* We calculate the number of collateral tokens that will be seized */
(uint amountSeizeError, uint seizeTokens) = comptroller.liquidateCalculateSeizeTokens(address(this), address(cTokenCollateral), actualRepayAmount);
require(amountSeizeError == uint(Error.NO_ERROR), "LIQUIDATE_COMPTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED");
/* Revert if borrower collateral token balance < seizeTokens */
require(cTokenCollateral.balanceOf(borrower) >= seizeTokens, "LIQUIDATE_SEIZE_TOO_MUCH");
// If this is also the collateral, run seizeInternal to avoid re-entrancy, otherwise make an external call
uint seizeError;
if (address(cTokenCollateral) == address(this)) {
seizeError = seizeInternal(address(this), liquidator, borrower, seizeTokens);
} else {
seizeError = cTokenCollateral.seize(liquidator, borrower, seizeTokens);
}
/* Revert if seize tokens fails (since we cannot be sure of side effects) */
require(seizeError == uint(Error.NO_ERROR), "token seizure failed");
/* We emit a LiquidateBorrow event */
emit LiquidateBorrow(liquidator, borrower, actualRepayAmount, address(cTokenCollateral), seizeTokens);
/* We call the defense hook */
// unused function
// comptroller.liquidateBorrowVerify(address(this), address(cTokenCollateral), liquidator, borrower, actualRepayAmount, seizeTokens);
return (uint(Error.NO_ERROR), actualRepayAmount);
}
| function liquidateBorrowFresh(address liquidator, address borrower, uint repayAmount, CTokenInterface cTokenCollateral) internal returns (uint, uint) {
/* Fail if liquidate not allowed */
uint allowed = comptroller.liquidateBorrowAllowed(address(this), address(cTokenCollateral), liquidator, borrower, repayAmount);
if (allowed != 0) {
return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.LIQUIDATE_COMPTROLLER_REJECTION, allowed), 0);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_FRESHNESS_CHECK), 0);
}
/* Verify cTokenCollateral market's block number equals current block number */
if (cTokenCollateral.accrualBlockNumber() != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_COLLATERAL_FRESHNESS_CHECK), 0);
}
/* Fail if borrower = liquidator */
if (borrower == liquidator) {
return (fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_LIQUIDATOR_IS_BORROWER), 0);
}
/* Fail if repayAmount = 0 */
if (repayAmount == 0) {
return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_ZERO), 0);
}
/* Fail if repayAmount = -1 */
if (repayAmount == uint(-1)) {
return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX), 0);
}
/* Fail if repayBorrow fails */
(uint repayBorrowError, uint actualRepayAmount) = repayBorrowFresh(liquidator, borrower, repayAmount);
if (repayBorrowError != uint(Error.NO_ERROR)) {
return (fail(Error(repayBorrowError), FailureInfo.LIQUIDATE_REPAY_BORROW_FRESH_FAILED), 0);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/* We calculate the number of collateral tokens that will be seized */
(uint amountSeizeError, uint seizeTokens) = comptroller.liquidateCalculateSeizeTokens(address(this), address(cTokenCollateral), actualRepayAmount);
require(amountSeizeError == uint(Error.NO_ERROR), "LIQUIDATE_COMPTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED");
/* Revert if borrower collateral token balance < seizeTokens */
require(cTokenCollateral.balanceOf(borrower) >= seizeTokens, "LIQUIDATE_SEIZE_TOO_MUCH");
// If this is also the collateral, run seizeInternal to avoid re-entrancy, otherwise make an external call
uint seizeError;
if (address(cTokenCollateral) == address(this)) {
seizeError = seizeInternal(address(this), liquidator, borrower, seizeTokens);
} else {
seizeError = cTokenCollateral.seize(liquidator, borrower, seizeTokens);
}
/* Revert if seize tokens fails (since we cannot be sure of side effects) */
require(seizeError == uint(Error.NO_ERROR), "token seizure failed");
/* We emit a LiquidateBorrow event */
emit LiquidateBorrow(liquidator, borrower, actualRepayAmount, address(cTokenCollateral), seizeTokens);
/* We call the defense hook */
// unused function
// comptroller.liquidateBorrowVerify(address(this), address(cTokenCollateral), liquidator, borrower, actualRepayAmount, seizeTokens);
return (uint(Error.NO_ERROR), actualRepayAmount);
}
| 18,457 |
105 | // Emitted exactly once by a pool when initialize is first called on the pool/Mint/Burn/Swap cannot be emitted by the pool before Initialize/sqrtPriceX96 The initial sqrt price of the pool, as a Q64.96/tick The initial tick of the pool, i.e. log base 1.0001 of the starting price of the pool | event Initialize(uint160 sqrtPriceX96, int24 tick);
| event Initialize(uint160 sqrtPriceX96, int24 tick);
| 29,786 |
28 | // function saltAsDecimalAndHashAsString(bytes32 lhs,bytes32 rhs) public purereturns(string memory) | //{
//return string(saltAsDecimalAndHash(
// lhs,
// rhs
// ));
//}
| //{
//return string(saltAsDecimalAndHash(
// lhs,
// rhs
// ));
//}
| 50,975 |
10 | // Initialize parent contracts | __AbstractStorefront_init__(platform, minter);
| __AbstractStorefront_init__(platform, minter);
| 44,454 |
32 | // If the call failed, ensure no ETH was spent and skip this NFT. | if (address(this).balance != balanceBefore) {
revert ContributionsSpentForFailedBuyError();
}
| if (address(this).balance != balanceBefore) {
revert ContributionsSpentForFailedBuyError();
}
| 26,527 |
96 | // OwnablePausableUpgradeableBundles Access Control, Pausable and Upgradeable contracts in one./ | abstract contract OwnablePausableUpgradeable is IOwnablePausable, PausableUpgradeable, AccessControlUpgradeable {
bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE");
/**
* @dev Modifier for checking whether the caller is an admin.
*/
modifier onlyAdmin() {
require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "OwnablePausable: access denied");
_;
}
/**
* @dev Modifier for checking whether the caller is a pauser.
*/
modifier onlyPauser() {
require(hasRole(PAUSER_ROLE, msg.sender), "OwnablePausable: access denied");
_;
}
// solhint-disable-next-line func-name-mixedcase
function __OwnablePausableUpgradeable_init(address _admin) internal initializer {
__Context_init_unchained();
__AccessControl_init_unchained();
__Pausable_init_unchained();
__OwnablePausableUpgradeable_init_unchained(_admin);
}
/**
* @dev Grants `DEFAULT_ADMIN_ROLE`, `PAUSER_ROLE` to the admin account.
*/
// solhint-disable-next-line func-name-mixedcase
function __OwnablePausableUpgradeable_init_unchained(address _admin) internal initializer {
_setupRole(DEFAULT_ADMIN_ROLE, _admin);
_setupRole(PAUSER_ROLE, _admin);
}
/**
* @dev See {IOwnablePausable-isAdmin}.
*/
function isAdmin(address _account) external override view returns (bool) {
return hasRole(DEFAULT_ADMIN_ROLE, _account);
}
/**
* @dev See {IOwnablePausable-addAdmin}.
*/
function addAdmin(address _account) external override {
grantRole(DEFAULT_ADMIN_ROLE, _account);
}
/**
* @dev See {IOwnablePausable-removeAdmin}.
*/
function removeAdmin(address _account) external override {
revokeRole(DEFAULT_ADMIN_ROLE, _account);
}
/**
* @dev See {IOwnablePausable-isPauser}.
*/
function isPauser(address _account) external override view returns (bool) {
return hasRole(PAUSER_ROLE, _account);
}
/**
* @dev See {IOwnablePausable-addPauser}.
*/
function addPauser(address _account) external override {
grantRole(PAUSER_ROLE, _account);
}
/**
* @dev See {IOwnablePausable-removePauser}.
*/
function removePauser(address _account) external override {
revokeRole(PAUSER_ROLE, _account);
}
/**
* @dev See {IOwnablePausable-pause}.
*/
function pause() external override onlyPauser {
_pause();
}
/**
* @dev See {IOwnablePausable-unpause}.
*/
function unpause() external override onlyPauser {
_unpause();
}
}
| abstract contract OwnablePausableUpgradeable is IOwnablePausable, PausableUpgradeable, AccessControlUpgradeable {
bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE");
/**
* @dev Modifier for checking whether the caller is an admin.
*/
modifier onlyAdmin() {
require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "OwnablePausable: access denied");
_;
}
/**
* @dev Modifier for checking whether the caller is a pauser.
*/
modifier onlyPauser() {
require(hasRole(PAUSER_ROLE, msg.sender), "OwnablePausable: access denied");
_;
}
// solhint-disable-next-line func-name-mixedcase
function __OwnablePausableUpgradeable_init(address _admin) internal initializer {
__Context_init_unchained();
__AccessControl_init_unchained();
__Pausable_init_unchained();
__OwnablePausableUpgradeable_init_unchained(_admin);
}
/**
* @dev Grants `DEFAULT_ADMIN_ROLE`, `PAUSER_ROLE` to the admin account.
*/
// solhint-disable-next-line func-name-mixedcase
function __OwnablePausableUpgradeable_init_unchained(address _admin) internal initializer {
_setupRole(DEFAULT_ADMIN_ROLE, _admin);
_setupRole(PAUSER_ROLE, _admin);
}
/**
* @dev See {IOwnablePausable-isAdmin}.
*/
function isAdmin(address _account) external override view returns (bool) {
return hasRole(DEFAULT_ADMIN_ROLE, _account);
}
/**
* @dev See {IOwnablePausable-addAdmin}.
*/
function addAdmin(address _account) external override {
grantRole(DEFAULT_ADMIN_ROLE, _account);
}
/**
* @dev See {IOwnablePausable-removeAdmin}.
*/
function removeAdmin(address _account) external override {
revokeRole(DEFAULT_ADMIN_ROLE, _account);
}
/**
* @dev See {IOwnablePausable-isPauser}.
*/
function isPauser(address _account) external override view returns (bool) {
return hasRole(PAUSER_ROLE, _account);
}
/**
* @dev See {IOwnablePausable-addPauser}.
*/
function addPauser(address _account) external override {
grantRole(PAUSER_ROLE, _account);
}
/**
* @dev See {IOwnablePausable-removePauser}.
*/
function removePauser(address _account) external override {
revokeRole(PAUSER_ROLE, _account);
}
/**
* @dev See {IOwnablePausable-pause}.
*/
function pause() external override onlyPauser {
_pause();
}
/**
* @dev See {IOwnablePausable-unpause}.
*/
function unpause() external override onlyPauser {
_unpause();
}
}
| 52,042 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.