contract_name
stringlengths
1
61
file_path
stringlengths
5
50.4k
contract_address
stringlengths
42
42
language
stringclasses
1 value
class_name
stringlengths
1
61
class_code
stringlengths
4
330k
class_documentation
stringlengths
0
29.1k
class_documentation_type
stringclasses
6 values
func_name
stringlengths
0
62
func_code
stringlengths
1
303k
func_documentation
stringlengths
2
14.9k
func_documentation_type
stringclasses
4 values
compiler_version
stringlengths
15
42
license_type
stringclasses
14 values
swarm_source
stringlengths
0
71
meta
dict
__index_level_0__
int64
0
60.4k
Fish
Fish.sol
0x80c1a36dcbdca742f59f09fda16c43e6ad877c2b
Solidity
Fish
contract Fish is owned, StandardToken { string public constant TermsOfUse = "https://github.com/triangles-things/fish.project/blob/master/terms-of-use.md"; /* * State variables */ string public constant symbol = "FSH"; string public constant name = "Fish"; uint8 public constant decimals = 3; /* * Constructor function */ function Fish() { owner = msg.sender; balances[msg.sender] = 1; // Owner can now be a referral totalSupply = 1; buyPrice_wie= 100000000000000; // 100 szabo per one token. One unit = 1000 tokens. 1 ether = 10 units sellPrice_wie = buyPrice_wie * sell_ppc / 100; } function () payable { revert(); } /* * SECTION: PRICE GROWTH * * This section is responsible for daily price increase. Once per day the buy price will be increased * through adjustPrice modifier. The price update happens before buy and sell functions are executed. * Contract owner has only one way to control the growth rate here - setGrowth. */ // Growth rate is present in parts per million (ppm) uint32 public dailyGrowth_ppm = 6100; // default growth is 20% (0.61% per day) uint public dailyGrowthUpdated_date = now; // Don't update it on first day of contract uint32 private constant dailyGrowthMin_ppm = 6096; // 20% every month in price growth or 0.00610 daily uint32 private constant dailyGrowthMax_ppm = 23374; // 100% in growth every month or 0,02337 daily uint32 public constant sell_ppc = 90; // Sell price is 90% of buy price event DailyGrowthUpdate(uint _newRate_ppm); event PriceAdjusted(uint _newBuyPrice_wei, uint _newSellPrice_wei); /* * MODIFIER * If last update happened more than one day ago, update the price, save the time of current price update * Adjust sell price and log the event */ modifier adjustPrice() { if ( (dailyGrowthUpdated_date + 1 days) < now ) { dailyGrowthUpdated_date = now; buyPrice_wie = buyPrice_wie * (1000000 + dailyGrowth_ppm) / 1000000; sellPrice_wie = buyPrice_wie * sell_ppc / 100; PriceAdjusted(buyPrice_wie, sellPrice_wie); } _; } /* * OWNER ONLY; EXTERNAL METHOD * setGrowth can accept values within range from 20% to 100% of growth per month (based on 30 days per month assumption). * * Formula is: * * buyPrice_eth = buyPrice_eth * (1000000 + dailyGrowthMin_ppm) / 1000000; * ^new value ^current value ^1.0061 (if dailyGrowth_ppm == 6100) * * 1.0061^30 = 1.20 (if dailyGrowth_ppm == 6100) * 1.023374^30 = 2 (if dailyGrowth_ppm == 23374) * * Some other daily rates * * Per month -> Value in ppm * 1.3 -> 8783 * 1.4 -> 11278 * 1.5 -> 13607 * 1.6 -> 15790 * 1.7 -> 17844 * 1.8 -> 19786 */ function setGrowth(uint32 _newGrowth_ppm) onlyOwner external returns(bool result) { if (_newGrowth_ppm >= dailyGrowthMin_ppm && _newGrowth_ppm <= dailyGrowthMax_ppm ) { dailyGrowth_ppm = _newGrowth_ppm; DailyGrowthUpdate(_newGrowth_ppm); return true; } else { return false; } } /* * SECTION: TRADING * * This section is responsible purely for trading the tokens. User can buy tokens, user can sell tokens. * */ uint256 public sellPrice_wie; uint256 public buyPrice_wie; /* * EXTERNAL METHOD * User can buy arbitrary amount of tokens. Before amount of tokens will be calculated, the price of tokens * has to be adjusted. This happens in adjustPrice modified before function call. * * Short description of this method * * Calculate tokens that user is buying * Assign awards ro refereals * Add some bounty for new users who set referral before first buy * Send tokens that belong to contract or if there is non issue more and send them to user * * Read -> https://github.com/triangles-things/fish.project/blob/master/terms-of-use.md */ function buy() adjustPrice payable external { require(msg.value >= buyPrice_wie); var amount = safeDiv(msg.value, buyPrice_wie); assignBountryToReferals(msg.sender, amount); // First assign bounty // Buy discount if User is a new user and has set referral if ( balances[msg.sender] == 0 && referrals[msg.sender][0] != 0 ) { // Check that user has to wait at least two weeks before he get break even on what he will get amount = amount * (100 + landingDiscount_ppc) / 100; } issueTo(msg.sender, amount); } /* * EXTERNAL METHOD * User can sell tokens back to contract. * * Short description of this method * * Adjust price * Calculate tokens price that user is selling * Make all possible checks * Transfer the money */ function sell(uint256 _amount) adjustPrice external { require(_amount > 0 && balances[msg.sender] >= _amount); uint moneyWorth = safeMul(_amount, sellPrice_wie); require(this.balance > moneyWorth); // We can't sell if we don't have enough money if ( balances[this] + _amount > balances[this] && balances[msg.sender] - _amount < balances[msg.sender] ) { balances[this] = safeAdd(balances[this], _amount); // adds the amount to owner's balance balances[msg.sender] = safeSub(balances[msg.sender], _amount); // subtracts the amount from seller's balance if (!msg.sender.send(moneyWorth)) { // sends ether to the seller. It's important revert(); // to do this last to avoid recursion attacks } else { Transfer(msg.sender, this, _amount); // executes an event reflecting on the change } } else { revert(); // checks if the sender has enough to sell } } /* * PRIVATE METHOD * Issue new tokens to contract */ function issueTo(address _beneficiary, uint256 _amount_tkns) private { if ( balances[this] >= _amount_tkns ) { // All tokens are taken from balance balances[this] = safeSub(balances[this], _amount_tkns); balances[_beneficiary] = safeAdd(balances[_beneficiary], _amount_tkns); } else { // Balance will be lowered and new tokens will be issued uint diff = safeSub(_amount_tkns, balances[this]); totalSupply = safeAdd(totalSupply, diff); balances[this] = 0; balances[_beneficiary] = safeAdd(balances[_beneficiary], _amount_tkns); } Transfer(this, _beneficiary, _amount_tkns); } /* * SECTION: BOUNTIES * * This section describes all possible awards. */ mapping(address => address[3]) referrals; mapping(address => uint256) bounties; uint32 public constant landingDiscount_ppc = 4; // Landing discount is 4% /* * EXTERNAL METHOD * Set your referral first. You will get 4% more tokens on your first buy and trigger a * reward of whoever told you about this contract. A win-win scenario. */ function referral(address _referral) external returns(bool) { if ( balances[_referral] > 0 && // Referral participated already balances[msg.sender] == 0 && // Sender is a new user referrals[msg.sender][0] == 0 // Not returning user. User can not reassign their referrals but they can assign them later on ) { var referral_referrals = referrals[_referral]; referrals[msg.sender] = [_referral, referral_referrals[0], referral_referrals[1]]; return true; } return false; } /* * PRIVATE METHOD * Award bounties to referrals. */ function assignBountryToReferals(address _referralsOf, uint256 _amount) private { var refs = referrals[_referralsOf]; if (refs[0] != 0) { issueTo(refs[0], (_amount * 4) / 100); // 4% bounty to direct referral if (refs[1] != 0) { issueTo(refs[1], (_amount * 2) / 100); // 2% bounty to referral of referral if (refs[2] != 0) { issueTo(refs[2], (_amount * 1) / 100); // 1% bounty to referral of referral of referral } } } } /* * OWNER ONLY; EXTERNAL METHOD * Santa is coming! Who ever made impact to promote the Fish and can prove it will get the bonus */ function assignBounty(address _account, uint256 _amount) onlyOwner external returns(bool) { require(_amount > 0); if (balances[_account] > 0 && // Account had participated already bounties[_account] + _amount <= 1000000 // no more than 100 token units per account ) { issueTo(_account, _amount); return true; } else { return false; } } }
Fish
function Fish() { owner = msg.sender; balances[msg.sender] = 1; // Owner can now be a referral totalSupply = 1; buyPrice_wie= 100000000000000; // 100 szabo per one token. One unit = 1000 tokens. 1 ether = 10 units sellPrice_wie = buyPrice_wie * sell_ppc / 100; }
/* * Constructor function */
Comment
v0.4.15+commit.bbb8e64f
bzzr://4613992a993e1bbc51872aa0c9329a881775179ceea4634a49734b7b20cbfb32
{ "func_code_index": [ 367, 755 ] }
8,600
Fish
Fish.sol
0x80c1a36dcbdca742f59f09fda16c43e6ad877c2b
Solidity
Fish
contract Fish is owned, StandardToken { string public constant TermsOfUse = "https://github.com/triangles-things/fish.project/blob/master/terms-of-use.md"; /* * State variables */ string public constant symbol = "FSH"; string public constant name = "Fish"; uint8 public constant decimals = 3; /* * Constructor function */ function Fish() { owner = msg.sender; balances[msg.sender] = 1; // Owner can now be a referral totalSupply = 1; buyPrice_wie= 100000000000000; // 100 szabo per one token. One unit = 1000 tokens. 1 ether = 10 units sellPrice_wie = buyPrice_wie * sell_ppc / 100; } function () payable { revert(); } /* * SECTION: PRICE GROWTH * * This section is responsible for daily price increase. Once per day the buy price will be increased * through adjustPrice modifier. The price update happens before buy and sell functions are executed. * Contract owner has only one way to control the growth rate here - setGrowth. */ // Growth rate is present in parts per million (ppm) uint32 public dailyGrowth_ppm = 6100; // default growth is 20% (0.61% per day) uint public dailyGrowthUpdated_date = now; // Don't update it on first day of contract uint32 private constant dailyGrowthMin_ppm = 6096; // 20% every month in price growth or 0.00610 daily uint32 private constant dailyGrowthMax_ppm = 23374; // 100% in growth every month or 0,02337 daily uint32 public constant sell_ppc = 90; // Sell price is 90% of buy price event DailyGrowthUpdate(uint _newRate_ppm); event PriceAdjusted(uint _newBuyPrice_wei, uint _newSellPrice_wei); /* * MODIFIER * If last update happened more than one day ago, update the price, save the time of current price update * Adjust sell price and log the event */ modifier adjustPrice() { if ( (dailyGrowthUpdated_date + 1 days) < now ) { dailyGrowthUpdated_date = now; buyPrice_wie = buyPrice_wie * (1000000 + dailyGrowth_ppm) / 1000000; sellPrice_wie = buyPrice_wie * sell_ppc / 100; PriceAdjusted(buyPrice_wie, sellPrice_wie); } _; } /* * OWNER ONLY; EXTERNAL METHOD * setGrowth can accept values within range from 20% to 100% of growth per month (based on 30 days per month assumption). * * Formula is: * * buyPrice_eth = buyPrice_eth * (1000000 + dailyGrowthMin_ppm) / 1000000; * ^new value ^current value ^1.0061 (if dailyGrowth_ppm == 6100) * * 1.0061^30 = 1.20 (if dailyGrowth_ppm == 6100) * 1.023374^30 = 2 (if dailyGrowth_ppm == 23374) * * Some other daily rates * * Per month -> Value in ppm * 1.3 -> 8783 * 1.4 -> 11278 * 1.5 -> 13607 * 1.6 -> 15790 * 1.7 -> 17844 * 1.8 -> 19786 */ function setGrowth(uint32 _newGrowth_ppm) onlyOwner external returns(bool result) { if (_newGrowth_ppm >= dailyGrowthMin_ppm && _newGrowth_ppm <= dailyGrowthMax_ppm ) { dailyGrowth_ppm = _newGrowth_ppm; DailyGrowthUpdate(_newGrowth_ppm); return true; } else { return false; } } /* * SECTION: TRADING * * This section is responsible purely for trading the tokens. User can buy tokens, user can sell tokens. * */ uint256 public sellPrice_wie; uint256 public buyPrice_wie; /* * EXTERNAL METHOD * User can buy arbitrary amount of tokens. Before amount of tokens will be calculated, the price of tokens * has to be adjusted. This happens in adjustPrice modified before function call. * * Short description of this method * * Calculate tokens that user is buying * Assign awards ro refereals * Add some bounty for new users who set referral before first buy * Send tokens that belong to contract or if there is non issue more and send them to user * * Read -> https://github.com/triangles-things/fish.project/blob/master/terms-of-use.md */ function buy() adjustPrice payable external { require(msg.value >= buyPrice_wie); var amount = safeDiv(msg.value, buyPrice_wie); assignBountryToReferals(msg.sender, amount); // First assign bounty // Buy discount if User is a new user and has set referral if ( balances[msg.sender] == 0 && referrals[msg.sender][0] != 0 ) { // Check that user has to wait at least two weeks before he get break even on what he will get amount = amount * (100 + landingDiscount_ppc) / 100; } issueTo(msg.sender, amount); } /* * EXTERNAL METHOD * User can sell tokens back to contract. * * Short description of this method * * Adjust price * Calculate tokens price that user is selling * Make all possible checks * Transfer the money */ function sell(uint256 _amount) adjustPrice external { require(_amount > 0 && balances[msg.sender] >= _amount); uint moneyWorth = safeMul(_amount, sellPrice_wie); require(this.balance > moneyWorth); // We can't sell if we don't have enough money if ( balances[this] + _amount > balances[this] && balances[msg.sender] - _amount < balances[msg.sender] ) { balances[this] = safeAdd(balances[this], _amount); // adds the amount to owner's balance balances[msg.sender] = safeSub(balances[msg.sender], _amount); // subtracts the amount from seller's balance if (!msg.sender.send(moneyWorth)) { // sends ether to the seller. It's important revert(); // to do this last to avoid recursion attacks } else { Transfer(msg.sender, this, _amount); // executes an event reflecting on the change } } else { revert(); // checks if the sender has enough to sell } } /* * PRIVATE METHOD * Issue new tokens to contract */ function issueTo(address _beneficiary, uint256 _amount_tkns) private { if ( balances[this] >= _amount_tkns ) { // All tokens are taken from balance balances[this] = safeSub(balances[this], _amount_tkns); balances[_beneficiary] = safeAdd(balances[_beneficiary], _amount_tkns); } else { // Balance will be lowered and new tokens will be issued uint diff = safeSub(_amount_tkns, balances[this]); totalSupply = safeAdd(totalSupply, diff); balances[this] = 0; balances[_beneficiary] = safeAdd(balances[_beneficiary], _amount_tkns); } Transfer(this, _beneficiary, _amount_tkns); } /* * SECTION: BOUNTIES * * This section describes all possible awards. */ mapping(address => address[3]) referrals; mapping(address => uint256) bounties; uint32 public constant landingDiscount_ppc = 4; // Landing discount is 4% /* * EXTERNAL METHOD * Set your referral first. You will get 4% more tokens on your first buy and trigger a * reward of whoever told you about this contract. A win-win scenario. */ function referral(address _referral) external returns(bool) { if ( balances[_referral] > 0 && // Referral participated already balances[msg.sender] == 0 && // Sender is a new user referrals[msg.sender][0] == 0 // Not returning user. User can not reassign their referrals but they can assign them later on ) { var referral_referrals = referrals[_referral]; referrals[msg.sender] = [_referral, referral_referrals[0], referral_referrals[1]]; return true; } return false; } /* * PRIVATE METHOD * Award bounties to referrals. */ function assignBountryToReferals(address _referralsOf, uint256 _amount) private { var refs = referrals[_referralsOf]; if (refs[0] != 0) { issueTo(refs[0], (_amount * 4) / 100); // 4% bounty to direct referral if (refs[1] != 0) { issueTo(refs[1], (_amount * 2) / 100); // 2% bounty to referral of referral if (refs[2] != 0) { issueTo(refs[2], (_amount * 1) / 100); // 1% bounty to referral of referral of referral } } } } /* * OWNER ONLY; EXTERNAL METHOD * Santa is coming! Who ever made impact to promote the Fish and can prove it will get the bonus */ function assignBounty(address _account, uint256 _amount) onlyOwner external returns(bool) { require(_amount > 0); if (balances[_account] > 0 && // Account had participated already bounties[_account] + _amount <= 1000000 // no more than 100 token units per account ) { issueTo(_account, _amount); return true; } else { return false; } } }
setGrowth
function setGrowth(uint32 _newGrowth_ppm) onlyOwner external returns(bool result) { if (_newGrowth_ppm >= dailyGrowthMin_ppm && _newGrowth_ppm <= dailyGrowthMax_ppm ) { dailyGrowth_ppm = _newGrowth_ppm; DailyGrowthUpdate(_newGrowth_ppm); return true; } else { return false; } }
/* * OWNER ONLY; EXTERNAL METHOD * setGrowth can accept values within range from 20% to 100% of growth per month (based on 30 days per month assumption). * * Formula is: * * buyPrice_eth = buyPrice_eth * (1000000 + dailyGrowthMin_ppm) / 1000000; * ^new value ^current value ^1.0061 (if dailyGrowth_ppm == 6100) * * 1.0061^30 = 1.20 (if dailyGrowth_ppm == 6100) * 1.023374^30 = 2 (if dailyGrowth_ppm == 23374) * * Some other daily rates * * Per month -> Value in ppm * 1.3 -> 8783 * 1.4 -> 11278 * 1.5 -> 13607 * 1.6 -> 15790 * 1.7 -> 17844 * 1.8 -> 19786 */
Comment
v0.4.15+commit.bbb8e64f
bzzr://4613992a993e1bbc51872aa0c9329a881775179ceea4634a49734b7b20cbfb32
{ "func_code_index": [ 3183, 3523 ] }
8,601
Fish
Fish.sol
0x80c1a36dcbdca742f59f09fda16c43e6ad877c2b
Solidity
Fish
contract Fish is owned, StandardToken { string public constant TermsOfUse = "https://github.com/triangles-things/fish.project/blob/master/terms-of-use.md"; /* * State variables */ string public constant symbol = "FSH"; string public constant name = "Fish"; uint8 public constant decimals = 3; /* * Constructor function */ function Fish() { owner = msg.sender; balances[msg.sender] = 1; // Owner can now be a referral totalSupply = 1; buyPrice_wie= 100000000000000; // 100 szabo per one token. One unit = 1000 tokens. 1 ether = 10 units sellPrice_wie = buyPrice_wie * sell_ppc / 100; } function () payable { revert(); } /* * SECTION: PRICE GROWTH * * This section is responsible for daily price increase. Once per day the buy price will be increased * through adjustPrice modifier. The price update happens before buy and sell functions are executed. * Contract owner has only one way to control the growth rate here - setGrowth. */ // Growth rate is present in parts per million (ppm) uint32 public dailyGrowth_ppm = 6100; // default growth is 20% (0.61% per day) uint public dailyGrowthUpdated_date = now; // Don't update it on first day of contract uint32 private constant dailyGrowthMin_ppm = 6096; // 20% every month in price growth or 0.00610 daily uint32 private constant dailyGrowthMax_ppm = 23374; // 100% in growth every month or 0,02337 daily uint32 public constant sell_ppc = 90; // Sell price is 90% of buy price event DailyGrowthUpdate(uint _newRate_ppm); event PriceAdjusted(uint _newBuyPrice_wei, uint _newSellPrice_wei); /* * MODIFIER * If last update happened more than one day ago, update the price, save the time of current price update * Adjust sell price and log the event */ modifier adjustPrice() { if ( (dailyGrowthUpdated_date + 1 days) < now ) { dailyGrowthUpdated_date = now; buyPrice_wie = buyPrice_wie * (1000000 + dailyGrowth_ppm) / 1000000; sellPrice_wie = buyPrice_wie * sell_ppc / 100; PriceAdjusted(buyPrice_wie, sellPrice_wie); } _; } /* * OWNER ONLY; EXTERNAL METHOD * setGrowth can accept values within range from 20% to 100% of growth per month (based on 30 days per month assumption). * * Formula is: * * buyPrice_eth = buyPrice_eth * (1000000 + dailyGrowthMin_ppm) / 1000000; * ^new value ^current value ^1.0061 (if dailyGrowth_ppm == 6100) * * 1.0061^30 = 1.20 (if dailyGrowth_ppm == 6100) * 1.023374^30 = 2 (if dailyGrowth_ppm == 23374) * * Some other daily rates * * Per month -> Value in ppm * 1.3 -> 8783 * 1.4 -> 11278 * 1.5 -> 13607 * 1.6 -> 15790 * 1.7 -> 17844 * 1.8 -> 19786 */ function setGrowth(uint32 _newGrowth_ppm) onlyOwner external returns(bool result) { if (_newGrowth_ppm >= dailyGrowthMin_ppm && _newGrowth_ppm <= dailyGrowthMax_ppm ) { dailyGrowth_ppm = _newGrowth_ppm; DailyGrowthUpdate(_newGrowth_ppm); return true; } else { return false; } } /* * SECTION: TRADING * * This section is responsible purely for trading the tokens. User can buy tokens, user can sell tokens. * */ uint256 public sellPrice_wie; uint256 public buyPrice_wie; /* * EXTERNAL METHOD * User can buy arbitrary amount of tokens. Before amount of tokens will be calculated, the price of tokens * has to be adjusted. This happens in adjustPrice modified before function call. * * Short description of this method * * Calculate tokens that user is buying * Assign awards ro refereals * Add some bounty for new users who set referral before first buy * Send tokens that belong to contract or if there is non issue more and send them to user * * Read -> https://github.com/triangles-things/fish.project/blob/master/terms-of-use.md */ function buy() adjustPrice payable external { require(msg.value >= buyPrice_wie); var amount = safeDiv(msg.value, buyPrice_wie); assignBountryToReferals(msg.sender, amount); // First assign bounty // Buy discount if User is a new user and has set referral if ( balances[msg.sender] == 0 && referrals[msg.sender][0] != 0 ) { // Check that user has to wait at least two weeks before he get break even on what he will get amount = amount * (100 + landingDiscount_ppc) / 100; } issueTo(msg.sender, amount); } /* * EXTERNAL METHOD * User can sell tokens back to contract. * * Short description of this method * * Adjust price * Calculate tokens price that user is selling * Make all possible checks * Transfer the money */ function sell(uint256 _amount) adjustPrice external { require(_amount > 0 && balances[msg.sender] >= _amount); uint moneyWorth = safeMul(_amount, sellPrice_wie); require(this.balance > moneyWorth); // We can't sell if we don't have enough money if ( balances[this] + _amount > balances[this] && balances[msg.sender] - _amount < balances[msg.sender] ) { balances[this] = safeAdd(balances[this], _amount); // adds the amount to owner's balance balances[msg.sender] = safeSub(balances[msg.sender], _amount); // subtracts the amount from seller's balance if (!msg.sender.send(moneyWorth)) { // sends ether to the seller. It's important revert(); // to do this last to avoid recursion attacks } else { Transfer(msg.sender, this, _amount); // executes an event reflecting on the change } } else { revert(); // checks if the sender has enough to sell } } /* * PRIVATE METHOD * Issue new tokens to contract */ function issueTo(address _beneficiary, uint256 _amount_tkns) private { if ( balances[this] >= _amount_tkns ) { // All tokens are taken from balance balances[this] = safeSub(balances[this], _amount_tkns); balances[_beneficiary] = safeAdd(balances[_beneficiary], _amount_tkns); } else { // Balance will be lowered and new tokens will be issued uint diff = safeSub(_amount_tkns, balances[this]); totalSupply = safeAdd(totalSupply, diff); balances[this] = 0; balances[_beneficiary] = safeAdd(balances[_beneficiary], _amount_tkns); } Transfer(this, _beneficiary, _amount_tkns); } /* * SECTION: BOUNTIES * * This section describes all possible awards. */ mapping(address => address[3]) referrals; mapping(address => uint256) bounties; uint32 public constant landingDiscount_ppc = 4; // Landing discount is 4% /* * EXTERNAL METHOD * Set your referral first. You will get 4% more tokens on your first buy and trigger a * reward of whoever told you about this contract. A win-win scenario. */ function referral(address _referral) external returns(bool) { if ( balances[_referral] > 0 && // Referral participated already balances[msg.sender] == 0 && // Sender is a new user referrals[msg.sender][0] == 0 // Not returning user. User can not reassign their referrals but they can assign them later on ) { var referral_referrals = referrals[_referral]; referrals[msg.sender] = [_referral, referral_referrals[0], referral_referrals[1]]; return true; } return false; } /* * PRIVATE METHOD * Award bounties to referrals. */ function assignBountryToReferals(address _referralsOf, uint256 _amount) private { var refs = referrals[_referralsOf]; if (refs[0] != 0) { issueTo(refs[0], (_amount * 4) / 100); // 4% bounty to direct referral if (refs[1] != 0) { issueTo(refs[1], (_amount * 2) / 100); // 2% bounty to referral of referral if (refs[2] != 0) { issueTo(refs[2], (_amount * 1) / 100); // 1% bounty to referral of referral of referral } } } } /* * OWNER ONLY; EXTERNAL METHOD * Santa is coming! Who ever made impact to promote the Fish and can prove it will get the bonus */ function assignBounty(address _account, uint256 _amount) onlyOwner external returns(bool) { require(_amount > 0); if (balances[_account] > 0 && // Account had participated already bounties[_account] + _amount <= 1000000 // no more than 100 token units per account ) { issueTo(_account, _amount); return true; } else { return false; } } }
buy
function buy() adjustPrice payable external { require(msg.value >= buyPrice_wie); var amount = safeDiv(msg.value, buyPrice_wie); assignBountryToReferals(msg.sender, amount); // First assign bounty // Buy discount if User is a new user and has set referral if ( balances[msg.sender] == 0 && referrals[msg.sender][0] != 0 ) { // Check that user has to wait at least two weeks before he get break even on what he will get amount = amount * (100 + landingDiscount_ppc) / 100; } issueTo(msg.sender, amount); }
/* * EXTERNAL METHOD * User can buy arbitrary amount of tokens. Before amount of tokens will be calculated, the price of tokens * has to be adjusted. This happens in adjustPrice modified before function call. * * Short description of this method * * Calculate tokens that user is buying * Assign awards ro refereals * Add some bounty for new users who set referral before first buy * Send tokens that belong to contract or if there is non issue more and send them to user * * Read -> https://github.com/triangles-things/fish.project/blob/master/terms-of-use.md */
Comment
v0.4.15+commit.bbb8e64f
bzzr://4613992a993e1bbc51872aa0c9329a881775179ceea4634a49734b7b20cbfb32
{ "func_code_index": [ 4380, 4976 ] }
8,602
Fish
Fish.sol
0x80c1a36dcbdca742f59f09fda16c43e6ad877c2b
Solidity
Fish
contract Fish is owned, StandardToken { string public constant TermsOfUse = "https://github.com/triangles-things/fish.project/blob/master/terms-of-use.md"; /* * State variables */ string public constant symbol = "FSH"; string public constant name = "Fish"; uint8 public constant decimals = 3; /* * Constructor function */ function Fish() { owner = msg.sender; balances[msg.sender] = 1; // Owner can now be a referral totalSupply = 1; buyPrice_wie= 100000000000000; // 100 szabo per one token. One unit = 1000 tokens. 1 ether = 10 units sellPrice_wie = buyPrice_wie * sell_ppc / 100; } function () payable { revert(); } /* * SECTION: PRICE GROWTH * * This section is responsible for daily price increase. Once per day the buy price will be increased * through adjustPrice modifier. The price update happens before buy and sell functions are executed. * Contract owner has only one way to control the growth rate here - setGrowth. */ // Growth rate is present in parts per million (ppm) uint32 public dailyGrowth_ppm = 6100; // default growth is 20% (0.61% per day) uint public dailyGrowthUpdated_date = now; // Don't update it on first day of contract uint32 private constant dailyGrowthMin_ppm = 6096; // 20% every month in price growth or 0.00610 daily uint32 private constant dailyGrowthMax_ppm = 23374; // 100% in growth every month or 0,02337 daily uint32 public constant sell_ppc = 90; // Sell price is 90% of buy price event DailyGrowthUpdate(uint _newRate_ppm); event PriceAdjusted(uint _newBuyPrice_wei, uint _newSellPrice_wei); /* * MODIFIER * If last update happened more than one day ago, update the price, save the time of current price update * Adjust sell price and log the event */ modifier adjustPrice() { if ( (dailyGrowthUpdated_date + 1 days) < now ) { dailyGrowthUpdated_date = now; buyPrice_wie = buyPrice_wie * (1000000 + dailyGrowth_ppm) / 1000000; sellPrice_wie = buyPrice_wie * sell_ppc / 100; PriceAdjusted(buyPrice_wie, sellPrice_wie); } _; } /* * OWNER ONLY; EXTERNAL METHOD * setGrowth can accept values within range from 20% to 100% of growth per month (based on 30 days per month assumption). * * Formula is: * * buyPrice_eth = buyPrice_eth * (1000000 + dailyGrowthMin_ppm) / 1000000; * ^new value ^current value ^1.0061 (if dailyGrowth_ppm == 6100) * * 1.0061^30 = 1.20 (if dailyGrowth_ppm == 6100) * 1.023374^30 = 2 (if dailyGrowth_ppm == 23374) * * Some other daily rates * * Per month -> Value in ppm * 1.3 -> 8783 * 1.4 -> 11278 * 1.5 -> 13607 * 1.6 -> 15790 * 1.7 -> 17844 * 1.8 -> 19786 */ function setGrowth(uint32 _newGrowth_ppm) onlyOwner external returns(bool result) { if (_newGrowth_ppm >= dailyGrowthMin_ppm && _newGrowth_ppm <= dailyGrowthMax_ppm ) { dailyGrowth_ppm = _newGrowth_ppm; DailyGrowthUpdate(_newGrowth_ppm); return true; } else { return false; } } /* * SECTION: TRADING * * This section is responsible purely for trading the tokens. User can buy tokens, user can sell tokens. * */ uint256 public sellPrice_wie; uint256 public buyPrice_wie; /* * EXTERNAL METHOD * User can buy arbitrary amount of tokens. Before amount of tokens will be calculated, the price of tokens * has to be adjusted. This happens in adjustPrice modified before function call. * * Short description of this method * * Calculate tokens that user is buying * Assign awards ro refereals * Add some bounty for new users who set referral before first buy * Send tokens that belong to contract or if there is non issue more and send them to user * * Read -> https://github.com/triangles-things/fish.project/blob/master/terms-of-use.md */ function buy() adjustPrice payable external { require(msg.value >= buyPrice_wie); var amount = safeDiv(msg.value, buyPrice_wie); assignBountryToReferals(msg.sender, amount); // First assign bounty // Buy discount if User is a new user and has set referral if ( balances[msg.sender] == 0 && referrals[msg.sender][0] != 0 ) { // Check that user has to wait at least two weeks before he get break even on what he will get amount = amount * (100 + landingDiscount_ppc) / 100; } issueTo(msg.sender, amount); } /* * EXTERNAL METHOD * User can sell tokens back to contract. * * Short description of this method * * Adjust price * Calculate tokens price that user is selling * Make all possible checks * Transfer the money */ function sell(uint256 _amount) adjustPrice external { require(_amount > 0 && balances[msg.sender] >= _amount); uint moneyWorth = safeMul(_amount, sellPrice_wie); require(this.balance > moneyWorth); // We can't sell if we don't have enough money if ( balances[this] + _amount > balances[this] && balances[msg.sender] - _amount < balances[msg.sender] ) { balances[this] = safeAdd(balances[this], _amount); // adds the amount to owner's balance balances[msg.sender] = safeSub(balances[msg.sender], _amount); // subtracts the amount from seller's balance if (!msg.sender.send(moneyWorth)) { // sends ether to the seller. It's important revert(); // to do this last to avoid recursion attacks } else { Transfer(msg.sender, this, _amount); // executes an event reflecting on the change } } else { revert(); // checks if the sender has enough to sell } } /* * PRIVATE METHOD * Issue new tokens to contract */ function issueTo(address _beneficiary, uint256 _amount_tkns) private { if ( balances[this] >= _amount_tkns ) { // All tokens are taken from balance balances[this] = safeSub(balances[this], _amount_tkns); balances[_beneficiary] = safeAdd(balances[_beneficiary], _amount_tkns); } else { // Balance will be lowered and new tokens will be issued uint diff = safeSub(_amount_tkns, balances[this]); totalSupply = safeAdd(totalSupply, diff); balances[this] = 0; balances[_beneficiary] = safeAdd(balances[_beneficiary], _amount_tkns); } Transfer(this, _beneficiary, _amount_tkns); } /* * SECTION: BOUNTIES * * This section describes all possible awards. */ mapping(address => address[3]) referrals; mapping(address => uint256) bounties; uint32 public constant landingDiscount_ppc = 4; // Landing discount is 4% /* * EXTERNAL METHOD * Set your referral first. You will get 4% more tokens on your first buy and trigger a * reward of whoever told you about this contract. A win-win scenario. */ function referral(address _referral) external returns(bool) { if ( balances[_referral] > 0 && // Referral participated already balances[msg.sender] == 0 && // Sender is a new user referrals[msg.sender][0] == 0 // Not returning user. User can not reassign their referrals but they can assign them later on ) { var referral_referrals = referrals[_referral]; referrals[msg.sender] = [_referral, referral_referrals[0], referral_referrals[1]]; return true; } return false; } /* * PRIVATE METHOD * Award bounties to referrals. */ function assignBountryToReferals(address _referralsOf, uint256 _amount) private { var refs = referrals[_referralsOf]; if (refs[0] != 0) { issueTo(refs[0], (_amount * 4) / 100); // 4% bounty to direct referral if (refs[1] != 0) { issueTo(refs[1], (_amount * 2) / 100); // 2% bounty to referral of referral if (refs[2] != 0) { issueTo(refs[2], (_amount * 1) / 100); // 1% bounty to referral of referral of referral } } } } /* * OWNER ONLY; EXTERNAL METHOD * Santa is coming! Who ever made impact to promote the Fish and can prove it will get the bonus */ function assignBounty(address _account, uint256 _amount) onlyOwner external returns(bool) { require(_amount > 0); if (balances[_account] > 0 && // Account had participated already bounties[_account] + _amount <= 1000000 // no more than 100 token units per account ) { issueTo(_account, _amount); return true; } else { return false; } } }
sell
function sell(uint256 _amount) adjustPrice external { require(_amount > 0 && balances[msg.sender] >= _amount); uint moneyWorth = safeMul(_amount, sellPrice_wie); require(this.balance > moneyWorth); // We can't sell if we don't have enough money if ( balances[this] + _amount > balances[this] && balances[msg.sender] - _amount < balances[msg.sender] ) { balances[this] = safeAdd(balances[this], _amount); // adds the amount to owner's balance balances[msg.sender] = safeSub(balances[msg.sender], _amount); // subtracts the amount from seller's balance if (!msg.sender.send(moneyWorth)) { // sends ether to the seller. It's important revert(); // to do this last to avoid recursion attacks } else { Transfer(msg.sender, this, _amount); // executes an event reflecting on the change } } else { revert(); // checks if the sender has enough to sell } }
/* * EXTERNAL METHOD * User can sell tokens back to contract. * * Short description of this method * * Adjust price * Calculate tokens price that user is selling * Make all possible checks * Transfer the money */
Comment
v0.4.15+commit.bbb8e64f
bzzr://4613992a993e1bbc51872aa0c9329a881775179ceea4634a49734b7b20cbfb32
{ "func_code_index": [ 5244, 6499 ] }
8,603
Fish
Fish.sol
0x80c1a36dcbdca742f59f09fda16c43e6ad877c2b
Solidity
Fish
contract Fish is owned, StandardToken { string public constant TermsOfUse = "https://github.com/triangles-things/fish.project/blob/master/terms-of-use.md"; /* * State variables */ string public constant symbol = "FSH"; string public constant name = "Fish"; uint8 public constant decimals = 3; /* * Constructor function */ function Fish() { owner = msg.sender; balances[msg.sender] = 1; // Owner can now be a referral totalSupply = 1; buyPrice_wie= 100000000000000; // 100 szabo per one token. One unit = 1000 tokens. 1 ether = 10 units sellPrice_wie = buyPrice_wie * sell_ppc / 100; } function () payable { revert(); } /* * SECTION: PRICE GROWTH * * This section is responsible for daily price increase. Once per day the buy price will be increased * through adjustPrice modifier. The price update happens before buy and sell functions are executed. * Contract owner has only one way to control the growth rate here - setGrowth. */ // Growth rate is present in parts per million (ppm) uint32 public dailyGrowth_ppm = 6100; // default growth is 20% (0.61% per day) uint public dailyGrowthUpdated_date = now; // Don't update it on first day of contract uint32 private constant dailyGrowthMin_ppm = 6096; // 20% every month in price growth or 0.00610 daily uint32 private constant dailyGrowthMax_ppm = 23374; // 100% in growth every month or 0,02337 daily uint32 public constant sell_ppc = 90; // Sell price is 90% of buy price event DailyGrowthUpdate(uint _newRate_ppm); event PriceAdjusted(uint _newBuyPrice_wei, uint _newSellPrice_wei); /* * MODIFIER * If last update happened more than one day ago, update the price, save the time of current price update * Adjust sell price and log the event */ modifier adjustPrice() { if ( (dailyGrowthUpdated_date + 1 days) < now ) { dailyGrowthUpdated_date = now; buyPrice_wie = buyPrice_wie * (1000000 + dailyGrowth_ppm) / 1000000; sellPrice_wie = buyPrice_wie * sell_ppc / 100; PriceAdjusted(buyPrice_wie, sellPrice_wie); } _; } /* * OWNER ONLY; EXTERNAL METHOD * setGrowth can accept values within range from 20% to 100% of growth per month (based on 30 days per month assumption). * * Formula is: * * buyPrice_eth = buyPrice_eth * (1000000 + dailyGrowthMin_ppm) / 1000000; * ^new value ^current value ^1.0061 (if dailyGrowth_ppm == 6100) * * 1.0061^30 = 1.20 (if dailyGrowth_ppm == 6100) * 1.023374^30 = 2 (if dailyGrowth_ppm == 23374) * * Some other daily rates * * Per month -> Value in ppm * 1.3 -> 8783 * 1.4 -> 11278 * 1.5 -> 13607 * 1.6 -> 15790 * 1.7 -> 17844 * 1.8 -> 19786 */ function setGrowth(uint32 _newGrowth_ppm) onlyOwner external returns(bool result) { if (_newGrowth_ppm >= dailyGrowthMin_ppm && _newGrowth_ppm <= dailyGrowthMax_ppm ) { dailyGrowth_ppm = _newGrowth_ppm; DailyGrowthUpdate(_newGrowth_ppm); return true; } else { return false; } } /* * SECTION: TRADING * * This section is responsible purely for trading the tokens. User can buy tokens, user can sell tokens. * */ uint256 public sellPrice_wie; uint256 public buyPrice_wie; /* * EXTERNAL METHOD * User can buy arbitrary amount of tokens. Before amount of tokens will be calculated, the price of tokens * has to be adjusted. This happens in adjustPrice modified before function call. * * Short description of this method * * Calculate tokens that user is buying * Assign awards ro refereals * Add some bounty for new users who set referral before first buy * Send tokens that belong to contract or if there is non issue more and send them to user * * Read -> https://github.com/triangles-things/fish.project/blob/master/terms-of-use.md */ function buy() adjustPrice payable external { require(msg.value >= buyPrice_wie); var amount = safeDiv(msg.value, buyPrice_wie); assignBountryToReferals(msg.sender, amount); // First assign bounty // Buy discount if User is a new user and has set referral if ( balances[msg.sender] == 0 && referrals[msg.sender][0] != 0 ) { // Check that user has to wait at least two weeks before he get break even on what he will get amount = amount * (100 + landingDiscount_ppc) / 100; } issueTo(msg.sender, amount); } /* * EXTERNAL METHOD * User can sell tokens back to contract. * * Short description of this method * * Adjust price * Calculate tokens price that user is selling * Make all possible checks * Transfer the money */ function sell(uint256 _amount) adjustPrice external { require(_amount > 0 && balances[msg.sender] >= _amount); uint moneyWorth = safeMul(_amount, sellPrice_wie); require(this.balance > moneyWorth); // We can't sell if we don't have enough money if ( balances[this] + _amount > balances[this] && balances[msg.sender] - _amount < balances[msg.sender] ) { balances[this] = safeAdd(balances[this], _amount); // adds the amount to owner's balance balances[msg.sender] = safeSub(balances[msg.sender], _amount); // subtracts the amount from seller's balance if (!msg.sender.send(moneyWorth)) { // sends ether to the seller. It's important revert(); // to do this last to avoid recursion attacks } else { Transfer(msg.sender, this, _amount); // executes an event reflecting on the change } } else { revert(); // checks if the sender has enough to sell } } /* * PRIVATE METHOD * Issue new tokens to contract */ function issueTo(address _beneficiary, uint256 _amount_tkns) private { if ( balances[this] >= _amount_tkns ) { // All tokens are taken from balance balances[this] = safeSub(balances[this], _amount_tkns); balances[_beneficiary] = safeAdd(balances[_beneficiary], _amount_tkns); } else { // Balance will be lowered and new tokens will be issued uint diff = safeSub(_amount_tkns, balances[this]); totalSupply = safeAdd(totalSupply, diff); balances[this] = 0; balances[_beneficiary] = safeAdd(balances[_beneficiary], _amount_tkns); } Transfer(this, _beneficiary, _amount_tkns); } /* * SECTION: BOUNTIES * * This section describes all possible awards. */ mapping(address => address[3]) referrals; mapping(address => uint256) bounties; uint32 public constant landingDiscount_ppc = 4; // Landing discount is 4% /* * EXTERNAL METHOD * Set your referral first. You will get 4% more tokens on your first buy and trigger a * reward of whoever told you about this contract. A win-win scenario. */ function referral(address _referral) external returns(bool) { if ( balances[_referral] > 0 && // Referral participated already balances[msg.sender] == 0 && // Sender is a new user referrals[msg.sender][0] == 0 // Not returning user. User can not reassign their referrals but they can assign them later on ) { var referral_referrals = referrals[_referral]; referrals[msg.sender] = [_referral, referral_referrals[0], referral_referrals[1]]; return true; } return false; } /* * PRIVATE METHOD * Award bounties to referrals. */ function assignBountryToReferals(address _referralsOf, uint256 _amount) private { var refs = referrals[_referralsOf]; if (refs[0] != 0) { issueTo(refs[0], (_amount * 4) / 100); // 4% bounty to direct referral if (refs[1] != 0) { issueTo(refs[1], (_amount * 2) / 100); // 2% bounty to referral of referral if (refs[2] != 0) { issueTo(refs[2], (_amount * 1) / 100); // 1% bounty to referral of referral of referral } } } } /* * OWNER ONLY; EXTERNAL METHOD * Santa is coming! Who ever made impact to promote the Fish and can prove it will get the bonus */ function assignBounty(address _account, uint256 _amount) onlyOwner external returns(bool) { require(_amount > 0); if (balances[_account] > 0 && // Account had participated already bounties[_account] + _amount <= 1000000 // no more than 100 token units per account ) { issueTo(_account, _amount); return true; } else { return false; } } }
issueTo
function issueTo(address _beneficiary, uint256 _amount_tkns) private { if ( balances[this] >= _amount_tkns ) { // All tokens are taken from balance balances[this] = safeSub(balances[this], _amount_tkns); balances[_beneficiary] = safeAdd(balances[_beneficiary], _amount_tkns); } else { // Balance will be lowered and new tokens will be issued uint diff = safeSub(_amount_tkns, balances[this]); totalSupply = safeAdd(totalSupply, diff); balances[this] = 0; balances[_beneficiary] = safeAdd(balances[_beneficiary], _amount_tkns); } Transfer(this, _beneficiary, _amount_tkns); }
/* * PRIVATE METHOD * Issue new tokens to contract */
Comment
v0.4.15+commit.bbb8e64f
bzzr://4613992a993e1bbc51872aa0c9329a881775179ceea4634a49734b7b20cbfb32
{ "func_code_index": [ 6572, 7250 ] }
8,604
Fish
Fish.sol
0x80c1a36dcbdca742f59f09fda16c43e6ad877c2b
Solidity
Fish
contract Fish is owned, StandardToken { string public constant TermsOfUse = "https://github.com/triangles-things/fish.project/blob/master/terms-of-use.md"; /* * State variables */ string public constant symbol = "FSH"; string public constant name = "Fish"; uint8 public constant decimals = 3; /* * Constructor function */ function Fish() { owner = msg.sender; balances[msg.sender] = 1; // Owner can now be a referral totalSupply = 1; buyPrice_wie= 100000000000000; // 100 szabo per one token. One unit = 1000 tokens. 1 ether = 10 units sellPrice_wie = buyPrice_wie * sell_ppc / 100; } function () payable { revert(); } /* * SECTION: PRICE GROWTH * * This section is responsible for daily price increase. Once per day the buy price will be increased * through adjustPrice modifier. The price update happens before buy and sell functions are executed. * Contract owner has only one way to control the growth rate here - setGrowth. */ // Growth rate is present in parts per million (ppm) uint32 public dailyGrowth_ppm = 6100; // default growth is 20% (0.61% per day) uint public dailyGrowthUpdated_date = now; // Don't update it on first day of contract uint32 private constant dailyGrowthMin_ppm = 6096; // 20% every month in price growth or 0.00610 daily uint32 private constant dailyGrowthMax_ppm = 23374; // 100% in growth every month or 0,02337 daily uint32 public constant sell_ppc = 90; // Sell price is 90% of buy price event DailyGrowthUpdate(uint _newRate_ppm); event PriceAdjusted(uint _newBuyPrice_wei, uint _newSellPrice_wei); /* * MODIFIER * If last update happened more than one day ago, update the price, save the time of current price update * Adjust sell price and log the event */ modifier adjustPrice() { if ( (dailyGrowthUpdated_date + 1 days) < now ) { dailyGrowthUpdated_date = now; buyPrice_wie = buyPrice_wie * (1000000 + dailyGrowth_ppm) / 1000000; sellPrice_wie = buyPrice_wie * sell_ppc / 100; PriceAdjusted(buyPrice_wie, sellPrice_wie); } _; } /* * OWNER ONLY; EXTERNAL METHOD * setGrowth can accept values within range from 20% to 100% of growth per month (based on 30 days per month assumption). * * Formula is: * * buyPrice_eth = buyPrice_eth * (1000000 + dailyGrowthMin_ppm) / 1000000; * ^new value ^current value ^1.0061 (if dailyGrowth_ppm == 6100) * * 1.0061^30 = 1.20 (if dailyGrowth_ppm == 6100) * 1.023374^30 = 2 (if dailyGrowth_ppm == 23374) * * Some other daily rates * * Per month -> Value in ppm * 1.3 -> 8783 * 1.4 -> 11278 * 1.5 -> 13607 * 1.6 -> 15790 * 1.7 -> 17844 * 1.8 -> 19786 */ function setGrowth(uint32 _newGrowth_ppm) onlyOwner external returns(bool result) { if (_newGrowth_ppm >= dailyGrowthMin_ppm && _newGrowth_ppm <= dailyGrowthMax_ppm ) { dailyGrowth_ppm = _newGrowth_ppm; DailyGrowthUpdate(_newGrowth_ppm); return true; } else { return false; } } /* * SECTION: TRADING * * This section is responsible purely for trading the tokens. User can buy tokens, user can sell tokens. * */ uint256 public sellPrice_wie; uint256 public buyPrice_wie; /* * EXTERNAL METHOD * User can buy arbitrary amount of tokens. Before amount of tokens will be calculated, the price of tokens * has to be adjusted. This happens in adjustPrice modified before function call. * * Short description of this method * * Calculate tokens that user is buying * Assign awards ro refereals * Add some bounty for new users who set referral before first buy * Send tokens that belong to contract or if there is non issue more and send them to user * * Read -> https://github.com/triangles-things/fish.project/blob/master/terms-of-use.md */ function buy() adjustPrice payable external { require(msg.value >= buyPrice_wie); var amount = safeDiv(msg.value, buyPrice_wie); assignBountryToReferals(msg.sender, amount); // First assign bounty // Buy discount if User is a new user and has set referral if ( balances[msg.sender] == 0 && referrals[msg.sender][0] != 0 ) { // Check that user has to wait at least two weeks before he get break even on what he will get amount = amount * (100 + landingDiscount_ppc) / 100; } issueTo(msg.sender, amount); } /* * EXTERNAL METHOD * User can sell tokens back to contract. * * Short description of this method * * Adjust price * Calculate tokens price that user is selling * Make all possible checks * Transfer the money */ function sell(uint256 _amount) adjustPrice external { require(_amount > 0 && balances[msg.sender] >= _amount); uint moneyWorth = safeMul(_amount, sellPrice_wie); require(this.balance > moneyWorth); // We can't sell if we don't have enough money if ( balances[this] + _amount > balances[this] && balances[msg.sender] - _amount < balances[msg.sender] ) { balances[this] = safeAdd(balances[this], _amount); // adds the amount to owner's balance balances[msg.sender] = safeSub(balances[msg.sender], _amount); // subtracts the amount from seller's balance if (!msg.sender.send(moneyWorth)) { // sends ether to the seller. It's important revert(); // to do this last to avoid recursion attacks } else { Transfer(msg.sender, this, _amount); // executes an event reflecting on the change } } else { revert(); // checks if the sender has enough to sell } } /* * PRIVATE METHOD * Issue new tokens to contract */ function issueTo(address _beneficiary, uint256 _amount_tkns) private { if ( balances[this] >= _amount_tkns ) { // All tokens are taken from balance balances[this] = safeSub(balances[this], _amount_tkns); balances[_beneficiary] = safeAdd(balances[_beneficiary], _amount_tkns); } else { // Balance will be lowered and new tokens will be issued uint diff = safeSub(_amount_tkns, balances[this]); totalSupply = safeAdd(totalSupply, diff); balances[this] = 0; balances[_beneficiary] = safeAdd(balances[_beneficiary], _amount_tkns); } Transfer(this, _beneficiary, _amount_tkns); } /* * SECTION: BOUNTIES * * This section describes all possible awards. */ mapping(address => address[3]) referrals; mapping(address => uint256) bounties; uint32 public constant landingDiscount_ppc = 4; // Landing discount is 4% /* * EXTERNAL METHOD * Set your referral first. You will get 4% more tokens on your first buy and trigger a * reward of whoever told you about this contract. A win-win scenario. */ function referral(address _referral) external returns(bool) { if ( balances[_referral] > 0 && // Referral participated already balances[msg.sender] == 0 && // Sender is a new user referrals[msg.sender][0] == 0 // Not returning user. User can not reassign their referrals but they can assign them later on ) { var referral_referrals = referrals[_referral]; referrals[msg.sender] = [_referral, referral_referrals[0], referral_referrals[1]]; return true; } return false; } /* * PRIVATE METHOD * Award bounties to referrals. */ function assignBountryToReferals(address _referralsOf, uint256 _amount) private { var refs = referrals[_referralsOf]; if (refs[0] != 0) { issueTo(refs[0], (_amount * 4) / 100); // 4% bounty to direct referral if (refs[1] != 0) { issueTo(refs[1], (_amount * 2) / 100); // 2% bounty to referral of referral if (refs[2] != 0) { issueTo(refs[2], (_amount * 1) / 100); // 1% bounty to referral of referral of referral } } } } /* * OWNER ONLY; EXTERNAL METHOD * Santa is coming! Who ever made impact to promote the Fish and can prove it will get the bonus */ function assignBounty(address _account, uint256 _amount) onlyOwner external returns(bool) { require(_amount > 0); if (balances[_account] > 0 && // Account had participated already bounties[_account] + _amount <= 1000000 // no more than 100 token units per account ) { issueTo(_account, _amount); return true; } else { return false; } } }
referral
function referral(address _referral) external returns(bool) { if ( balances[_referral] > 0 && // Referral participated already balances[msg.sender] == 0 && // Sender is a new user referrals[msg.sender][0] == 0 // Not returning user. User can not reassign their referrals but they can assign them later on ) { var referral_referrals = referrals[_referral]; referrals[msg.sender] = [_referral, referral_referrals[0], referral_referrals[1]]; return true; } return false; }
/* * EXTERNAL METHOD * Set your referral first. You will get 4% more tokens on your first buy and trigger a * reward of whoever told you about this contract. A win-win scenario. */
Comment
v0.4.15+commit.bbb8e64f
bzzr://4613992a993e1bbc51872aa0c9329a881775179ceea4634a49734b7b20cbfb32
{ "func_code_index": [ 7752, 8423 ] }
8,605
Fish
Fish.sol
0x80c1a36dcbdca742f59f09fda16c43e6ad877c2b
Solidity
Fish
contract Fish is owned, StandardToken { string public constant TermsOfUse = "https://github.com/triangles-things/fish.project/blob/master/terms-of-use.md"; /* * State variables */ string public constant symbol = "FSH"; string public constant name = "Fish"; uint8 public constant decimals = 3; /* * Constructor function */ function Fish() { owner = msg.sender; balances[msg.sender] = 1; // Owner can now be a referral totalSupply = 1; buyPrice_wie= 100000000000000; // 100 szabo per one token. One unit = 1000 tokens. 1 ether = 10 units sellPrice_wie = buyPrice_wie * sell_ppc / 100; } function () payable { revert(); } /* * SECTION: PRICE GROWTH * * This section is responsible for daily price increase. Once per day the buy price will be increased * through adjustPrice modifier. The price update happens before buy and sell functions are executed. * Contract owner has only one way to control the growth rate here - setGrowth. */ // Growth rate is present in parts per million (ppm) uint32 public dailyGrowth_ppm = 6100; // default growth is 20% (0.61% per day) uint public dailyGrowthUpdated_date = now; // Don't update it on first day of contract uint32 private constant dailyGrowthMin_ppm = 6096; // 20% every month in price growth or 0.00610 daily uint32 private constant dailyGrowthMax_ppm = 23374; // 100% in growth every month or 0,02337 daily uint32 public constant sell_ppc = 90; // Sell price is 90% of buy price event DailyGrowthUpdate(uint _newRate_ppm); event PriceAdjusted(uint _newBuyPrice_wei, uint _newSellPrice_wei); /* * MODIFIER * If last update happened more than one day ago, update the price, save the time of current price update * Adjust sell price and log the event */ modifier adjustPrice() { if ( (dailyGrowthUpdated_date + 1 days) < now ) { dailyGrowthUpdated_date = now; buyPrice_wie = buyPrice_wie * (1000000 + dailyGrowth_ppm) / 1000000; sellPrice_wie = buyPrice_wie * sell_ppc / 100; PriceAdjusted(buyPrice_wie, sellPrice_wie); } _; } /* * OWNER ONLY; EXTERNAL METHOD * setGrowth can accept values within range from 20% to 100% of growth per month (based on 30 days per month assumption). * * Formula is: * * buyPrice_eth = buyPrice_eth * (1000000 + dailyGrowthMin_ppm) / 1000000; * ^new value ^current value ^1.0061 (if dailyGrowth_ppm == 6100) * * 1.0061^30 = 1.20 (if dailyGrowth_ppm == 6100) * 1.023374^30 = 2 (if dailyGrowth_ppm == 23374) * * Some other daily rates * * Per month -> Value in ppm * 1.3 -> 8783 * 1.4 -> 11278 * 1.5 -> 13607 * 1.6 -> 15790 * 1.7 -> 17844 * 1.8 -> 19786 */ function setGrowth(uint32 _newGrowth_ppm) onlyOwner external returns(bool result) { if (_newGrowth_ppm >= dailyGrowthMin_ppm && _newGrowth_ppm <= dailyGrowthMax_ppm ) { dailyGrowth_ppm = _newGrowth_ppm; DailyGrowthUpdate(_newGrowth_ppm); return true; } else { return false; } } /* * SECTION: TRADING * * This section is responsible purely for trading the tokens. User can buy tokens, user can sell tokens. * */ uint256 public sellPrice_wie; uint256 public buyPrice_wie; /* * EXTERNAL METHOD * User can buy arbitrary amount of tokens. Before amount of tokens will be calculated, the price of tokens * has to be adjusted. This happens in adjustPrice modified before function call. * * Short description of this method * * Calculate tokens that user is buying * Assign awards ro refereals * Add some bounty for new users who set referral before first buy * Send tokens that belong to contract or if there is non issue more and send them to user * * Read -> https://github.com/triangles-things/fish.project/blob/master/terms-of-use.md */ function buy() adjustPrice payable external { require(msg.value >= buyPrice_wie); var amount = safeDiv(msg.value, buyPrice_wie); assignBountryToReferals(msg.sender, amount); // First assign bounty // Buy discount if User is a new user and has set referral if ( balances[msg.sender] == 0 && referrals[msg.sender][0] != 0 ) { // Check that user has to wait at least two weeks before he get break even on what he will get amount = amount * (100 + landingDiscount_ppc) / 100; } issueTo(msg.sender, amount); } /* * EXTERNAL METHOD * User can sell tokens back to contract. * * Short description of this method * * Adjust price * Calculate tokens price that user is selling * Make all possible checks * Transfer the money */ function sell(uint256 _amount) adjustPrice external { require(_amount > 0 && balances[msg.sender] >= _amount); uint moneyWorth = safeMul(_amount, sellPrice_wie); require(this.balance > moneyWorth); // We can't sell if we don't have enough money if ( balances[this] + _amount > balances[this] && balances[msg.sender] - _amount < balances[msg.sender] ) { balances[this] = safeAdd(balances[this], _amount); // adds the amount to owner's balance balances[msg.sender] = safeSub(balances[msg.sender], _amount); // subtracts the amount from seller's balance if (!msg.sender.send(moneyWorth)) { // sends ether to the seller. It's important revert(); // to do this last to avoid recursion attacks } else { Transfer(msg.sender, this, _amount); // executes an event reflecting on the change } } else { revert(); // checks if the sender has enough to sell } } /* * PRIVATE METHOD * Issue new tokens to contract */ function issueTo(address _beneficiary, uint256 _amount_tkns) private { if ( balances[this] >= _amount_tkns ) { // All tokens are taken from balance balances[this] = safeSub(balances[this], _amount_tkns); balances[_beneficiary] = safeAdd(balances[_beneficiary], _amount_tkns); } else { // Balance will be lowered and new tokens will be issued uint diff = safeSub(_amount_tkns, balances[this]); totalSupply = safeAdd(totalSupply, diff); balances[this] = 0; balances[_beneficiary] = safeAdd(balances[_beneficiary], _amount_tkns); } Transfer(this, _beneficiary, _amount_tkns); } /* * SECTION: BOUNTIES * * This section describes all possible awards. */ mapping(address => address[3]) referrals; mapping(address => uint256) bounties; uint32 public constant landingDiscount_ppc = 4; // Landing discount is 4% /* * EXTERNAL METHOD * Set your referral first. You will get 4% more tokens on your first buy and trigger a * reward of whoever told you about this contract. A win-win scenario. */ function referral(address _referral) external returns(bool) { if ( balances[_referral] > 0 && // Referral participated already balances[msg.sender] == 0 && // Sender is a new user referrals[msg.sender][0] == 0 // Not returning user. User can not reassign their referrals but they can assign them later on ) { var referral_referrals = referrals[_referral]; referrals[msg.sender] = [_referral, referral_referrals[0], referral_referrals[1]]; return true; } return false; } /* * PRIVATE METHOD * Award bounties to referrals. */ function assignBountryToReferals(address _referralsOf, uint256 _amount) private { var refs = referrals[_referralsOf]; if (refs[0] != 0) { issueTo(refs[0], (_amount * 4) / 100); // 4% bounty to direct referral if (refs[1] != 0) { issueTo(refs[1], (_amount * 2) / 100); // 2% bounty to referral of referral if (refs[2] != 0) { issueTo(refs[2], (_amount * 1) / 100); // 1% bounty to referral of referral of referral } } } } /* * OWNER ONLY; EXTERNAL METHOD * Santa is coming! Who ever made impact to promote the Fish and can prove it will get the bonus */ function assignBounty(address _account, uint256 _amount) onlyOwner external returns(bool) { require(_amount > 0); if (balances[_account] > 0 && // Account had participated already bounties[_account] + _amount <= 1000000 // no more than 100 token units per account ) { issueTo(_account, _amount); return true; } else { return false; } } }
assignBountryToReferals
function assignBountryToReferals(address _referralsOf, uint256 _amount) private { var refs = referrals[_referralsOf]; if (refs[0] != 0) { issueTo(refs[0], (_amount * 4) / 100); // 4% bounty to direct referral if (refs[1] != 0) { issueTo(refs[1], (_amount * 2) / 100); // 2% bounty to referral of referral if (refs[2] != 0) { issueTo(refs[2], (_amount * 1) / 100); // 1% bounty to referral of referral of referral } } } }
/* * PRIVATE METHOD * Award bounties to referrals. */
Comment
v0.4.15+commit.bbb8e64f
bzzr://4613992a993e1bbc51872aa0c9329a881775179ceea4634a49734b7b20cbfb32
{ "func_code_index": [ 8496, 9100 ] }
8,606
Fish
Fish.sol
0x80c1a36dcbdca742f59f09fda16c43e6ad877c2b
Solidity
Fish
contract Fish is owned, StandardToken { string public constant TermsOfUse = "https://github.com/triangles-things/fish.project/blob/master/terms-of-use.md"; /* * State variables */ string public constant symbol = "FSH"; string public constant name = "Fish"; uint8 public constant decimals = 3; /* * Constructor function */ function Fish() { owner = msg.sender; balances[msg.sender] = 1; // Owner can now be a referral totalSupply = 1; buyPrice_wie= 100000000000000; // 100 szabo per one token. One unit = 1000 tokens. 1 ether = 10 units sellPrice_wie = buyPrice_wie * sell_ppc / 100; } function () payable { revert(); } /* * SECTION: PRICE GROWTH * * This section is responsible for daily price increase. Once per day the buy price will be increased * through adjustPrice modifier. The price update happens before buy and sell functions are executed. * Contract owner has only one way to control the growth rate here - setGrowth. */ // Growth rate is present in parts per million (ppm) uint32 public dailyGrowth_ppm = 6100; // default growth is 20% (0.61% per day) uint public dailyGrowthUpdated_date = now; // Don't update it on first day of contract uint32 private constant dailyGrowthMin_ppm = 6096; // 20% every month in price growth or 0.00610 daily uint32 private constant dailyGrowthMax_ppm = 23374; // 100% in growth every month or 0,02337 daily uint32 public constant sell_ppc = 90; // Sell price is 90% of buy price event DailyGrowthUpdate(uint _newRate_ppm); event PriceAdjusted(uint _newBuyPrice_wei, uint _newSellPrice_wei); /* * MODIFIER * If last update happened more than one day ago, update the price, save the time of current price update * Adjust sell price and log the event */ modifier adjustPrice() { if ( (dailyGrowthUpdated_date + 1 days) < now ) { dailyGrowthUpdated_date = now; buyPrice_wie = buyPrice_wie * (1000000 + dailyGrowth_ppm) / 1000000; sellPrice_wie = buyPrice_wie * sell_ppc / 100; PriceAdjusted(buyPrice_wie, sellPrice_wie); } _; } /* * OWNER ONLY; EXTERNAL METHOD * setGrowth can accept values within range from 20% to 100% of growth per month (based on 30 days per month assumption). * * Formula is: * * buyPrice_eth = buyPrice_eth * (1000000 + dailyGrowthMin_ppm) / 1000000; * ^new value ^current value ^1.0061 (if dailyGrowth_ppm == 6100) * * 1.0061^30 = 1.20 (if dailyGrowth_ppm == 6100) * 1.023374^30 = 2 (if dailyGrowth_ppm == 23374) * * Some other daily rates * * Per month -> Value in ppm * 1.3 -> 8783 * 1.4 -> 11278 * 1.5 -> 13607 * 1.6 -> 15790 * 1.7 -> 17844 * 1.8 -> 19786 */ function setGrowth(uint32 _newGrowth_ppm) onlyOwner external returns(bool result) { if (_newGrowth_ppm >= dailyGrowthMin_ppm && _newGrowth_ppm <= dailyGrowthMax_ppm ) { dailyGrowth_ppm = _newGrowth_ppm; DailyGrowthUpdate(_newGrowth_ppm); return true; } else { return false; } } /* * SECTION: TRADING * * This section is responsible purely for trading the tokens. User can buy tokens, user can sell tokens. * */ uint256 public sellPrice_wie; uint256 public buyPrice_wie; /* * EXTERNAL METHOD * User can buy arbitrary amount of tokens. Before amount of tokens will be calculated, the price of tokens * has to be adjusted. This happens in adjustPrice modified before function call. * * Short description of this method * * Calculate tokens that user is buying * Assign awards ro refereals * Add some bounty for new users who set referral before first buy * Send tokens that belong to contract or if there is non issue more and send them to user * * Read -> https://github.com/triangles-things/fish.project/blob/master/terms-of-use.md */ function buy() adjustPrice payable external { require(msg.value >= buyPrice_wie); var amount = safeDiv(msg.value, buyPrice_wie); assignBountryToReferals(msg.sender, amount); // First assign bounty // Buy discount if User is a new user and has set referral if ( balances[msg.sender] == 0 && referrals[msg.sender][0] != 0 ) { // Check that user has to wait at least two weeks before he get break even on what he will get amount = amount * (100 + landingDiscount_ppc) / 100; } issueTo(msg.sender, amount); } /* * EXTERNAL METHOD * User can sell tokens back to contract. * * Short description of this method * * Adjust price * Calculate tokens price that user is selling * Make all possible checks * Transfer the money */ function sell(uint256 _amount) adjustPrice external { require(_amount > 0 && balances[msg.sender] >= _amount); uint moneyWorth = safeMul(_amount, sellPrice_wie); require(this.balance > moneyWorth); // We can't sell if we don't have enough money if ( balances[this] + _amount > balances[this] && balances[msg.sender] - _amount < balances[msg.sender] ) { balances[this] = safeAdd(balances[this], _amount); // adds the amount to owner's balance balances[msg.sender] = safeSub(balances[msg.sender], _amount); // subtracts the amount from seller's balance if (!msg.sender.send(moneyWorth)) { // sends ether to the seller. It's important revert(); // to do this last to avoid recursion attacks } else { Transfer(msg.sender, this, _amount); // executes an event reflecting on the change } } else { revert(); // checks if the sender has enough to sell } } /* * PRIVATE METHOD * Issue new tokens to contract */ function issueTo(address _beneficiary, uint256 _amount_tkns) private { if ( balances[this] >= _amount_tkns ) { // All tokens are taken from balance balances[this] = safeSub(balances[this], _amount_tkns); balances[_beneficiary] = safeAdd(balances[_beneficiary], _amount_tkns); } else { // Balance will be lowered and new tokens will be issued uint diff = safeSub(_amount_tkns, balances[this]); totalSupply = safeAdd(totalSupply, diff); balances[this] = 0; balances[_beneficiary] = safeAdd(balances[_beneficiary], _amount_tkns); } Transfer(this, _beneficiary, _amount_tkns); } /* * SECTION: BOUNTIES * * This section describes all possible awards. */ mapping(address => address[3]) referrals; mapping(address => uint256) bounties; uint32 public constant landingDiscount_ppc = 4; // Landing discount is 4% /* * EXTERNAL METHOD * Set your referral first. You will get 4% more tokens on your first buy and trigger a * reward of whoever told you about this contract. A win-win scenario. */ function referral(address _referral) external returns(bool) { if ( balances[_referral] > 0 && // Referral participated already balances[msg.sender] == 0 && // Sender is a new user referrals[msg.sender][0] == 0 // Not returning user. User can not reassign their referrals but they can assign them later on ) { var referral_referrals = referrals[_referral]; referrals[msg.sender] = [_referral, referral_referrals[0], referral_referrals[1]]; return true; } return false; } /* * PRIVATE METHOD * Award bounties to referrals. */ function assignBountryToReferals(address _referralsOf, uint256 _amount) private { var refs = referrals[_referralsOf]; if (refs[0] != 0) { issueTo(refs[0], (_amount * 4) / 100); // 4% bounty to direct referral if (refs[1] != 0) { issueTo(refs[1], (_amount * 2) / 100); // 2% bounty to referral of referral if (refs[2] != 0) { issueTo(refs[2], (_amount * 1) / 100); // 1% bounty to referral of referral of referral } } } } /* * OWNER ONLY; EXTERNAL METHOD * Santa is coming! Who ever made impact to promote the Fish and can prove it will get the bonus */ function assignBounty(address _account, uint256 _amount) onlyOwner external returns(bool) { require(_amount > 0); if (balances[_account] > 0 && // Account had participated already bounties[_account] + _amount <= 1000000 // no more than 100 token units per account ) { issueTo(_account, _amount); return true; } else { return false; } } }
assignBounty
function assignBounty(address _account, uint256 _amount) onlyOwner external returns(bool) { require(_amount > 0); if (balances[_account] > 0 && // Account had participated already bounties[_account] + _amount <= 1000000 // no more than 100 token units per account ) { issueTo(_account, _amount); return true; } else { return false; } }
/* * OWNER ONLY; EXTERNAL METHOD * Santa is coming! Who ever made impact to promote the Fish and can prove it will get the bonus */
Comment
v0.4.15+commit.bbb8e64f
bzzr://4613992a993e1bbc51872aa0c9329a881775179ceea4634a49734b7b20cbfb32
{ "func_code_index": [ 9250, 9732 ] }
8,607
LinguaFranca
@openzeppelin/contracts/token/ERC721/ERC721.sol
0x9a7a5ff2c9563e96fbbed4dda94d5549b30f1efb
Solidity
ERC721
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} }
supportsInterface
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); }
/** * @dev See {IERC165-supportsInterface}. */
NatSpecMultiLine
v0.8.7+commit.e28d00a7
MIT
ipfs://ec30ad3b2c7be55c484ddb84aa17c0c44a22d432c6fab023a60ec5e2d7d4b3de
{ "func_code_index": [ 971, 1281 ] }
8,608
LinguaFranca
@openzeppelin/contracts/token/ERC721/ERC721.sol
0x9a7a5ff2c9563e96fbbed4dda94d5549b30f1efb
Solidity
ERC721
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} }
balanceOf
function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; }
/** * @dev See {IERC721-balanceOf}. */
NatSpecMultiLine
v0.8.7+commit.e28d00a7
MIT
ipfs://ec30ad3b2c7be55c484ddb84aa17c0c44a22d432c6fab023a60ec5e2d7d4b3de
{ "func_code_index": [ 1340, 1553 ] }
8,609
LinguaFranca
@openzeppelin/contracts/token/ERC721/ERC721.sol
0x9a7a5ff2c9563e96fbbed4dda94d5549b30f1efb
Solidity
ERC721
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} }
ownerOf
function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; }
/** * @dev See {IERC721-ownerOf}. */
NatSpecMultiLine
v0.8.7+commit.e28d00a7
MIT
ipfs://ec30ad3b2c7be55c484ddb84aa17c0c44a22d432c6fab023a60ec5e2d7d4b3de
{ "func_code_index": [ 1610, 1854 ] }
8,610
LinguaFranca
@openzeppelin/contracts/token/ERC721/ERC721.sol
0x9a7a5ff2c9563e96fbbed4dda94d5549b30f1efb
Solidity
ERC721
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} }
name
function name() public view virtual override returns (string memory) { return _name; }
/** * @dev See {IERC721Metadata-name}. */
NatSpecMultiLine
v0.8.7+commit.e28d00a7
MIT
ipfs://ec30ad3b2c7be55c484ddb84aa17c0c44a22d432c6fab023a60ec5e2d7d4b3de
{ "func_code_index": [ 1916, 2021 ] }
8,611
LinguaFranca
@openzeppelin/contracts/token/ERC721/ERC721.sol
0x9a7a5ff2c9563e96fbbed4dda94d5549b30f1efb
Solidity
ERC721
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} }
symbol
function symbol() public view virtual override returns (string memory) { return _symbol; }
/** * @dev See {IERC721Metadata-symbol}. */
NatSpecMultiLine
v0.8.7+commit.e28d00a7
MIT
ipfs://ec30ad3b2c7be55c484ddb84aa17c0c44a22d432c6fab023a60ec5e2d7d4b3de
{ "func_code_index": [ 2085, 2194 ] }
8,612
LinguaFranca
@openzeppelin/contracts/token/ERC721/ERC721.sol
0x9a7a5ff2c9563e96fbbed4dda94d5549b30f1efb
Solidity
ERC721
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} }
tokenURI
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; }
/** * @dev See {IERC721Metadata-tokenURI}. */
NatSpecMultiLine
v0.8.7+commit.e28d00a7
MIT
ipfs://ec30ad3b2c7be55c484ddb84aa17c0c44a22d432c6fab023a60ec5e2d7d4b3de
{ "func_code_index": [ 2260, 2599 ] }
8,613
LinguaFranca
@openzeppelin/contracts/token/ERC721/ERC721.sol
0x9a7a5ff2c9563e96fbbed4dda94d5549b30f1efb
Solidity
ERC721
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} }
_baseURI
function _baseURI() internal view virtual returns (string memory) { return ""; }
/** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */
NatSpecMultiLine
v0.8.7+commit.e28d00a7
MIT
ipfs://ec30ad3b2c7be55c484ddb84aa17c0c44a22d432c6fab023a60ec5e2d7d4b3de
{ "func_code_index": [ 2842, 2941 ] }
8,614
LinguaFranca
@openzeppelin/contracts/token/ERC721/ERC721.sol
0x9a7a5ff2c9563e96fbbed4dda94d5549b30f1efb
Solidity
ERC721
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} }
approve
function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); }
/** * @dev See {IERC721-approve}. */
NatSpecMultiLine
v0.8.7+commit.e28d00a7
MIT
ipfs://ec30ad3b2c7be55c484ddb84aa17c0c44a22d432c6fab023a60ec5e2d7d4b3de
{ "func_code_index": [ 2998, 3414 ] }
8,615
LinguaFranca
@openzeppelin/contracts/token/ERC721/ERC721.sol
0x9a7a5ff2c9563e96fbbed4dda94d5549b30f1efb
Solidity
ERC721
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} }
getApproved
function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; }
/** * @dev See {IERC721-getApproved}. */
NatSpecMultiLine
v0.8.7+commit.e28d00a7
MIT
ipfs://ec30ad3b2c7be55c484ddb84aa17c0c44a22d432c6fab023a60ec5e2d7d4b3de
{ "func_code_index": [ 3475, 3701 ] }
8,616
LinguaFranca
@openzeppelin/contracts/token/ERC721/ERC721.sol
0x9a7a5ff2c9563e96fbbed4dda94d5549b30f1efb
Solidity
ERC721
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} }
setApprovalForAll
function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); }
/** * @dev See {IERC721-setApprovalForAll}. */
NatSpecMultiLine
v0.8.7+commit.e28d00a7
MIT
ipfs://ec30ad3b2c7be55c484ddb84aa17c0c44a22d432c6fab023a60ec5e2d7d4b3de
{ "func_code_index": [ 3768, 4068 ] }
8,617
LinguaFranca
@openzeppelin/contracts/token/ERC721/ERC721.sol
0x9a7a5ff2c9563e96fbbed4dda94d5549b30f1efb
Solidity
ERC721
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} }
isApprovedForAll
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; }
/** * @dev See {IERC721-isApprovedForAll}. */
NatSpecMultiLine
v0.8.7+commit.e28d00a7
MIT
ipfs://ec30ad3b2c7be55c484ddb84aa17c0c44a22d432c6fab023a60ec5e2d7d4b3de
{ "func_code_index": [ 4134, 4303 ] }
8,618
LinguaFranca
@openzeppelin/contracts/token/ERC721/ERC721.sol
0x9a7a5ff2c9563e96fbbed4dda94d5549b30f1efb
Solidity
ERC721
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} }
transferFrom
function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); }
/** * @dev See {IERC721-transferFrom}. */
NatSpecMultiLine
v0.8.7+commit.e28d00a7
MIT
ipfs://ec30ad3b2c7be55c484ddb84aa17c0c44a22d432c6fab023a60ec5e2d7d4b3de
{ "func_code_index": [ 4365, 4709 ] }
8,619
LinguaFranca
@openzeppelin/contracts/token/ERC721/ERC721.sol
0x9a7a5ff2c9563e96fbbed4dda94d5549b30f1efb
Solidity
ERC721
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} }
safeTransferFrom
function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); }
/** * @dev See {IERC721-safeTransferFrom}. */
NatSpecMultiLine
v0.8.7+commit.e28d00a7
MIT
ipfs://ec30ad3b2c7be55c484ddb84aa17c0c44a22d432c6fab023a60ec5e2d7d4b3de
{ "func_code_index": [ 4775, 4965 ] }
8,620
LinguaFranca
@openzeppelin/contracts/token/ERC721/ERC721.sol
0x9a7a5ff2c9563e96fbbed4dda94d5549b30f1efb
Solidity
ERC721
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} }
safeTransferFrom
function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); }
/** * @dev See {IERC721-safeTransferFrom}. */
NatSpecMultiLine
v0.8.7+commit.e28d00a7
MIT
ipfs://ec30ad3b2c7be55c484ddb84aa17c0c44a22d432c6fab023a60ec5e2d7d4b3de
{ "func_code_index": [ 5031, 5364 ] }
8,621
LinguaFranca
@openzeppelin/contracts/token/ERC721/ERC721.sol
0x9a7a5ff2c9563e96fbbed4dda94d5549b30f1efb
Solidity
ERC721
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} }
_approve
function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); }
/** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */
NatSpecMultiLine
v0.8.7+commit.e28d00a7
MIT
ipfs://ec30ad3b2c7be55c484ddb84aa17c0c44a22d432c6fab023a60ec5e2d7d4b3de
{ "func_code_index": [ 8115, 8294 ] }
8,622
KomicaToken
KomicaToken.sol
0xa7c0728bf78328dc3c3e6c7e7e0da08a20eec1cb
Solidity
KomicaToken
contract KomicaToken is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; bytes32 public currentChallenge; // The coin starts with a challenge uint public timeOfLastProof = now; // Variable to keep track of when rewards were given uint public difficulty = 10**32; // Difficulty starts reasonably low mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ function KomicaToken() public { symbol = "KOMICA"; name = "Komica Token"; decimals = 18; _totalSupply = 188300000000000000000000000000; balances[0x006bdc1a30995Fd5a318B48c78F01A4ecFeA209E] = _totalSupply; Transfer(address(0), 0x006bdc1a30995Fd5a318B48c78F01A4ecFeA209E, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to to account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer tokens from the from account to the to account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the from account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account. The spender contract function // receiveApproval(...) is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () public payable { revert(); } function proofOfWork(uint nonce){ bytes8 n = bytes8(sha3(nonce, currentChallenge)); // Generate a random hash based on input require(n >= bytes8(difficulty)); // Check if it's under the difficulty uint timeSinceLastProof = (now - timeOfLastProof); // Calculate time since last reward was given require(timeSinceLastProof >= 5 seconds); // Rewards cannot be given too quickly balances[msg.sender] += timeSinceLastProof / 60 seconds; // The reward to the winner grows by the minute difficulty = difficulty * 10 minutes / timeSinceLastProof + 1; // Adjusts the difficulty timeOfLastProof = now; // Reset the counter currentChallenge = sha3(nonce, currentChallenge, block.blockhash(block.number - 1)); // Save a hash that will be used as the next proof } }
// ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and assisted // token transfers // ----------------------------------------------------------------------------
LineComment
KomicaToken
function KomicaToken() public { symbol = "KOMICA"; name = "Komica Token"; decimals = 18; _totalSupply = 188300000000000000000000000000; balances[0x006bdc1a30995Fd5a318B48c78F01A4ecFeA209E] = _totalSupply; Transfer(address(0), 0x006bdc1a30995Fd5a318B48c78F01A4ecFeA209E, _totalSupply); }
// ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------
LineComment
v0.4.23+commit.124ca40d
bzzr://4c6c8ebca81579c41a48e19e01d6c6fe800b097643ac441fadac67cf06780c97
{ "func_code_index": [ 749, 1099 ] }
8,623
KomicaToken
KomicaToken.sol
0xa7c0728bf78328dc3c3e6c7e7e0da08a20eec1cb
Solidity
KomicaToken
contract KomicaToken is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; bytes32 public currentChallenge; // The coin starts with a challenge uint public timeOfLastProof = now; // Variable to keep track of when rewards were given uint public difficulty = 10**32; // Difficulty starts reasonably low mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ function KomicaToken() public { symbol = "KOMICA"; name = "Komica Token"; decimals = 18; _totalSupply = 188300000000000000000000000000; balances[0x006bdc1a30995Fd5a318B48c78F01A4ecFeA209E] = _totalSupply; Transfer(address(0), 0x006bdc1a30995Fd5a318B48c78F01A4ecFeA209E, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to to account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer tokens from the from account to the to account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the from account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account. The spender contract function // receiveApproval(...) is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () public payable { revert(); } function proofOfWork(uint nonce){ bytes8 n = bytes8(sha3(nonce, currentChallenge)); // Generate a random hash based on input require(n >= bytes8(difficulty)); // Check if it's under the difficulty uint timeSinceLastProof = (now - timeOfLastProof); // Calculate time since last reward was given require(timeSinceLastProof >= 5 seconds); // Rewards cannot be given too quickly balances[msg.sender] += timeSinceLastProof / 60 seconds; // The reward to the winner grows by the minute difficulty = difficulty * 10 minutes / timeSinceLastProof + 1; // Adjusts the difficulty timeOfLastProof = now; // Reset the counter currentChallenge = sha3(nonce, currentChallenge, block.blockhash(block.number - 1)); // Save a hash that will be used as the next proof } }
// ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and assisted // token transfers // ----------------------------------------------------------------------------
LineComment
totalSupply
function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; }
// ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------
LineComment
v0.4.23+commit.124ca40d
bzzr://4c6c8ebca81579c41a48e19e01d6c6fe800b097643ac441fadac67cf06780c97
{ "func_code_index": [ 1287, 1408 ] }
8,624
KomicaToken
KomicaToken.sol
0xa7c0728bf78328dc3c3e6c7e7e0da08a20eec1cb
Solidity
KomicaToken
contract KomicaToken is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; bytes32 public currentChallenge; // The coin starts with a challenge uint public timeOfLastProof = now; // Variable to keep track of when rewards were given uint public difficulty = 10**32; // Difficulty starts reasonably low mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ function KomicaToken() public { symbol = "KOMICA"; name = "Komica Token"; decimals = 18; _totalSupply = 188300000000000000000000000000; balances[0x006bdc1a30995Fd5a318B48c78F01A4ecFeA209E] = _totalSupply; Transfer(address(0), 0x006bdc1a30995Fd5a318B48c78F01A4ecFeA209E, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to to account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer tokens from the from account to the to account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the from account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account. The spender contract function // receiveApproval(...) is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () public payable { revert(); } function proofOfWork(uint nonce){ bytes8 n = bytes8(sha3(nonce, currentChallenge)); // Generate a random hash based on input require(n >= bytes8(difficulty)); // Check if it's under the difficulty uint timeSinceLastProof = (now - timeOfLastProof); // Calculate time since last reward was given require(timeSinceLastProof >= 5 seconds); // Rewards cannot be given too quickly balances[msg.sender] += timeSinceLastProof / 60 seconds; // The reward to the winner grows by the minute difficulty = difficulty * 10 minutes / timeSinceLastProof + 1; // Adjusts the difficulty timeOfLastProof = now; // Reset the counter currentChallenge = sha3(nonce, currentChallenge, block.blockhash(block.number - 1)); // Save a hash that will be used as the next proof } }
// ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and assisted // token transfers // ----------------------------------------------------------------------------
LineComment
balanceOf
function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; }
// ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------
LineComment
v0.4.23+commit.124ca40d
bzzr://4c6c8ebca81579c41a48e19e01d6c6fe800b097643ac441fadac67cf06780c97
{ "func_code_index": [ 1628, 1757 ] }
8,625
KomicaToken
KomicaToken.sol
0xa7c0728bf78328dc3c3e6c7e7e0da08a20eec1cb
Solidity
KomicaToken
contract KomicaToken is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; bytes32 public currentChallenge; // The coin starts with a challenge uint public timeOfLastProof = now; // Variable to keep track of when rewards were given uint public difficulty = 10**32; // Difficulty starts reasonably low mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ function KomicaToken() public { symbol = "KOMICA"; name = "Komica Token"; decimals = 18; _totalSupply = 188300000000000000000000000000; balances[0x006bdc1a30995Fd5a318B48c78F01A4ecFeA209E] = _totalSupply; Transfer(address(0), 0x006bdc1a30995Fd5a318B48c78F01A4ecFeA209E, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to to account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer tokens from the from account to the to account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the from account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account. The spender contract function // receiveApproval(...) is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () public payable { revert(); } function proofOfWork(uint nonce){ bytes8 n = bytes8(sha3(nonce, currentChallenge)); // Generate a random hash based on input require(n >= bytes8(difficulty)); // Check if it's under the difficulty uint timeSinceLastProof = (now - timeOfLastProof); // Calculate time since last reward was given require(timeSinceLastProof >= 5 seconds); // Rewards cannot be given too quickly balances[msg.sender] += timeSinceLastProof / 60 seconds; // The reward to the winner grows by the minute difficulty = difficulty * 10 minutes / timeSinceLastProof + 1; // Adjusts the difficulty timeOfLastProof = now; // Reset the counter currentChallenge = sha3(nonce, currentChallenge, block.blockhash(block.number - 1)); // Save a hash that will be used as the next proof } }
// ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and assisted // token transfers // ----------------------------------------------------------------------------
LineComment
transfer
function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(msg.sender, to, tokens); return true; }
// ------------------------------------------------------------------------ // Transfer the balance from token owner's account to to account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------
LineComment
v0.4.23+commit.124ca40d
bzzr://4c6c8ebca81579c41a48e19e01d6c6fe800b097643ac441fadac67cf06780c97
{ "func_code_index": [ 2101, 2378 ] }
8,626
KomicaToken
KomicaToken.sol
0xa7c0728bf78328dc3c3e6c7e7e0da08a20eec1cb
Solidity
KomicaToken
contract KomicaToken is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; bytes32 public currentChallenge; // The coin starts with a challenge uint public timeOfLastProof = now; // Variable to keep track of when rewards were given uint public difficulty = 10**32; // Difficulty starts reasonably low mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ function KomicaToken() public { symbol = "KOMICA"; name = "Komica Token"; decimals = 18; _totalSupply = 188300000000000000000000000000; balances[0x006bdc1a30995Fd5a318B48c78F01A4ecFeA209E] = _totalSupply; Transfer(address(0), 0x006bdc1a30995Fd5a318B48c78F01A4ecFeA209E, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to to account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer tokens from the from account to the to account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the from account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account. The spender contract function // receiveApproval(...) is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () public payable { revert(); } function proofOfWork(uint nonce){ bytes8 n = bytes8(sha3(nonce, currentChallenge)); // Generate a random hash based on input require(n >= bytes8(difficulty)); // Check if it's under the difficulty uint timeSinceLastProof = (now - timeOfLastProof); // Calculate time since last reward was given require(timeSinceLastProof >= 5 seconds); // Rewards cannot be given too quickly balances[msg.sender] += timeSinceLastProof / 60 seconds; // The reward to the winner grows by the minute difficulty = difficulty * 10 minutes / timeSinceLastProof + 1; // Adjusts the difficulty timeOfLastProof = now; // Reset the counter currentChallenge = sha3(nonce, currentChallenge, block.blockhash(block.number - 1)); // Save a hash that will be used as the next proof } }
// ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and assisted // token transfers // ----------------------------------------------------------------------------
LineComment
approve
function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); return true; }
// ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------
LineComment
v0.4.23+commit.124ca40d
bzzr://4c6c8ebca81579c41a48e19e01d6c6fe800b097643ac441fadac67cf06780c97
{ "func_code_index": [ 2886, 3094 ] }
8,627
KomicaToken
KomicaToken.sol
0xa7c0728bf78328dc3c3e6c7e7e0da08a20eec1cb
Solidity
KomicaToken
contract KomicaToken is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; bytes32 public currentChallenge; // The coin starts with a challenge uint public timeOfLastProof = now; // Variable to keep track of when rewards were given uint public difficulty = 10**32; // Difficulty starts reasonably low mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ function KomicaToken() public { symbol = "KOMICA"; name = "Komica Token"; decimals = 18; _totalSupply = 188300000000000000000000000000; balances[0x006bdc1a30995Fd5a318B48c78F01A4ecFeA209E] = _totalSupply; Transfer(address(0), 0x006bdc1a30995Fd5a318B48c78F01A4ecFeA209E, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to to account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer tokens from the from account to the to account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the from account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account. The spender contract function // receiveApproval(...) is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () public payable { revert(); } function proofOfWork(uint nonce){ bytes8 n = bytes8(sha3(nonce, currentChallenge)); // Generate a random hash based on input require(n >= bytes8(difficulty)); // Check if it's under the difficulty uint timeSinceLastProof = (now - timeOfLastProof); // Calculate time since last reward was given require(timeSinceLastProof >= 5 seconds); // Rewards cannot be given too quickly balances[msg.sender] += timeSinceLastProof / 60 seconds; // The reward to the winner grows by the minute difficulty = difficulty * 10 minutes / timeSinceLastProof + 1; // Adjusts the difficulty timeOfLastProof = now; // Reset the counter currentChallenge = sha3(nonce, currentChallenge, block.blockhash(block.number - 1)); // Save a hash that will be used as the next proof } }
// ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and assisted // token transfers // ----------------------------------------------------------------------------
LineComment
transferFrom
function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(from, to, tokens); return true; }
// ------------------------------------------------------------------------ // Transfer tokens from the from account to the to account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the from account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------
LineComment
v0.4.23+commit.124ca40d
bzzr://4c6c8ebca81579c41a48e19e01d6c6fe800b097643ac441fadac67cf06780c97
{ "func_code_index": [ 3625, 3983 ] }
8,628
KomicaToken
KomicaToken.sol
0xa7c0728bf78328dc3c3e6c7e7e0da08a20eec1cb
Solidity
KomicaToken
contract KomicaToken is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; bytes32 public currentChallenge; // The coin starts with a challenge uint public timeOfLastProof = now; // Variable to keep track of when rewards were given uint public difficulty = 10**32; // Difficulty starts reasonably low mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ function KomicaToken() public { symbol = "KOMICA"; name = "Komica Token"; decimals = 18; _totalSupply = 188300000000000000000000000000; balances[0x006bdc1a30995Fd5a318B48c78F01A4ecFeA209E] = _totalSupply; Transfer(address(0), 0x006bdc1a30995Fd5a318B48c78F01A4ecFeA209E, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to to account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer tokens from the from account to the to account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the from account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account. The spender contract function // receiveApproval(...) is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () public payable { revert(); } function proofOfWork(uint nonce){ bytes8 n = bytes8(sha3(nonce, currentChallenge)); // Generate a random hash based on input require(n >= bytes8(difficulty)); // Check if it's under the difficulty uint timeSinceLastProof = (now - timeOfLastProof); // Calculate time since last reward was given require(timeSinceLastProof >= 5 seconds); // Rewards cannot be given too quickly balances[msg.sender] += timeSinceLastProof / 60 seconds; // The reward to the winner grows by the minute difficulty = difficulty * 10 minutes / timeSinceLastProof + 1; // Adjusts the difficulty timeOfLastProof = now; // Reset the counter currentChallenge = sha3(nonce, currentChallenge, block.blockhash(block.number - 1)); // Save a hash that will be used as the next proof } }
// ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and assisted // token transfers // ----------------------------------------------------------------------------
LineComment
allowance
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; }
// ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------
LineComment
v0.4.23+commit.124ca40d
bzzr://4c6c8ebca81579c41a48e19e01d6c6fe800b097643ac441fadac67cf06780c97
{ "func_code_index": [ 4266, 4422 ] }
8,629
KomicaToken
KomicaToken.sol
0xa7c0728bf78328dc3c3e6c7e7e0da08a20eec1cb
Solidity
KomicaToken
contract KomicaToken is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; bytes32 public currentChallenge; // The coin starts with a challenge uint public timeOfLastProof = now; // Variable to keep track of when rewards were given uint public difficulty = 10**32; // Difficulty starts reasonably low mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ function KomicaToken() public { symbol = "KOMICA"; name = "Komica Token"; decimals = 18; _totalSupply = 188300000000000000000000000000; balances[0x006bdc1a30995Fd5a318B48c78F01A4ecFeA209E] = _totalSupply; Transfer(address(0), 0x006bdc1a30995Fd5a318B48c78F01A4ecFeA209E, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to to account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer tokens from the from account to the to account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the from account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account. The spender contract function // receiveApproval(...) is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () public payable { revert(); } function proofOfWork(uint nonce){ bytes8 n = bytes8(sha3(nonce, currentChallenge)); // Generate a random hash based on input require(n >= bytes8(difficulty)); // Check if it's under the difficulty uint timeSinceLastProof = (now - timeOfLastProof); // Calculate time since last reward was given require(timeSinceLastProof >= 5 seconds); // Rewards cannot be given too quickly balances[msg.sender] += timeSinceLastProof / 60 seconds; // The reward to the winner grows by the minute difficulty = difficulty * 10 minutes / timeSinceLastProof + 1; // Adjusts the difficulty timeOfLastProof = now; // Reset the counter currentChallenge = sha3(nonce, currentChallenge, block.blockhash(block.number - 1)); // Save a hash that will be used as the next proof } }
// ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and assisted // token transfers // ----------------------------------------------------------------------------
LineComment
approveAndCall
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; }
// ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account. The spender contract function // receiveApproval(...) is then executed // ------------------------------------------------------------------------
LineComment
v0.4.23+commit.124ca40d
bzzr://4c6c8ebca81579c41a48e19e01d6c6fe800b097643ac441fadac67cf06780c97
{ "func_code_index": [ 4777, 5094 ] }
8,630
KomicaToken
KomicaToken.sol
0xa7c0728bf78328dc3c3e6c7e7e0da08a20eec1cb
Solidity
KomicaToken
contract KomicaToken is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; bytes32 public currentChallenge; // The coin starts with a challenge uint public timeOfLastProof = now; // Variable to keep track of when rewards were given uint public difficulty = 10**32; // Difficulty starts reasonably low mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ function KomicaToken() public { symbol = "KOMICA"; name = "Komica Token"; decimals = 18; _totalSupply = 188300000000000000000000000000; balances[0x006bdc1a30995Fd5a318B48c78F01A4ecFeA209E] = _totalSupply; Transfer(address(0), 0x006bdc1a30995Fd5a318B48c78F01A4ecFeA209E, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to to account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer tokens from the from account to the to account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the from account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account. The spender contract function // receiveApproval(...) is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () public payable { revert(); } function proofOfWork(uint nonce){ bytes8 n = bytes8(sha3(nonce, currentChallenge)); // Generate a random hash based on input require(n >= bytes8(difficulty)); // Check if it's under the difficulty uint timeSinceLastProof = (now - timeOfLastProof); // Calculate time since last reward was given require(timeSinceLastProof >= 5 seconds); // Rewards cannot be given too quickly balances[msg.sender] += timeSinceLastProof / 60 seconds; // The reward to the winner grows by the minute difficulty = difficulty * 10 minutes / timeSinceLastProof + 1; // Adjusts the difficulty timeOfLastProof = now; // Reset the counter currentChallenge = sha3(nonce, currentChallenge, block.blockhash(block.number - 1)); // Save a hash that will be used as the next proof } }
// ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and assisted // token transfers // ----------------------------------------------------------------------------
LineComment
transferAnyERC20Token
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); }
// ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------
LineComment
v0.4.23+commit.124ca40d
bzzr://4c6c8ebca81579c41a48e19e01d6c6fe800b097643ac441fadac67cf06780c97
{ "func_code_index": [ 5327, 5516 ] }
8,631
KomicaToken
KomicaToken.sol
0xa7c0728bf78328dc3c3e6c7e7e0da08a20eec1cb
Solidity
KomicaToken
contract KomicaToken is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; bytes32 public currentChallenge; // The coin starts with a challenge uint public timeOfLastProof = now; // Variable to keep track of when rewards were given uint public difficulty = 10**32; // Difficulty starts reasonably low mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ function KomicaToken() public { symbol = "KOMICA"; name = "Komica Token"; decimals = 18; _totalSupply = 188300000000000000000000000000; balances[0x006bdc1a30995Fd5a318B48c78F01A4ecFeA209E] = _totalSupply; Transfer(address(0), 0x006bdc1a30995Fd5a318B48c78F01A4ecFeA209E, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to to account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer tokens from the from account to the to account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the from account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account. The spender contract function // receiveApproval(...) is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () public payable { revert(); } function proofOfWork(uint nonce){ bytes8 n = bytes8(sha3(nonce, currentChallenge)); // Generate a random hash based on input require(n >= bytes8(difficulty)); // Check if it's under the difficulty uint timeSinceLastProof = (now - timeOfLastProof); // Calculate time since last reward was given require(timeSinceLastProof >= 5 seconds); // Rewards cannot be given too quickly balances[msg.sender] += timeSinceLastProof / 60 seconds; // The reward to the winner grows by the minute difficulty = difficulty * 10 minutes / timeSinceLastProof + 1; // Adjusts the difficulty timeOfLastProof = now; // Reset the counter currentChallenge = sha3(nonce, currentChallenge, block.blockhash(block.number - 1)); // Save a hash that will be used as the next proof } }
// ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and assisted // token transfers // ----------------------------------------------------------------------------
LineComment
function () public payable { revert(); }
// ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------
LineComment
v0.4.23+commit.124ca40d
bzzr://4c6c8ebca81579c41a48e19e01d6c6fe800b097643ac441fadac67cf06780c97
{ "func_code_index": [ 5708, 5767 ] }
8,632
EthTime
EthTime.sol
0xe339d6f5a42e581dce5a479fca0ed02248a6dca4
Solidity
BokkyPooBahsDateTimeLibrary
library BokkyPooBahsDateTimeLibrary { uint constant SECONDS_PER_DAY = 24 * 60 * 60; uint constant SECONDS_PER_HOUR = 60 * 60; uint constant SECONDS_PER_MINUTE = 60; int constant OFFSET19700101 = 2440588; uint constant DOW_MON = 1; uint constant DOW_TUE = 2; uint constant DOW_WED = 3; uint constant DOW_THU = 4; uint constant DOW_FRI = 5; uint constant DOW_SAT = 6; uint constant DOW_SUN = 7; // ------------------------------------------------------------------------ // Calculate the number of days from 1970/01/01 to year/month/day using // the date conversion algorithm from // http://aa.usno.navy.mil/faq/docs/JD_Formula.php // and subtracting the offset 2440588 so that 1970/01/01 is day 0 // // days = day // - 32075 // + 1461 * (year + 4800 + (month - 14) / 12) / 4 // + 367 * (month - 2 - (month - 14) / 12 * 12) / 12 // - 3 * ((year + 4900 + (month - 14) / 12) / 100) / 4 // - offset // ------------------------------------------------------------------------ function _daysFromDate(uint year, uint month, uint day) internal pure returns (uint _days) { require(year >= 1970); int _year = int(year); int _month = int(month); int _day = int(day); int __days = _day - 32075 + 1461 * (_year + 4800 + (_month - 14) / 12) / 4 + 367 * (_month - 2 - (_month - 14) / 12 * 12) / 12 - 3 * ((_year + 4900 + (_month - 14) / 12) / 100) / 4 - OFFSET19700101; _days = uint(__days); } // ------------------------------------------------------------------------ // Calculate year/month/day from the number of days since 1970/01/01 using // the date conversion algorithm from // http://aa.usno.navy.mil/faq/docs/JD_Formula.php // and adding the offset 2440588 so that 1970/01/01 is day 0 // // int L = days + 68569 + offset // int N = 4 * L / 146097 // L = L - (146097 * N + 3) / 4 // year = 4000 * (L + 1) / 1461001 // L = L - 1461 * year / 4 + 31 // month = 80 * L / 2447 // dd = L - 2447 * month / 80 // L = month / 11 // month = month + 2 - 12 * L // year = 100 * (N - 49) + year + L // ------------------------------------------------------------------------ function _daysToDate(uint _days) internal pure returns (uint year, uint month, uint day) { int __days = int(_days); int L = __days + 68569 + OFFSET19700101; int N = 4 * L / 146097; L = L - (146097 * N + 3) / 4; int _year = 4000 * (L + 1) / 1461001; L = L - 1461 * _year / 4 + 31; int _month = 80 * L / 2447; int _day = L - 2447 * _month / 80; L = _month / 11; _month = _month + 2 - 12 * L; _year = 100 * (N - 49) + _year + L; year = uint(_year); month = uint(_month); day = uint(_day); } function timestampFromDate(uint year, uint month, uint day) internal pure returns (uint timestamp) { timestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY; } function timestampFromDateTime(uint year, uint month, uint day, uint hour, uint minute, uint second) internal pure returns (uint timestamp) { timestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + hour * SECONDS_PER_HOUR + minute * SECONDS_PER_MINUTE + second; } function timestampToDate(uint timestamp) internal pure returns (uint year, uint month, uint day) { (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function timestampToDateTime(uint timestamp) internal pure returns (uint year, uint month, uint day, uint hour, uint minute, uint second) { (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); uint secs = timestamp % SECONDS_PER_DAY; hour = secs / SECONDS_PER_HOUR; secs = secs % SECONDS_PER_HOUR; minute = secs / SECONDS_PER_MINUTE; second = secs % SECONDS_PER_MINUTE; } function isValidDate(uint year, uint month, uint day) internal pure returns (bool valid) { if (year >= 1970 && month > 0 && month <= 12) { uint daysInMonth = _getDaysInMonth(year, month); if (day > 0 && day <= daysInMonth) { valid = true; } } } function isValidDateTime(uint year, uint month, uint day, uint hour, uint minute, uint second) internal pure returns (bool valid) { if (isValidDate(year, month, day)) { if (hour < 24 && minute < 60 && second < 60) { valid = true; } } } function isLeapYear(uint timestamp) internal pure returns (bool leapYear) { (uint year,,) = _daysToDate(timestamp / SECONDS_PER_DAY); leapYear = _isLeapYear(year); } function _isLeapYear(uint year) internal pure returns (bool leapYear) { leapYear = ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0); } function isWeekDay(uint timestamp) internal pure returns (bool weekDay) { weekDay = getDayOfWeek(timestamp) <= DOW_FRI; } function isWeekEnd(uint timestamp) internal pure returns (bool weekEnd) { weekEnd = getDayOfWeek(timestamp) >= DOW_SAT; } function getDaysInMonth(uint timestamp) internal pure returns (uint daysInMonth) { (uint year, uint month,) = _daysToDate(timestamp / SECONDS_PER_DAY); daysInMonth = _getDaysInMonth(year, month); } function _getDaysInMonth(uint year, uint month) internal pure returns (uint daysInMonth) { if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) { daysInMonth = 31; } else if (month != 2) { daysInMonth = 30; } else { daysInMonth = _isLeapYear(year) ? 29 : 28; } } // 1 = Monday, 7 = Sunday function getDayOfWeek(uint timestamp) internal pure returns (uint dayOfWeek) { uint _days = timestamp / SECONDS_PER_DAY; dayOfWeek = (_days + 3) % 7 + 1; } function getYear(uint timestamp) internal pure returns (uint year) { (year,,) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getMonth(uint timestamp) internal pure returns (uint month) { (,month,) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getDay(uint timestamp) internal pure returns (uint day) { (,,day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getHour(uint timestamp) internal pure returns (uint hour) { uint secs = timestamp % SECONDS_PER_DAY; hour = secs / SECONDS_PER_HOUR; } function getMinute(uint timestamp) internal pure returns (uint minute) { uint secs = timestamp % SECONDS_PER_HOUR; minute = secs / SECONDS_PER_MINUTE; } function getSecond(uint timestamp) internal pure returns (uint second) { second = timestamp % SECONDS_PER_MINUTE; } function addYears(uint timestamp, uint _years) internal pure returns (uint newTimestamp) { (uint year, uint month, uint day) = _daysToDate(timestamp / SECONDS_PER_DAY); year += _years; uint daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; require(newTimestamp >= timestamp); } function addMonths(uint timestamp, uint _months) internal pure returns (uint newTimestamp) { (uint year, uint month, uint day) = _daysToDate(timestamp / SECONDS_PER_DAY); month += _months; year += (month - 1) / 12; month = (month - 1) % 12 + 1; uint daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; require(newTimestamp >= timestamp); } function addDays(uint timestamp, uint _days) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _days * SECONDS_PER_DAY; require(newTimestamp >= timestamp); } function addHours(uint timestamp, uint _hours) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _hours * SECONDS_PER_HOUR; require(newTimestamp >= timestamp); } function addMinutes(uint timestamp, uint _minutes) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _minutes * SECONDS_PER_MINUTE; require(newTimestamp >= timestamp); } function addSeconds(uint timestamp, uint _seconds) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _seconds; require(newTimestamp >= timestamp); } function subYears(uint timestamp, uint _years) internal pure returns (uint newTimestamp) { (uint year, uint month, uint day) = _daysToDate(timestamp / SECONDS_PER_DAY); year -= _years; uint daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; require(newTimestamp <= timestamp); } function subMonths(uint timestamp, uint _months) internal pure returns (uint newTimestamp) { (uint year, uint month, uint day) = _daysToDate(timestamp / SECONDS_PER_DAY); uint yearMonth = year * 12 + (month - 1) - _months; year = yearMonth / 12; month = yearMonth % 12 + 1; uint daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; require(newTimestamp <= timestamp); } function subDays(uint timestamp, uint _days) internal pure returns (uint newTimestamp) { newTimestamp = timestamp - _days * SECONDS_PER_DAY; require(newTimestamp <= timestamp); } function subHours(uint timestamp, uint _hours) internal pure returns (uint newTimestamp) { newTimestamp = timestamp - _hours * SECONDS_PER_HOUR; require(newTimestamp <= timestamp); } function subMinutes(uint timestamp, uint _minutes) internal pure returns (uint newTimestamp) { newTimestamp = timestamp - _minutes * SECONDS_PER_MINUTE; require(newTimestamp <= timestamp); } function subSeconds(uint timestamp, uint _seconds) internal pure returns (uint newTimestamp) { newTimestamp = timestamp - _seconds; require(newTimestamp <= timestamp); } function diffYears(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _years) { require(fromTimestamp <= toTimestamp); (uint fromYear,,) = _daysToDate(fromTimestamp / SECONDS_PER_DAY); (uint toYear,,) = _daysToDate(toTimestamp / SECONDS_PER_DAY); _years = toYear - fromYear; } function diffMonths(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _months) { require(fromTimestamp <= toTimestamp); (uint fromYear, uint fromMonth,) = _daysToDate(fromTimestamp / SECONDS_PER_DAY); (uint toYear, uint toMonth,) = _daysToDate(toTimestamp / SECONDS_PER_DAY); _months = toYear * 12 + toMonth - fromYear * 12 - fromMonth; } function diffDays(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _days) { require(fromTimestamp <= toTimestamp); _days = (toTimestamp - fromTimestamp) / SECONDS_PER_DAY; } function diffHours(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _hours) { require(fromTimestamp <= toTimestamp); _hours = (toTimestamp - fromTimestamp) / SECONDS_PER_HOUR; } function diffMinutes(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _minutes) { require(fromTimestamp <= toTimestamp); _minutes = (toTimestamp - fromTimestamp) / SECONDS_PER_MINUTE; } function diffSeconds(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _seconds) { require(fromTimestamp <= toTimestamp); _seconds = toTimestamp - fromTimestamp; } }
// ---------------------------------------------------------------------------- // BokkyPooBah's DateTime Library v1.01 // // A gas-efficient Solidity date and time library // // https://github.com/bokkypoobah/BokkyPooBahsDateTimeLibrary // // Tested date range 1970/01/01 to 2345/12/31 // // Conventions: // Unit | Range | Notes // :-------- |:-------------:|:----- // timestamp | >= 0 | Unix timestamp, number of seconds since 1970/01/01 00:00:00 UTC // year | 1970 ... 2345 | // month | 1 ... 12 | // day | 1 ... 31 | // hour | 0 ... 23 | // minute | 0 ... 59 | // second | 0 ... 59 | // dayOfWeek | 1 ... 7 | 1 = Monday, ..., 7 = Sunday // // // Enjoy. (c) BokkyPooBah / Bok Consulting Pty Ltd 2018-2019. The MIT Licence. // ----------------------------------------------------------------------------
LineComment
_daysFromDate
function _daysFromDate(uint year, uint month, uint day) internal pure returns (uint _days) { require(year >= 1970); int _year = int(year); int _month = int(month); int _day = int(day); int __days = _day - 32075 + 1461 * (_year + 4800 + (_month - 14) / 12) / 4 + 367 * (_month - 2 - (_month - 14) / 12 * 12) / 12 - 3 * ((_year + 4900 + (_month - 14) / 12) / 100) / 4 - OFFSET19700101; _days = uint(__days); }
// ------------------------------------------------------------------------ // Calculate the number of days from 1970/01/01 to year/month/day using // the date conversion algorithm from // http://aa.usno.navy.mil/faq/docs/JD_Formula.php // and subtracting the offset 2440588 so that 1970/01/01 is day 0 // // days = day // - 32075 // + 1461 * (year + 4800 + (month - 14) / 12) / 4 // + 367 * (month - 2 - (month - 14) / 12 * 12) / 12 // - 3 * ((year + 4900 + (month - 14) / 12) / 100) / 4 // - offset // ------------------------------------------------------------------------
LineComment
v0.8.10+commit.fc410830
{ "func_code_index": [ 1096, 1611 ] }
8,633
EthTime
EthTime.sol
0xe339d6f5a42e581dce5a479fca0ed02248a6dca4
Solidity
BokkyPooBahsDateTimeLibrary
library BokkyPooBahsDateTimeLibrary { uint constant SECONDS_PER_DAY = 24 * 60 * 60; uint constant SECONDS_PER_HOUR = 60 * 60; uint constant SECONDS_PER_MINUTE = 60; int constant OFFSET19700101 = 2440588; uint constant DOW_MON = 1; uint constant DOW_TUE = 2; uint constant DOW_WED = 3; uint constant DOW_THU = 4; uint constant DOW_FRI = 5; uint constant DOW_SAT = 6; uint constant DOW_SUN = 7; // ------------------------------------------------------------------------ // Calculate the number of days from 1970/01/01 to year/month/day using // the date conversion algorithm from // http://aa.usno.navy.mil/faq/docs/JD_Formula.php // and subtracting the offset 2440588 so that 1970/01/01 is day 0 // // days = day // - 32075 // + 1461 * (year + 4800 + (month - 14) / 12) / 4 // + 367 * (month - 2 - (month - 14) / 12 * 12) / 12 // - 3 * ((year + 4900 + (month - 14) / 12) / 100) / 4 // - offset // ------------------------------------------------------------------------ function _daysFromDate(uint year, uint month, uint day) internal pure returns (uint _days) { require(year >= 1970); int _year = int(year); int _month = int(month); int _day = int(day); int __days = _day - 32075 + 1461 * (_year + 4800 + (_month - 14) / 12) / 4 + 367 * (_month - 2 - (_month - 14) / 12 * 12) / 12 - 3 * ((_year + 4900 + (_month - 14) / 12) / 100) / 4 - OFFSET19700101; _days = uint(__days); } // ------------------------------------------------------------------------ // Calculate year/month/day from the number of days since 1970/01/01 using // the date conversion algorithm from // http://aa.usno.navy.mil/faq/docs/JD_Formula.php // and adding the offset 2440588 so that 1970/01/01 is day 0 // // int L = days + 68569 + offset // int N = 4 * L / 146097 // L = L - (146097 * N + 3) / 4 // year = 4000 * (L + 1) / 1461001 // L = L - 1461 * year / 4 + 31 // month = 80 * L / 2447 // dd = L - 2447 * month / 80 // L = month / 11 // month = month + 2 - 12 * L // year = 100 * (N - 49) + year + L // ------------------------------------------------------------------------ function _daysToDate(uint _days) internal pure returns (uint year, uint month, uint day) { int __days = int(_days); int L = __days + 68569 + OFFSET19700101; int N = 4 * L / 146097; L = L - (146097 * N + 3) / 4; int _year = 4000 * (L + 1) / 1461001; L = L - 1461 * _year / 4 + 31; int _month = 80 * L / 2447; int _day = L - 2447 * _month / 80; L = _month / 11; _month = _month + 2 - 12 * L; _year = 100 * (N - 49) + _year + L; year = uint(_year); month = uint(_month); day = uint(_day); } function timestampFromDate(uint year, uint month, uint day) internal pure returns (uint timestamp) { timestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY; } function timestampFromDateTime(uint year, uint month, uint day, uint hour, uint minute, uint second) internal pure returns (uint timestamp) { timestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + hour * SECONDS_PER_HOUR + minute * SECONDS_PER_MINUTE + second; } function timestampToDate(uint timestamp) internal pure returns (uint year, uint month, uint day) { (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function timestampToDateTime(uint timestamp) internal pure returns (uint year, uint month, uint day, uint hour, uint minute, uint second) { (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); uint secs = timestamp % SECONDS_PER_DAY; hour = secs / SECONDS_PER_HOUR; secs = secs % SECONDS_PER_HOUR; minute = secs / SECONDS_PER_MINUTE; second = secs % SECONDS_PER_MINUTE; } function isValidDate(uint year, uint month, uint day) internal pure returns (bool valid) { if (year >= 1970 && month > 0 && month <= 12) { uint daysInMonth = _getDaysInMonth(year, month); if (day > 0 && day <= daysInMonth) { valid = true; } } } function isValidDateTime(uint year, uint month, uint day, uint hour, uint minute, uint second) internal pure returns (bool valid) { if (isValidDate(year, month, day)) { if (hour < 24 && minute < 60 && second < 60) { valid = true; } } } function isLeapYear(uint timestamp) internal pure returns (bool leapYear) { (uint year,,) = _daysToDate(timestamp / SECONDS_PER_DAY); leapYear = _isLeapYear(year); } function _isLeapYear(uint year) internal pure returns (bool leapYear) { leapYear = ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0); } function isWeekDay(uint timestamp) internal pure returns (bool weekDay) { weekDay = getDayOfWeek(timestamp) <= DOW_FRI; } function isWeekEnd(uint timestamp) internal pure returns (bool weekEnd) { weekEnd = getDayOfWeek(timestamp) >= DOW_SAT; } function getDaysInMonth(uint timestamp) internal pure returns (uint daysInMonth) { (uint year, uint month,) = _daysToDate(timestamp / SECONDS_PER_DAY); daysInMonth = _getDaysInMonth(year, month); } function _getDaysInMonth(uint year, uint month) internal pure returns (uint daysInMonth) { if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) { daysInMonth = 31; } else if (month != 2) { daysInMonth = 30; } else { daysInMonth = _isLeapYear(year) ? 29 : 28; } } // 1 = Monday, 7 = Sunday function getDayOfWeek(uint timestamp) internal pure returns (uint dayOfWeek) { uint _days = timestamp / SECONDS_PER_DAY; dayOfWeek = (_days + 3) % 7 + 1; } function getYear(uint timestamp) internal pure returns (uint year) { (year,,) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getMonth(uint timestamp) internal pure returns (uint month) { (,month,) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getDay(uint timestamp) internal pure returns (uint day) { (,,day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getHour(uint timestamp) internal pure returns (uint hour) { uint secs = timestamp % SECONDS_PER_DAY; hour = secs / SECONDS_PER_HOUR; } function getMinute(uint timestamp) internal pure returns (uint minute) { uint secs = timestamp % SECONDS_PER_HOUR; minute = secs / SECONDS_PER_MINUTE; } function getSecond(uint timestamp) internal pure returns (uint second) { second = timestamp % SECONDS_PER_MINUTE; } function addYears(uint timestamp, uint _years) internal pure returns (uint newTimestamp) { (uint year, uint month, uint day) = _daysToDate(timestamp / SECONDS_PER_DAY); year += _years; uint daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; require(newTimestamp >= timestamp); } function addMonths(uint timestamp, uint _months) internal pure returns (uint newTimestamp) { (uint year, uint month, uint day) = _daysToDate(timestamp / SECONDS_PER_DAY); month += _months; year += (month - 1) / 12; month = (month - 1) % 12 + 1; uint daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; require(newTimestamp >= timestamp); } function addDays(uint timestamp, uint _days) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _days * SECONDS_PER_DAY; require(newTimestamp >= timestamp); } function addHours(uint timestamp, uint _hours) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _hours * SECONDS_PER_HOUR; require(newTimestamp >= timestamp); } function addMinutes(uint timestamp, uint _minutes) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _minutes * SECONDS_PER_MINUTE; require(newTimestamp >= timestamp); } function addSeconds(uint timestamp, uint _seconds) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _seconds; require(newTimestamp >= timestamp); } function subYears(uint timestamp, uint _years) internal pure returns (uint newTimestamp) { (uint year, uint month, uint day) = _daysToDate(timestamp / SECONDS_PER_DAY); year -= _years; uint daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; require(newTimestamp <= timestamp); } function subMonths(uint timestamp, uint _months) internal pure returns (uint newTimestamp) { (uint year, uint month, uint day) = _daysToDate(timestamp / SECONDS_PER_DAY); uint yearMonth = year * 12 + (month - 1) - _months; year = yearMonth / 12; month = yearMonth % 12 + 1; uint daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; require(newTimestamp <= timestamp); } function subDays(uint timestamp, uint _days) internal pure returns (uint newTimestamp) { newTimestamp = timestamp - _days * SECONDS_PER_DAY; require(newTimestamp <= timestamp); } function subHours(uint timestamp, uint _hours) internal pure returns (uint newTimestamp) { newTimestamp = timestamp - _hours * SECONDS_PER_HOUR; require(newTimestamp <= timestamp); } function subMinutes(uint timestamp, uint _minutes) internal pure returns (uint newTimestamp) { newTimestamp = timestamp - _minutes * SECONDS_PER_MINUTE; require(newTimestamp <= timestamp); } function subSeconds(uint timestamp, uint _seconds) internal pure returns (uint newTimestamp) { newTimestamp = timestamp - _seconds; require(newTimestamp <= timestamp); } function diffYears(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _years) { require(fromTimestamp <= toTimestamp); (uint fromYear,,) = _daysToDate(fromTimestamp / SECONDS_PER_DAY); (uint toYear,,) = _daysToDate(toTimestamp / SECONDS_PER_DAY); _years = toYear - fromYear; } function diffMonths(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _months) { require(fromTimestamp <= toTimestamp); (uint fromYear, uint fromMonth,) = _daysToDate(fromTimestamp / SECONDS_PER_DAY); (uint toYear, uint toMonth,) = _daysToDate(toTimestamp / SECONDS_PER_DAY); _months = toYear * 12 + toMonth - fromYear * 12 - fromMonth; } function diffDays(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _days) { require(fromTimestamp <= toTimestamp); _days = (toTimestamp - fromTimestamp) / SECONDS_PER_DAY; } function diffHours(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _hours) { require(fromTimestamp <= toTimestamp); _hours = (toTimestamp - fromTimestamp) / SECONDS_PER_HOUR; } function diffMinutes(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _minutes) { require(fromTimestamp <= toTimestamp); _minutes = (toTimestamp - fromTimestamp) / SECONDS_PER_MINUTE; } function diffSeconds(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _seconds) { require(fromTimestamp <= toTimestamp); _seconds = toTimestamp - fromTimestamp; } }
// ---------------------------------------------------------------------------- // BokkyPooBah's DateTime Library v1.01 // // A gas-efficient Solidity date and time library // // https://github.com/bokkypoobah/BokkyPooBahsDateTimeLibrary // // Tested date range 1970/01/01 to 2345/12/31 // // Conventions: // Unit | Range | Notes // :-------- |:-------------:|:----- // timestamp | >= 0 | Unix timestamp, number of seconds since 1970/01/01 00:00:00 UTC // year | 1970 ... 2345 | // month | 1 ... 12 | // day | 1 ... 31 | // hour | 0 ... 23 | // minute | 0 ... 59 | // second | 0 ... 59 | // dayOfWeek | 1 ... 7 | 1 = Monday, ..., 7 = Sunday // // // Enjoy. (c) BokkyPooBah / Bok Consulting Pty Ltd 2018-2019. The MIT Licence. // ----------------------------------------------------------------------------
LineComment
_daysToDate
function _daysToDate(uint _days) internal pure returns (uint year, uint month, uint day) { int __days = int(_days); int L = __days + 68569 + OFFSET19700101; int N = 4 * L / 146097; L = L - (146097 * N + 3) / 4; int _year = 4000 * (L + 1) / 1461001; L = L - 1461 * _year / 4 + 31; int _month = 80 * L / 2447; int _day = L - 2447 * _month / 80; L = _month / 11; _month = _month + 2 - 12 * L; _year = 100 * (N - 49) + _year + L; year = uint(_year); month = uint(_month); day = uint(_day); }
// ------------------------------------------------------------------------ // Calculate year/month/day from the number of days since 1970/01/01 using // the date conversion algorithm from // http://aa.usno.navy.mil/faq/docs/JD_Formula.php // and adding the offset 2440588 so that 1970/01/01 is day 0 // // int L = days + 68569 + offset // int N = 4 * L / 146097 // L = L - (146097 * N + 3) / 4 // year = 4000 * (L + 1) / 1461001 // L = L - 1461 * year / 4 + 31 // month = 80 * L / 2447 // dd = L - 2447 * month / 80 // L = month / 11 // month = month + 2 - 12 * L // year = 100 * (N - 49) + year + L // ------------------------------------------------------------------------
LineComment
v0.8.10+commit.fc410830
{ "func_code_index": [ 2360, 2969 ] }
8,634
EthTime
EthTime.sol
0xe339d6f5a42e581dce5a479fca0ed02248a6dca4
Solidity
BokkyPooBahsDateTimeLibrary
library BokkyPooBahsDateTimeLibrary { uint constant SECONDS_PER_DAY = 24 * 60 * 60; uint constant SECONDS_PER_HOUR = 60 * 60; uint constant SECONDS_PER_MINUTE = 60; int constant OFFSET19700101 = 2440588; uint constant DOW_MON = 1; uint constant DOW_TUE = 2; uint constant DOW_WED = 3; uint constant DOW_THU = 4; uint constant DOW_FRI = 5; uint constant DOW_SAT = 6; uint constant DOW_SUN = 7; // ------------------------------------------------------------------------ // Calculate the number of days from 1970/01/01 to year/month/day using // the date conversion algorithm from // http://aa.usno.navy.mil/faq/docs/JD_Formula.php // and subtracting the offset 2440588 so that 1970/01/01 is day 0 // // days = day // - 32075 // + 1461 * (year + 4800 + (month - 14) / 12) / 4 // + 367 * (month - 2 - (month - 14) / 12 * 12) / 12 // - 3 * ((year + 4900 + (month - 14) / 12) / 100) / 4 // - offset // ------------------------------------------------------------------------ function _daysFromDate(uint year, uint month, uint day) internal pure returns (uint _days) { require(year >= 1970); int _year = int(year); int _month = int(month); int _day = int(day); int __days = _day - 32075 + 1461 * (_year + 4800 + (_month - 14) / 12) / 4 + 367 * (_month - 2 - (_month - 14) / 12 * 12) / 12 - 3 * ((_year + 4900 + (_month - 14) / 12) / 100) / 4 - OFFSET19700101; _days = uint(__days); } // ------------------------------------------------------------------------ // Calculate year/month/day from the number of days since 1970/01/01 using // the date conversion algorithm from // http://aa.usno.navy.mil/faq/docs/JD_Formula.php // and adding the offset 2440588 so that 1970/01/01 is day 0 // // int L = days + 68569 + offset // int N = 4 * L / 146097 // L = L - (146097 * N + 3) / 4 // year = 4000 * (L + 1) / 1461001 // L = L - 1461 * year / 4 + 31 // month = 80 * L / 2447 // dd = L - 2447 * month / 80 // L = month / 11 // month = month + 2 - 12 * L // year = 100 * (N - 49) + year + L // ------------------------------------------------------------------------ function _daysToDate(uint _days) internal pure returns (uint year, uint month, uint day) { int __days = int(_days); int L = __days + 68569 + OFFSET19700101; int N = 4 * L / 146097; L = L - (146097 * N + 3) / 4; int _year = 4000 * (L + 1) / 1461001; L = L - 1461 * _year / 4 + 31; int _month = 80 * L / 2447; int _day = L - 2447 * _month / 80; L = _month / 11; _month = _month + 2 - 12 * L; _year = 100 * (N - 49) + _year + L; year = uint(_year); month = uint(_month); day = uint(_day); } function timestampFromDate(uint year, uint month, uint day) internal pure returns (uint timestamp) { timestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY; } function timestampFromDateTime(uint year, uint month, uint day, uint hour, uint minute, uint second) internal pure returns (uint timestamp) { timestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + hour * SECONDS_PER_HOUR + minute * SECONDS_PER_MINUTE + second; } function timestampToDate(uint timestamp) internal pure returns (uint year, uint month, uint day) { (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function timestampToDateTime(uint timestamp) internal pure returns (uint year, uint month, uint day, uint hour, uint minute, uint second) { (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); uint secs = timestamp % SECONDS_PER_DAY; hour = secs / SECONDS_PER_HOUR; secs = secs % SECONDS_PER_HOUR; minute = secs / SECONDS_PER_MINUTE; second = secs % SECONDS_PER_MINUTE; } function isValidDate(uint year, uint month, uint day) internal pure returns (bool valid) { if (year >= 1970 && month > 0 && month <= 12) { uint daysInMonth = _getDaysInMonth(year, month); if (day > 0 && day <= daysInMonth) { valid = true; } } } function isValidDateTime(uint year, uint month, uint day, uint hour, uint minute, uint second) internal pure returns (bool valid) { if (isValidDate(year, month, day)) { if (hour < 24 && minute < 60 && second < 60) { valid = true; } } } function isLeapYear(uint timestamp) internal pure returns (bool leapYear) { (uint year,,) = _daysToDate(timestamp / SECONDS_PER_DAY); leapYear = _isLeapYear(year); } function _isLeapYear(uint year) internal pure returns (bool leapYear) { leapYear = ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0); } function isWeekDay(uint timestamp) internal pure returns (bool weekDay) { weekDay = getDayOfWeek(timestamp) <= DOW_FRI; } function isWeekEnd(uint timestamp) internal pure returns (bool weekEnd) { weekEnd = getDayOfWeek(timestamp) >= DOW_SAT; } function getDaysInMonth(uint timestamp) internal pure returns (uint daysInMonth) { (uint year, uint month,) = _daysToDate(timestamp / SECONDS_PER_DAY); daysInMonth = _getDaysInMonth(year, month); } function _getDaysInMonth(uint year, uint month) internal pure returns (uint daysInMonth) { if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) { daysInMonth = 31; } else if (month != 2) { daysInMonth = 30; } else { daysInMonth = _isLeapYear(year) ? 29 : 28; } } // 1 = Monday, 7 = Sunday function getDayOfWeek(uint timestamp) internal pure returns (uint dayOfWeek) { uint _days = timestamp / SECONDS_PER_DAY; dayOfWeek = (_days + 3) % 7 + 1; } function getYear(uint timestamp) internal pure returns (uint year) { (year,,) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getMonth(uint timestamp) internal pure returns (uint month) { (,month,) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getDay(uint timestamp) internal pure returns (uint day) { (,,day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getHour(uint timestamp) internal pure returns (uint hour) { uint secs = timestamp % SECONDS_PER_DAY; hour = secs / SECONDS_PER_HOUR; } function getMinute(uint timestamp) internal pure returns (uint minute) { uint secs = timestamp % SECONDS_PER_HOUR; minute = secs / SECONDS_PER_MINUTE; } function getSecond(uint timestamp) internal pure returns (uint second) { second = timestamp % SECONDS_PER_MINUTE; } function addYears(uint timestamp, uint _years) internal pure returns (uint newTimestamp) { (uint year, uint month, uint day) = _daysToDate(timestamp / SECONDS_PER_DAY); year += _years; uint daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; require(newTimestamp >= timestamp); } function addMonths(uint timestamp, uint _months) internal pure returns (uint newTimestamp) { (uint year, uint month, uint day) = _daysToDate(timestamp / SECONDS_PER_DAY); month += _months; year += (month - 1) / 12; month = (month - 1) % 12 + 1; uint daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; require(newTimestamp >= timestamp); } function addDays(uint timestamp, uint _days) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _days * SECONDS_PER_DAY; require(newTimestamp >= timestamp); } function addHours(uint timestamp, uint _hours) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _hours * SECONDS_PER_HOUR; require(newTimestamp >= timestamp); } function addMinutes(uint timestamp, uint _minutes) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _minutes * SECONDS_PER_MINUTE; require(newTimestamp >= timestamp); } function addSeconds(uint timestamp, uint _seconds) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _seconds; require(newTimestamp >= timestamp); } function subYears(uint timestamp, uint _years) internal pure returns (uint newTimestamp) { (uint year, uint month, uint day) = _daysToDate(timestamp / SECONDS_PER_DAY); year -= _years; uint daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; require(newTimestamp <= timestamp); } function subMonths(uint timestamp, uint _months) internal pure returns (uint newTimestamp) { (uint year, uint month, uint day) = _daysToDate(timestamp / SECONDS_PER_DAY); uint yearMonth = year * 12 + (month - 1) - _months; year = yearMonth / 12; month = yearMonth % 12 + 1; uint daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; require(newTimestamp <= timestamp); } function subDays(uint timestamp, uint _days) internal pure returns (uint newTimestamp) { newTimestamp = timestamp - _days * SECONDS_PER_DAY; require(newTimestamp <= timestamp); } function subHours(uint timestamp, uint _hours) internal pure returns (uint newTimestamp) { newTimestamp = timestamp - _hours * SECONDS_PER_HOUR; require(newTimestamp <= timestamp); } function subMinutes(uint timestamp, uint _minutes) internal pure returns (uint newTimestamp) { newTimestamp = timestamp - _minutes * SECONDS_PER_MINUTE; require(newTimestamp <= timestamp); } function subSeconds(uint timestamp, uint _seconds) internal pure returns (uint newTimestamp) { newTimestamp = timestamp - _seconds; require(newTimestamp <= timestamp); } function diffYears(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _years) { require(fromTimestamp <= toTimestamp); (uint fromYear,,) = _daysToDate(fromTimestamp / SECONDS_PER_DAY); (uint toYear,,) = _daysToDate(toTimestamp / SECONDS_PER_DAY); _years = toYear - fromYear; } function diffMonths(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _months) { require(fromTimestamp <= toTimestamp); (uint fromYear, uint fromMonth,) = _daysToDate(fromTimestamp / SECONDS_PER_DAY); (uint toYear, uint toMonth,) = _daysToDate(toTimestamp / SECONDS_PER_DAY); _months = toYear * 12 + toMonth - fromYear * 12 - fromMonth; } function diffDays(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _days) { require(fromTimestamp <= toTimestamp); _days = (toTimestamp - fromTimestamp) / SECONDS_PER_DAY; } function diffHours(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _hours) { require(fromTimestamp <= toTimestamp); _hours = (toTimestamp - fromTimestamp) / SECONDS_PER_HOUR; } function diffMinutes(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _minutes) { require(fromTimestamp <= toTimestamp); _minutes = (toTimestamp - fromTimestamp) / SECONDS_PER_MINUTE; } function diffSeconds(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _seconds) { require(fromTimestamp <= toTimestamp); _seconds = toTimestamp - fromTimestamp; } }
// ---------------------------------------------------------------------------- // BokkyPooBah's DateTime Library v1.01 // // A gas-efficient Solidity date and time library // // https://github.com/bokkypoobah/BokkyPooBahsDateTimeLibrary // // Tested date range 1970/01/01 to 2345/12/31 // // Conventions: // Unit | Range | Notes // :-------- |:-------------:|:----- // timestamp | >= 0 | Unix timestamp, number of seconds since 1970/01/01 00:00:00 UTC // year | 1970 ... 2345 | // month | 1 ... 12 | // day | 1 ... 31 | // hour | 0 ... 23 | // minute | 0 ... 59 | // second | 0 ... 59 | // dayOfWeek | 1 ... 7 | 1 = Monday, ..., 7 = Sunday // // // Enjoy. (c) BokkyPooBah / Bok Consulting Pty Ltd 2018-2019. The MIT Licence. // ----------------------------------------------------------------------------
LineComment
getDayOfWeek
function getDayOfWeek(uint timestamp) internal pure returns (uint dayOfWeek) { uint _days = timestamp / SECONDS_PER_DAY; dayOfWeek = (_days + 3) % 7 + 1; }
// 1 = Monday, 7 = Sunday
LineComment
v0.8.10+commit.fc410830
{ "func_code_index": [ 5949, 6128 ] }
8,635
EthTime
EthTime.sol
0xe339d6f5a42e581dce5a479fca0ed02248a6dca4
Solidity
Ownable
abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } }
/** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */
NatSpecMultiLine
owner
function owner() public view virtual returns (address) { return _owner; }
/** * @dev Returns the address of the current owner. */
NatSpecMultiLine
v0.8.10+commit.fc410830
{ "func_code_index": [ 393, 482 ] }
8,636
EthTime
EthTime.sol
0xe339d6f5a42e581dce5a479fca0ed02248a6dca4
Solidity
Ownable
abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } }
/** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */
NatSpecMultiLine
renounceOwnership
function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); }
/** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */
NatSpecMultiLine
v0.8.10+commit.fc410830
{ "func_code_index": [ 1025, 1130 ] }
8,637
EthTime
EthTime.sol
0xe339d6f5a42e581dce5a479fca0ed02248a6dca4
Solidity
Ownable
abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } }
/** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */
NatSpecMultiLine
transferOwnership
function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); }
/** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */
NatSpecMultiLine
v0.8.10+commit.fc410830
{ "func_code_index": [ 1275, 1477 ] }
8,638
EthTime
EthTime.sol
0xe339d6f5a42e581dce5a479fca0ed02248a6dca4
Solidity
Ownable
abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } }
/** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */
NatSpecMultiLine
_transferOwnership
function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); }
/** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */
NatSpecMultiLine
v0.8.10+commit.fc410830
{ "func_code_index": [ 1627, 1818 ] }
8,639
EthTime
EthTime.sol
0xe339d6f5a42e581dce5a479fca0ed02248a6dca4
Solidity
Strings
library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } }
/** * @dev String operations. */
NatSpecMultiLine
toString
function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); }
/** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */
NatSpecMultiLine
v0.8.10+commit.fc410830
{ "func_code_index": [ 178, 885 ] }
8,640
EthTime
EthTime.sol
0xe339d6f5a42e581dce5a479fca0ed02248a6dca4
Solidity
Strings
library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } }
/** * @dev String operations. */
NatSpecMultiLine
toHexString
function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); }
/** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */
NatSpecMultiLine
v0.8.10+commit.fc410830
{ "func_code_index": [ 986, 1319 ] }
8,641
EthTime
EthTime.sol
0xe339d6f5a42e581dce5a479fca0ed02248a6dca4
Solidity
Strings
library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } }
/** * @dev String operations. */
NatSpecMultiLine
toHexString
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); }
/** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */
NatSpecMultiLine
v0.8.10+commit.fc410830
{ "func_code_index": [ 1438, 1883 ] }
8,642
EthTime
EthTime.sol
0xe339d6f5a42e581dce5a479fca0ed02248a6dca4
Solidity
ERC721
abstract contract ERC721 { /*/////////////////////////////////////////////////////////////// EVENTS //////////////////////////////////////////////////////////////*/ event Transfer(address indexed from, address indexed to, uint256 indexed id); event Approval(address indexed owner, address indexed spender, uint256 indexed id); event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /*/////////////////////////////////////////////////////////////// METADATA STORAGE/LOGIC //////////////////////////////////////////////////////////////*/ string public name; string public symbol; function tokenURI(uint256 id) public view virtual returns (string memory); /*/////////////////////////////////////////////////////////////// ERC721 STORAGE //////////////////////////////////////////////////////////////*/ mapping(address => uint256) public balanceOf; mapping(uint256 => address) public ownerOf; mapping(uint256 => address) public getApproved; mapping(address => mapping(address => bool)) public isApprovedForAll; /*/////////////////////////////////////////////////////////////// CONSTRUCTOR //////////////////////////////////////////////////////////////*/ constructor(string memory _name, string memory _symbol) { name = _name; symbol = _symbol; } /*/////////////////////////////////////////////////////////////// ERC721 LOGIC //////////////////////////////////////////////////////////////*/ function approve(address spender, uint256 id) public virtual { address owner = ownerOf[id]; require(msg.sender == owner || isApprovedForAll[owner][msg.sender], "NOT_AUTHORIZED"); getApproved[id] = spender; emit Approval(owner, spender, id); } function setApprovalForAll(address operator, bool approved) public virtual { isApprovedForAll[msg.sender][operator] = approved; emit ApprovalForAll(msg.sender, operator, approved); } function transferFrom( address from, address to, uint256 id ) public virtual { require(from == ownerOf[id], "WRONG_FROM"); require(to != address(0), "INVALID_RECIPIENT"); require( msg.sender == from || msg.sender == getApproved[id] || isApprovedForAll[from][msg.sender], "NOT_AUTHORIZED" ); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. unchecked { balanceOf[from]--; balanceOf[to]++; } ownerOf[id] = to; delete getApproved[id]; emit Transfer(from, to, id); } function safeTransferFrom( address from, address to, uint256 id ) public virtual { transferFrom(from, to, id); require( to.code.length == 0 || ERC721TokenReceiver(to).onERC721Received(msg.sender, from, id, "") == ERC721TokenReceiver.onERC721Received.selector, "UNSAFE_RECIPIENT" ); } function safeTransferFrom( address from, address to, uint256 id, bytes memory data ) public virtual { transferFrom(from, to, id); require( to.code.length == 0 || ERC721TokenReceiver(to).onERC721Received(msg.sender, from, id, data) == ERC721TokenReceiver.onERC721Received.selector, "UNSAFE_RECIPIENT" ); } /*/////////////////////////////////////////////////////////////// ERC165 LOGIC //////////////////////////////////////////////////////////////*/ function supportsInterface(bytes4 interfaceId) public pure virtual returns (bool) { return interfaceId == 0x01ffc9a7 || // ERC165 Interface ID for ERC165 interfaceId == 0x80ac58cd || // ERC165 Interface ID for ERC721 interfaceId == 0x5b5e139f; // ERC165 Interface ID for ERC721Metadata } /*/////////////////////////////////////////////////////////////// INTERNAL MINT/BURN LOGIC //////////////////////////////////////////////////////////////*/ function _mint(address to, uint256 id) internal virtual { require(to != address(0), "INVALID_RECIPIENT"); require(ownerOf[id] == address(0), "ALREADY_MINTED"); // Counter overflow is incredibly unrealistic. unchecked { balanceOf[to]++; } ownerOf[id] = to; emit Transfer(address(0), to, id); } function _burn(uint256 id) internal virtual { address owner = ownerOf[id]; require(ownerOf[id] != address(0), "NOT_MINTED"); // Ownership check above ensures no underflow. unchecked { balanceOf[owner]--; } delete ownerOf[id]; delete getApproved[id]; emit Transfer(owner, address(0), id); } /*/////////////////////////////////////////////////////////////// INTERNAL SAFE MINT LOGIC //////////////////////////////////////////////////////////////*/ function _safeMint(address to, uint256 id) internal virtual { _mint(to, id); require( to.code.length == 0 || ERC721TokenReceiver(to).onERC721Received(msg.sender, address(0), id, "") == ERC721TokenReceiver.onERC721Received.selector, "UNSAFE_RECIPIENT" ); } function _safeMint( address to, uint256 id, bytes memory data ) internal virtual { _mint(to, id); require( to.code.length == 0 || ERC721TokenReceiver(to).onERC721Received(msg.sender, address(0), id, data) == ERC721TokenReceiver.onERC721Received.selector, "UNSAFE_RECIPIENT" ); } }
/// @notice Modern, minimalist, and gas efficient ERC-721 implementation. /// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/tokens/ERC721.sol) /// @dev Note that balanceOf does not revert if passed the zero address, in defiance of the ERC.
NatSpecSingleLine
approve
function approve(address spender, uint256 id) public virtual { address owner = ownerOf[id]; require(msg.sender == owner || isApprovedForAll[owner][msg.sender], "NOT_AUTHORIZED"); getApproved[id] = spender; emit Approval(owner, spender, id); }
/*/////////////////////////////////////////////////////////////// ERC721 LOGIC //////////////////////////////////////////////////////////////*/
Comment
v0.8.10+commit.fc410830
{ "func_code_index": [ 1708, 1993 ] }
8,643
EthTime
EthTime.sol
0xe339d6f5a42e581dce5a479fca0ed02248a6dca4
Solidity
ERC721
abstract contract ERC721 { /*/////////////////////////////////////////////////////////////// EVENTS //////////////////////////////////////////////////////////////*/ event Transfer(address indexed from, address indexed to, uint256 indexed id); event Approval(address indexed owner, address indexed spender, uint256 indexed id); event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /*/////////////////////////////////////////////////////////////// METADATA STORAGE/LOGIC //////////////////////////////////////////////////////////////*/ string public name; string public symbol; function tokenURI(uint256 id) public view virtual returns (string memory); /*/////////////////////////////////////////////////////////////// ERC721 STORAGE //////////////////////////////////////////////////////////////*/ mapping(address => uint256) public balanceOf; mapping(uint256 => address) public ownerOf; mapping(uint256 => address) public getApproved; mapping(address => mapping(address => bool)) public isApprovedForAll; /*/////////////////////////////////////////////////////////////// CONSTRUCTOR //////////////////////////////////////////////////////////////*/ constructor(string memory _name, string memory _symbol) { name = _name; symbol = _symbol; } /*/////////////////////////////////////////////////////////////// ERC721 LOGIC //////////////////////////////////////////////////////////////*/ function approve(address spender, uint256 id) public virtual { address owner = ownerOf[id]; require(msg.sender == owner || isApprovedForAll[owner][msg.sender], "NOT_AUTHORIZED"); getApproved[id] = spender; emit Approval(owner, spender, id); } function setApprovalForAll(address operator, bool approved) public virtual { isApprovedForAll[msg.sender][operator] = approved; emit ApprovalForAll(msg.sender, operator, approved); } function transferFrom( address from, address to, uint256 id ) public virtual { require(from == ownerOf[id], "WRONG_FROM"); require(to != address(0), "INVALID_RECIPIENT"); require( msg.sender == from || msg.sender == getApproved[id] || isApprovedForAll[from][msg.sender], "NOT_AUTHORIZED" ); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. unchecked { balanceOf[from]--; balanceOf[to]++; } ownerOf[id] = to; delete getApproved[id]; emit Transfer(from, to, id); } function safeTransferFrom( address from, address to, uint256 id ) public virtual { transferFrom(from, to, id); require( to.code.length == 0 || ERC721TokenReceiver(to).onERC721Received(msg.sender, from, id, "") == ERC721TokenReceiver.onERC721Received.selector, "UNSAFE_RECIPIENT" ); } function safeTransferFrom( address from, address to, uint256 id, bytes memory data ) public virtual { transferFrom(from, to, id); require( to.code.length == 0 || ERC721TokenReceiver(to).onERC721Received(msg.sender, from, id, data) == ERC721TokenReceiver.onERC721Received.selector, "UNSAFE_RECIPIENT" ); } /*/////////////////////////////////////////////////////////////// ERC165 LOGIC //////////////////////////////////////////////////////////////*/ function supportsInterface(bytes4 interfaceId) public pure virtual returns (bool) { return interfaceId == 0x01ffc9a7 || // ERC165 Interface ID for ERC165 interfaceId == 0x80ac58cd || // ERC165 Interface ID for ERC721 interfaceId == 0x5b5e139f; // ERC165 Interface ID for ERC721Metadata } /*/////////////////////////////////////////////////////////////// INTERNAL MINT/BURN LOGIC //////////////////////////////////////////////////////////////*/ function _mint(address to, uint256 id) internal virtual { require(to != address(0), "INVALID_RECIPIENT"); require(ownerOf[id] == address(0), "ALREADY_MINTED"); // Counter overflow is incredibly unrealistic. unchecked { balanceOf[to]++; } ownerOf[id] = to; emit Transfer(address(0), to, id); } function _burn(uint256 id) internal virtual { address owner = ownerOf[id]; require(ownerOf[id] != address(0), "NOT_MINTED"); // Ownership check above ensures no underflow. unchecked { balanceOf[owner]--; } delete ownerOf[id]; delete getApproved[id]; emit Transfer(owner, address(0), id); } /*/////////////////////////////////////////////////////////////// INTERNAL SAFE MINT LOGIC //////////////////////////////////////////////////////////////*/ function _safeMint(address to, uint256 id) internal virtual { _mint(to, id); require( to.code.length == 0 || ERC721TokenReceiver(to).onERC721Received(msg.sender, address(0), id, "") == ERC721TokenReceiver.onERC721Received.selector, "UNSAFE_RECIPIENT" ); } function _safeMint( address to, uint256 id, bytes memory data ) internal virtual { _mint(to, id); require( to.code.length == 0 || ERC721TokenReceiver(to).onERC721Received(msg.sender, address(0), id, data) == ERC721TokenReceiver.onERC721Received.selector, "UNSAFE_RECIPIENT" ); } }
/// @notice Modern, minimalist, and gas efficient ERC-721 implementation. /// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/tokens/ERC721.sol) /// @dev Note that balanceOf does not revert if passed the zero address, in defiance of the ERC.
NatSpecSingleLine
supportsInterface
function supportsInterface(bytes4 interfaceId) public pure virtual returns (bool) { return interfaceId == 0x01ffc9a7 || // ERC165 Interface ID for ERC165 interfaceId == 0x80ac58cd || // ERC165 Interface ID for ERC721 interfaceId == 0x5b5e139f; // ERC165 Interface ID for ERC721Metadata }
/*/////////////////////////////////////////////////////////////// ERC165 LOGIC //////////////////////////////////////////////////////////////*/
Comment
v0.8.10+commit.fc410830
{ "func_code_index": [ 3963, 4302 ] }
8,644
EthTime
EthTime.sol
0xe339d6f5a42e581dce5a479fca0ed02248a6dca4
Solidity
ERC721
abstract contract ERC721 { /*/////////////////////////////////////////////////////////////// EVENTS //////////////////////////////////////////////////////////////*/ event Transfer(address indexed from, address indexed to, uint256 indexed id); event Approval(address indexed owner, address indexed spender, uint256 indexed id); event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /*/////////////////////////////////////////////////////////////// METADATA STORAGE/LOGIC //////////////////////////////////////////////////////////////*/ string public name; string public symbol; function tokenURI(uint256 id) public view virtual returns (string memory); /*/////////////////////////////////////////////////////////////// ERC721 STORAGE //////////////////////////////////////////////////////////////*/ mapping(address => uint256) public balanceOf; mapping(uint256 => address) public ownerOf; mapping(uint256 => address) public getApproved; mapping(address => mapping(address => bool)) public isApprovedForAll; /*/////////////////////////////////////////////////////////////// CONSTRUCTOR //////////////////////////////////////////////////////////////*/ constructor(string memory _name, string memory _symbol) { name = _name; symbol = _symbol; } /*/////////////////////////////////////////////////////////////// ERC721 LOGIC //////////////////////////////////////////////////////////////*/ function approve(address spender, uint256 id) public virtual { address owner = ownerOf[id]; require(msg.sender == owner || isApprovedForAll[owner][msg.sender], "NOT_AUTHORIZED"); getApproved[id] = spender; emit Approval(owner, spender, id); } function setApprovalForAll(address operator, bool approved) public virtual { isApprovedForAll[msg.sender][operator] = approved; emit ApprovalForAll(msg.sender, operator, approved); } function transferFrom( address from, address to, uint256 id ) public virtual { require(from == ownerOf[id], "WRONG_FROM"); require(to != address(0), "INVALID_RECIPIENT"); require( msg.sender == from || msg.sender == getApproved[id] || isApprovedForAll[from][msg.sender], "NOT_AUTHORIZED" ); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. unchecked { balanceOf[from]--; balanceOf[to]++; } ownerOf[id] = to; delete getApproved[id]; emit Transfer(from, to, id); } function safeTransferFrom( address from, address to, uint256 id ) public virtual { transferFrom(from, to, id); require( to.code.length == 0 || ERC721TokenReceiver(to).onERC721Received(msg.sender, from, id, "") == ERC721TokenReceiver.onERC721Received.selector, "UNSAFE_RECIPIENT" ); } function safeTransferFrom( address from, address to, uint256 id, bytes memory data ) public virtual { transferFrom(from, to, id); require( to.code.length == 0 || ERC721TokenReceiver(to).onERC721Received(msg.sender, from, id, data) == ERC721TokenReceiver.onERC721Received.selector, "UNSAFE_RECIPIENT" ); } /*/////////////////////////////////////////////////////////////// ERC165 LOGIC //////////////////////////////////////////////////////////////*/ function supportsInterface(bytes4 interfaceId) public pure virtual returns (bool) { return interfaceId == 0x01ffc9a7 || // ERC165 Interface ID for ERC165 interfaceId == 0x80ac58cd || // ERC165 Interface ID for ERC721 interfaceId == 0x5b5e139f; // ERC165 Interface ID for ERC721Metadata } /*/////////////////////////////////////////////////////////////// INTERNAL MINT/BURN LOGIC //////////////////////////////////////////////////////////////*/ function _mint(address to, uint256 id) internal virtual { require(to != address(0), "INVALID_RECIPIENT"); require(ownerOf[id] == address(0), "ALREADY_MINTED"); // Counter overflow is incredibly unrealistic. unchecked { balanceOf[to]++; } ownerOf[id] = to; emit Transfer(address(0), to, id); } function _burn(uint256 id) internal virtual { address owner = ownerOf[id]; require(ownerOf[id] != address(0), "NOT_MINTED"); // Ownership check above ensures no underflow. unchecked { balanceOf[owner]--; } delete ownerOf[id]; delete getApproved[id]; emit Transfer(owner, address(0), id); } /*/////////////////////////////////////////////////////////////// INTERNAL SAFE MINT LOGIC //////////////////////////////////////////////////////////////*/ function _safeMint(address to, uint256 id) internal virtual { _mint(to, id); require( to.code.length == 0 || ERC721TokenReceiver(to).onERC721Received(msg.sender, address(0), id, "") == ERC721TokenReceiver.onERC721Received.selector, "UNSAFE_RECIPIENT" ); } function _safeMint( address to, uint256 id, bytes memory data ) internal virtual { _mint(to, id); require( to.code.length == 0 || ERC721TokenReceiver(to).onERC721Received(msg.sender, address(0), id, data) == ERC721TokenReceiver.onERC721Received.selector, "UNSAFE_RECIPIENT" ); } }
/// @notice Modern, minimalist, and gas efficient ERC-721 implementation. /// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/tokens/ERC721.sol) /// @dev Note that balanceOf does not revert if passed the zero address, in defiance of the ERC.
NatSpecSingleLine
_mint
function _mint(address to, uint256 id) internal virtual { require(to != address(0), "INVALID_RECIPIENT"); require(ownerOf[id] == address(0), "ALREADY_MINTED"); // Counter overflow is incredibly unrealistic. unchecked { balanceOf[to]++; } ownerOf[id] = to; emit Transfer(address(0), to, id); }
/*/////////////////////////////////////////////////////////////// INTERNAL MINT/BURN LOGIC //////////////////////////////////////////////////////////////*/
Comment
v0.8.10+commit.fc410830
{ "func_code_index": [ 4492, 4864 ] }
8,645
EthTime
EthTime.sol
0xe339d6f5a42e581dce5a479fca0ed02248a6dca4
Solidity
ERC721
abstract contract ERC721 { /*/////////////////////////////////////////////////////////////// EVENTS //////////////////////////////////////////////////////////////*/ event Transfer(address indexed from, address indexed to, uint256 indexed id); event Approval(address indexed owner, address indexed spender, uint256 indexed id); event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /*/////////////////////////////////////////////////////////////// METADATA STORAGE/LOGIC //////////////////////////////////////////////////////////////*/ string public name; string public symbol; function tokenURI(uint256 id) public view virtual returns (string memory); /*/////////////////////////////////////////////////////////////// ERC721 STORAGE //////////////////////////////////////////////////////////////*/ mapping(address => uint256) public balanceOf; mapping(uint256 => address) public ownerOf; mapping(uint256 => address) public getApproved; mapping(address => mapping(address => bool)) public isApprovedForAll; /*/////////////////////////////////////////////////////////////// CONSTRUCTOR //////////////////////////////////////////////////////////////*/ constructor(string memory _name, string memory _symbol) { name = _name; symbol = _symbol; } /*/////////////////////////////////////////////////////////////// ERC721 LOGIC //////////////////////////////////////////////////////////////*/ function approve(address spender, uint256 id) public virtual { address owner = ownerOf[id]; require(msg.sender == owner || isApprovedForAll[owner][msg.sender], "NOT_AUTHORIZED"); getApproved[id] = spender; emit Approval(owner, spender, id); } function setApprovalForAll(address operator, bool approved) public virtual { isApprovedForAll[msg.sender][operator] = approved; emit ApprovalForAll(msg.sender, operator, approved); } function transferFrom( address from, address to, uint256 id ) public virtual { require(from == ownerOf[id], "WRONG_FROM"); require(to != address(0), "INVALID_RECIPIENT"); require( msg.sender == from || msg.sender == getApproved[id] || isApprovedForAll[from][msg.sender], "NOT_AUTHORIZED" ); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. unchecked { balanceOf[from]--; balanceOf[to]++; } ownerOf[id] = to; delete getApproved[id]; emit Transfer(from, to, id); } function safeTransferFrom( address from, address to, uint256 id ) public virtual { transferFrom(from, to, id); require( to.code.length == 0 || ERC721TokenReceiver(to).onERC721Received(msg.sender, from, id, "") == ERC721TokenReceiver.onERC721Received.selector, "UNSAFE_RECIPIENT" ); } function safeTransferFrom( address from, address to, uint256 id, bytes memory data ) public virtual { transferFrom(from, to, id); require( to.code.length == 0 || ERC721TokenReceiver(to).onERC721Received(msg.sender, from, id, data) == ERC721TokenReceiver.onERC721Received.selector, "UNSAFE_RECIPIENT" ); } /*/////////////////////////////////////////////////////////////// ERC165 LOGIC //////////////////////////////////////////////////////////////*/ function supportsInterface(bytes4 interfaceId) public pure virtual returns (bool) { return interfaceId == 0x01ffc9a7 || // ERC165 Interface ID for ERC165 interfaceId == 0x80ac58cd || // ERC165 Interface ID for ERC721 interfaceId == 0x5b5e139f; // ERC165 Interface ID for ERC721Metadata } /*/////////////////////////////////////////////////////////////// INTERNAL MINT/BURN LOGIC //////////////////////////////////////////////////////////////*/ function _mint(address to, uint256 id) internal virtual { require(to != address(0), "INVALID_RECIPIENT"); require(ownerOf[id] == address(0), "ALREADY_MINTED"); // Counter overflow is incredibly unrealistic. unchecked { balanceOf[to]++; } ownerOf[id] = to; emit Transfer(address(0), to, id); } function _burn(uint256 id) internal virtual { address owner = ownerOf[id]; require(ownerOf[id] != address(0), "NOT_MINTED"); // Ownership check above ensures no underflow. unchecked { balanceOf[owner]--; } delete ownerOf[id]; delete getApproved[id]; emit Transfer(owner, address(0), id); } /*/////////////////////////////////////////////////////////////// INTERNAL SAFE MINT LOGIC //////////////////////////////////////////////////////////////*/ function _safeMint(address to, uint256 id) internal virtual { _mint(to, id); require( to.code.length == 0 || ERC721TokenReceiver(to).onERC721Received(msg.sender, address(0), id, "") == ERC721TokenReceiver.onERC721Received.selector, "UNSAFE_RECIPIENT" ); } function _safeMint( address to, uint256 id, bytes memory data ) internal virtual { _mint(to, id); require( to.code.length == 0 || ERC721TokenReceiver(to).onERC721Received(msg.sender, address(0), id, data) == ERC721TokenReceiver.onERC721Received.selector, "UNSAFE_RECIPIENT" ); } }
/// @notice Modern, minimalist, and gas efficient ERC-721 implementation. /// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/tokens/ERC721.sol) /// @dev Note that balanceOf does not revert if passed the zero address, in defiance of the ERC.
NatSpecSingleLine
_safeMint
function _safeMint(address to, uint256 id) internal virtual { _mint(to, id); require( to.code.length == 0 || ERC721TokenReceiver(to).onERC721Received(msg.sender, address(0), id, "") == ERC721TokenReceiver.onERC721Received.selector, "UNSAFE_RECIPIENT" ); }
/*/////////////////////////////////////////////////////////////// INTERNAL SAFE MINT LOGIC //////////////////////////////////////////////////////////////*/
Comment
v0.8.10+commit.fc410830
{ "func_code_index": [ 5434, 5778 ] }
8,646
EthTime
EthTime.sol
0xe339d6f5a42e581dce5a479fca0ed02248a6dca4
Solidity
CharitySplitter
contract CharitySplitter { ////////////////////////////////////////////////////////////////////////// // // // Constructor // // // ////////////////////////////////////////////////////////////////////////// /// @dev Charity address, can be changed with a time-lock. address payable public charity; /// @dev Charity fee, in basis points. 1% = 100 bp. uint256 public charityFeeBp; constructor(address payable _charity, uint256 _charityFeeBp) { // checks: address not zero. Don't want to burn eth. if (_charity == address(0)) { revert CharitySplitter__InvalidCharityAddress(); } // checks: fee > 0%. Don't want to deal with no fee edge cases. if (_charityFeeBp == 0) { revert CharitySplitter__InvalidCharityFee(); } charity = _charity; charityFeeBp = _charityFeeBp; } ////////////////////////////////////////////////////////////////////////// // // // Charity Address Management // // // ////////////////////////////////////////////////////////////////////////// /// @dev Emitted when the charity address is updated. event CharityUpdated(address charity); /// @dev Update the charity address. function _updateCharity(address payable _charity) internal { if (_charity == address(0)) { revert CharitySplitter__InvalidCharityAddress(); } charity = _charity; } ////////////////////////////////////////////////////////////////////////// // // // Profit Tracking // // // ////////////////////////////////////////////////////////////////////////// /// @dev Balance owed to the charity. uint256 public charityBalance; /// @dev Balance owed to the owner. uint256 public ownerBalance; /// @dev Denominator used when computing fee. 100% in bp. uint256 private constant BP_DENOMINATOR = 10000; /// @dev Update charity and owner balance. function _updateBalance(uint256 value) internal { // checks: if value is zero nothing to update. if (value == 0) { return; } uint256 charityValue = (value * charityFeeBp) / BP_DENOMINATOR; uint256 ownerValue = value - charityValue; // effects: update balances. charityBalance += charityValue; ownerBalance += ownerValue; } ////////////////////////////////////////////////////////////////////////// // // // Withdrawing Funds // // // ////////////////////////////////////////////////////////////////////////// /// @notice Withdraw funds to charity address. function _withdrawCharityBalance() internal { uint256 value = charityBalance; // checks: no money to withdraw. if (value == 0) { return; } // effects: reset charity balance to zero. charityBalance = 0; // interactions: send money to charity address. (bool sent, ) = charity.call{value: value}(""); require(sent); } /// @notice Withdraw funds to owner address. /// @param destination the address that receives the funds. function _withdrawOwnerBalance(address payable destination) internal { uint256 value = ownerBalance; // checks: no money to withdraw. if (value == 0) { return; } // effects: reset owner balance to zero. ownerBalance = 0; // interactions: send money to destination address. (bool sent, ) = destination.call{value: value}(""); require(sent); } }
/// @notice Tracks splitting profits with a charity. /// @dev This module essentialy does two things: /// * Tracks how much money goes to the charity and how much to someone else. /// * Implements a simple time-lock to avoid the contract owner changing the /// charity address to one they own. /// /// Anyone can call the method to send the funds to the charity.
NatSpecSingleLine
_updateCharity
function _updateCharity(address payable _charity) internal { if (_charity == address(0)) { revert CharitySplitter__InvalidCharityAddress(); } charity = _charity; }
/// @dev Update the charity address.
NatSpecSingleLine
v0.8.10+commit.fc410830
{ "func_code_index": [ 1637, 1857 ] }
8,647
EthTime
EthTime.sol
0xe339d6f5a42e581dce5a479fca0ed02248a6dca4
Solidity
CharitySplitter
contract CharitySplitter { ////////////////////////////////////////////////////////////////////////// // // // Constructor // // // ////////////////////////////////////////////////////////////////////////// /// @dev Charity address, can be changed with a time-lock. address payable public charity; /// @dev Charity fee, in basis points. 1% = 100 bp. uint256 public charityFeeBp; constructor(address payable _charity, uint256 _charityFeeBp) { // checks: address not zero. Don't want to burn eth. if (_charity == address(0)) { revert CharitySplitter__InvalidCharityAddress(); } // checks: fee > 0%. Don't want to deal with no fee edge cases. if (_charityFeeBp == 0) { revert CharitySplitter__InvalidCharityFee(); } charity = _charity; charityFeeBp = _charityFeeBp; } ////////////////////////////////////////////////////////////////////////// // // // Charity Address Management // // // ////////////////////////////////////////////////////////////////////////// /// @dev Emitted when the charity address is updated. event CharityUpdated(address charity); /// @dev Update the charity address. function _updateCharity(address payable _charity) internal { if (_charity == address(0)) { revert CharitySplitter__InvalidCharityAddress(); } charity = _charity; } ////////////////////////////////////////////////////////////////////////// // // // Profit Tracking // // // ////////////////////////////////////////////////////////////////////////// /// @dev Balance owed to the charity. uint256 public charityBalance; /// @dev Balance owed to the owner. uint256 public ownerBalance; /// @dev Denominator used when computing fee. 100% in bp. uint256 private constant BP_DENOMINATOR = 10000; /// @dev Update charity and owner balance. function _updateBalance(uint256 value) internal { // checks: if value is zero nothing to update. if (value == 0) { return; } uint256 charityValue = (value * charityFeeBp) / BP_DENOMINATOR; uint256 ownerValue = value - charityValue; // effects: update balances. charityBalance += charityValue; ownerBalance += ownerValue; } ////////////////////////////////////////////////////////////////////////// // // // Withdrawing Funds // // // ////////////////////////////////////////////////////////////////////////// /// @notice Withdraw funds to charity address. function _withdrawCharityBalance() internal { uint256 value = charityBalance; // checks: no money to withdraw. if (value == 0) { return; } // effects: reset charity balance to zero. charityBalance = 0; // interactions: send money to charity address. (bool sent, ) = charity.call{value: value}(""); require(sent); } /// @notice Withdraw funds to owner address. /// @param destination the address that receives the funds. function _withdrawOwnerBalance(address payable destination) internal { uint256 value = ownerBalance; // checks: no money to withdraw. if (value == 0) { return; } // effects: reset owner balance to zero. ownerBalance = 0; // interactions: send money to destination address. (bool sent, ) = destination.call{value: value}(""); require(sent); } }
/// @notice Tracks splitting profits with a charity. /// @dev This module essentialy does two things: /// * Tracks how much money goes to the charity and how much to someone else. /// * Implements a simple time-lock to avoid the contract owner changing the /// charity address to one they own. /// /// Anyone can call the method to send the funds to the charity.
NatSpecSingleLine
_updateBalance
function _updateBalance(uint256 value) internal { // checks: if value is zero nothing to update. if (value == 0) { return; } uint256 charityValue = (value * charityFeeBp) / BP_DENOMINATOR; uint256 ownerValue = value - charityValue; // effects: update balances. charityBalance += charityValue; ownerBalance += ownerValue; }
/// @dev Update charity and owner balance.
NatSpecSingleLine
v0.8.10+commit.fc410830
{ "func_code_index": [ 2570, 2990 ] }
8,648
EthTime
EthTime.sol
0xe339d6f5a42e581dce5a479fca0ed02248a6dca4
Solidity
CharitySplitter
contract CharitySplitter { ////////////////////////////////////////////////////////////////////////// // // // Constructor // // // ////////////////////////////////////////////////////////////////////////// /// @dev Charity address, can be changed with a time-lock. address payable public charity; /// @dev Charity fee, in basis points. 1% = 100 bp. uint256 public charityFeeBp; constructor(address payable _charity, uint256 _charityFeeBp) { // checks: address not zero. Don't want to burn eth. if (_charity == address(0)) { revert CharitySplitter__InvalidCharityAddress(); } // checks: fee > 0%. Don't want to deal with no fee edge cases. if (_charityFeeBp == 0) { revert CharitySplitter__InvalidCharityFee(); } charity = _charity; charityFeeBp = _charityFeeBp; } ////////////////////////////////////////////////////////////////////////// // // // Charity Address Management // // // ////////////////////////////////////////////////////////////////////////// /// @dev Emitted when the charity address is updated. event CharityUpdated(address charity); /// @dev Update the charity address. function _updateCharity(address payable _charity) internal { if (_charity == address(0)) { revert CharitySplitter__InvalidCharityAddress(); } charity = _charity; } ////////////////////////////////////////////////////////////////////////// // // // Profit Tracking // // // ////////////////////////////////////////////////////////////////////////// /// @dev Balance owed to the charity. uint256 public charityBalance; /// @dev Balance owed to the owner. uint256 public ownerBalance; /// @dev Denominator used when computing fee. 100% in bp. uint256 private constant BP_DENOMINATOR = 10000; /// @dev Update charity and owner balance. function _updateBalance(uint256 value) internal { // checks: if value is zero nothing to update. if (value == 0) { return; } uint256 charityValue = (value * charityFeeBp) / BP_DENOMINATOR; uint256 ownerValue = value - charityValue; // effects: update balances. charityBalance += charityValue; ownerBalance += ownerValue; } ////////////////////////////////////////////////////////////////////////// // // // Withdrawing Funds // // // ////////////////////////////////////////////////////////////////////////// /// @notice Withdraw funds to charity address. function _withdrawCharityBalance() internal { uint256 value = charityBalance; // checks: no money to withdraw. if (value == 0) { return; } // effects: reset charity balance to zero. charityBalance = 0; // interactions: send money to charity address. (bool sent, ) = charity.call{value: value}(""); require(sent); } /// @notice Withdraw funds to owner address. /// @param destination the address that receives the funds. function _withdrawOwnerBalance(address payable destination) internal { uint256 value = ownerBalance; // checks: no money to withdraw. if (value == 0) { return; } // effects: reset owner balance to zero. ownerBalance = 0; // interactions: send money to destination address. (bool sent, ) = destination.call{value: value}(""); require(sent); } }
/// @notice Tracks splitting profits with a charity. /// @dev This module essentialy does two things: /// * Tracks how much money goes to the charity and how much to someone else. /// * Implements a simple time-lock to avoid the contract owner changing the /// charity address to one they own. /// /// Anyone can call the method to send the funds to the charity.
NatSpecSingleLine
_withdrawCharityBalance
function _withdrawCharityBalance() internal { uint256 value = charityBalance; // checks: no money to withdraw. if (value == 0) { return; } // effects: reset charity balance to zero. charityBalance = 0; // interactions: send money to charity address. (bool sent, ) = charity.call{value: value}(""); require(sent); }
////////////////////////////////////////////////////////////////////////// /// @notice Withdraw funds to charity address.
NatSpecSingleLine
v0.8.10+commit.fc410830
{ "func_code_index": [ 3439, 3860 ] }
8,649
EthTime
EthTime.sol
0xe339d6f5a42e581dce5a479fca0ed02248a6dca4
Solidity
CharitySplitter
contract CharitySplitter { ////////////////////////////////////////////////////////////////////////// // // // Constructor // // // ////////////////////////////////////////////////////////////////////////// /// @dev Charity address, can be changed with a time-lock. address payable public charity; /// @dev Charity fee, in basis points. 1% = 100 bp. uint256 public charityFeeBp; constructor(address payable _charity, uint256 _charityFeeBp) { // checks: address not zero. Don't want to burn eth. if (_charity == address(0)) { revert CharitySplitter__InvalidCharityAddress(); } // checks: fee > 0%. Don't want to deal with no fee edge cases. if (_charityFeeBp == 0) { revert CharitySplitter__InvalidCharityFee(); } charity = _charity; charityFeeBp = _charityFeeBp; } ////////////////////////////////////////////////////////////////////////// // // // Charity Address Management // // // ////////////////////////////////////////////////////////////////////////// /// @dev Emitted when the charity address is updated. event CharityUpdated(address charity); /// @dev Update the charity address. function _updateCharity(address payable _charity) internal { if (_charity == address(0)) { revert CharitySplitter__InvalidCharityAddress(); } charity = _charity; } ////////////////////////////////////////////////////////////////////////// // // // Profit Tracking // // // ////////////////////////////////////////////////////////////////////////// /// @dev Balance owed to the charity. uint256 public charityBalance; /// @dev Balance owed to the owner. uint256 public ownerBalance; /// @dev Denominator used when computing fee. 100% in bp. uint256 private constant BP_DENOMINATOR = 10000; /// @dev Update charity and owner balance. function _updateBalance(uint256 value) internal { // checks: if value is zero nothing to update. if (value == 0) { return; } uint256 charityValue = (value * charityFeeBp) / BP_DENOMINATOR; uint256 ownerValue = value - charityValue; // effects: update balances. charityBalance += charityValue; ownerBalance += ownerValue; } ////////////////////////////////////////////////////////////////////////// // // // Withdrawing Funds // // // ////////////////////////////////////////////////////////////////////////// /// @notice Withdraw funds to charity address. function _withdrawCharityBalance() internal { uint256 value = charityBalance; // checks: no money to withdraw. if (value == 0) { return; } // effects: reset charity balance to zero. charityBalance = 0; // interactions: send money to charity address. (bool sent, ) = charity.call{value: value}(""); require(sent); } /// @notice Withdraw funds to owner address. /// @param destination the address that receives the funds. function _withdrawOwnerBalance(address payable destination) internal { uint256 value = ownerBalance; // checks: no money to withdraw. if (value == 0) { return; } // effects: reset owner balance to zero. ownerBalance = 0; // interactions: send money to destination address. (bool sent, ) = destination.call{value: value}(""); require(sent); } }
/// @notice Tracks splitting profits with a charity. /// @dev This module essentialy does two things: /// * Tracks how much money goes to the charity and how much to someone else. /// * Implements a simple time-lock to avoid the contract owner changing the /// charity address to one they own. /// /// Anyone can call the method to send the funds to the charity.
NatSpecSingleLine
_withdrawOwnerBalance
function _withdrawOwnerBalance(address payable destination) internal { uint256 value = ownerBalance; // checks: no money to withdraw. if (value == 0) { return; } // effects: reset owner balance to zero. ownerBalance = 0; // interactions: send money to destination address. (bool sent, ) = destination.call{value: value}(""); require(sent); }
/// @notice Withdraw funds to owner address. /// @param destination the address that receives the funds.
NatSpecSingleLine
v0.8.10+commit.fc410830
{ "func_code_index": [ 3975, 4423 ] }
8,650
EthTime
EthTime.sol
0xe339d6f5a42e581dce5a479fca0ed02248a6dca4
Solidity
EthTime
contract EthTime is ERC721, CharitySplitter, Ownable, ReentrancyGuard { ////////////////////////////////////////////////////////////////////////// // // // Constructor // // // ////////////////////////////////////////////////////////////////////////// constructor(address payable charity, uint256 charityFeeBp) ERC721("ETH Time", "ETHT") CharitySplitter(charity, charityFeeBp) { } receive() external payable {} ////////////////////////////////////////////////////////////////////////// // // // Transfer with History // // // ////////////////////////////////////////////////////////////////////////// /// @notice The state of each NFT. mapping(uint256 => uint160) public historyAccumulator; function transferFrom(address from, address to, uint256 id) public nonReentrant override { _transferFrom(from, to, id); } function safeTransferFrom(address from, address to, uint256 id) public nonReentrant override { _transferFrom(from, to, id); // interactions: check destination can handle ERC721 require( to.code.length == 0 || ERC721TokenReceiver(to).onERC721Received(msg.sender, from, id, "") == ERC721TokenReceiver.onERC721Received.selector, "UNSAFE_RECIPIENT" ); } function safeTransferFrom(address from, address to, uint256 id, bytes memory /* data */) public nonReentrant override { _transferFrom(from, to, id); // interactions: check destination can handle ERC721 require( to.code.length == 0 || ERC721TokenReceiver(to).onERC721Received(msg.sender, from, id, "") == ERC721TokenReceiver.onERC721Received.selector, "UNSAFE_RECIPIENT" ); } ////////////////////////////////////////////////////////////////////////// // // // Charity Splitter // // // ////////////////////////////////////////////////////////////////////////// /// @notice Withdraw charity balance to charity address. /// @dev Anyone can call this at any time. function withdrawCharityBalance() public nonReentrant { _withdrawCharityBalance(); } /// @notice Withdraw owner balance to the specified address. /// @param destination the address that receives the owner balance. function withdrawOwnerBalance(address payable destination) public onlyOwner nonReentrant { _withdrawOwnerBalance(destination); } /// @notice Update the address that receives the charity fee. /// @param charity the new charity address. function updateCharity(address payable charity) public onlyOwner nonReentrant { _updateCharity(charity); } ////////////////////////////////////////////////////////////////////////// // // // Timezone Management // // // ////////////////////////////////////////////////////////////////////////// mapping(uint256 => int128) public timeOffsetMinutes; event TimeOffsetUpdated(uint256 indexed id, int128 offsetMinutes); /// @notice Sets the time offset of the given token id. /// @dev Use minutes because some timezones (like IST) are offset by half an hour. /// @param id the NFT unique id. /// @param offsetMinutes the offset in minutes. function setTimeOffsetMinutes(uint256 id, int128 offsetMinutes) public { // checks: id exists if (ownerOf[id] == address(0)) { revert EthTime__DoesNotExist(); } // checks: sender is owner. if (ownerOf[id] != msg.sender) { revert EthTime__NotOwner(); } // checks: validate time offset _validateTimeOffset(offsetMinutes); // effects: update time offset timeOffsetMinutes[id] = offsetMinutes; emit TimeOffsetUpdated(id, offsetMinutes); } function _validateTimeOffset(int128 offsetMinutes) internal { int128 offsetSeconds = offsetMinutes * 60; // checks: offset is [-12, +14] hours UTC if (offsetSeconds > 14 hours || offsetSeconds < -12 hours) { revert EthTime__InvalidTimeOffset(); } } ////////////////////////////////////////////////////////////////////////// // // // Minting // // // ////////////////////////////////////////////////////////////////////////// /// @dev The number of tokens minted. uint256 public totalSupply; /// @dev The maximum number of mintable tokens. uint256 public constant maximumSupply = 100; uint256 private constant TARGET_PRICE = 1 ether; uint256 private constant PRICE_INCREMENT = TARGET_PRICE / maximumSupply * 2; /// @notice Mint a new NFT, transfering ownership to the given account. /// @dev If the token id already exists, this method fails. /// @param to the NFT ower. /// @param offsetMinutes the time offset in minutes. /// @param id the NFT unique id. function mint(address to, int128 offsetMinutes, uint256 id) public payable nonReentrant virtual { // interactions: mint. uint256 valueLeft = _mint(to, offsetMinutes, id, msg.value); // interactions: send back leftover value. if (valueLeft > 0) { (bool success, ) = msg.sender.call{value: valueLeft}(""); require(success); } } /// @notice Mint new NFTs, transfering ownership to the given account. /// @dev If any of the token ids already exists, this method fails. /// @param to the NFT ower. /// @param offsetMinutes the time offset in minutes. /// @param ids the NFT unique ids. function batchMint(address to, int128 offsetMinutes, uint256[] calldata ids) public payable nonReentrant virtual { uint256 count = ids.length; // checks: can mint count nfts _validateBatchMintCount(count); uint256 valueLeft = msg.value; for (uint256 i = 0; i < count; i++) { // interactions: mint. valueLeft = _mint(to, offsetMinutes, ids[i], valueLeft); } // interactions: send back leftover value. if (valueLeft > 0) { (bool success, ) = msg.sender.call{value: valueLeft}(""); require(success); } } /// @notice Get the price for minting the next `count` NFT. function getBatchMintPrice(uint256 count) public view returns (uint256) { // checks: can mint count nfts _validateBatchMintCount(count); uint256 supply = totalSupply; uint256 price = 0; for (uint256 i = 0; i < count; i++) { price += _priceAtSupplyLevel(supply + i); } return price; } /// @notice Get the price for minting the next NFT. function getMintPrice() public view returns (uint256) { return _priceAtSupplyLevel(totalSupply); } function _mint(address to, int128 offsetMinutes, uint256 id, uint256 value) internal returns (uint256 valueLeft) { uint256 price = _priceAtSupplyLevel(totalSupply); // checks: value is enough to mint the nft. if (value < price) { revert EthTime__InvalidMintValue(); } // checks: minting causes going over maximum supply. if (totalSupply == maximumSupply) { revert EthTime__CollectionMintClosed(); } // checks: validate offset _validateTimeOffset(offsetMinutes); // effects: seed history with unique starting value. historyAccumulator[id] = uint160(id >> 4); // effects: increment total supply. totalSupply += 1; // effects: update charity split. _updateBalance(value); // effects: set time offset timeOffsetMinutes[id] = offsetMinutes; // interactions: safe mint _safeMint(to, id); // return value left to be sent back to user. valueLeft = value - price; } function _priceAtSupplyLevel(uint256 supply) internal pure returns (uint256) { uint256 price = supply * PRICE_INCREMENT; if (supply > 50) { price = TARGET_PRICE; } return price; } function _validateBatchMintCount(uint256 count) internal view { // checks: no more than 10. if (count > 10) { revert EthTime__InvalidMintAmount(); } // checks: minting does not push over the limit. // notice that it would fail anyway. if (totalSupply + count > maximumSupply) { revert EthTime__InvalidMintAmount(); } } ////////////////////////////////////////////////////////////////////////// // // // Token URI // // // ////////////////////////////////////////////////////////////////////////// /// @notice Returns the URI with the NFT metadata. /// @dev Returns the base64 encoded metadata inline. /// @param id the NFT unique id function tokenURI(uint256 id) public view override returns (string memory) { if (ownerOf[id] == address(0)) { revert EthTime__DoesNotExist(); } string memory tokenId = Strings.toString(id); (uint256 hour, uint256 minute) = _adjustedHourMinutes(id); bytes memory topHue = _computeHue(historyAccumulator[id], id); bytes memory bottomHue = _computeHue(uint160(ownerOf[id]), id); int128 offset = timeOffsetMinutes[id]; bytes memory offsetSign = offset >= 0 ? bytes('+') : bytes('-'); uint256 offsetUnsigned = offset >= 0 ? uint256(int256(offset)) : uint256(int256(-offset)); return string( bytes.concat( 'data:application/json;base64,', bytes( Base64.encode( bytes.concat( '{"name": "ETH Time #', bytes(tokenId), '", "description": "ETH Time", "image": "data:image/svg+xml;base64,', bytes(_tokenImage(topHue, bottomHue, hour, minute)), '", "attributes": [{"trait_type": "top_color", "value": "hsl(', topHue, ',100%,89%)"},', '{"trait_type": "bottom_color", "value": "hsl(', bottomHue, ',77%,36%)"},', '{"trait_type": "time_offset", "value": "', offsetSign, bytes(Strings.toString(offsetUnsigned)), '"},', '{"trait_type": "time", "value": "', bytes(Strings.toString(hour)), ':', bytes(Strings.toString(minute)), '"}]}' ) ) ) ) ); } /// @dev Generate a preview of the token that will be minted. /// @param to the minter. /// @param id the NFT unique id. function tokenImagePreview(address to, uint256 id) public view returns (string memory) { (uint256 hour, uint256 minute) = _adjustedHourMinutes(id); bytes memory topHue = _computeHue(uint160(id >> 4), id); bytes memory bottomHue = _computeHue(uint160(to), id); return _tokenImage(topHue, bottomHue, hour, minute); } ////////////////////////////////////////////////////////////////////////// // // // Private Functions // // // ////////////////////////////////////////////////////////////////////////// /// @dev Update the NFT history based on the transfer to the given account. /// @param to the address that will receive the nft. /// @param id the NFT unique id. function _updateHistory(address to, uint256 id) internal { // effects: xor existing value with address bytes content. historyAccumulator[id] ^= uint160(to) << 2; } function _transferFrom(address from, address to, uint256 id) internal { // checks: sender and destination require(from == ownerOf[id], "WRONG_FROM"); require(to != address(0), "INVALID_RECIPIENT"); // checks: can transfer require( msg.sender == from || msg.sender == getApproved[id] || isApprovedForAll[from][msg.sender], "NOT_AUTHORIZED" ); // effects: update balance // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. unchecked { balanceOf[from]--; balanceOf[to]++; } // effects: update owership ownerOf[id] = to; // effects: reclaim storage delete getApproved[id]; // effects: update history _updateHistory(to, id); emit Transfer(from, to, id); } bytes constant onColor = "FFF"; bytes constant offColor = "333"; /// @dev Generate the SVG image for the given NFT. function _tokenImage(bytes memory topHue, bytes memory bottomHue, uint256 hour, uint256 minute) internal pure returns (string memory) { return Base64.encode( bytes.concat( '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1000 1000">', '<linearGradient id="bg" gradientTransform="rotate(90)">', '<stop offset="0%" stop-color="hsl(', topHue, ',100%,89%)"/>', '<stop offset="100%" stop-color="hsl(', bottomHue, ',77%,36%)"/>', '</linearGradient>', '<rect x="0" y="0" width="1000" height="1000" fill="url(#bg)"/>', _binaryHour(hour), _binaryMinute(minute), '</svg>' ) ); } function _binaryHour(uint256 hour) internal pure returns (bytes memory) { if (hour > 24) { revert EthTime__NumberOutOfRange(); } bytes[7] memory colors = _binaryColor(hour); return bytes.concat( '<circle cx="665" cy="875" r="25" fill="#', colors[0], '"/>', '<circle cx="665" cy="805" r="25" fill="#', colors[1], '"/>', // skip colors[2] '<circle cx="735" cy="875" r="25" fill="#', colors[3], '"/>', '<circle cx="735" cy="805" r="25" fill="#', colors[4], '"/>', '<circle cx="735" cy="735" r="25" fill="#', colors[5], '"/>', '<circle cx="735" cy="665" r="25" fill="#', colors[6], '"/>' ); } function _binaryMinute(uint256 minute) internal pure returns (bytes memory) { if (minute > 59) { revert EthTime__NumberOutOfRange(); } bytes[7] memory colors = _binaryColor(minute); return bytes.concat( '<circle cx="805" cy="875" r="25" fill="#', colors[0], '"/>', '<circle cx="805" cy="805" r="25" fill="#', colors[1], '"/>', '<circle cx="805" cy="735" r="25" fill="#', colors[2], '"/>', '<circle cx="875" cy="875" r="25" fill="#', colors[3], '"/>', '<circle cx="875" cy="805" r="25" fill="#', colors[4], '"/>', '<circle cx="875" cy="735" r="25" fill="#', colors[5], '"/>', '<circle cx="875" cy="665" r="25" fill="#', colors[6], '"/>' ); } /// @dev Returns the colors to be used to display the time. /// The first 3 bytes are used for the first digit, the remaining 4 bytes /// for the second digit. function _binaryColor(uint256 n) internal pure returns (bytes[7] memory) { unchecked { uint256 firstDigit = n / 10; uint256 secondDigit = n % 10; return [ (firstDigit & 0x1 != 0) ? onColor : offColor, (firstDigit & 0x2 != 0) ? onColor : offColor, (firstDigit & 0x4 != 0) ? onColor : offColor, (secondDigit & 0x1 != 0) ? onColor : offColor, (secondDigit & 0x2 != 0) ? onColor : offColor, (secondDigit & 0x4 != 0) ? onColor : offColor, (secondDigit & 0x8 != 0) ? onColor : offColor ]; } } function _computeHue(uint160 n, uint256 id) internal pure returns (bytes memory) { uint160 t = n ^ uint160(id); uint160 acc = t % 360; return bytes(Strings.toString(acc)); } function _adjustedHourMinutes(uint256 id) internal view returns (uint256 hour, uint256 minute) { int256 signedUserTimestamp = int256(block.timestamp) - 60 * timeOffsetMinutes[id]; uint256 userTimestamp; // this won't realistically ever happen if (signedUserTimestamp <= 0) { userTimestamp = 0; } else { userTimestamp = uint256(signedUserTimestamp); } hour = BokkyPooBahsDateTimeLibrary.getHour(userTimestamp); minute = BokkyPooBahsDateTimeLibrary.getMinute(userTimestamp); } }
/// @notice ETH-Time NFT contract.
NatSpecSingleLine
withdrawCharityBalance
function withdrawCharityBalance() public nonReentrant { _withdrawCharityBalance(); }
////////////////////////////////////////////////////////////////////////// /// @notice Withdraw charity balance to charity address. /// @dev Anyone can call this at any time.
NatSpecSingleLine
v0.8.10+commit.fc410830
{ "func_code_index": [ 2804, 2924 ] }
8,651
EthTime
EthTime.sol
0xe339d6f5a42e581dce5a479fca0ed02248a6dca4
Solidity
EthTime
contract EthTime is ERC721, CharitySplitter, Ownable, ReentrancyGuard { ////////////////////////////////////////////////////////////////////////// // // // Constructor // // // ////////////////////////////////////////////////////////////////////////// constructor(address payable charity, uint256 charityFeeBp) ERC721("ETH Time", "ETHT") CharitySplitter(charity, charityFeeBp) { } receive() external payable {} ////////////////////////////////////////////////////////////////////////// // // // Transfer with History // // // ////////////////////////////////////////////////////////////////////////// /// @notice The state of each NFT. mapping(uint256 => uint160) public historyAccumulator; function transferFrom(address from, address to, uint256 id) public nonReentrant override { _transferFrom(from, to, id); } function safeTransferFrom(address from, address to, uint256 id) public nonReentrant override { _transferFrom(from, to, id); // interactions: check destination can handle ERC721 require( to.code.length == 0 || ERC721TokenReceiver(to).onERC721Received(msg.sender, from, id, "") == ERC721TokenReceiver.onERC721Received.selector, "UNSAFE_RECIPIENT" ); } function safeTransferFrom(address from, address to, uint256 id, bytes memory /* data */) public nonReentrant override { _transferFrom(from, to, id); // interactions: check destination can handle ERC721 require( to.code.length == 0 || ERC721TokenReceiver(to).onERC721Received(msg.sender, from, id, "") == ERC721TokenReceiver.onERC721Received.selector, "UNSAFE_RECIPIENT" ); } ////////////////////////////////////////////////////////////////////////// // // // Charity Splitter // // // ////////////////////////////////////////////////////////////////////////// /// @notice Withdraw charity balance to charity address. /// @dev Anyone can call this at any time. function withdrawCharityBalance() public nonReentrant { _withdrawCharityBalance(); } /// @notice Withdraw owner balance to the specified address. /// @param destination the address that receives the owner balance. function withdrawOwnerBalance(address payable destination) public onlyOwner nonReentrant { _withdrawOwnerBalance(destination); } /// @notice Update the address that receives the charity fee. /// @param charity the new charity address. function updateCharity(address payable charity) public onlyOwner nonReentrant { _updateCharity(charity); } ////////////////////////////////////////////////////////////////////////// // // // Timezone Management // // // ////////////////////////////////////////////////////////////////////////// mapping(uint256 => int128) public timeOffsetMinutes; event TimeOffsetUpdated(uint256 indexed id, int128 offsetMinutes); /// @notice Sets the time offset of the given token id. /// @dev Use minutes because some timezones (like IST) are offset by half an hour. /// @param id the NFT unique id. /// @param offsetMinutes the offset in minutes. function setTimeOffsetMinutes(uint256 id, int128 offsetMinutes) public { // checks: id exists if (ownerOf[id] == address(0)) { revert EthTime__DoesNotExist(); } // checks: sender is owner. if (ownerOf[id] != msg.sender) { revert EthTime__NotOwner(); } // checks: validate time offset _validateTimeOffset(offsetMinutes); // effects: update time offset timeOffsetMinutes[id] = offsetMinutes; emit TimeOffsetUpdated(id, offsetMinutes); } function _validateTimeOffset(int128 offsetMinutes) internal { int128 offsetSeconds = offsetMinutes * 60; // checks: offset is [-12, +14] hours UTC if (offsetSeconds > 14 hours || offsetSeconds < -12 hours) { revert EthTime__InvalidTimeOffset(); } } ////////////////////////////////////////////////////////////////////////// // // // Minting // // // ////////////////////////////////////////////////////////////////////////// /// @dev The number of tokens minted. uint256 public totalSupply; /// @dev The maximum number of mintable tokens. uint256 public constant maximumSupply = 100; uint256 private constant TARGET_PRICE = 1 ether; uint256 private constant PRICE_INCREMENT = TARGET_PRICE / maximumSupply * 2; /// @notice Mint a new NFT, transfering ownership to the given account. /// @dev If the token id already exists, this method fails. /// @param to the NFT ower. /// @param offsetMinutes the time offset in minutes. /// @param id the NFT unique id. function mint(address to, int128 offsetMinutes, uint256 id) public payable nonReentrant virtual { // interactions: mint. uint256 valueLeft = _mint(to, offsetMinutes, id, msg.value); // interactions: send back leftover value. if (valueLeft > 0) { (bool success, ) = msg.sender.call{value: valueLeft}(""); require(success); } } /// @notice Mint new NFTs, transfering ownership to the given account. /// @dev If any of the token ids already exists, this method fails. /// @param to the NFT ower. /// @param offsetMinutes the time offset in minutes. /// @param ids the NFT unique ids. function batchMint(address to, int128 offsetMinutes, uint256[] calldata ids) public payable nonReentrant virtual { uint256 count = ids.length; // checks: can mint count nfts _validateBatchMintCount(count); uint256 valueLeft = msg.value; for (uint256 i = 0; i < count; i++) { // interactions: mint. valueLeft = _mint(to, offsetMinutes, ids[i], valueLeft); } // interactions: send back leftover value. if (valueLeft > 0) { (bool success, ) = msg.sender.call{value: valueLeft}(""); require(success); } } /// @notice Get the price for minting the next `count` NFT. function getBatchMintPrice(uint256 count) public view returns (uint256) { // checks: can mint count nfts _validateBatchMintCount(count); uint256 supply = totalSupply; uint256 price = 0; for (uint256 i = 0; i < count; i++) { price += _priceAtSupplyLevel(supply + i); } return price; } /// @notice Get the price for minting the next NFT. function getMintPrice() public view returns (uint256) { return _priceAtSupplyLevel(totalSupply); } function _mint(address to, int128 offsetMinutes, uint256 id, uint256 value) internal returns (uint256 valueLeft) { uint256 price = _priceAtSupplyLevel(totalSupply); // checks: value is enough to mint the nft. if (value < price) { revert EthTime__InvalidMintValue(); } // checks: minting causes going over maximum supply. if (totalSupply == maximumSupply) { revert EthTime__CollectionMintClosed(); } // checks: validate offset _validateTimeOffset(offsetMinutes); // effects: seed history with unique starting value. historyAccumulator[id] = uint160(id >> 4); // effects: increment total supply. totalSupply += 1; // effects: update charity split. _updateBalance(value); // effects: set time offset timeOffsetMinutes[id] = offsetMinutes; // interactions: safe mint _safeMint(to, id); // return value left to be sent back to user. valueLeft = value - price; } function _priceAtSupplyLevel(uint256 supply) internal pure returns (uint256) { uint256 price = supply * PRICE_INCREMENT; if (supply > 50) { price = TARGET_PRICE; } return price; } function _validateBatchMintCount(uint256 count) internal view { // checks: no more than 10. if (count > 10) { revert EthTime__InvalidMintAmount(); } // checks: minting does not push over the limit. // notice that it would fail anyway. if (totalSupply + count > maximumSupply) { revert EthTime__InvalidMintAmount(); } } ////////////////////////////////////////////////////////////////////////// // // // Token URI // // // ////////////////////////////////////////////////////////////////////////// /// @notice Returns the URI with the NFT metadata. /// @dev Returns the base64 encoded metadata inline. /// @param id the NFT unique id function tokenURI(uint256 id) public view override returns (string memory) { if (ownerOf[id] == address(0)) { revert EthTime__DoesNotExist(); } string memory tokenId = Strings.toString(id); (uint256 hour, uint256 minute) = _adjustedHourMinutes(id); bytes memory topHue = _computeHue(historyAccumulator[id], id); bytes memory bottomHue = _computeHue(uint160(ownerOf[id]), id); int128 offset = timeOffsetMinutes[id]; bytes memory offsetSign = offset >= 0 ? bytes('+') : bytes('-'); uint256 offsetUnsigned = offset >= 0 ? uint256(int256(offset)) : uint256(int256(-offset)); return string( bytes.concat( 'data:application/json;base64,', bytes( Base64.encode( bytes.concat( '{"name": "ETH Time #', bytes(tokenId), '", "description": "ETH Time", "image": "data:image/svg+xml;base64,', bytes(_tokenImage(topHue, bottomHue, hour, minute)), '", "attributes": [{"trait_type": "top_color", "value": "hsl(', topHue, ',100%,89%)"},', '{"trait_type": "bottom_color", "value": "hsl(', bottomHue, ',77%,36%)"},', '{"trait_type": "time_offset", "value": "', offsetSign, bytes(Strings.toString(offsetUnsigned)), '"},', '{"trait_type": "time", "value": "', bytes(Strings.toString(hour)), ':', bytes(Strings.toString(minute)), '"}]}' ) ) ) ) ); } /// @dev Generate a preview of the token that will be minted. /// @param to the minter. /// @param id the NFT unique id. function tokenImagePreview(address to, uint256 id) public view returns (string memory) { (uint256 hour, uint256 minute) = _adjustedHourMinutes(id); bytes memory topHue = _computeHue(uint160(id >> 4), id); bytes memory bottomHue = _computeHue(uint160(to), id); return _tokenImage(topHue, bottomHue, hour, minute); } ////////////////////////////////////////////////////////////////////////// // // // Private Functions // // // ////////////////////////////////////////////////////////////////////////// /// @dev Update the NFT history based on the transfer to the given account. /// @param to the address that will receive the nft. /// @param id the NFT unique id. function _updateHistory(address to, uint256 id) internal { // effects: xor existing value with address bytes content. historyAccumulator[id] ^= uint160(to) << 2; } function _transferFrom(address from, address to, uint256 id) internal { // checks: sender and destination require(from == ownerOf[id], "WRONG_FROM"); require(to != address(0), "INVALID_RECIPIENT"); // checks: can transfer require( msg.sender == from || msg.sender == getApproved[id] || isApprovedForAll[from][msg.sender], "NOT_AUTHORIZED" ); // effects: update balance // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. unchecked { balanceOf[from]--; balanceOf[to]++; } // effects: update owership ownerOf[id] = to; // effects: reclaim storage delete getApproved[id]; // effects: update history _updateHistory(to, id); emit Transfer(from, to, id); } bytes constant onColor = "FFF"; bytes constant offColor = "333"; /// @dev Generate the SVG image for the given NFT. function _tokenImage(bytes memory topHue, bytes memory bottomHue, uint256 hour, uint256 minute) internal pure returns (string memory) { return Base64.encode( bytes.concat( '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1000 1000">', '<linearGradient id="bg" gradientTransform="rotate(90)">', '<stop offset="0%" stop-color="hsl(', topHue, ',100%,89%)"/>', '<stop offset="100%" stop-color="hsl(', bottomHue, ',77%,36%)"/>', '</linearGradient>', '<rect x="0" y="0" width="1000" height="1000" fill="url(#bg)"/>', _binaryHour(hour), _binaryMinute(minute), '</svg>' ) ); } function _binaryHour(uint256 hour) internal pure returns (bytes memory) { if (hour > 24) { revert EthTime__NumberOutOfRange(); } bytes[7] memory colors = _binaryColor(hour); return bytes.concat( '<circle cx="665" cy="875" r="25" fill="#', colors[0], '"/>', '<circle cx="665" cy="805" r="25" fill="#', colors[1], '"/>', // skip colors[2] '<circle cx="735" cy="875" r="25" fill="#', colors[3], '"/>', '<circle cx="735" cy="805" r="25" fill="#', colors[4], '"/>', '<circle cx="735" cy="735" r="25" fill="#', colors[5], '"/>', '<circle cx="735" cy="665" r="25" fill="#', colors[6], '"/>' ); } function _binaryMinute(uint256 minute) internal pure returns (bytes memory) { if (minute > 59) { revert EthTime__NumberOutOfRange(); } bytes[7] memory colors = _binaryColor(minute); return bytes.concat( '<circle cx="805" cy="875" r="25" fill="#', colors[0], '"/>', '<circle cx="805" cy="805" r="25" fill="#', colors[1], '"/>', '<circle cx="805" cy="735" r="25" fill="#', colors[2], '"/>', '<circle cx="875" cy="875" r="25" fill="#', colors[3], '"/>', '<circle cx="875" cy="805" r="25" fill="#', colors[4], '"/>', '<circle cx="875" cy="735" r="25" fill="#', colors[5], '"/>', '<circle cx="875" cy="665" r="25" fill="#', colors[6], '"/>' ); } /// @dev Returns the colors to be used to display the time. /// The first 3 bytes are used for the first digit, the remaining 4 bytes /// for the second digit. function _binaryColor(uint256 n) internal pure returns (bytes[7] memory) { unchecked { uint256 firstDigit = n / 10; uint256 secondDigit = n % 10; return [ (firstDigit & 0x1 != 0) ? onColor : offColor, (firstDigit & 0x2 != 0) ? onColor : offColor, (firstDigit & 0x4 != 0) ? onColor : offColor, (secondDigit & 0x1 != 0) ? onColor : offColor, (secondDigit & 0x2 != 0) ? onColor : offColor, (secondDigit & 0x4 != 0) ? onColor : offColor, (secondDigit & 0x8 != 0) ? onColor : offColor ]; } } function _computeHue(uint160 n, uint256 id) internal pure returns (bytes memory) { uint160 t = n ^ uint160(id); uint160 acc = t % 360; return bytes(Strings.toString(acc)); } function _adjustedHourMinutes(uint256 id) internal view returns (uint256 hour, uint256 minute) { int256 signedUserTimestamp = int256(block.timestamp) - 60 * timeOffsetMinutes[id]; uint256 userTimestamp; // this won't realistically ever happen if (signedUserTimestamp <= 0) { userTimestamp = 0; } else { userTimestamp = uint256(signedUserTimestamp); } hour = BokkyPooBahsDateTimeLibrary.getHour(userTimestamp); minute = BokkyPooBahsDateTimeLibrary.getMinute(userTimestamp); } }
/// @notice ETH-Time NFT contract.
NatSpecSingleLine
withdrawOwnerBalance
function withdrawOwnerBalance(address payable destination) public onlyOwner nonReentrant { _withdrawOwnerBalance(destination); }
/// @notice Withdraw owner balance to the specified address. /// @param destination the address that receives the owner balance.
NatSpecSingleLine
v0.8.10+commit.fc410830
{ "func_code_index": [ 3063, 3235 ] }
8,652
EthTime
EthTime.sol
0xe339d6f5a42e581dce5a479fca0ed02248a6dca4
Solidity
EthTime
contract EthTime is ERC721, CharitySplitter, Ownable, ReentrancyGuard { ////////////////////////////////////////////////////////////////////////// // // // Constructor // // // ////////////////////////////////////////////////////////////////////////// constructor(address payable charity, uint256 charityFeeBp) ERC721("ETH Time", "ETHT") CharitySplitter(charity, charityFeeBp) { } receive() external payable {} ////////////////////////////////////////////////////////////////////////// // // // Transfer with History // // // ////////////////////////////////////////////////////////////////////////// /// @notice The state of each NFT. mapping(uint256 => uint160) public historyAccumulator; function transferFrom(address from, address to, uint256 id) public nonReentrant override { _transferFrom(from, to, id); } function safeTransferFrom(address from, address to, uint256 id) public nonReentrant override { _transferFrom(from, to, id); // interactions: check destination can handle ERC721 require( to.code.length == 0 || ERC721TokenReceiver(to).onERC721Received(msg.sender, from, id, "") == ERC721TokenReceiver.onERC721Received.selector, "UNSAFE_RECIPIENT" ); } function safeTransferFrom(address from, address to, uint256 id, bytes memory /* data */) public nonReentrant override { _transferFrom(from, to, id); // interactions: check destination can handle ERC721 require( to.code.length == 0 || ERC721TokenReceiver(to).onERC721Received(msg.sender, from, id, "") == ERC721TokenReceiver.onERC721Received.selector, "UNSAFE_RECIPIENT" ); } ////////////////////////////////////////////////////////////////////////// // // // Charity Splitter // // // ////////////////////////////////////////////////////////////////////////// /// @notice Withdraw charity balance to charity address. /// @dev Anyone can call this at any time. function withdrawCharityBalance() public nonReentrant { _withdrawCharityBalance(); } /// @notice Withdraw owner balance to the specified address. /// @param destination the address that receives the owner balance. function withdrawOwnerBalance(address payable destination) public onlyOwner nonReentrant { _withdrawOwnerBalance(destination); } /// @notice Update the address that receives the charity fee. /// @param charity the new charity address. function updateCharity(address payable charity) public onlyOwner nonReentrant { _updateCharity(charity); } ////////////////////////////////////////////////////////////////////////// // // // Timezone Management // // // ////////////////////////////////////////////////////////////////////////// mapping(uint256 => int128) public timeOffsetMinutes; event TimeOffsetUpdated(uint256 indexed id, int128 offsetMinutes); /// @notice Sets the time offset of the given token id. /// @dev Use minutes because some timezones (like IST) are offset by half an hour. /// @param id the NFT unique id. /// @param offsetMinutes the offset in minutes. function setTimeOffsetMinutes(uint256 id, int128 offsetMinutes) public { // checks: id exists if (ownerOf[id] == address(0)) { revert EthTime__DoesNotExist(); } // checks: sender is owner. if (ownerOf[id] != msg.sender) { revert EthTime__NotOwner(); } // checks: validate time offset _validateTimeOffset(offsetMinutes); // effects: update time offset timeOffsetMinutes[id] = offsetMinutes; emit TimeOffsetUpdated(id, offsetMinutes); } function _validateTimeOffset(int128 offsetMinutes) internal { int128 offsetSeconds = offsetMinutes * 60; // checks: offset is [-12, +14] hours UTC if (offsetSeconds > 14 hours || offsetSeconds < -12 hours) { revert EthTime__InvalidTimeOffset(); } } ////////////////////////////////////////////////////////////////////////// // // // Minting // // // ////////////////////////////////////////////////////////////////////////// /// @dev The number of tokens minted. uint256 public totalSupply; /// @dev The maximum number of mintable tokens. uint256 public constant maximumSupply = 100; uint256 private constant TARGET_PRICE = 1 ether; uint256 private constant PRICE_INCREMENT = TARGET_PRICE / maximumSupply * 2; /// @notice Mint a new NFT, transfering ownership to the given account. /// @dev If the token id already exists, this method fails. /// @param to the NFT ower. /// @param offsetMinutes the time offset in minutes. /// @param id the NFT unique id. function mint(address to, int128 offsetMinutes, uint256 id) public payable nonReentrant virtual { // interactions: mint. uint256 valueLeft = _mint(to, offsetMinutes, id, msg.value); // interactions: send back leftover value. if (valueLeft > 0) { (bool success, ) = msg.sender.call{value: valueLeft}(""); require(success); } } /// @notice Mint new NFTs, transfering ownership to the given account. /// @dev If any of the token ids already exists, this method fails. /// @param to the NFT ower. /// @param offsetMinutes the time offset in minutes. /// @param ids the NFT unique ids. function batchMint(address to, int128 offsetMinutes, uint256[] calldata ids) public payable nonReentrant virtual { uint256 count = ids.length; // checks: can mint count nfts _validateBatchMintCount(count); uint256 valueLeft = msg.value; for (uint256 i = 0; i < count; i++) { // interactions: mint. valueLeft = _mint(to, offsetMinutes, ids[i], valueLeft); } // interactions: send back leftover value. if (valueLeft > 0) { (bool success, ) = msg.sender.call{value: valueLeft}(""); require(success); } } /// @notice Get the price for minting the next `count` NFT. function getBatchMintPrice(uint256 count) public view returns (uint256) { // checks: can mint count nfts _validateBatchMintCount(count); uint256 supply = totalSupply; uint256 price = 0; for (uint256 i = 0; i < count; i++) { price += _priceAtSupplyLevel(supply + i); } return price; } /// @notice Get the price for minting the next NFT. function getMintPrice() public view returns (uint256) { return _priceAtSupplyLevel(totalSupply); } function _mint(address to, int128 offsetMinutes, uint256 id, uint256 value) internal returns (uint256 valueLeft) { uint256 price = _priceAtSupplyLevel(totalSupply); // checks: value is enough to mint the nft. if (value < price) { revert EthTime__InvalidMintValue(); } // checks: minting causes going over maximum supply. if (totalSupply == maximumSupply) { revert EthTime__CollectionMintClosed(); } // checks: validate offset _validateTimeOffset(offsetMinutes); // effects: seed history with unique starting value. historyAccumulator[id] = uint160(id >> 4); // effects: increment total supply. totalSupply += 1; // effects: update charity split. _updateBalance(value); // effects: set time offset timeOffsetMinutes[id] = offsetMinutes; // interactions: safe mint _safeMint(to, id); // return value left to be sent back to user. valueLeft = value - price; } function _priceAtSupplyLevel(uint256 supply) internal pure returns (uint256) { uint256 price = supply * PRICE_INCREMENT; if (supply > 50) { price = TARGET_PRICE; } return price; } function _validateBatchMintCount(uint256 count) internal view { // checks: no more than 10. if (count > 10) { revert EthTime__InvalidMintAmount(); } // checks: minting does not push over the limit. // notice that it would fail anyway. if (totalSupply + count > maximumSupply) { revert EthTime__InvalidMintAmount(); } } ////////////////////////////////////////////////////////////////////////// // // // Token URI // // // ////////////////////////////////////////////////////////////////////////// /// @notice Returns the URI with the NFT metadata. /// @dev Returns the base64 encoded metadata inline. /// @param id the NFT unique id function tokenURI(uint256 id) public view override returns (string memory) { if (ownerOf[id] == address(0)) { revert EthTime__DoesNotExist(); } string memory tokenId = Strings.toString(id); (uint256 hour, uint256 minute) = _adjustedHourMinutes(id); bytes memory topHue = _computeHue(historyAccumulator[id], id); bytes memory bottomHue = _computeHue(uint160(ownerOf[id]), id); int128 offset = timeOffsetMinutes[id]; bytes memory offsetSign = offset >= 0 ? bytes('+') : bytes('-'); uint256 offsetUnsigned = offset >= 0 ? uint256(int256(offset)) : uint256(int256(-offset)); return string( bytes.concat( 'data:application/json;base64,', bytes( Base64.encode( bytes.concat( '{"name": "ETH Time #', bytes(tokenId), '", "description": "ETH Time", "image": "data:image/svg+xml;base64,', bytes(_tokenImage(topHue, bottomHue, hour, minute)), '", "attributes": [{"trait_type": "top_color", "value": "hsl(', topHue, ',100%,89%)"},', '{"trait_type": "bottom_color", "value": "hsl(', bottomHue, ',77%,36%)"},', '{"trait_type": "time_offset", "value": "', offsetSign, bytes(Strings.toString(offsetUnsigned)), '"},', '{"trait_type": "time", "value": "', bytes(Strings.toString(hour)), ':', bytes(Strings.toString(minute)), '"}]}' ) ) ) ) ); } /// @dev Generate a preview of the token that will be minted. /// @param to the minter. /// @param id the NFT unique id. function tokenImagePreview(address to, uint256 id) public view returns (string memory) { (uint256 hour, uint256 minute) = _adjustedHourMinutes(id); bytes memory topHue = _computeHue(uint160(id >> 4), id); bytes memory bottomHue = _computeHue(uint160(to), id); return _tokenImage(topHue, bottomHue, hour, minute); } ////////////////////////////////////////////////////////////////////////// // // // Private Functions // // // ////////////////////////////////////////////////////////////////////////// /// @dev Update the NFT history based on the transfer to the given account. /// @param to the address that will receive the nft. /// @param id the NFT unique id. function _updateHistory(address to, uint256 id) internal { // effects: xor existing value with address bytes content. historyAccumulator[id] ^= uint160(to) << 2; } function _transferFrom(address from, address to, uint256 id) internal { // checks: sender and destination require(from == ownerOf[id], "WRONG_FROM"); require(to != address(0), "INVALID_RECIPIENT"); // checks: can transfer require( msg.sender == from || msg.sender == getApproved[id] || isApprovedForAll[from][msg.sender], "NOT_AUTHORIZED" ); // effects: update balance // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. unchecked { balanceOf[from]--; balanceOf[to]++; } // effects: update owership ownerOf[id] = to; // effects: reclaim storage delete getApproved[id]; // effects: update history _updateHistory(to, id); emit Transfer(from, to, id); } bytes constant onColor = "FFF"; bytes constant offColor = "333"; /// @dev Generate the SVG image for the given NFT. function _tokenImage(bytes memory topHue, bytes memory bottomHue, uint256 hour, uint256 minute) internal pure returns (string memory) { return Base64.encode( bytes.concat( '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1000 1000">', '<linearGradient id="bg" gradientTransform="rotate(90)">', '<stop offset="0%" stop-color="hsl(', topHue, ',100%,89%)"/>', '<stop offset="100%" stop-color="hsl(', bottomHue, ',77%,36%)"/>', '</linearGradient>', '<rect x="0" y="0" width="1000" height="1000" fill="url(#bg)"/>', _binaryHour(hour), _binaryMinute(minute), '</svg>' ) ); } function _binaryHour(uint256 hour) internal pure returns (bytes memory) { if (hour > 24) { revert EthTime__NumberOutOfRange(); } bytes[7] memory colors = _binaryColor(hour); return bytes.concat( '<circle cx="665" cy="875" r="25" fill="#', colors[0], '"/>', '<circle cx="665" cy="805" r="25" fill="#', colors[1], '"/>', // skip colors[2] '<circle cx="735" cy="875" r="25" fill="#', colors[3], '"/>', '<circle cx="735" cy="805" r="25" fill="#', colors[4], '"/>', '<circle cx="735" cy="735" r="25" fill="#', colors[5], '"/>', '<circle cx="735" cy="665" r="25" fill="#', colors[6], '"/>' ); } function _binaryMinute(uint256 minute) internal pure returns (bytes memory) { if (minute > 59) { revert EthTime__NumberOutOfRange(); } bytes[7] memory colors = _binaryColor(minute); return bytes.concat( '<circle cx="805" cy="875" r="25" fill="#', colors[0], '"/>', '<circle cx="805" cy="805" r="25" fill="#', colors[1], '"/>', '<circle cx="805" cy="735" r="25" fill="#', colors[2], '"/>', '<circle cx="875" cy="875" r="25" fill="#', colors[3], '"/>', '<circle cx="875" cy="805" r="25" fill="#', colors[4], '"/>', '<circle cx="875" cy="735" r="25" fill="#', colors[5], '"/>', '<circle cx="875" cy="665" r="25" fill="#', colors[6], '"/>' ); } /// @dev Returns the colors to be used to display the time. /// The first 3 bytes are used for the first digit, the remaining 4 bytes /// for the second digit. function _binaryColor(uint256 n) internal pure returns (bytes[7] memory) { unchecked { uint256 firstDigit = n / 10; uint256 secondDigit = n % 10; return [ (firstDigit & 0x1 != 0) ? onColor : offColor, (firstDigit & 0x2 != 0) ? onColor : offColor, (firstDigit & 0x4 != 0) ? onColor : offColor, (secondDigit & 0x1 != 0) ? onColor : offColor, (secondDigit & 0x2 != 0) ? onColor : offColor, (secondDigit & 0x4 != 0) ? onColor : offColor, (secondDigit & 0x8 != 0) ? onColor : offColor ]; } } function _computeHue(uint160 n, uint256 id) internal pure returns (bytes memory) { uint160 t = n ^ uint160(id); uint160 acc = t % 360; return bytes(Strings.toString(acc)); } function _adjustedHourMinutes(uint256 id) internal view returns (uint256 hour, uint256 minute) { int256 signedUserTimestamp = int256(block.timestamp) - 60 * timeOffsetMinutes[id]; uint256 userTimestamp; // this won't realistically ever happen if (signedUserTimestamp <= 0) { userTimestamp = 0; } else { userTimestamp = uint256(signedUserTimestamp); } hour = BokkyPooBahsDateTimeLibrary.getHour(userTimestamp); minute = BokkyPooBahsDateTimeLibrary.getMinute(userTimestamp); } }
/// @notice ETH-Time NFT contract.
NatSpecSingleLine
updateCharity
function updateCharity(address payable charity) public onlyOwner nonReentrant { _updateCharity(charity); }
/// @notice Update the address that receives the charity fee. /// @param charity the new charity address.
NatSpecSingleLine
v0.8.10+commit.fc410830
{ "func_code_index": [ 3351, 3501 ] }
8,653
EthTime
EthTime.sol
0xe339d6f5a42e581dce5a479fca0ed02248a6dca4
Solidity
EthTime
contract EthTime is ERC721, CharitySplitter, Ownable, ReentrancyGuard { ////////////////////////////////////////////////////////////////////////// // // // Constructor // // // ////////////////////////////////////////////////////////////////////////// constructor(address payable charity, uint256 charityFeeBp) ERC721("ETH Time", "ETHT") CharitySplitter(charity, charityFeeBp) { } receive() external payable {} ////////////////////////////////////////////////////////////////////////// // // // Transfer with History // // // ////////////////////////////////////////////////////////////////////////// /// @notice The state of each NFT. mapping(uint256 => uint160) public historyAccumulator; function transferFrom(address from, address to, uint256 id) public nonReentrant override { _transferFrom(from, to, id); } function safeTransferFrom(address from, address to, uint256 id) public nonReentrant override { _transferFrom(from, to, id); // interactions: check destination can handle ERC721 require( to.code.length == 0 || ERC721TokenReceiver(to).onERC721Received(msg.sender, from, id, "") == ERC721TokenReceiver.onERC721Received.selector, "UNSAFE_RECIPIENT" ); } function safeTransferFrom(address from, address to, uint256 id, bytes memory /* data */) public nonReentrant override { _transferFrom(from, to, id); // interactions: check destination can handle ERC721 require( to.code.length == 0 || ERC721TokenReceiver(to).onERC721Received(msg.sender, from, id, "") == ERC721TokenReceiver.onERC721Received.selector, "UNSAFE_RECIPIENT" ); } ////////////////////////////////////////////////////////////////////////// // // // Charity Splitter // // // ////////////////////////////////////////////////////////////////////////// /// @notice Withdraw charity balance to charity address. /// @dev Anyone can call this at any time. function withdrawCharityBalance() public nonReentrant { _withdrawCharityBalance(); } /// @notice Withdraw owner balance to the specified address. /// @param destination the address that receives the owner balance. function withdrawOwnerBalance(address payable destination) public onlyOwner nonReentrant { _withdrawOwnerBalance(destination); } /// @notice Update the address that receives the charity fee. /// @param charity the new charity address. function updateCharity(address payable charity) public onlyOwner nonReentrant { _updateCharity(charity); } ////////////////////////////////////////////////////////////////////////// // // // Timezone Management // // // ////////////////////////////////////////////////////////////////////////// mapping(uint256 => int128) public timeOffsetMinutes; event TimeOffsetUpdated(uint256 indexed id, int128 offsetMinutes); /// @notice Sets the time offset of the given token id. /// @dev Use minutes because some timezones (like IST) are offset by half an hour. /// @param id the NFT unique id. /// @param offsetMinutes the offset in minutes. function setTimeOffsetMinutes(uint256 id, int128 offsetMinutes) public { // checks: id exists if (ownerOf[id] == address(0)) { revert EthTime__DoesNotExist(); } // checks: sender is owner. if (ownerOf[id] != msg.sender) { revert EthTime__NotOwner(); } // checks: validate time offset _validateTimeOffset(offsetMinutes); // effects: update time offset timeOffsetMinutes[id] = offsetMinutes; emit TimeOffsetUpdated(id, offsetMinutes); } function _validateTimeOffset(int128 offsetMinutes) internal { int128 offsetSeconds = offsetMinutes * 60; // checks: offset is [-12, +14] hours UTC if (offsetSeconds > 14 hours || offsetSeconds < -12 hours) { revert EthTime__InvalidTimeOffset(); } } ////////////////////////////////////////////////////////////////////////// // // // Minting // // // ////////////////////////////////////////////////////////////////////////// /// @dev The number of tokens minted. uint256 public totalSupply; /// @dev The maximum number of mintable tokens. uint256 public constant maximumSupply = 100; uint256 private constant TARGET_PRICE = 1 ether; uint256 private constant PRICE_INCREMENT = TARGET_PRICE / maximumSupply * 2; /// @notice Mint a new NFT, transfering ownership to the given account. /// @dev If the token id already exists, this method fails. /// @param to the NFT ower. /// @param offsetMinutes the time offset in minutes. /// @param id the NFT unique id. function mint(address to, int128 offsetMinutes, uint256 id) public payable nonReentrant virtual { // interactions: mint. uint256 valueLeft = _mint(to, offsetMinutes, id, msg.value); // interactions: send back leftover value. if (valueLeft > 0) { (bool success, ) = msg.sender.call{value: valueLeft}(""); require(success); } } /// @notice Mint new NFTs, transfering ownership to the given account. /// @dev If any of the token ids already exists, this method fails. /// @param to the NFT ower. /// @param offsetMinutes the time offset in minutes. /// @param ids the NFT unique ids. function batchMint(address to, int128 offsetMinutes, uint256[] calldata ids) public payable nonReentrant virtual { uint256 count = ids.length; // checks: can mint count nfts _validateBatchMintCount(count); uint256 valueLeft = msg.value; for (uint256 i = 0; i < count; i++) { // interactions: mint. valueLeft = _mint(to, offsetMinutes, ids[i], valueLeft); } // interactions: send back leftover value. if (valueLeft > 0) { (bool success, ) = msg.sender.call{value: valueLeft}(""); require(success); } } /// @notice Get the price for minting the next `count` NFT. function getBatchMintPrice(uint256 count) public view returns (uint256) { // checks: can mint count nfts _validateBatchMintCount(count); uint256 supply = totalSupply; uint256 price = 0; for (uint256 i = 0; i < count; i++) { price += _priceAtSupplyLevel(supply + i); } return price; } /// @notice Get the price for minting the next NFT. function getMintPrice() public view returns (uint256) { return _priceAtSupplyLevel(totalSupply); } function _mint(address to, int128 offsetMinutes, uint256 id, uint256 value) internal returns (uint256 valueLeft) { uint256 price = _priceAtSupplyLevel(totalSupply); // checks: value is enough to mint the nft. if (value < price) { revert EthTime__InvalidMintValue(); } // checks: minting causes going over maximum supply. if (totalSupply == maximumSupply) { revert EthTime__CollectionMintClosed(); } // checks: validate offset _validateTimeOffset(offsetMinutes); // effects: seed history with unique starting value. historyAccumulator[id] = uint160(id >> 4); // effects: increment total supply. totalSupply += 1; // effects: update charity split. _updateBalance(value); // effects: set time offset timeOffsetMinutes[id] = offsetMinutes; // interactions: safe mint _safeMint(to, id); // return value left to be sent back to user. valueLeft = value - price; } function _priceAtSupplyLevel(uint256 supply) internal pure returns (uint256) { uint256 price = supply * PRICE_INCREMENT; if (supply > 50) { price = TARGET_PRICE; } return price; } function _validateBatchMintCount(uint256 count) internal view { // checks: no more than 10. if (count > 10) { revert EthTime__InvalidMintAmount(); } // checks: minting does not push over the limit. // notice that it would fail anyway. if (totalSupply + count > maximumSupply) { revert EthTime__InvalidMintAmount(); } } ////////////////////////////////////////////////////////////////////////// // // // Token URI // // // ////////////////////////////////////////////////////////////////////////// /// @notice Returns the URI with the NFT metadata. /// @dev Returns the base64 encoded metadata inline. /// @param id the NFT unique id function tokenURI(uint256 id) public view override returns (string memory) { if (ownerOf[id] == address(0)) { revert EthTime__DoesNotExist(); } string memory tokenId = Strings.toString(id); (uint256 hour, uint256 minute) = _adjustedHourMinutes(id); bytes memory topHue = _computeHue(historyAccumulator[id], id); bytes memory bottomHue = _computeHue(uint160(ownerOf[id]), id); int128 offset = timeOffsetMinutes[id]; bytes memory offsetSign = offset >= 0 ? bytes('+') : bytes('-'); uint256 offsetUnsigned = offset >= 0 ? uint256(int256(offset)) : uint256(int256(-offset)); return string( bytes.concat( 'data:application/json;base64,', bytes( Base64.encode( bytes.concat( '{"name": "ETH Time #', bytes(tokenId), '", "description": "ETH Time", "image": "data:image/svg+xml;base64,', bytes(_tokenImage(topHue, bottomHue, hour, minute)), '", "attributes": [{"trait_type": "top_color", "value": "hsl(', topHue, ',100%,89%)"},', '{"trait_type": "bottom_color", "value": "hsl(', bottomHue, ',77%,36%)"},', '{"trait_type": "time_offset", "value": "', offsetSign, bytes(Strings.toString(offsetUnsigned)), '"},', '{"trait_type": "time", "value": "', bytes(Strings.toString(hour)), ':', bytes(Strings.toString(minute)), '"}]}' ) ) ) ) ); } /// @dev Generate a preview of the token that will be minted. /// @param to the minter. /// @param id the NFT unique id. function tokenImagePreview(address to, uint256 id) public view returns (string memory) { (uint256 hour, uint256 minute) = _adjustedHourMinutes(id); bytes memory topHue = _computeHue(uint160(id >> 4), id); bytes memory bottomHue = _computeHue(uint160(to), id); return _tokenImage(topHue, bottomHue, hour, minute); } ////////////////////////////////////////////////////////////////////////// // // // Private Functions // // // ////////////////////////////////////////////////////////////////////////// /// @dev Update the NFT history based on the transfer to the given account. /// @param to the address that will receive the nft. /// @param id the NFT unique id. function _updateHistory(address to, uint256 id) internal { // effects: xor existing value with address bytes content. historyAccumulator[id] ^= uint160(to) << 2; } function _transferFrom(address from, address to, uint256 id) internal { // checks: sender and destination require(from == ownerOf[id], "WRONG_FROM"); require(to != address(0), "INVALID_RECIPIENT"); // checks: can transfer require( msg.sender == from || msg.sender == getApproved[id] || isApprovedForAll[from][msg.sender], "NOT_AUTHORIZED" ); // effects: update balance // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. unchecked { balanceOf[from]--; balanceOf[to]++; } // effects: update owership ownerOf[id] = to; // effects: reclaim storage delete getApproved[id]; // effects: update history _updateHistory(to, id); emit Transfer(from, to, id); } bytes constant onColor = "FFF"; bytes constant offColor = "333"; /// @dev Generate the SVG image for the given NFT. function _tokenImage(bytes memory topHue, bytes memory bottomHue, uint256 hour, uint256 minute) internal pure returns (string memory) { return Base64.encode( bytes.concat( '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1000 1000">', '<linearGradient id="bg" gradientTransform="rotate(90)">', '<stop offset="0%" stop-color="hsl(', topHue, ',100%,89%)"/>', '<stop offset="100%" stop-color="hsl(', bottomHue, ',77%,36%)"/>', '</linearGradient>', '<rect x="0" y="0" width="1000" height="1000" fill="url(#bg)"/>', _binaryHour(hour), _binaryMinute(minute), '</svg>' ) ); } function _binaryHour(uint256 hour) internal pure returns (bytes memory) { if (hour > 24) { revert EthTime__NumberOutOfRange(); } bytes[7] memory colors = _binaryColor(hour); return bytes.concat( '<circle cx="665" cy="875" r="25" fill="#', colors[0], '"/>', '<circle cx="665" cy="805" r="25" fill="#', colors[1], '"/>', // skip colors[2] '<circle cx="735" cy="875" r="25" fill="#', colors[3], '"/>', '<circle cx="735" cy="805" r="25" fill="#', colors[4], '"/>', '<circle cx="735" cy="735" r="25" fill="#', colors[5], '"/>', '<circle cx="735" cy="665" r="25" fill="#', colors[6], '"/>' ); } function _binaryMinute(uint256 minute) internal pure returns (bytes memory) { if (minute > 59) { revert EthTime__NumberOutOfRange(); } bytes[7] memory colors = _binaryColor(minute); return bytes.concat( '<circle cx="805" cy="875" r="25" fill="#', colors[0], '"/>', '<circle cx="805" cy="805" r="25" fill="#', colors[1], '"/>', '<circle cx="805" cy="735" r="25" fill="#', colors[2], '"/>', '<circle cx="875" cy="875" r="25" fill="#', colors[3], '"/>', '<circle cx="875" cy="805" r="25" fill="#', colors[4], '"/>', '<circle cx="875" cy="735" r="25" fill="#', colors[5], '"/>', '<circle cx="875" cy="665" r="25" fill="#', colors[6], '"/>' ); } /// @dev Returns the colors to be used to display the time. /// The first 3 bytes are used for the first digit, the remaining 4 bytes /// for the second digit. function _binaryColor(uint256 n) internal pure returns (bytes[7] memory) { unchecked { uint256 firstDigit = n / 10; uint256 secondDigit = n % 10; return [ (firstDigit & 0x1 != 0) ? onColor : offColor, (firstDigit & 0x2 != 0) ? onColor : offColor, (firstDigit & 0x4 != 0) ? onColor : offColor, (secondDigit & 0x1 != 0) ? onColor : offColor, (secondDigit & 0x2 != 0) ? onColor : offColor, (secondDigit & 0x4 != 0) ? onColor : offColor, (secondDigit & 0x8 != 0) ? onColor : offColor ]; } } function _computeHue(uint160 n, uint256 id) internal pure returns (bytes memory) { uint160 t = n ^ uint160(id); uint160 acc = t % 360; return bytes(Strings.toString(acc)); } function _adjustedHourMinutes(uint256 id) internal view returns (uint256 hour, uint256 minute) { int256 signedUserTimestamp = int256(block.timestamp) - 60 * timeOffsetMinutes[id]; uint256 userTimestamp; // this won't realistically ever happen if (signedUserTimestamp <= 0) { userTimestamp = 0; } else { userTimestamp = uint256(signedUserTimestamp); } hour = BokkyPooBahsDateTimeLibrary.getHour(userTimestamp); minute = BokkyPooBahsDateTimeLibrary.getMinute(userTimestamp); } }
/// @notice ETH-Time NFT contract.
NatSpecSingleLine
setTimeOffsetMinutes
function setTimeOffsetMinutes(uint256 id, int128 offsetMinutes) public { // checks: id exists if (ownerOf[id] == address(0)) { revert EthTime__DoesNotExist(); } // checks: sender is owner. if (ownerOf[id] != msg.sender) { revert EthTime__NotOwner(); } // checks: validate time offset _validateTimeOffset(offsetMinutes); // effects: update time offset timeOffsetMinutes[id] = offsetMinutes; emit TimeOffsetUpdated(id, offsetMinutes); }
/// @notice Sets the time offset of the given token id. /// @dev Use minutes because some timezones (like IST) are offset by half an hour. /// @param id the NFT unique id. /// @param offsetMinutes the offset in minutes.
NatSpecSingleLine
v0.8.10+commit.fc410830
{ "func_code_index": [ 4265, 4835 ] }
8,654
EthTime
EthTime.sol
0xe339d6f5a42e581dce5a479fca0ed02248a6dca4
Solidity
EthTime
contract EthTime is ERC721, CharitySplitter, Ownable, ReentrancyGuard { ////////////////////////////////////////////////////////////////////////// // // // Constructor // // // ////////////////////////////////////////////////////////////////////////// constructor(address payable charity, uint256 charityFeeBp) ERC721("ETH Time", "ETHT") CharitySplitter(charity, charityFeeBp) { } receive() external payable {} ////////////////////////////////////////////////////////////////////////// // // // Transfer with History // // // ////////////////////////////////////////////////////////////////////////// /// @notice The state of each NFT. mapping(uint256 => uint160) public historyAccumulator; function transferFrom(address from, address to, uint256 id) public nonReentrant override { _transferFrom(from, to, id); } function safeTransferFrom(address from, address to, uint256 id) public nonReentrant override { _transferFrom(from, to, id); // interactions: check destination can handle ERC721 require( to.code.length == 0 || ERC721TokenReceiver(to).onERC721Received(msg.sender, from, id, "") == ERC721TokenReceiver.onERC721Received.selector, "UNSAFE_RECIPIENT" ); } function safeTransferFrom(address from, address to, uint256 id, bytes memory /* data */) public nonReentrant override { _transferFrom(from, to, id); // interactions: check destination can handle ERC721 require( to.code.length == 0 || ERC721TokenReceiver(to).onERC721Received(msg.sender, from, id, "") == ERC721TokenReceiver.onERC721Received.selector, "UNSAFE_RECIPIENT" ); } ////////////////////////////////////////////////////////////////////////// // // // Charity Splitter // // // ////////////////////////////////////////////////////////////////////////// /// @notice Withdraw charity balance to charity address. /// @dev Anyone can call this at any time. function withdrawCharityBalance() public nonReentrant { _withdrawCharityBalance(); } /// @notice Withdraw owner balance to the specified address. /// @param destination the address that receives the owner balance. function withdrawOwnerBalance(address payable destination) public onlyOwner nonReentrant { _withdrawOwnerBalance(destination); } /// @notice Update the address that receives the charity fee. /// @param charity the new charity address. function updateCharity(address payable charity) public onlyOwner nonReentrant { _updateCharity(charity); } ////////////////////////////////////////////////////////////////////////// // // // Timezone Management // // // ////////////////////////////////////////////////////////////////////////// mapping(uint256 => int128) public timeOffsetMinutes; event TimeOffsetUpdated(uint256 indexed id, int128 offsetMinutes); /// @notice Sets the time offset of the given token id. /// @dev Use minutes because some timezones (like IST) are offset by half an hour. /// @param id the NFT unique id. /// @param offsetMinutes the offset in minutes. function setTimeOffsetMinutes(uint256 id, int128 offsetMinutes) public { // checks: id exists if (ownerOf[id] == address(0)) { revert EthTime__DoesNotExist(); } // checks: sender is owner. if (ownerOf[id] != msg.sender) { revert EthTime__NotOwner(); } // checks: validate time offset _validateTimeOffset(offsetMinutes); // effects: update time offset timeOffsetMinutes[id] = offsetMinutes; emit TimeOffsetUpdated(id, offsetMinutes); } function _validateTimeOffset(int128 offsetMinutes) internal { int128 offsetSeconds = offsetMinutes * 60; // checks: offset is [-12, +14] hours UTC if (offsetSeconds > 14 hours || offsetSeconds < -12 hours) { revert EthTime__InvalidTimeOffset(); } } ////////////////////////////////////////////////////////////////////////// // // // Minting // // // ////////////////////////////////////////////////////////////////////////// /// @dev The number of tokens minted. uint256 public totalSupply; /// @dev The maximum number of mintable tokens. uint256 public constant maximumSupply = 100; uint256 private constant TARGET_PRICE = 1 ether; uint256 private constant PRICE_INCREMENT = TARGET_PRICE / maximumSupply * 2; /// @notice Mint a new NFT, transfering ownership to the given account. /// @dev If the token id already exists, this method fails. /// @param to the NFT ower. /// @param offsetMinutes the time offset in minutes. /// @param id the NFT unique id. function mint(address to, int128 offsetMinutes, uint256 id) public payable nonReentrant virtual { // interactions: mint. uint256 valueLeft = _mint(to, offsetMinutes, id, msg.value); // interactions: send back leftover value. if (valueLeft > 0) { (bool success, ) = msg.sender.call{value: valueLeft}(""); require(success); } } /// @notice Mint new NFTs, transfering ownership to the given account. /// @dev If any of the token ids already exists, this method fails. /// @param to the NFT ower. /// @param offsetMinutes the time offset in minutes. /// @param ids the NFT unique ids. function batchMint(address to, int128 offsetMinutes, uint256[] calldata ids) public payable nonReentrant virtual { uint256 count = ids.length; // checks: can mint count nfts _validateBatchMintCount(count); uint256 valueLeft = msg.value; for (uint256 i = 0; i < count; i++) { // interactions: mint. valueLeft = _mint(to, offsetMinutes, ids[i], valueLeft); } // interactions: send back leftover value. if (valueLeft > 0) { (bool success, ) = msg.sender.call{value: valueLeft}(""); require(success); } } /// @notice Get the price for minting the next `count` NFT. function getBatchMintPrice(uint256 count) public view returns (uint256) { // checks: can mint count nfts _validateBatchMintCount(count); uint256 supply = totalSupply; uint256 price = 0; for (uint256 i = 0; i < count; i++) { price += _priceAtSupplyLevel(supply + i); } return price; } /// @notice Get the price for minting the next NFT. function getMintPrice() public view returns (uint256) { return _priceAtSupplyLevel(totalSupply); } function _mint(address to, int128 offsetMinutes, uint256 id, uint256 value) internal returns (uint256 valueLeft) { uint256 price = _priceAtSupplyLevel(totalSupply); // checks: value is enough to mint the nft. if (value < price) { revert EthTime__InvalidMintValue(); } // checks: minting causes going over maximum supply. if (totalSupply == maximumSupply) { revert EthTime__CollectionMintClosed(); } // checks: validate offset _validateTimeOffset(offsetMinutes); // effects: seed history with unique starting value. historyAccumulator[id] = uint160(id >> 4); // effects: increment total supply. totalSupply += 1; // effects: update charity split. _updateBalance(value); // effects: set time offset timeOffsetMinutes[id] = offsetMinutes; // interactions: safe mint _safeMint(to, id); // return value left to be sent back to user. valueLeft = value - price; } function _priceAtSupplyLevel(uint256 supply) internal pure returns (uint256) { uint256 price = supply * PRICE_INCREMENT; if (supply > 50) { price = TARGET_PRICE; } return price; } function _validateBatchMintCount(uint256 count) internal view { // checks: no more than 10. if (count > 10) { revert EthTime__InvalidMintAmount(); } // checks: minting does not push over the limit. // notice that it would fail anyway. if (totalSupply + count > maximumSupply) { revert EthTime__InvalidMintAmount(); } } ////////////////////////////////////////////////////////////////////////// // // // Token URI // // // ////////////////////////////////////////////////////////////////////////// /// @notice Returns the URI with the NFT metadata. /// @dev Returns the base64 encoded metadata inline. /// @param id the NFT unique id function tokenURI(uint256 id) public view override returns (string memory) { if (ownerOf[id] == address(0)) { revert EthTime__DoesNotExist(); } string memory tokenId = Strings.toString(id); (uint256 hour, uint256 minute) = _adjustedHourMinutes(id); bytes memory topHue = _computeHue(historyAccumulator[id], id); bytes memory bottomHue = _computeHue(uint160(ownerOf[id]), id); int128 offset = timeOffsetMinutes[id]; bytes memory offsetSign = offset >= 0 ? bytes('+') : bytes('-'); uint256 offsetUnsigned = offset >= 0 ? uint256(int256(offset)) : uint256(int256(-offset)); return string( bytes.concat( 'data:application/json;base64,', bytes( Base64.encode( bytes.concat( '{"name": "ETH Time #', bytes(tokenId), '", "description": "ETH Time", "image": "data:image/svg+xml;base64,', bytes(_tokenImage(topHue, bottomHue, hour, minute)), '", "attributes": [{"trait_type": "top_color", "value": "hsl(', topHue, ',100%,89%)"},', '{"trait_type": "bottom_color", "value": "hsl(', bottomHue, ',77%,36%)"},', '{"trait_type": "time_offset", "value": "', offsetSign, bytes(Strings.toString(offsetUnsigned)), '"},', '{"trait_type": "time", "value": "', bytes(Strings.toString(hour)), ':', bytes(Strings.toString(minute)), '"}]}' ) ) ) ) ); } /// @dev Generate a preview of the token that will be minted. /// @param to the minter. /// @param id the NFT unique id. function tokenImagePreview(address to, uint256 id) public view returns (string memory) { (uint256 hour, uint256 minute) = _adjustedHourMinutes(id); bytes memory topHue = _computeHue(uint160(id >> 4), id); bytes memory bottomHue = _computeHue(uint160(to), id); return _tokenImage(topHue, bottomHue, hour, minute); } ////////////////////////////////////////////////////////////////////////// // // // Private Functions // // // ////////////////////////////////////////////////////////////////////////// /// @dev Update the NFT history based on the transfer to the given account. /// @param to the address that will receive the nft. /// @param id the NFT unique id. function _updateHistory(address to, uint256 id) internal { // effects: xor existing value with address bytes content. historyAccumulator[id] ^= uint160(to) << 2; } function _transferFrom(address from, address to, uint256 id) internal { // checks: sender and destination require(from == ownerOf[id], "WRONG_FROM"); require(to != address(0), "INVALID_RECIPIENT"); // checks: can transfer require( msg.sender == from || msg.sender == getApproved[id] || isApprovedForAll[from][msg.sender], "NOT_AUTHORIZED" ); // effects: update balance // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. unchecked { balanceOf[from]--; balanceOf[to]++; } // effects: update owership ownerOf[id] = to; // effects: reclaim storage delete getApproved[id]; // effects: update history _updateHistory(to, id); emit Transfer(from, to, id); } bytes constant onColor = "FFF"; bytes constant offColor = "333"; /// @dev Generate the SVG image for the given NFT. function _tokenImage(bytes memory topHue, bytes memory bottomHue, uint256 hour, uint256 minute) internal pure returns (string memory) { return Base64.encode( bytes.concat( '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1000 1000">', '<linearGradient id="bg" gradientTransform="rotate(90)">', '<stop offset="0%" stop-color="hsl(', topHue, ',100%,89%)"/>', '<stop offset="100%" stop-color="hsl(', bottomHue, ',77%,36%)"/>', '</linearGradient>', '<rect x="0" y="0" width="1000" height="1000" fill="url(#bg)"/>', _binaryHour(hour), _binaryMinute(minute), '</svg>' ) ); } function _binaryHour(uint256 hour) internal pure returns (bytes memory) { if (hour > 24) { revert EthTime__NumberOutOfRange(); } bytes[7] memory colors = _binaryColor(hour); return bytes.concat( '<circle cx="665" cy="875" r="25" fill="#', colors[0], '"/>', '<circle cx="665" cy="805" r="25" fill="#', colors[1], '"/>', // skip colors[2] '<circle cx="735" cy="875" r="25" fill="#', colors[3], '"/>', '<circle cx="735" cy="805" r="25" fill="#', colors[4], '"/>', '<circle cx="735" cy="735" r="25" fill="#', colors[5], '"/>', '<circle cx="735" cy="665" r="25" fill="#', colors[6], '"/>' ); } function _binaryMinute(uint256 minute) internal pure returns (bytes memory) { if (minute > 59) { revert EthTime__NumberOutOfRange(); } bytes[7] memory colors = _binaryColor(minute); return bytes.concat( '<circle cx="805" cy="875" r="25" fill="#', colors[0], '"/>', '<circle cx="805" cy="805" r="25" fill="#', colors[1], '"/>', '<circle cx="805" cy="735" r="25" fill="#', colors[2], '"/>', '<circle cx="875" cy="875" r="25" fill="#', colors[3], '"/>', '<circle cx="875" cy="805" r="25" fill="#', colors[4], '"/>', '<circle cx="875" cy="735" r="25" fill="#', colors[5], '"/>', '<circle cx="875" cy="665" r="25" fill="#', colors[6], '"/>' ); } /// @dev Returns the colors to be used to display the time. /// The first 3 bytes are used for the first digit, the remaining 4 bytes /// for the second digit. function _binaryColor(uint256 n) internal pure returns (bytes[7] memory) { unchecked { uint256 firstDigit = n / 10; uint256 secondDigit = n % 10; return [ (firstDigit & 0x1 != 0) ? onColor : offColor, (firstDigit & 0x2 != 0) ? onColor : offColor, (firstDigit & 0x4 != 0) ? onColor : offColor, (secondDigit & 0x1 != 0) ? onColor : offColor, (secondDigit & 0x2 != 0) ? onColor : offColor, (secondDigit & 0x4 != 0) ? onColor : offColor, (secondDigit & 0x8 != 0) ? onColor : offColor ]; } } function _computeHue(uint160 n, uint256 id) internal pure returns (bytes memory) { uint160 t = n ^ uint160(id); uint160 acc = t % 360; return bytes(Strings.toString(acc)); } function _adjustedHourMinutes(uint256 id) internal view returns (uint256 hour, uint256 minute) { int256 signedUserTimestamp = int256(block.timestamp) - 60 * timeOffsetMinutes[id]; uint256 userTimestamp; // this won't realistically ever happen if (signedUserTimestamp <= 0) { userTimestamp = 0; } else { userTimestamp = uint256(signedUserTimestamp); } hour = BokkyPooBahsDateTimeLibrary.getHour(userTimestamp); minute = BokkyPooBahsDateTimeLibrary.getMinute(userTimestamp); } }
/// @notice ETH-Time NFT contract.
NatSpecSingleLine
mint
function mint(address to, int128 offsetMinutes, uint256 id) public payable nonReentrant virtual { // interactions: mint. uint256 valueLeft = _mint(to, offsetMinutes, id, msg.value); // interactions: send back leftover value. if (valueLeft > 0) { (bool success, ) = msg.sender.call{value: valueLeft}(""); require(success); } }
/// @notice Mint a new NFT, transfering ownership to the given account. /// @dev If the token id already exists, this method fails. /// @param to the NFT ower. /// @param offsetMinutes the time offset in minutes. /// @param id the NFT unique id.
NatSpecSingleLine
v0.8.10+commit.fc410830
{ "func_code_index": [ 6127, 6565 ] }
8,655
EthTime
EthTime.sol
0xe339d6f5a42e581dce5a479fca0ed02248a6dca4
Solidity
EthTime
contract EthTime is ERC721, CharitySplitter, Ownable, ReentrancyGuard { ////////////////////////////////////////////////////////////////////////// // // // Constructor // // // ////////////////////////////////////////////////////////////////////////// constructor(address payable charity, uint256 charityFeeBp) ERC721("ETH Time", "ETHT") CharitySplitter(charity, charityFeeBp) { } receive() external payable {} ////////////////////////////////////////////////////////////////////////// // // // Transfer with History // // // ////////////////////////////////////////////////////////////////////////// /// @notice The state of each NFT. mapping(uint256 => uint160) public historyAccumulator; function transferFrom(address from, address to, uint256 id) public nonReentrant override { _transferFrom(from, to, id); } function safeTransferFrom(address from, address to, uint256 id) public nonReentrant override { _transferFrom(from, to, id); // interactions: check destination can handle ERC721 require( to.code.length == 0 || ERC721TokenReceiver(to).onERC721Received(msg.sender, from, id, "") == ERC721TokenReceiver.onERC721Received.selector, "UNSAFE_RECIPIENT" ); } function safeTransferFrom(address from, address to, uint256 id, bytes memory /* data */) public nonReentrant override { _transferFrom(from, to, id); // interactions: check destination can handle ERC721 require( to.code.length == 0 || ERC721TokenReceiver(to).onERC721Received(msg.sender, from, id, "") == ERC721TokenReceiver.onERC721Received.selector, "UNSAFE_RECIPIENT" ); } ////////////////////////////////////////////////////////////////////////// // // // Charity Splitter // // // ////////////////////////////////////////////////////////////////////////// /// @notice Withdraw charity balance to charity address. /// @dev Anyone can call this at any time. function withdrawCharityBalance() public nonReentrant { _withdrawCharityBalance(); } /// @notice Withdraw owner balance to the specified address. /// @param destination the address that receives the owner balance. function withdrawOwnerBalance(address payable destination) public onlyOwner nonReentrant { _withdrawOwnerBalance(destination); } /// @notice Update the address that receives the charity fee. /// @param charity the new charity address. function updateCharity(address payable charity) public onlyOwner nonReentrant { _updateCharity(charity); } ////////////////////////////////////////////////////////////////////////// // // // Timezone Management // // // ////////////////////////////////////////////////////////////////////////// mapping(uint256 => int128) public timeOffsetMinutes; event TimeOffsetUpdated(uint256 indexed id, int128 offsetMinutes); /// @notice Sets the time offset of the given token id. /// @dev Use minutes because some timezones (like IST) are offset by half an hour. /// @param id the NFT unique id. /// @param offsetMinutes the offset in minutes. function setTimeOffsetMinutes(uint256 id, int128 offsetMinutes) public { // checks: id exists if (ownerOf[id] == address(0)) { revert EthTime__DoesNotExist(); } // checks: sender is owner. if (ownerOf[id] != msg.sender) { revert EthTime__NotOwner(); } // checks: validate time offset _validateTimeOffset(offsetMinutes); // effects: update time offset timeOffsetMinutes[id] = offsetMinutes; emit TimeOffsetUpdated(id, offsetMinutes); } function _validateTimeOffset(int128 offsetMinutes) internal { int128 offsetSeconds = offsetMinutes * 60; // checks: offset is [-12, +14] hours UTC if (offsetSeconds > 14 hours || offsetSeconds < -12 hours) { revert EthTime__InvalidTimeOffset(); } } ////////////////////////////////////////////////////////////////////////// // // // Minting // // // ////////////////////////////////////////////////////////////////////////// /// @dev The number of tokens minted. uint256 public totalSupply; /// @dev The maximum number of mintable tokens. uint256 public constant maximumSupply = 100; uint256 private constant TARGET_PRICE = 1 ether; uint256 private constant PRICE_INCREMENT = TARGET_PRICE / maximumSupply * 2; /// @notice Mint a new NFT, transfering ownership to the given account. /// @dev If the token id already exists, this method fails. /// @param to the NFT ower. /// @param offsetMinutes the time offset in minutes. /// @param id the NFT unique id. function mint(address to, int128 offsetMinutes, uint256 id) public payable nonReentrant virtual { // interactions: mint. uint256 valueLeft = _mint(to, offsetMinutes, id, msg.value); // interactions: send back leftover value. if (valueLeft > 0) { (bool success, ) = msg.sender.call{value: valueLeft}(""); require(success); } } /// @notice Mint new NFTs, transfering ownership to the given account. /// @dev If any of the token ids already exists, this method fails. /// @param to the NFT ower. /// @param offsetMinutes the time offset in minutes. /// @param ids the NFT unique ids. function batchMint(address to, int128 offsetMinutes, uint256[] calldata ids) public payable nonReentrant virtual { uint256 count = ids.length; // checks: can mint count nfts _validateBatchMintCount(count); uint256 valueLeft = msg.value; for (uint256 i = 0; i < count; i++) { // interactions: mint. valueLeft = _mint(to, offsetMinutes, ids[i], valueLeft); } // interactions: send back leftover value. if (valueLeft > 0) { (bool success, ) = msg.sender.call{value: valueLeft}(""); require(success); } } /// @notice Get the price for minting the next `count` NFT. function getBatchMintPrice(uint256 count) public view returns (uint256) { // checks: can mint count nfts _validateBatchMintCount(count); uint256 supply = totalSupply; uint256 price = 0; for (uint256 i = 0; i < count; i++) { price += _priceAtSupplyLevel(supply + i); } return price; } /// @notice Get the price for minting the next NFT. function getMintPrice() public view returns (uint256) { return _priceAtSupplyLevel(totalSupply); } function _mint(address to, int128 offsetMinutes, uint256 id, uint256 value) internal returns (uint256 valueLeft) { uint256 price = _priceAtSupplyLevel(totalSupply); // checks: value is enough to mint the nft. if (value < price) { revert EthTime__InvalidMintValue(); } // checks: minting causes going over maximum supply. if (totalSupply == maximumSupply) { revert EthTime__CollectionMintClosed(); } // checks: validate offset _validateTimeOffset(offsetMinutes); // effects: seed history with unique starting value. historyAccumulator[id] = uint160(id >> 4); // effects: increment total supply. totalSupply += 1; // effects: update charity split. _updateBalance(value); // effects: set time offset timeOffsetMinutes[id] = offsetMinutes; // interactions: safe mint _safeMint(to, id); // return value left to be sent back to user. valueLeft = value - price; } function _priceAtSupplyLevel(uint256 supply) internal pure returns (uint256) { uint256 price = supply * PRICE_INCREMENT; if (supply > 50) { price = TARGET_PRICE; } return price; } function _validateBatchMintCount(uint256 count) internal view { // checks: no more than 10. if (count > 10) { revert EthTime__InvalidMintAmount(); } // checks: minting does not push over the limit. // notice that it would fail anyway. if (totalSupply + count > maximumSupply) { revert EthTime__InvalidMintAmount(); } } ////////////////////////////////////////////////////////////////////////// // // // Token URI // // // ////////////////////////////////////////////////////////////////////////// /// @notice Returns the URI with the NFT metadata. /// @dev Returns the base64 encoded metadata inline. /// @param id the NFT unique id function tokenURI(uint256 id) public view override returns (string memory) { if (ownerOf[id] == address(0)) { revert EthTime__DoesNotExist(); } string memory tokenId = Strings.toString(id); (uint256 hour, uint256 minute) = _adjustedHourMinutes(id); bytes memory topHue = _computeHue(historyAccumulator[id], id); bytes memory bottomHue = _computeHue(uint160(ownerOf[id]), id); int128 offset = timeOffsetMinutes[id]; bytes memory offsetSign = offset >= 0 ? bytes('+') : bytes('-'); uint256 offsetUnsigned = offset >= 0 ? uint256(int256(offset)) : uint256(int256(-offset)); return string( bytes.concat( 'data:application/json;base64,', bytes( Base64.encode( bytes.concat( '{"name": "ETH Time #', bytes(tokenId), '", "description": "ETH Time", "image": "data:image/svg+xml;base64,', bytes(_tokenImage(topHue, bottomHue, hour, minute)), '", "attributes": [{"trait_type": "top_color", "value": "hsl(', topHue, ',100%,89%)"},', '{"trait_type": "bottom_color", "value": "hsl(', bottomHue, ',77%,36%)"},', '{"trait_type": "time_offset", "value": "', offsetSign, bytes(Strings.toString(offsetUnsigned)), '"},', '{"trait_type": "time", "value": "', bytes(Strings.toString(hour)), ':', bytes(Strings.toString(minute)), '"}]}' ) ) ) ) ); } /// @dev Generate a preview of the token that will be minted. /// @param to the minter. /// @param id the NFT unique id. function tokenImagePreview(address to, uint256 id) public view returns (string memory) { (uint256 hour, uint256 minute) = _adjustedHourMinutes(id); bytes memory topHue = _computeHue(uint160(id >> 4), id); bytes memory bottomHue = _computeHue(uint160(to), id); return _tokenImage(topHue, bottomHue, hour, minute); } ////////////////////////////////////////////////////////////////////////// // // // Private Functions // // // ////////////////////////////////////////////////////////////////////////// /// @dev Update the NFT history based on the transfer to the given account. /// @param to the address that will receive the nft. /// @param id the NFT unique id. function _updateHistory(address to, uint256 id) internal { // effects: xor existing value with address bytes content. historyAccumulator[id] ^= uint160(to) << 2; } function _transferFrom(address from, address to, uint256 id) internal { // checks: sender and destination require(from == ownerOf[id], "WRONG_FROM"); require(to != address(0), "INVALID_RECIPIENT"); // checks: can transfer require( msg.sender == from || msg.sender == getApproved[id] || isApprovedForAll[from][msg.sender], "NOT_AUTHORIZED" ); // effects: update balance // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. unchecked { balanceOf[from]--; balanceOf[to]++; } // effects: update owership ownerOf[id] = to; // effects: reclaim storage delete getApproved[id]; // effects: update history _updateHistory(to, id); emit Transfer(from, to, id); } bytes constant onColor = "FFF"; bytes constant offColor = "333"; /// @dev Generate the SVG image for the given NFT. function _tokenImage(bytes memory topHue, bytes memory bottomHue, uint256 hour, uint256 minute) internal pure returns (string memory) { return Base64.encode( bytes.concat( '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1000 1000">', '<linearGradient id="bg" gradientTransform="rotate(90)">', '<stop offset="0%" stop-color="hsl(', topHue, ',100%,89%)"/>', '<stop offset="100%" stop-color="hsl(', bottomHue, ',77%,36%)"/>', '</linearGradient>', '<rect x="0" y="0" width="1000" height="1000" fill="url(#bg)"/>', _binaryHour(hour), _binaryMinute(minute), '</svg>' ) ); } function _binaryHour(uint256 hour) internal pure returns (bytes memory) { if (hour > 24) { revert EthTime__NumberOutOfRange(); } bytes[7] memory colors = _binaryColor(hour); return bytes.concat( '<circle cx="665" cy="875" r="25" fill="#', colors[0], '"/>', '<circle cx="665" cy="805" r="25" fill="#', colors[1], '"/>', // skip colors[2] '<circle cx="735" cy="875" r="25" fill="#', colors[3], '"/>', '<circle cx="735" cy="805" r="25" fill="#', colors[4], '"/>', '<circle cx="735" cy="735" r="25" fill="#', colors[5], '"/>', '<circle cx="735" cy="665" r="25" fill="#', colors[6], '"/>' ); } function _binaryMinute(uint256 minute) internal pure returns (bytes memory) { if (minute > 59) { revert EthTime__NumberOutOfRange(); } bytes[7] memory colors = _binaryColor(minute); return bytes.concat( '<circle cx="805" cy="875" r="25" fill="#', colors[0], '"/>', '<circle cx="805" cy="805" r="25" fill="#', colors[1], '"/>', '<circle cx="805" cy="735" r="25" fill="#', colors[2], '"/>', '<circle cx="875" cy="875" r="25" fill="#', colors[3], '"/>', '<circle cx="875" cy="805" r="25" fill="#', colors[4], '"/>', '<circle cx="875" cy="735" r="25" fill="#', colors[5], '"/>', '<circle cx="875" cy="665" r="25" fill="#', colors[6], '"/>' ); } /// @dev Returns the colors to be used to display the time. /// The first 3 bytes are used for the first digit, the remaining 4 bytes /// for the second digit. function _binaryColor(uint256 n) internal pure returns (bytes[7] memory) { unchecked { uint256 firstDigit = n / 10; uint256 secondDigit = n % 10; return [ (firstDigit & 0x1 != 0) ? onColor : offColor, (firstDigit & 0x2 != 0) ? onColor : offColor, (firstDigit & 0x4 != 0) ? onColor : offColor, (secondDigit & 0x1 != 0) ? onColor : offColor, (secondDigit & 0x2 != 0) ? onColor : offColor, (secondDigit & 0x4 != 0) ? onColor : offColor, (secondDigit & 0x8 != 0) ? onColor : offColor ]; } } function _computeHue(uint160 n, uint256 id) internal pure returns (bytes memory) { uint160 t = n ^ uint160(id); uint160 acc = t % 360; return bytes(Strings.toString(acc)); } function _adjustedHourMinutes(uint256 id) internal view returns (uint256 hour, uint256 minute) { int256 signedUserTimestamp = int256(block.timestamp) - 60 * timeOffsetMinutes[id]; uint256 userTimestamp; // this won't realistically ever happen if (signedUserTimestamp <= 0) { userTimestamp = 0; } else { userTimestamp = uint256(signedUserTimestamp); } hour = BokkyPooBahsDateTimeLibrary.getHour(userTimestamp); minute = BokkyPooBahsDateTimeLibrary.getMinute(userTimestamp); } }
/// @notice ETH-Time NFT contract.
NatSpecSingleLine
batchMint
function batchMint(address to, int128 offsetMinutes, uint256[] calldata ids) public payable nonReentrant virtual { uint256 count = ids.length; // checks: can mint count nfts _validateBatchMintCount(count); uint256 valueLeft = msg.value; for (uint256 i = 0; i < count; i++) { // interactions: mint. valueLeft = _mint(to, offsetMinutes, ids[i], valueLeft); } // interactions: send back leftover value. if (valueLeft > 0) { (bool success, ) = msg.sender.call{value: valueLeft}(""); require(success); } }
/// @notice Mint new NFTs, transfering ownership to the given account. /// @dev If any of the token ids already exists, this method fails. /// @param to the NFT ower. /// @param offsetMinutes the time offset in minutes. /// @param ids the NFT unique ids.
NatSpecSingleLine
v0.8.10+commit.fc410830
{ "func_code_index": [ 6842, 7509 ] }
8,656
EthTime
EthTime.sol
0xe339d6f5a42e581dce5a479fca0ed02248a6dca4
Solidity
EthTime
contract EthTime is ERC721, CharitySplitter, Ownable, ReentrancyGuard { ////////////////////////////////////////////////////////////////////////// // // // Constructor // // // ////////////////////////////////////////////////////////////////////////// constructor(address payable charity, uint256 charityFeeBp) ERC721("ETH Time", "ETHT") CharitySplitter(charity, charityFeeBp) { } receive() external payable {} ////////////////////////////////////////////////////////////////////////// // // // Transfer with History // // // ////////////////////////////////////////////////////////////////////////// /// @notice The state of each NFT. mapping(uint256 => uint160) public historyAccumulator; function transferFrom(address from, address to, uint256 id) public nonReentrant override { _transferFrom(from, to, id); } function safeTransferFrom(address from, address to, uint256 id) public nonReentrant override { _transferFrom(from, to, id); // interactions: check destination can handle ERC721 require( to.code.length == 0 || ERC721TokenReceiver(to).onERC721Received(msg.sender, from, id, "") == ERC721TokenReceiver.onERC721Received.selector, "UNSAFE_RECIPIENT" ); } function safeTransferFrom(address from, address to, uint256 id, bytes memory /* data */) public nonReentrant override { _transferFrom(from, to, id); // interactions: check destination can handle ERC721 require( to.code.length == 0 || ERC721TokenReceiver(to).onERC721Received(msg.sender, from, id, "") == ERC721TokenReceiver.onERC721Received.selector, "UNSAFE_RECIPIENT" ); } ////////////////////////////////////////////////////////////////////////// // // // Charity Splitter // // // ////////////////////////////////////////////////////////////////////////// /// @notice Withdraw charity balance to charity address. /// @dev Anyone can call this at any time. function withdrawCharityBalance() public nonReentrant { _withdrawCharityBalance(); } /// @notice Withdraw owner balance to the specified address. /// @param destination the address that receives the owner balance. function withdrawOwnerBalance(address payable destination) public onlyOwner nonReentrant { _withdrawOwnerBalance(destination); } /// @notice Update the address that receives the charity fee. /// @param charity the new charity address. function updateCharity(address payable charity) public onlyOwner nonReentrant { _updateCharity(charity); } ////////////////////////////////////////////////////////////////////////// // // // Timezone Management // // // ////////////////////////////////////////////////////////////////////////// mapping(uint256 => int128) public timeOffsetMinutes; event TimeOffsetUpdated(uint256 indexed id, int128 offsetMinutes); /// @notice Sets the time offset of the given token id. /// @dev Use minutes because some timezones (like IST) are offset by half an hour. /// @param id the NFT unique id. /// @param offsetMinutes the offset in minutes. function setTimeOffsetMinutes(uint256 id, int128 offsetMinutes) public { // checks: id exists if (ownerOf[id] == address(0)) { revert EthTime__DoesNotExist(); } // checks: sender is owner. if (ownerOf[id] != msg.sender) { revert EthTime__NotOwner(); } // checks: validate time offset _validateTimeOffset(offsetMinutes); // effects: update time offset timeOffsetMinutes[id] = offsetMinutes; emit TimeOffsetUpdated(id, offsetMinutes); } function _validateTimeOffset(int128 offsetMinutes) internal { int128 offsetSeconds = offsetMinutes * 60; // checks: offset is [-12, +14] hours UTC if (offsetSeconds > 14 hours || offsetSeconds < -12 hours) { revert EthTime__InvalidTimeOffset(); } } ////////////////////////////////////////////////////////////////////////// // // // Minting // // // ////////////////////////////////////////////////////////////////////////// /// @dev The number of tokens minted. uint256 public totalSupply; /// @dev The maximum number of mintable tokens. uint256 public constant maximumSupply = 100; uint256 private constant TARGET_PRICE = 1 ether; uint256 private constant PRICE_INCREMENT = TARGET_PRICE / maximumSupply * 2; /// @notice Mint a new NFT, transfering ownership to the given account. /// @dev If the token id already exists, this method fails. /// @param to the NFT ower. /// @param offsetMinutes the time offset in minutes. /// @param id the NFT unique id. function mint(address to, int128 offsetMinutes, uint256 id) public payable nonReentrant virtual { // interactions: mint. uint256 valueLeft = _mint(to, offsetMinutes, id, msg.value); // interactions: send back leftover value. if (valueLeft > 0) { (bool success, ) = msg.sender.call{value: valueLeft}(""); require(success); } } /// @notice Mint new NFTs, transfering ownership to the given account. /// @dev If any of the token ids already exists, this method fails. /// @param to the NFT ower. /// @param offsetMinutes the time offset in minutes. /// @param ids the NFT unique ids. function batchMint(address to, int128 offsetMinutes, uint256[] calldata ids) public payable nonReentrant virtual { uint256 count = ids.length; // checks: can mint count nfts _validateBatchMintCount(count); uint256 valueLeft = msg.value; for (uint256 i = 0; i < count; i++) { // interactions: mint. valueLeft = _mint(to, offsetMinutes, ids[i], valueLeft); } // interactions: send back leftover value. if (valueLeft > 0) { (bool success, ) = msg.sender.call{value: valueLeft}(""); require(success); } } /// @notice Get the price for minting the next `count` NFT. function getBatchMintPrice(uint256 count) public view returns (uint256) { // checks: can mint count nfts _validateBatchMintCount(count); uint256 supply = totalSupply; uint256 price = 0; for (uint256 i = 0; i < count; i++) { price += _priceAtSupplyLevel(supply + i); } return price; } /// @notice Get the price for minting the next NFT. function getMintPrice() public view returns (uint256) { return _priceAtSupplyLevel(totalSupply); } function _mint(address to, int128 offsetMinutes, uint256 id, uint256 value) internal returns (uint256 valueLeft) { uint256 price = _priceAtSupplyLevel(totalSupply); // checks: value is enough to mint the nft. if (value < price) { revert EthTime__InvalidMintValue(); } // checks: minting causes going over maximum supply. if (totalSupply == maximumSupply) { revert EthTime__CollectionMintClosed(); } // checks: validate offset _validateTimeOffset(offsetMinutes); // effects: seed history with unique starting value. historyAccumulator[id] = uint160(id >> 4); // effects: increment total supply. totalSupply += 1; // effects: update charity split. _updateBalance(value); // effects: set time offset timeOffsetMinutes[id] = offsetMinutes; // interactions: safe mint _safeMint(to, id); // return value left to be sent back to user. valueLeft = value - price; } function _priceAtSupplyLevel(uint256 supply) internal pure returns (uint256) { uint256 price = supply * PRICE_INCREMENT; if (supply > 50) { price = TARGET_PRICE; } return price; } function _validateBatchMintCount(uint256 count) internal view { // checks: no more than 10. if (count > 10) { revert EthTime__InvalidMintAmount(); } // checks: minting does not push over the limit. // notice that it would fail anyway. if (totalSupply + count > maximumSupply) { revert EthTime__InvalidMintAmount(); } } ////////////////////////////////////////////////////////////////////////// // // // Token URI // // // ////////////////////////////////////////////////////////////////////////// /// @notice Returns the URI with the NFT metadata. /// @dev Returns the base64 encoded metadata inline. /// @param id the NFT unique id function tokenURI(uint256 id) public view override returns (string memory) { if (ownerOf[id] == address(0)) { revert EthTime__DoesNotExist(); } string memory tokenId = Strings.toString(id); (uint256 hour, uint256 minute) = _adjustedHourMinutes(id); bytes memory topHue = _computeHue(historyAccumulator[id], id); bytes memory bottomHue = _computeHue(uint160(ownerOf[id]), id); int128 offset = timeOffsetMinutes[id]; bytes memory offsetSign = offset >= 0 ? bytes('+') : bytes('-'); uint256 offsetUnsigned = offset >= 0 ? uint256(int256(offset)) : uint256(int256(-offset)); return string( bytes.concat( 'data:application/json;base64,', bytes( Base64.encode( bytes.concat( '{"name": "ETH Time #', bytes(tokenId), '", "description": "ETH Time", "image": "data:image/svg+xml;base64,', bytes(_tokenImage(topHue, bottomHue, hour, minute)), '", "attributes": [{"trait_type": "top_color", "value": "hsl(', topHue, ',100%,89%)"},', '{"trait_type": "bottom_color", "value": "hsl(', bottomHue, ',77%,36%)"},', '{"trait_type": "time_offset", "value": "', offsetSign, bytes(Strings.toString(offsetUnsigned)), '"},', '{"trait_type": "time", "value": "', bytes(Strings.toString(hour)), ':', bytes(Strings.toString(minute)), '"}]}' ) ) ) ) ); } /// @dev Generate a preview of the token that will be minted. /// @param to the minter. /// @param id the NFT unique id. function tokenImagePreview(address to, uint256 id) public view returns (string memory) { (uint256 hour, uint256 minute) = _adjustedHourMinutes(id); bytes memory topHue = _computeHue(uint160(id >> 4), id); bytes memory bottomHue = _computeHue(uint160(to), id); return _tokenImage(topHue, bottomHue, hour, minute); } ////////////////////////////////////////////////////////////////////////// // // // Private Functions // // // ////////////////////////////////////////////////////////////////////////// /// @dev Update the NFT history based on the transfer to the given account. /// @param to the address that will receive the nft. /// @param id the NFT unique id. function _updateHistory(address to, uint256 id) internal { // effects: xor existing value with address bytes content. historyAccumulator[id] ^= uint160(to) << 2; } function _transferFrom(address from, address to, uint256 id) internal { // checks: sender and destination require(from == ownerOf[id], "WRONG_FROM"); require(to != address(0), "INVALID_RECIPIENT"); // checks: can transfer require( msg.sender == from || msg.sender == getApproved[id] || isApprovedForAll[from][msg.sender], "NOT_AUTHORIZED" ); // effects: update balance // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. unchecked { balanceOf[from]--; balanceOf[to]++; } // effects: update owership ownerOf[id] = to; // effects: reclaim storage delete getApproved[id]; // effects: update history _updateHistory(to, id); emit Transfer(from, to, id); } bytes constant onColor = "FFF"; bytes constant offColor = "333"; /// @dev Generate the SVG image for the given NFT. function _tokenImage(bytes memory topHue, bytes memory bottomHue, uint256 hour, uint256 minute) internal pure returns (string memory) { return Base64.encode( bytes.concat( '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1000 1000">', '<linearGradient id="bg" gradientTransform="rotate(90)">', '<stop offset="0%" stop-color="hsl(', topHue, ',100%,89%)"/>', '<stop offset="100%" stop-color="hsl(', bottomHue, ',77%,36%)"/>', '</linearGradient>', '<rect x="0" y="0" width="1000" height="1000" fill="url(#bg)"/>', _binaryHour(hour), _binaryMinute(minute), '</svg>' ) ); } function _binaryHour(uint256 hour) internal pure returns (bytes memory) { if (hour > 24) { revert EthTime__NumberOutOfRange(); } bytes[7] memory colors = _binaryColor(hour); return bytes.concat( '<circle cx="665" cy="875" r="25" fill="#', colors[0], '"/>', '<circle cx="665" cy="805" r="25" fill="#', colors[1], '"/>', // skip colors[2] '<circle cx="735" cy="875" r="25" fill="#', colors[3], '"/>', '<circle cx="735" cy="805" r="25" fill="#', colors[4], '"/>', '<circle cx="735" cy="735" r="25" fill="#', colors[5], '"/>', '<circle cx="735" cy="665" r="25" fill="#', colors[6], '"/>' ); } function _binaryMinute(uint256 minute) internal pure returns (bytes memory) { if (minute > 59) { revert EthTime__NumberOutOfRange(); } bytes[7] memory colors = _binaryColor(minute); return bytes.concat( '<circle cx="805" cy="875" r="25" fill="#', colors[0], '"/>', '<circle cx="805" cy="805" r="25" fill="#', colors[1], '"/>', '<circle cx="805" cy="735" r="25" fill="#', colors[2], '"/>', '<circle cx="875" cy="875" r="25" fill="#', colors[3], '"/>', '<circle cx="875" cy="805" r="25" fill="#', colors[4], '"/>', '<circle cx="875" cy="735" r="25" fill="#', colors[5], '"/>', '<circle cx="875" cy="665" r="25" fill="#', colors[6], '"/>' ); } /// @dev Returns the colors to be used to display the time. /// The first 3 bytes are used for the first digit, the remaining 4 bytes /// for the second digit. function _binaryColor(uint256 n) internal pure returns (bytes[7] memory) { unchecked { uint256 firstDigit = n / 10; uint256 secondDigit = n % 10; return [ (firstDigit & 0x1 != 0) ? onColor : offColor, (firstDigit & 0x2 != 0) ? onColor : offColor, (firstDigit & 0x4 != 0) ? onColor : offColor, (secondDigit & 0x1 != 0) ? onColor : offColor, (secondDigit & 0x2 != 0) ? onColor : offColor, (secondDigit & 0x4 != 0) ? onColor : offColor, (secondDigit & 0x8 != 0) ? onColor : offColor ]; } } function _computeHue(uint160 n, uint256 id) internal pure returns (bytes memory) { uint160 t = n ^ uint160(id); uint160 acc = t % 360; return bytes(Strings.toString(acc)); } function _adjustedHourMinutes(uint256 id) internal view returns (uint256 hour, uint256 minute) { int256 signedUserTimestamp = int256(block.timestamp) - 60 * timeOffsetMinutes[id]; uint256 userTimestamp; // this won't realistically ever happen if (signedUserTimestamp <= 0) { userTimestamp = 0; } else { userTimestamp = uint256(signedUserTimestamp); } hour = BokkyPooBahsDateTimeLibrary.getHour(userTimestamp); minute = BokkyPooBahsDateTimeLibrary.getMinute(userTimestamp); } }
/// @notice ETH-Time NFT contract.
NatSpecSingleLine
getBatchMintPrice
function getBatchMintPrice(uint256 count) public view returns (uint256) { // checks: can mint count nfts _validateBatchMintCount(count); uint256 supply = totalSupply; uint256 price = 0; for (uint256 i = 0; i < count; i++) { price += _priceAtSupplyLevel(supply + i); } return price; }
/// @notice Get the price for minting the next `count` NFT.
NatSpecSingleLine
v0.8.10+commit.fc410830
{ "func_code_index": [ 7575, 7972 ] }
8,657
EthTime
EthTime.sol
0xe339d6f5a42e581dce5a479fca0ed02248a6dca4
Solidity
EthTime
contract EthTime is ERC721, CharitySplitter, Ownable, ReentrancyGuard { ////////////////////////////////////////////////////////////////////////// // // // Constructor // // // ////////////////////////////////////////////////////////////////////////// constructor(address payable charity, uint256 charityFeeBp) ERC721("ETH Time", "ETHT") CharitySplitter(charity, charityFeeBp) { } receive() external payable {} ////////////////////////////////////////////////////////////////////////// // // // Transfer with History // // // ////////////////////////////////////////////////////////////////////////// /// @notice The state of each NFT. mapping(uint256 => uint160) public historyAccumulator; function transferFrom(address from, address to, uint256 id) public nonReentrant override { _transferFrom(from, to, id); } function safeTransferFrom(address from, address to, uint256 id) public nonReentrant override { _transferFrom(from, to, id); // interactions: check destination can handle ERC721 require( to.code.length == 0 || ERC721TokenReceiver(to).onERC721Received(msg.sender, from, id, "") == ERC721TokenReceiver.onERC721Received.selector, "UNSAFE_RECIPIENT" ); } function safeTransferFrom(address from, address to, uint256 id, bytes memory /* data */) public nonReentrant override { _transferFrom(from, to, id); // interactions: check destination can handle ERC721 require( to.code.length == 0 || ERC721TokenReceiver(to).onERC721Received(msg.sender, from, id, "") == ERC721TokenReceiver.onERC721Received.selector, "UNSAFE_RECIPIENT" ); } ////////////////////////////////////////////////////////////////////////// // // // Charity Splitter // // // ////////////////////////////////////////////////////////////////////////// /// @notice Withdraw charity balance to charity address. /// @dev Anyone can call this at any time. function withdrawCharityBalance() public nonReentrant { _withdrawCharityBalance(); } /// @notice Withdraw owner balance to the specified address. /// @param destination the address that receives the owner balance. function withdrawOwnerBalance(address payable destination) public onlyOwner nonReentrant { _withdrawOwnerBalance(destination); } /// @notice Update the address that receives the charity fee. /// @param charity the new charity address. function updateCharity(address payable charity) public onlyOwner nonReentrant { _updateCharity(charity); } ////////////////////////////////////////////////////////////////////////// // // // Timezone Management // // // ////////////////////////////////////////////////////////////////////////// mapping(uint256 => int128) public timeOffsetMinutes; event TimeOffsetUpdated(uint256 indexed id, int128 offsetMinutes); /// @notice Sets the time offset of the given token id. /// @dev Use minutes because some timezones (like IST) are offset by half an hour. /// @param id the NFT unique id. /// @param offsetMinutes the offset in minutes. function setTimeOffsetMinutes(uint256 id, int128 offsetMinutes) public { // checks: id exists if (ownerOf[id] == address(0)) { revert EthTime__DoesNotExist(); } // checks: sender is owner. if (ownerOf[id] != msg.sender) { revert EthTime__NotOwner(); } // checks: validate time offset _validateTimeOffset(offsetMinutes); // effects: update time offset timeOffsetMinutes[id] = offsetMinutes; emit TimeOffsetUpdated(id, offsetMinutes); } function _validateTimeOffset(int128 offsetMinutes) internal { int128 offsetSeconds = offsetMinutes * 60; // checks: offset is [-12, +14] hours UTC if (offsetSeconds > 14 hours || offsetSeconds < -12 hours) { revert EthTime__InvalidTimeOffset(); } } ////////////////////////////////////////////////////////////////////////// // // // Minting // // // ////////////////////////////////////////////////////////////////////////// /// @dev The number of tokens minted. uint256 public totalSupply; /// @dev The maximum number of mintable tokens. uint256 public constant maximumSupply = 100; uint256 private constant TARGET_PRICE = 1 ether; uint256 private constant PRICE_INCREMENT = TARGET_PRICE / maximumSupply * 2; /// @notice Mint a new NFT, transfering ownership to the given account. /// @dev If the token id already exists, this method fails. /// @param to the NFT ower. /// @param offsetMinutes the time offset in minutes. /// @param id the NFT unique id. function mint(address to, int128 offsetMinutes, uint256 id) public payable nonReentrant virtual { // interactions: mint. uint256 valueLeft = _mint(to, offsetMinutes, id, msg.value); // interactions: send back leftover value. if (valueLeft > 0) { (bool success, ) = msg.sender.call{value: valueLeft}(""); require(success); } } /// @notice Mint new NFTs, transfering ownership to the given account. /// @dev If any of the token ids already exists, this method fails. /// @param to the NFT ower. /// @param offsetMinutes the time offset in minutes. /// @param ids the NFT unique ids. function batchMint(address to, int128 offsetMinutes, uint256[] calldata ids) public payable nonReentrant virtual { uint256 count = ids.length; // checks: can mint count nfts _validateBatchMintCount(count); uint256 valueLeft = msg.value; for (uint256 i = 0; i < count; i++) { // interactions: mint. valueLeft = _mint(to, offsetMinutes, ids[i], valueLeft); } // interactions: send back leftover value. if (valueLeft > 0) { (bool success, ) = msg.sender.call{value: valueLeft}(""); require(success); } } /// @notice Get the price for minting the next `count` NFT. function getBatchMintPrice(uint256 count) public view returns (uint256) { // checks: can mint count nfts _validateBatchMintCount(count); uint256 supply = totalSupply; uint256 price = 0; for (uint256 i = 0; i < count; i++) { price += _priceAtSupplyLevel(supply + i); } return price; } /// @notice Get the price for minting the next NFT. function getMintPrice() public view returns (uint256) { return _priceAtSupplyLevel(totalSupply); } function _mint(address to, int128 offsetMinutes, uint256 id, uint256 value) internal returns (uint256 valueLeft) { uint256 price = _priceAtSupplyLevel(totalSupply); // checks: value is enough to mint the nft. if (value < price) { revert EthTime__InvalidMintValue(); } // checks: minting causes going over maximum supply. if (totalSupply == maximumSupply) { revert EthTime__CollectionMintClosed(); } // checks: validate offset _validateTimeOffset(offsetMinutes); // effects: seed history with unique starting value. historyAccumulator[id] = uint160(id >> 4); // effects: increment total supply. totalSupply += 1; // effects: update charity split. _updateBalance(value); // effects: set time offset timeOffsetMinutes[id] = offsetMinutes; // interactions: safe mint _safeMint(to, id); // return value left to be sent back to user. valueLeft = value - price; } function _priceAtSupplyLevel(uint256 supply) internal pure returns (uint256) { uint256 price = supply * PRICE_INCREMENT; if (supply > 50) { price = TARGET_PRICE; } return price; } function _validateBatchMintCount(uint256 count) internal view { // checks: no more than 10. if (count > 10) { revert EthTime__InvalidMintAmount(); } // checks: minting does not push over the limit. // notice that it would fail anyway. if (totalSupply + count > maximumSupply) { revert EthTime__InvalidMintAmount(); } } ////////////////////////////////////////////////////////////////////////// // // // Token URI // // // ////////////////////////////////////////////////////////////////////////// /// @notice Returns the URI with the NFT metadata. /// @dev Returns the base64 encoded metadata inline. /// @param id the NFT unique id function tokenURI(uint256 id) public view override returns (string memory) { if (ownerOf[id] == address(0)) { revert EthTime__DoesNotExist(); } string memory tokenId = Strings.toString(id); (uint256 hour, uint256 minute) = _adjustedHourMinutes(id); bytes memory topHue = _computeHue(historyAccumulator[id], id); bytes memory bottomHue = _computeHue(uint160(ownerOf[id]), id); int128 offset = timeOffsetMinutes[id]; bytes memory offsetSign = offset >= 0 ? bytes('+') : bytes('-'); uint256 offsetUnsigned = offset >= 0 ? uint256(int256(offset)) : uint256(int256(-offset)); return string( bytes.concat( 'data:application/json;base64,', bytes( Base64.encode( bytes.concat( '{"name": "ETH Time #', bytes(tokenId), '", "description": "ETH Time", "image": "data:image/svg+xml;base64,', bytes(_tokenImage(topHue, bottomHue, hour, minute)), '", "attributes": [{"trait_type": "top_color", "value": "hsl(', topHue, ',100%,89%)"},', '{"trait_type": "bottom_color", "value": "hsl(', bottomHue, ',77%,36%)"},', '{"trait_type": "time_offset", "value": "', offsetSign, bytes(Strings.toString(offsetUnsigned)), '"},', '{"trait_type": "time", "value": "', bytes(Strings.toString(hour)), ':', bytes(Strings.toString(minute)), '"}]}' ) ) ) ) ); } /// @dev Generate a preview of the token that will be minted. /// @param to the minter. /// @param id the NFT unique id. function tokenImagePreview(address to, uint256 id) public view returns (string memory) { (uint256 hour, uint256 minute) = _adjustedHourMinutes(id); bytes memory topHue = _computeHue(uint160(id >> 4), id); bytes memory bottomHue = _computeHue(uint160(to), id); return _tokenImage(topHue, bottomHue, hour, minute); } ////////////////////////////////////////////////////////////////////////// // // // Private Functions // // // ////////////////////////////////////////////////////////////////////////// /// @dev Update the NFT history based on the transfer to the given account. /// @param to the address that will receive the nft. /// @param id the NFT unique id. function _updateHistory(address to, uint256 id) internal { // effects: xor existing value with address bytes content. historyAccumulator[id] ^= uint160(to) << 2; } function _transferFrom(address from, address to, uint256 id) internal { // checks: sender and destination require(from == ownerOf[id], "WRONG_FROM"); require(to != address(0), "INVALID_RECIPIENT"); // checks: can transfer require( msg.sender == from || msg.sender == getApproved[id] || isApprovedForAll[from][msg.sender], "NOT_AUTHORIZED" ); // effects: update balance // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. unchecked { balanceOf[from]--; balanceOf[to]++; } // effects: update owership ownerOf[id] = to; // effects: reclaim storage delete getApproved[id]; // effects: update history _updateHistory(to, id); emit Transfer(from, to, id); } bytes constant onColor = "FFF"; bytes constant offColor = "333"; /// @dev Generate the SVG image for the given NFT. function _tokenImage(bytes memory topHue, bytes memory bottomHue, uint256 hour, uint256 minute) internal pure returns (string memory) { return Base64.encode( bytes.concat( '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1000 1000">', '<linearGradient id="bg" gradientTransform="rotate(90)">', '<stop offset="0%" stop-color="hsl(', topHue, ',100%,89%)"/>', '<stop offset="100%" stop-color="hsl(', bottomHue, ',77%,36%)"/>', '</linearGradient>', '<rect x="0" y="0" width="1000" height="1000" fill="url(#bg)"/>', _binaryHour(hour), _binaryMinute(minute), '</svg>' ) ); } function _binaryHour(uint256 hour) internal pure returns (bytes memory) { if (hour > 24) { revert EthTime__NumberOutOfRange(); } bytes[7] memory colors = _binaryColor(hour); return bytes.concat( '<circle cx="665" cy="875" r="25" fill="#', colors[0], '"/>', '<circle cx="665" cy="805" r="25" fill="#', colors[1], '"/>', // skip colors[2] '<circle cx="735" cy="875" r="25" fill="#', colors[3], '"/>', '<circle cx="735" cy="805" r="25" fill="#', colors[4], '"/>', '<circle cx="735" cy="735" r="25" fill="#', colors[5], '"/>', '<circle cx="735" cy="665" r="25" fill="#', colors[6], '"/>' ); } function _binaryMinute(uint256 minute) internal pure returns (bytes memory) { if (minute > 59) { revert EthTime__NumberOutOfRange(); } bytes[7] memory colors = _binaryColor(minute); return bytes.concat( '<circle cx="805" cy="875" r="25" fill="#', colors[0], '"/>', '<circle cx="805" cy="805" r="25" fill="#', colors[1], '"/>', '<circle cx="805" cy="735" r="25" fill="#', colors[2], '"/>', '<circle cx="875" cy="875" r="25" fill="#', colors[3], '"/>', '<circle cx="875" cy="805" r="25" fill="#', colors[4], '"/>', '<circle cx="875" cy="735" r="25" fill="#', colors[5], '"/>', '<circle cx="875" cy="665" r="25" fill="#', colors[6], '"/>' ); } /// @dev Returns the colors to be used to display the time. /// The first 3 bytes are used for the first digit, the remaining 4 bytes /// for the second digit. function _binaryColor(uint256 n) internal pure returns (bytes[7] memory) { unchecked { uint256 firstDigit = n / 10; uint256 secondDigit = n % 10; return [ (firstDigit & 0x1 != 0) ? onColor : offColor, (firstDigit & 0x2 != 0) ? onColor : offColor, (firstDigit & 0x4 != 0) ? onColor : offColor, (secondDigit & 0x1 != 0) ? onColor : offColor, (secondDigit & 0x2 != 0) ? onColor : offColor, (secondDigit & 0x4 != 0) ? onColor : offColor, (secondDigit & 0x8 != 0) ? onColor : offColor ]; } } function _computeHue(uint160 n, uint256 id) internal pure returns (bytes memory) { uint160 t = n ^ uint160(id); uint160 acc = t % 360; return bytes(Strings.toString(acc)); } function _adjustedHourMinutes(uint256 id) internal view returns (uint256 hour, uint256 minute) { int256 signedUserTimestamp = int256(block.timestamp) - 60 * timeOffsetMinutes[id]; uint256 userTimestamp; // this won't realistically ever happen if (signedUserTimestamp <= 0) { userTimestamp = 0; } else { userTimestamp = uint256(signedUserTimestamp); } hour = BokkyPooBahsDateTimeLibrary.getHour(userTimestamp); minute = BokkyPooBahsDateTimeLibrary.getMinute(userTimestamp); } }
/// @notice ETH-Time NFT contract.
NatSpecSingleLine
getMintPrice
function getMintPrice() public view returns (uint256) { return _priceAtSupplyLevel(totalSupply); }
/// @notice Get the price for minting the next NFT.
NatSpecSingleLine
v0.8.10+commit.fc410830
{ "func_code_index": [ 8030, 8172 ] }
8,658
EthTime
EthTime.sol
0xe339d6f5a42e581dce5a479fca0ed02248a6dca4
Solidity
EthTime
contract EthTime is ERC721, CharitySplitter, Ownable, ReentrancyGuard { ////////////////////////////////////////////////////////////////////////// // // // Constructor // // // ////////////////////////////////////////////////////////////////////////// constructor(address payable charity, uint256 charityFeeBp) ERC721("ETH Time", "ETHT") CharitySplitter(charity, charityFeeBp) { } receive() external payable {} ////////////////////////////////////////////////////////////////////////// // // // Transfer with History // // // ////////////////////////////////////////////////////////////////////////// /// @notice The state of each NFT. mapping(uint256 => uint160) public historyAccumulator; function transferFrom(address from, address to, uint256 id) public nonReentrant override { _transferFrom(from, to, id); } function safeTransferFrom(address from, address to, uint256 id) public nonReentrant override { _transferFrom(from, to, id); // interactions: check destination can handle ERC721 require( to.code.length == 0 || ERC721TokenReceiver(to).onERC721Received(msg.sender, from, id, "") == ERC721TokenReceiver.onERC721Received.selector, "UNSAFE_RECIPIENT" ); } function safeTransferFrom(address from, address to, uint256 id, bytes memory /* data */) public nonReentrant override { _transferFrom(from, to, id); // interactions: check destination can handle ERC721 require( to.code.length == 0 || ERC721TokenReceiver(to).onERC721Received(msg.sender, from, id, "") == ERC721TokenReceiver.onERC721Received.selector, "UNSAFE_RECIPIENT" ); } ////////////////////////////////////////////////////////////////////////// // // // Charity Splitter // // // ////////////////////////////////////////////////////////////////////////// /// @notice Withdraw charity balance to charity address. /// @dev Anyone can call this at any time. function withdrawCharityBalance() public nonReentrant { _withdrawCharityBalance(); } /// @notice Withdraw owner balance to the specified address. /// @param destination the address that receives the owner balance. function withdrawOwnerBalance(address payable destination) public onlyOwner nonReentrant { _withdrawOwnerBalance(destination); } /// @notice Update the address that receives the charity fee. /// @param charity the new charity address. function updateCharity(address payable charity) public onlyOwner nonReentrant { _updateCharity(charity); } ////////////////////////////////////////////////////////////////////////// // // // Timezone Management // // // ////////////////////////////////////////////////////////////////////////// mapping(uint256 => int128) public timeOffsetMinutes; event TimeOffsetUpdated(uint256 indexed id, int128 offsetMinutes); /// @notice Sets the time offset of the given token id. /// @dev Use minutes because some timezones (like IST) are offset by half an hour. /// @param id the NFT unique id. /// @param offsetMinutes the offset in minutes. function setTimeOffsetMinutes(uint256 id, int128 offsetMinutes) public { // checks: id exists if (ownerOf[id] == address(0)) { revert EthTime__DoesNotExist(); } // checks: sender is owner. if (ownerOf[id] != msg.sender) { revert EthTime__NotOwner(); } // checks: validate time offset _validateTimeOffset(offsetMinutes); // effects: update time offset timeOffsetMinutes[id] = offsetMinutes; emit TimeOffsetUpdated(id, offsetMinutes); } function _validateTimeOffset(int128 offsetMinutes) internal { int128 offsetSeconds = offsetMinutes * 60; // checks: offset is [-12, +14] hours UTC if (offsetSeconds > 14 hours || offsetSeconds < -12 hours) { revert EthTime__InvalidTimeOffset(); } } ////////////////////////////////////////////////////////////////////////// // // // Minting // // // ////////////////////////////////////////////////////////////////////////// /// @dev The number of tokens minted. uint256 public totalSupply; /// @dev The maximum number of mintable tokens. uint256 public constant maximumSupply = 100; uint256 private constant TARGET_PRICE = 1 ether; uint256 private constant PRICE_INCREMENT = TARGET_PRICE / maximumSupply * 2; /// @notice Mint a new NFT, transfering ownership to the given account. /// @dev If the token id already exists, this method fails. /// @param to the NFT ower. /// @param offsetMinutes the time offset in minutes. /// @param id the NFT unique id. function mint(address to, int128 offsetMinutes, uint256 id) public payable nonReentrant virtual { // interactions: mint. uint256 valueLeft = _mint(to, offsetMinutes, id, msg.value); // interactions: send back leftover value. if (valueLeft > 0) { (bool success, ) = msg.sender.call{value: valueLeft}(""); require(success); } } /// @notice Mint new NFTs, transfering ownership to the given account. /// @dev If any of the token ids already exists, this method fails. /// @param to the NFT ower. /// @param offsetMinutes the time offset in minutes. /// @param ids the NFT unique ids. function batchMint(address to, int128 offsetMinutes, uint256[] calldata ids) public payable nonReentrant virtual { uint256 count = ids.length; // checks: can mint count nfts _validateBatchMintCount(count); uint256 valueLeft = msg.value; for (uint256 i = 0; i < count; i++) { // interactions: mint. valueLeft = _mint(to, offsetMinutes, ids[i], valueLeft); } // interactions: send back leftover value. if (valueLeft > 0) { (bool success, ) = msg.sender.call{value: valueLeft}(""); require(success); } } /// @notice Get the price for minting the next `count` NFT. function getBatchMintPrice(uint256 count) public view returns (uint256) { // checks: can mint count nfts _validateBatchMintCount(count); uint256 supply = totalSupply; uint256 price = 0; for (uint256 i = 0; i < count; i++) { price += _priceAtSupplyLevel(supply + i); } return price; } /// @notice Get the price for minting the next NFT. function getMintPrice() public view returns (uint256) { return _priceAtSupplyLevel(totalSupply); } function _mint(address to, int128 offsetMinutes, uint256 id, uint256 value) internal returns (uint256 valueLeft) { uint256 price = _priceAtSupplyLevel(totalSupply); // checks: value is enough to mint the nft. if (value < price) { revert EthTime__InvalidMintValue(); } // checks: minting causes going over maximum supply. if (totalSupply == maximumSupply) { revert EthTime__CollectionMintClosed(); } // checks: validate offset _validateTimeOffset(offsetMinutes); // effects: seed history with unique starting value. historyAccumulator[id] = uint160(id >> 4); // effects: increment total supply. totalSupply += 1; // effects: update charity split. _updateBalance(value); // effects: set time offset timeOffsetMinutes[id] = offsetMinutes; // interactions: safe mint _safeMint(to, id); // return value left to be sent back to user. valueLeft = value - price; } function _priceAtSupplyLevel(uint256 supply) internal pure returns (uint256) { uint256 price = supply * PRICE_INCREMENT; if (supply > 50) { price = TARGET_PRICE; } return price; } function _validateBatchMintCount(uint256 count) internal view { // checks: no more than 10. if (count > 10) { revert EthTime__InvalidMintAmount(); } // checks: minting does not push over the limit. // notice that it would fail anyway. if (totalSupply + count > maximumSupply) { revert EthTime__InvalidMintAmount(); } } ////////////////////////////////////////////////////////////////////////// // // // Token URI // // // ////////////////////////////////////////////////////////////////////////// /// @notice Returns the URI with the NFT metadata. /// @dev Returns the base64 encoded metadata inline. /// @param id the NFT unique id function tokenURI(uint256 id) public view override returns (string memory) { if (ownerOf[id] == address(0)) { revert EthTime__DoesNotExist(); } string memory tokenId = Strings.toString(id); (uint256 hour, uint256 minute) = _adjustedHourMinutes(id); bytes memory topHue = _computeHue(historyAccumulator[id], id); bytes memory bottomHue = _computeHue(uint160(ownerOf[id]), id); int128 offset = timeOffsetMinutes[id]; bytes memory offsetSign = offset >= 0 ? bytes('+') : bytes('-'); uint256 offsetUnsigned = offset >= 0 ? uint256(int256(offset)) : uint256(int256(-offset)); return string( bytes.concat( 'data:application/json;base64,', bytes( Base64.encode( bytes.concat( '{"name": "ETH Time #', bytes(tokenId), '", "description": "ETH Time", "image": "data:image/svg+xml;base64,', bytes(_tokenImage(topHue, bottomHue, hour, minute)), '", "attributes": [{"trait_type": "top_color", "value": "hsl(', topHue, ',100%,89%)"},', '{"trait_type": "bottom_color", "value": "hsl(', bottomHue, ',77%,36%)"},', '{"trait_type": "time_offset", "value": "', offsetSign, bytes(Strings.toString(offsetUnsigned)), '"},', '{"trait_type": "time", "value": "', bytes(Strings.toString(hour)), ':', bytes(Strings.toString(minute)), '"}]}' ) ) ) ) ); } /// @dev Generate a preview of the token that will be minted. /// @param to the minter. /// @param id the NFT unique id. function tokenImagePreview(address to, uint256 id) public view returns (string memory) { (uint256 hour, uint256 minute) = _adjustedHourMinutes(id); bytes memory topHue = _computeHue(uint160(id >> 4), id); bytes memory bottomHue = _computeHue(uint160(to), id); return _tokenImage(topHue, bottomHue, hour, minute); } ////////////////////////////////////////////////////////////////////////// // // // Private Functions // // // ////////////////////////////////////////////////////////////////////////// /// @dev Update the NFT history based on the transfer to the given account. /// @param to the address that will receive the nft. /// @param id the NFT unique id. function _updateHistory(address to, uint256 id) internal { // effects: xor existing value with address bytes content. historyAccumulator[id] ^= uint160(to) << 2; } function _transferFrom(address from, address to, uint256 id) internal { // checks: sender and destination require(from == ownerOf[id], "WRONG_FROM"); require(to != address(0), "INVALID_RECIPIENT"); // checks: can transfer require( msg.sender == from || msg.sender == getApproved[id] || isApprovedForAll[from][msg.sender], "NOT_AUTHORIZED" ); // effects: update balance // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. unchecked { balanceOf[from]--; balanceOf[to]++; } // effects: update owership ownerOf[id] = to; // effects: reclaim storage delete getApproved[id]; // effects: update history _updateHistory(to, id); emit Transfer(from, to, id); } bytes constant onColor = "FFF"; bytes constant offColor = "333"; /// @dev Generate the SVG image for the given NFT. function _tokenImage(bytes memory topHue, bytes memory bottomHue, uint256 hour, uint256 minute) internal pure returns (string memory) { return Base64.encode( bytes.concat( '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1000 1000">', '<linearGradient id="bg" gradientTransform="rotate(90)">', '<stop offset="0%" stop-color="hsl(', topHue, ',100%,89%)"/>', '<stop offset="100%" stop-color="hsl(', bottomHue, ',77%,36%)"/>', '</linearGradient>', '<rect x="0" y="0" width="1000" height="1000" fill="url(#bg)"/>', _binaryHour(hour), _binaryMinute(minute), '</svg>' ) ); } function _binaryHour(uint256 hour) internal pure returns (bytes memory) { if (hour > 24) { revert EthTime__NumberOutOfRange(); } bytes[7] memory colors = _binaryColor(hour); return bytes.concat( '<circle cx="665" cy="875" r="25" fill="#', colors[0], '"/>', '<circle cx="665" cy="805" r="25" fill="#', colors[1], '"/>', // skip colors[2] '<circle cx="735" cy="875" r="25" fill="#', colors[3], '"/>', '<circle cx="735" cy="805" r="25" fill="#', colors[4], '"/>', '<circle cx="735" cy="735" r="25" fill="#', colors[5], '"/>', '<circle cx="735" cy="665" r="25" fill="#', colors[6], '"/>' ); } function _binaryMinute(uint256 minute) internal pure returns (bytes memory) { if (minute > 59) { revert EthTime__NumberOutOfRange(); } bytes[7] memory colors = _binaryColor(minute); return bytes.concat( '<circle cx="805" cy="875" r="25" fill="#', colors[0], '"/>', '<circle cx="805" cy="805" r="25" fill="#', colors[1], '"/>', '<circle cx="805" cy="735" r="25" fill="#', colors[2], '"/>', '<circle cx="875" cy="875" r="25" fill="#', colors[3], '"/>', '<circle cx="875" cy="805" r="25" fill="#', colors[4], '"/>', '<circle cx="875" cy="735" r="25" fill="#', colors[5], '"/>', '<circle cx="875" cy="665" r="25" fill="#', colors[6], '"/>' ); } /// @dev Returns the colors to be used to display the time. /// The first 3 bytes are used for the first digit, the remaining 4 bytes /// for the second digit. function _binaryColor(uint256 n) internal pure returns (bytes[7] memory) { unchecked { uint256 firstDigit = n / 10; uint256 secondDigit = n % 10; return [ (firstDigit & 0x1 != 0) ? onColor : offColor, (firstDigit & 0x2 != 0) ? onColor : offColor, (firstDigit & 0x4 != 0) ? onColor : offColor, (secondDigit & 0x1 != 0) ? onColor : offColor, (secondDigit & 0x2 != 0) ? onColor : offColor, (secondDigit & 0x4 != 0) ? onColor : offColor, (secondDigit & 0x8 != 0) ? onColor : offColor ]; } } function _computeHue(uint160 n, uint256 id) internal pure returns (bytes memory) { uint160 t = n ^ uint160(id); uint160 acc = t % 360; return bytes(Strings.toString(acc)); } function _adjustedHourMinutes(uint256 id) internal view returns (uint256 hour, uint256 minute) { int256 signedUserTimestamp = int256(block.timestamp) - 60 * timeOffsetMinutes[id]; uint256 userTimestamp; // this won't realistically ever happen if (signedUserTimestamp <= 0) { userTimestamp = 0; } else { userTimestamp = uint256(signedUserTimestamp); } hour = BokkyPooBahsDateTimeLibrary.getHour(userTimestamp); minute = BokkyPooBahsDateTimeLibrary.getMinute(userTimestamp); } }
/// @notice ETH-Time NFT contract.
NatSpecSingleLine
tokenURI
function tokenURI(uint256 id) public view override returns (string memory) { if (ownerOf[id] == address(0)) { revert EthTime__DoesNotExist(); } string memory tokenId = Strings.toString(id); (uint256 hour, uint256 minute) = _adjustedHourMinutes(id); bytes memory topHue = _computeHue(historyAccumulator[id], id); bytes memory bottomHue = _computeHue(uint160(ownerOf[id]), id); int128 offset = timeOffsetMinutes[id]; bytes memory offsetSign = offset >= 0 ? bytes('+') : bytes('-'); uint256 offsetUnsigned = offset >= 0 ? uint256(int256(offset)) : uint256(int256(-offset)); return string( bytes.concat( 'data:application/json;base64,', bytes( Base64.encode( bytes.concat( '{"name": "ETH Time #', bytes(tokenId), '", "description": "ETH Time", "image": "data:image/svg+xml;base64,', bytes(_tokenImage(topHue, bottomHue, hour, minute)), '", "attributes": [{"trait_type": "top_color", "value": "hsl(', topHue, ',100%,89%)"},', '{"trait_type": "bottom_color", "value": "hsl(', bottomHue, ',77%,36%)"},', '{"trait_type": "time_offset", "value": "', offsetSign, bytes(Strings.toString(offsetUnsigned)), '"},', '{"trait_type": "time", "value": "', bytes(Strings.toString(hour)), ':', bytes(Strings.toString(minute)), '"}]}' ) ) ) ) ); }
////////////////////////////////////////////////////////////////////////// /// @notice Returns the URI with the NFT metadata. /// @dev Returns the base64 encoded metadata inline. /// @param id the NFT unique id
NatSpecSingleLine
v0.8.10+commit.fc410830
{ "func_code_index": [ 10497, 12341 ] }
8,659
EthTime
EthTime.sol
0xe339d6f5a42e581dce5a479fca0ed02248a6dca4
Solidity
EthTime
contract EthTime is ERC721, CharitySplitter, Ownable, ReentrancyGuard { ////////////////////////////////////////////////////////////////////////// // // // Constructor // // // ////////////////////////////////////////////////////////////////////////// constructor(address payable charity, uint256 charityFeeBp) ERC721("ETH Time", "ETHT") CharitySplitter(charity, charityFeeBp) { } receive() external payable {} ////////////////////////////////////////////////////////////////////////// // // // Transfer with History // // // ////////////////////////////////////////////////////////////////////////// /// @notice The state of each NFT. mapping(uint256 => uint160) public historyAccumulator; function transferFrom(address from, address to, uint256 id) public nonReentrant override { _transferFrom(from, to, id); } function safeTransferFrom(address from, address to, uint256 id) public nonReentrant override { _transferFrom(from, to, id); // interactions: check destination can handle ERC721 require( to.code.length == 0 || ERC721TokenReceiver(to).onERC721Received(msg.sender, from, id, "") == ERC721TokenReceiver.onERC721Received.selector, "UNSAFE_RECIPIENT" ); } function safeTransferFrom(address from, address to, uint256 id, bytes memory /* data */) public nonReentrant override { _transferFrom(from, to, id); // interactions: check destination can handle ERC721 require( to.code.length == 0 || ERC721TokenReceiver(to).onERC721Received(msg.sender, from, id, "") == ERC721TokenReceiver.onERC721Received.selector, "UNSAFE_RECIPIENT" ); } ////////////////////////////////////////////////////////////////////////// // // // Charity Splitter // // // ////////////////////////////////////////////////////////////////////////// /// @notice Withdraw charity balance to charity address. /// @dev Anyone can call this at any time. function withdrawCharityBalance() public nonReentrant { _withdrawCharityBalance(); } /// @notice Withdraw owner balance to the specified address. /// @param destination the address that receives the owner balance. function withdrawOwnerBalance(address payable destination) public onlyOwner nonReentrant { _withdrawOwnerBalance(destination); } /// @notice Update the address that receives the charity fee. /// @param charity the new charity address. function updateCharity(address payable charity) public onlyOwner nonReentrant { _updateCharity(charity); } ////////////////////////////////////////////////////////////////////////// // // // Timezone Management // // // ////////////////////////////////////////////////////////////////////////// mapping(uint256 => int128) public timeOffsetMinutes; event TimeOffsetUpdated(uint256 indexed id, int128 offsetMinutes); /// @notice Sets the time offset of the given token id. /// @dev Use minutes because some timezones (like IST) are offset by half an hour. /// @param id the NFT unique id. /// @param offsetMinutes the offset in minutes. function setTimeOffsetMinutes(uint256 id, int128 offsetMinutes) public { // checks: id exists if (ownerOf[id] == address(0)) { revert EthTime__DoesNotExist(); } // checks: sender is owner. if (ownerOf[id] != msg.sender) { revert EthTime__NotOwner(); } // checks: validate time offset _validateTimeOffset(offsetMinutes); // effects: update time offset timeOffsetMinutes[id] = offsetMinutes; emit TimeOffsetUpdated(id, offsetMinutes); } function _validateTimeOffset(int128 offsetMinutes) internal { int128 offsetSeconds = offsetMinutes * 60; // checks: offset is [-12, +14] hours UTC if (offsetSeconds > 14 hours || offsetSeconds < -12 hours) { revert EthTime__InvalidTimeOffset(); } } ////////////////////////////////////////////////////////////////////////// // // // Minting // // // ////////////////////////////////////////////////////////////////////////// /// @dev The number of tokens minted. uint256 public totalSupply; /// @dev The maximum number of mintable tokens. uint256 public constant maximumSupply = 100; uint256 private constant TARGET_PRICE = 1 ether; uint256 private constant PRICE_INCREMENT = TARGET_PRICE / maximumSupply * 2; /// @notice Mint a new NFT, transfering ownership to the given account. /// @dev If the token id already exists, this method fails. /// @param to the NFT ower. /// @param offsetMinutes the time offset in minutes. /// @param id the NFT unique id. function mint(address to, int128 offsetMinutes, uint256 id) public payable nonReentrant virtual { // interactions: mint. uint256 valueLeft = _mint(to, offsetMinutes, id, msg.value); // interactions: send back leftover value. if (valueLeft > 0) { (bool success, ) = msg.sender.call{value: valueLeft}(""); require(success); } } /// @notice Mint new NFTs, transfering ownership to the given account. /// @dev If any of the token ids already exists, this method fails. /// @param to the NFT ower. /// @param offsetMinutes the time offset in minutes. /// @param ids the NFT unique ids. function batchMint(address to, int128 offsetMinutes, uint256[] calldata ids) public payable nonReentrant virtual { uint256 count = ids.length; // checks: can mint count nfts _validateBatchMintCount(count); uint256 valueLeft = msg.value; for (uint256 i = 0; i < count; i++) { // interactions: mint. valueLeft = _mint(to, offsetMinutes, ids[i], valueLeft); } // interactions: send back leftover value. if (valueLeft > 0) { (bool success, ) = msg.sender.call{value: valueLeft}(""); require(success); } } /// @notice Get the price for minting the next `count` NFT. function getBatchMintPrice(uint256 count) public view returns (uint256) { // checks: can mint count nfts _validateBatchMintCount(count); uint256 supply = totalSupply; uint256 price = 0; for (uint256 i = 0; i < count; i++) { price += _priceAtSupplyLevel(supply + i); } return price; } /// @notice Get the price for minting the next NFT. function getMintPrice() public view returns (uint256) { return _priceAtSupplyLevel(totalSupply); } function _mint(address to, int128 offsetMinutes, uint256 id, uint256 value) internal returns (uint256 valueLeft) { uint256 price = _priceAtSupplyLevel(totalSupply); // checks: value is enough to mint the nft. if (value < price) { revert EthTime__InvalidMintValue(); } // checks: minting causes going over maximum supply. if (totalSupply == maximumSupply) { revert EthTime__CollectionMintClosed(); } // checks: validate offset _validateTimeOffset(offsetMinutes); // effects: seed history with unique starting value. historyAccumulator[id] = uint160(id >> 4); // effects: increment total supply. totalSupply += 1; // effects: update charity split. _updateBalance(value); // effects: set time offset timeOffsetMinutes[id] = offsetMinutes; // interactions: safe mint _safeMint(to, id); // return value left to be sent back to user. valueLeft = value - price; } function _priceAtSupplyLevel(uint256 supply) internal pure returns (uint256) { uint256 price = supply * PRICE_INCREMENT; if (supply > 50) { price = TARGET_PRICE; } return price; } function _validateBatchMintCount(uint256 count) internal view { // checks: no more than 10. if (count > 10) { revert EthTime__InvalidMintAmount(); } // checks: minting does not push over the limit. // notice that it would fail anyway. if (totalSupply + count > maximumSupply) { revert EthTime__InvalidMintAmount(); } } ////////////////////////////////////////////////////////////////////////// // // // Token URI // // // ////////////////////////////////////////////////////////////////////////// /// @notice Returns the URI with the NFT metadata. /// @dev Returns the base64 encoded metadata inline. /// @param id the NFT unique id function tokenURI(uint256 id) public view override returns (string memory) { if (ownerOf[id] == address(0)) { revert EthTime__DoesNotExist(); } string memory tokenId = Strings.toString(id); (uint256 hour, uint256 minute) = _adjustedHourMinutes(id); bytes memory topHue = _computeHue(historyAccumulator[id], id); bytes memory bottomHue = _computeHue(uint160(ownerOf[id]), id); int128 offset = timeOffsetMinutes[id]; bytes memory offsetSign = offset >= 0 ? bytes('+') : bytes('-'); uint256 offsetUnsigned = offset >= 0 ? uint256(int256(offset)) : uint256(int256(-offset)); return string( bytes.concat( 'data:application/json;base64,', bytes( Base64.encode( bytes.concat( '{"name": "ETH Time #', bytes(tokenId), '", "description": "ETH Time", "image": "data:image/svg+xml;base64,', bytes(_tokenImage(topHue, bottomHue, hour, minute)), '", "attributes": [{"trait_type": "top_color", "value": "hsl(', topHue, ',100%,89%)"},', '{"trait_type": "bottom_color", "value": "hsl(', bottomHue, ',77%,36%)"},', '{"trait_type": "time_offset", "value": "', offsetSign, bytes(Strings.toString(offsetUnsigned)), '"},', '{"trait_type": "time", "value": "', bytes(Strings.toString(hour)), ':', bytes(Strings.toString(minute)), '"}]}' ) ) ) ) ); } /// @dev Generate a preview of the token that will be minted. /// @param to the minter. /// @param id the NFT unique id. function tokenImagePreview(address to, uint256 id) public view returns (string memory) { (uint256 hour, uint256 minute) = _adjustedHourMinutes(id); bytes memory topHue = _computeHue(uint160(id >> 4), id); bytes memory bottomHue = _computeHue(uint160(to), id); return _tokenImage(topHue, bottomHue, hour, minute); } ////////////////////////////////////////////////////////////////////////// // // // Private Functions // // // ////////////////////////////////////////////////////////////////////////// /// @dev Update the NFT history based on the transfer to the given account. /// @param to the address that will receive the nft. /// @param id the NFT unique id. function _updateHistory(address to, uint256 id) internal { // effects: xor existing value with address bytes content. historyAccumulator[id] ^= uint160(to) << 2; } function _transferFrom(address from, address to, uint256 id) internal { // checks: sender and destination require(from == ownerOf[id], "WRONG_FROM"); require(to != address(0), "INVALID_RECIPIENT"); // checks: can transfer require( msg.sender == from || msg.sender == getApproved[id] || isApprovedForAll[from][msg.sender], "NOT_AUTHORIZED" ); // effects: update balance // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. unchecked { balanceOf[from]--; balanceOf[to]++; } // effects: update owership ownerOf[id] = to; // effects: reclaim storage delete getApproved[id]; // effects: update history _updateHistory(to, id); emit Transfer(from, to, id); } bytes constant onColor = "FFF"; bytes constant offColor = "333"; /// @dev Generate the SVG image for the given NFT. function _tokenImage(bytes memory topHue, bytes memory bottomHue, uint256 hour, uint256 minute) internal pure returns (string memory) { return Base64.encode( bytes.concat( '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1000 1000">', '<linearGradient id="bg" gradientTransform="rotate(90)">', '<stop offset="0%" stop-color="hsl(', topHue, ',100%,89%)"/>', '<stop offset="100%" stop-color="hsl(', bottomHue, ',77%,36%)"/>', '</linearGradient>', '<rect x="0" y="0" width="1000" height="1000" fill="url(#bg)"/>', _binaryHour(hour), _binaryMinute(minute), '</svg>' ) ); } function _binaryHour(uint256 hour) internal pure returns (bytes memory) { if (hour > 24) { revert EthTime__NumberOutOfRange(); } bytes[7] memory colors = _binaryColor(hour); return bytes.concat( '<circle cx="665" cy="875" r="25" fill="#', colors[0], '"/>', '<circle cx="665" cy="805" r="25" fill="#', colors[1], '"/>', // skip colors[2] '<circle cx="735" cy="875" r="25" fill="#', colors[3], '"/>', '<circle cx="735" cy="805" r="25" fill="#', colors[4], '"/>', '<circle cx="735" cy="735" r="25" fill="#', colors[5], '"/>', '<circle cx="735" cy="665" r="25" fill="#', colors[6], '"/>' ); } function _binaryMinute(uint256 minute) internal pure returns (bytes memory) { if (minute > 59) { revert EthTime__NumberOutOfRange(); } bytes[7] memory colors = _binaryColor(minute); return bytes.concat( '<circle cx="805" cy="875" r="25" fill="#', colors[0], '"/>', '<circle cx="805" cy="805" r="25" fill="#', colors[1], '"/>', '<circle cx="805" cy="735" r="25" fill="#', colors[2], '"/>', '<circle cx="875" cy="875" r="25" fill="#', colors[3], '"/>', '<circle cx="875" cy="805" r="25" fill="#', colors[4], '"/>', '<circle cx="875" cy="735" r="25" fill="#', colors[5], '"/>', '<circle cx="875" cy="665" r="25" fill="#', colors[6], '"/>' ); } /// @dev Returns the colors to be used to display the time. /// The first 3 bytes are used for the first digit, the remaining 4 bytes /// for the second digit. function _binaryColor(uint256 n) internal pure returns (bytes[7] memory) { unchecked { uint256 firstDigit = n / 10; uint256 secondDigit = n % 10; return [ (firstDigit & 0x1 != 0) ? onColor : offColor, (firstDigit & 0x2 != 0) ? onColor : offColor, (firstDigit & 0x4 != 0) ? onColor : offColor, (secondDigit & 0x1 != 0) ? onColor : offColor, (secondDigit & 0x2 != 0) ? onColor : offColor, (secondDigit & 0x4 != 0) ? onColor : offColor, (secondDigit & 0x8 != 0) ? onColor : offColor ]; } } function _computeHue(uint160 n, uint256 id) internal pure returns (bytes memory) { uint160 t = n ^ uint160(id); uint160 acc = t % 360; return bytes(Strings.toString(acc)); } function _adjustedHourMinutes(uint256 id) internal view returns (uint256 hour, uint256 minute) { int256 signedUserTimestamp = int256(block.timestamp) - 60 * timeOffsetMinutes[id]; uint256 userTimestamp; // this won't realistically ever happen if (signedUserTimestamp <= 0) { userTimestamp = 0; } else { userTimestamp = uint256(signedUserTimestamp); } hour = BokkyPooBahsDateTimeLibrary.getHour(userTimestamp); minute = BokkyPooBahsDateTimeLibrary.getMinute(userTimestamp); } }
/// @notice ETH-Time NFT contract.
NatSpecSingleLine
tokenImagePreview
function tokenImagePreview(address to, uint256 id) public view returns (string memory) { (uint256 hour, uint256 minute) = _adjustedHourMinutes(id); bytes memory topHue = _computeHue(uint160(id >> 4), id); bytes memory bottomHue = _computeHue(uint160(to), id); return _tokenImage(topHue, bottomHue, hour, minute); }
/// @dev Generate a preview of the token that will be minted. /// @param to the minter. /// @param id the NFT unique id.
NatSpecSingleLine
v0.8.10+commit.fc410830
{ "func_code_index": [ 12476, 12860 ] }
8,660
EthTime
EthTime.sol
0xe339d6f5a42e581dce5a479fca0ed02248a6dca4
Solidity
EthTime
contract EthTime is ERC721, CharitySplitter, Ownable, ReentrancyGuard { ////////////////////////////////////////////////////////////////////////// // // // Constructor // // // ////////////////////////////////////////////////////////////////////////// constructor(address payable charity, uint256 charityFeeBp) ERC721("ETH Time", "ETHT") CharitySplitter(charity, charityFeeBp) { } receive() external payable {} ////////////////////////////////////////////////////////////////////////// // // // Transfer with History // // // ////////////////////////////////////////////////////////////////////////// /// @notice The state of each NFT. mapping(uint256 => uint160) public historyAccumulator; function transferFrom(address from, address to, uint256 id) public nonReentrant override { _transferFrom(from, to, id); } function safeTransferFrom(address from, address to, uint256 id) public nonReentrant override { _transferFrom(from, to, id); // interactions: check destination can handle ERC721 require( to.code.length == 0 || ERC721TokenReceiver(to).onERC721Received(msg.sender, from, id, "") == ERC721TokenReceiver.onERC721Received.selector, "UNSAFE_RECIPIENT" ); } function safeTransferFrom(address from, address to, uint256 id, bytes memory /* data */) public nonReentrant override { _transferFrom(from, to, id); // interactions: check destination can handle ERC721 require( to.code.length == 0 || ERC721TokenReceiver(to).onERC721Received(msg.sender, from, id, "") == ERC721TokenReceiver.onERC721Received.selector, "UNSAFE_RECIPIENT" ); } ////////////////////////////////////////////////////////////////////////// // // // Charity Splitter // // // ////////////////////////////////////////////////////////////////////////// /// @notice Withdraw charity balance to charity address. /// @dev Anyone can call this at any time. function withdrawCharityBalance() public nonReentrant { _withdrawCharityBalance(); } /// @notice Withdraw owner balance to the specified address. /// @param destination the address that receives the owner balance. function withdrawOwnerBalance(address payable destination) public onlyOwner nonReentrant { _withdrawOwnerBalance(destination); } /// @notice Update the address that receives the charity fee. /// @param charity the new charity address. function updateCharity(address payable charity) public onlyOwner nonReentrant { _updateCharity(charity); } ////////////////////////////////////////////////////////////////////////// // // // Timezone Management // // // ////////////////////////////////////////////////////////////////////////// mapping(uint256 => int128) public timeOffsetMinutes; event TimeOffsetUpdated(uint256 indexed id, int128 offsetMinutes); /// @notice Sets the time offset of the given token id. /// @dev Use minutes because some timezones (like IST) are offset by half an hour. /// @param id the NFT unique id. /// @param offsetMinutes the offset in minutes. function setTimeOffsetMinutes(uint256 id, int128 offsetMinutes) public { // checks: id exists if (ownerOf[id] == address(0)) { revert EthTime__DoesNotExist(); } // checks: sender is owner. if (ownerOf[id] != msg.sender) { revert EthTime__NotOwner(); } // checks: validate time offset _validateTimeOffset(offsetMinutes); // effects: update time offset timeOffsetMinutes[id] = offsetMinutes; emit TimeOffsetUpdated(id, offsetMinutes); } function _validateTimeOffset(int128 offsetMinutes) internal { int128 offsetSeconds = offsetMinutes * 60; // checks: offset is [-12, +14] hours UTC if (offsetSeconds > 14 hours || offsetSeconds < -12 hours) { revert EthTime__InvalidTimeOffset(); } } ////////////////////////////////////////////////////////////////////////// // // // Minting // // // ////////////////////////////////////////////////////////////////////////// /// @dev The number of tokens minted. uint256 public totalSupply; /// @dev The maximum number of mintable tokens. uint256 public constant maximumSupply = 100; uint256 private constant TARGET_PRICE = 1 ether; uint256 private constant PRICE_INCREMENT = TARGET_PRICE / maximumSupply * 2; /// @notice Mint a new NFT, transfering ownership to the given account. /// @dev If the token id already exists, this method fails. /// @param to the NFT ower. /// @param offsetMinutes the time offset in minutes. /// @param id the NFT unique id. function mint(address to, int128 offsetMinutes, uint256 id) public payable nonReentrant virtual { // interactions: mint. uint256 valueLeft = _mint(to, offsetMinutes, id, msg.value); // interactions: send back leftover value. if (valueLeft > 0) { (bool success, ) = msg.sender.call{value: valueLeft}(""); require(success); } } /// @notice Mint new NFTs, transfering ownership to the given account. /// @dev If any of the token ids already exists, this method fails. /// @param to the NFT ower. /// @param offsetMinutes the time offset in minutes. /// @param ids the NFT unique ids. function batchMint(address to, int128 offsetMinutes, uint256[] calldata ids) public payable nonReentrant virtual { uint256 count = ids.length; // checks: can mint count nfts _validateBatchMintCount(count); uint256 valueLeft = msg.value; for (uint256 i = 0; i < count; i++) { // interactions: mint. valueLeft = _mint(to, offsetMinutes, ids[i], valueLeft); } // interactions: send back leftover value. if (valueLeft > 0) { (bool success, ) = msg.sender.call{value: valueLeft}(""); require(success); } } /// @notice Get the price for minting the next `count` NFT. function getBatchMintPrice(uint256 count) public view returns (uint256) { // checks: can mint count nfts _validateBatchMintCount(count); uint256 supply = totalSupply; uint256 price = 0; for (uint256 i = 0; i < count; i++) { price += _priceAtSupplyLevel(supply + i); } return price; } /// @notice Get the price for minting the next NFT. function getMintPrice() public view returns (uint256) { return _priceAtSupplyLevel(totalSupply); } function _mint(address to, int128 offsetMinutes, uint256 id, uint256 value) internal returns (uint256 valueLeft) { uint256 price = _priceAtSupplyLevel(totalSupply); // checks: value is enough to mint the nft. if (value < price) { revert EthTime__InvalidMintValue(); } // checks: minting causes going over maximum supply. if (totalSupply == maximumSupply) { revert EthTime__CollectionMintClosed(); } // checks: validate offset _validateTimeOffset(offsetMinutes); // effects: seed history with unique starting value. historyAccumulator[id] = uint160(id >> 4); // effects: increment total supply. totalSupply += 1; // effects: update charity split. _updateBalance(value); // effects: set time offset timeOffsetMinutes[id] = offsetMinutes; // interactions: safe mint _safeMint(to, id); // return value left to be sent back to user. valueLeft = value - price; } function _priceAtSupplyLevel(uint256 supply) internal pure returns (uint256) { uint256 price = supply * PRICE_INCREMENT; if (supply > 50) { price = TARGET_PRICE; } return price; } function _validateBatchMintCount(uint256 count) internal view { // checks: no more than 10. if (count > 10) { revert EthTime__InvalidMintAmount(); } // checks: minting does not push over the limit. // notice that it would fail anyway. if (totalSupply + count > maximumSupply) { revert EthTime__InvalidMintAmount(); } } ////////////////////////////////////////////////////////////////////////// // // // Token URI // // // ////////////////////////////////////////////////////////////////////////// /// @notice Returns the URI with the NFT metadata. /// @dev Returns the base64 encoded metadata inline. /// @param id the NFT unique id function tokenURI(uint256 id) public view override returns (string memory) { if (ownerOf[id] == address(0)) { revert EthTime__DoesNotExist(); } string memory tokenId = Strings.toString(id); (uint256 hour, uint256 minute) = _adjustedHourMinutes(id); bytes memory topHue = _computeHue(historyAccumulator[id], id); bytes memory bottomHue = _computeHue(uint160(ownerOf[id]), id); int128 offset = timeOffsetMinutes[id]; bytes memory offsetSign = offset >= 0 ? bytes('+') : bytes('-'); uint256 offsetUnsigned = offset >= 0 ? uint256(int256(offset)) : uint256(int256(-offset)); return string( bytes.concat( 'data:application/json;base64,', bytes( Base64.encode( bytes.concat( '{"name": "ETH Time #', bytes(tokenId), '", "description": "ETH Time", "image": "data:image/svg+xml;base64,', bytes(_tokenImage(topHue, bottomHue, hour, minute)), '", "attributes": [{"trait_type": "top_color", "value": "hsl(', topHue, ',100%,89%)"},', '{"trait_type": "bottom_color", "value": "hsl(', bottomHue, ',77%,36%)"},', '{"trait_type": "time_offset", "value": "', offsetSign, bytes(Strings.toString(offsetUnsigned)), '"},', '{"trait_type": "time", "value": "', bytes(Strings.toString(hour)), ':', bytes(Strings.toString(minute)), '"}]}' ) ) ) ) ); } /// @dev Generate a preview of the token that will be minted. /// @param to the minter. /// @param id the NFT unique id. function tokenImagePreview(address to, uint256 id) public view returns (string memory) { (uint256 hour, uint256 minute) = _adjustedHourMinutes(id); bytes memory topHue = _computeHue(uint160(id >> 4), id); bytes memory bottomHue = _computeHue(uint160(to), id); return _tokenImage(topHue, bottomHue, hour, minute); } ////////////////////////////////////////////////////////////////////////// // // // Private Functions // // // ////////////////////////////////////////////////////////////////////////// /// @dev Update the NFT history based on the transfer to the given account. /// @param to the address that will receive the nft. /// @param id the NFT unique id. function _updateHistory(address to, uint256 id) internal { // effects: xor existing value with address bytes content. historyAccumulator[id] ^= uint160(to) << 2; } function _transferFrom(address from, address to, uint256 id) internal { // checks: sender and destination require(from == ownerOf[id], "WRONG_FROM"); require(to != address(0), "INVALID_RECIPIENT"); // checks: can transfer require( msg.sender == from || msg.sender == getApproved[id] || isApprovedForAll[from][msg.sender], "NOT_AUTHORIZED" ); // effects: update balance // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. unchecked { balanceOf[from]--; balanceOf[to]++; } // effects: update owership ownerOf[id] = to; // effects: reclaim storage delete getApproved[id]; // effects: update history _updateHistory(to, id); emit Transfer(from, to, id); } bytes constant onColor = "FFF"; bytes constant offColor = "333"; /// @dev Generate the SVG image for the given NFT. function _tokenImage(bytes memory topHue, bytes memory bottomHue, uint256 hour, uint256 minute) internal pure returns (string memory) { return Base64.encode( bytes.concat( '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1000 1000">', '<linearGradient id="bg" gradientTransform="rotate(90)">', '<stop offset="0%" stop-color="hsl(', topHue, ',100%,89%)"/>', '<stop offset="100%" stop-color="hsl(', bottomHue, ',77%,36%)"/>', '</linearGradient>', '<rect x="0" y="0" width="1000" height="1000" fill="url(#bg)"/>', _binaryHour(hour), _binaryMinute(minute), '</svg>' ) ); } function _binaryHour(uint256 hour) internal pure returns (bytes memory) { if (hour > 24) { revert EthTime__NumberOutOfRange(); } bytes[7] memory colors = _binaryColor(hour); return bytes.concat( '<circle cx="665" cy="875" r="25" fill="#', colors[0], '"/>', '<circle cx="665" cy="805" r="25" fill="#', colors[1], '"/>', // skip colors[2] '<circle cx="735" cy="875" r="25" fill="#', colors[3], '"/>', '<circle cx="735" cy="805" r="25" fill="#', colors[4], '"/>', '<circle cx="735" cy="735" r="25" fill="#', colors[5], '"/>', '<circle cx="735" cy="665" r="25" fill="#', colors[6], '"/>' ); } function _binaryMinute(uint256 minute) internal pure returns (bytes memory) { if (minute > 59) { revert EthTime__NumberOutOfRange(); } bytes[7] memory colors = _binaryColor(minute); return bytes.concat( '<circle cx="805" cy="875" r="25" fill="#', colors[0], '"/>', '<circle cx="805" cy="805" r="25" fill="#', colors[1], '"/>', '<circle cx="805" cy="735" r="25" fill="#', colors[2], '"/>', '<circle cx="875" cy="875" r="25" fill="#', colors[3], '"/>', '<circle cx="875" cy="805" r="25" fill="#', colors[4], '"/>', '<circle cx="875" cy="735" r="25" fill="#', colors[5], '"/>', '<circle cx="875" cy="665" r="25" fill="#', colors[6], '"/>' ); } /// @dev Returns the colors to be used to display the time. /// The first 3 bytes are used for the first digit, the remaining 4 bytes /// for the second digit. function _binaryColor(uint256 n) internal pure returns (bytes[7] memory) { unchecked { uint256 firstDigit = n / 10; uint256 secondDigit = n % 10; return [ (firstDigit & 0x1 != 0) ? onColor : offColor, (firstDigit & 0x2 != 0) ? onColor : offColor, (firstDigit & 0x4 != 0) ? onColor : offColor, (secondDigit & 0x1 != 0) ? onColor : offColor, (secondDigit & 0x2 != 0) ? onColor : offColor, (secondDigit & 0x4 != 0) ? onColor : offColor, (secondDigit & 0x8 != 0) ? onColor : offColor ]; } } function _computeHue(uint160 n, uint256 id) internal pure returns (bytes memory) { uint160 t = n ^ uint160(id); uint160 acc = t % 360; return bytes(Strings.toString(acc)); } function _adjustedHourMinutes(uint256 id) internal view returns (uint256 hour, uint256 minute) { int256 signedUserTimestamp = int256(block.timestamp) - 60 * timeOffsetMinutes[id]; uint256 userTimestamp; // this won't realistically ever happen if (signedUserTimestamp <= 0) { userTimestamp = 0; } else { userTimestamp = uint256(signedUserTimestamp); } hour = BokkyPooBahsDateTimeLibrary.getHour(userTimestamp); minute = BokkyPooBahsDateTimeLibrary.getMinute(userTimestamp); } }
/// @notice ETH-Time NFT contract.
NatSpecSingleLine
_updateHistory
function _updateHistory(address to, uint256 id) internal { // effects: xor existing value with address bytes content. historyAccumulator[id] ^= uint160(to) << 2; }
////////////////////////////////////////////////////////////////////////// /// @dev Update the NFT history based on the transfer to the given account. /// @param to the address that will receive the nft. /// @param id the NFT unique id.
NatSpecSingleLine
v0.8.10+commit.fc410830
{ "func_code_index": [ 13432, 13631 ] }
8,661
EthTime
EthTime.sol
0xe339d6f5a42e581dce5a479fca0ed02248a6dca4
Solidity
EthTime
contract EthTime is ERC721, CharitySplitter, Ownable, ReentrancyGuard { ////////////////////////////////////////////////////////////////////////// // // // Constructor // // // ////////////////////////////////////////////////////////////////////////// constructor(address payable charity, uint256 charityFeeBp) ERC721("ETH Time", "ETHT") CharitySplitter(charity, charityFeeBp) { } receive() external payable {} ////////////////////////////////////////////////////////////////////////// // // // Transfer with History // // // ////////////////////////////////////////////////////////////////////////// /// @notice The state of each NFT. mapping(uint256 => uint160) public historyAccumulator; function transferFrom(address from, address to, uint256 id) public nonReentrant override { _transferFrom(from, to, id); } function safeTransferFrom(address from, address to, uint256 id) public nonReentrant override { _transferFrom(from, to, id); // interactions: check destination can handle ERC721 require( to.code.length == 0 || ERC721TokenReceiver(to).onERC721Received(msg.sender, from, id, "") == ERC721TokenReceiver.onERC721Received.selector, "UNSAFE_RECIPIENT" ); } function safeTransferFrom(address from, address to, uint256 id, bytes memory /* data */) public nonReentrant override { _transferFrom(from, to, id); // interactions: check destination can handle ERC721 require( to.code.length == 0 || ERC721TokenReceiver(to).onERC721Received(msg.sender, from, id, "") == ERC721TokenReceiver.onERC721Received.selector, "UNSAFE_RECIPIENT" ); } ////////////////////////////////////////////////////////////////////////// // // // Charity Splitter // // // ////////////////////////////////////////////////////////////////////////// /// @notice Withdraw charity balance to charity address. /// @dev Anyone can call this at any time. function withdrawCharityBalance() public nonReentrant { _withdrawCharityBalance(); } /// @notice Withdraw owner balance to the specified address. /// @param destination the address that receives the owner balance. function withdrawOwnerBalance(address payable destination) public onlyOwner nonReentrant { _withdrawOwnerBalance(destination); } /// @notice Update the address that receives the charity fee. /// @param charity the new charity address. function updateCharity(address payable charity) public onlyOwner nonReentrant { _updateCharity(charity); } ////////////////////////////////////////////////////////////////////////// // // // Timezone Management // // // ////////////////////////////////////////////////////////////////////////// mapping(uint256 => int128) public timeOffsetMinutes; event TimeOffsetUpdated(uint256 indexed id, int128 offsetMinutes); /// @notice Sets the time offset of the given token id. /// @dev Use minutes because some timezones (like IST) are offset by half an hour. /// @param id the NFT unique id. /// @param offsetMinutes the offset in minutes. function setTimeOffsetMinutes(uint256 id, int128 offsetMinutes) public { // checks: id exists if (ownerOf[id] == address(0)) { revert EthTime__DoesNotExist(); } // checks: sender is owner. if (ownerOf[id] != msg.sender) { revert EthTime__NotOwner(); } // checks: validate time offset _validateTimeOffset(offsetMinutes); // effects: update time offset timeOffsetMinutes[id] = offsetMinutes; emit TimeOffsetUpdated(id, offsetMinutes); } function _validateTimeOffset(int128 offsetMinutes) internal { int128 offsetSeconds = offsetMinutes * 60; // checks: offset is [-12, +14] hours UTC if (offsetSeconds > 14 hours || offsetSeconds < -12 hours) { revert EthTime__InvalidTimeOffset(); } } ////////////////////////////////////////////////////////////////////////// // // // Minting // // // ////////////////////////////////////////////////////////////////////////// /// @dev The number of tokens minted. uint256 public totalSupply; /// @dev The maximum number of mintable tokens. uint256 public constant maximumSupply = 100; uint256 private constant TARGET_PRICE = 1 ether; uint256 private constant PRICE_INCREMENT = TARGET_PRICE / maximumSupply * 2; /// @notice Mint a new NFT, transfering ownership to the given account. /// @dev If the token id already exists, this method fails. /// @param to the NFT ower. /// @param offsetMinutes the time offset in minutes. /// @param id the NFT unique id. function mint(address to, int128 offsetMinutes, uint256 id) public payable nonReentrant virtual { // interactions: mint. uint256 valueLeft = _mint(to, offsetMinutes, id, msg.value); // interactions: send back leftover value. if (valueLeft > 0) { (bool success, ) = msg.sender.call{value: valueLeft}(""); require(success); } } /// @notice Mint new NFTs, transfering ownership to the given account. /// @dev If any of the token ids already exists, this method fails. /// @param to the NFT ower. /// @param offsetMinutes the time offset in minutes. /// @param ids the NFT unique ids. function batchMint(address to, int128 offsetMinutes, uint256[] calldata ids) public payable nonReentrant virtual { uint256 count = ids.length; // checks: can mint count nfts _validateBatchMintCount(count); uint256 valueLeft = msg.value; for (uint256 i = 0; i < count; i++) { // interactions: mint. valueLeft = _mint(to, offsetMinutes, ids[i], valueLeft); } // interactions: send back leftover value. if (valueLeft > 0) { (bool success, ) = msg.sender.call{value: valueLeft}(""); require(success); } } /// @notice Get the price for minting the next `count` NFT. function getBatchMintPrice(uint256 count) public view returns (uint256) { // checks: can mint count nfts _validateBatchMintCount(count); uint256 supply = totalSupply; uint256 price = 0; for (uint256 i = 0; i < count; i++) { price += _priceAtSupplyLevel(supply + i); } return price; } /// @notice Get the price for minting the next NFT. function getMintPrice() public view returns (uint256) { return _priceAtSupplyLevel(totalSupply); } function _mint(address to, int128 offsetMinutes, uint256 id, uint256 value) internal returns (uint256 valueLeft) { uint256 price = _priceAtSupplyLevel(totalSupply); // checks: value is enough to mint the nft. if (value < price) { revert EthTime__InvalidMintValue(); } // checks: minting causes going over maximum supply. if (totalSupply == maximumSupply) { revert EthTime__CollectionMintClosed(); } // checks: validate offset _validateTimeOffset(offsetMinutes); // effects: seed history with unique starting value. historyAccumulator[id] = uint160(id >> 4); // effects: increment total supply. totalSupply += 1; // effects: update charity split. _updateBalance(value); // effects: set time offset timeOffsetMinutes[id] = offsetMinutes; // interactions: safe mint _safeMint(to, id); // return value left to be sent back to user. valueLeft = value - price; } function _priceAtSupplyLevel(uint256 supply) internal pure returns (uint256) { uint256 price = supply * PRICE_INCREMENT; if (supply > 50) { price = TARGET_PRICE; } return price; } function _validateBatchMintCount(uint256 count) internal view { // checks: no more than 10. if (count > 10) { revert EthTime__InvalidMintAmount(); } // checks: minting does not push over the limit. // notice that it would fail anyway. if (totalSupply + count > maximumSupply) { revert EthTime__InvalidMintAmount(); } } ////////////////////////////////////////////////////////////////////////// // // // Token URI // // // ////////////////////////////////////////////////////////////////////////// /// @notice Returns the URI with the NFT metadata. /// @dev Returns the base64 encoded metadata inline. /// @param id the NFT unique id function tokenURI(uint256 id) public view override returns (string memory) { if (ownerOf[id] == address(0)) { revert EthTime__DoesNotExist(); } string memory tokenId = Strings.toString(id); (uint256 hour, uint256 minute) = _adjustedHourMinutes(id); bytes memory topHue = _computeHue(historyAccumulator[id], id); bytes memory bottomHue = _computeHue(uint160(ownerOf[id]), id); int128 offset = timeOffsetMinutes[id]; bytes memory offsetSign = offset >= 0 ? bytes('+') : bytes('-'); uint256 offsetUnsigned = offset >= 0 ? uint256(int256(offset)) : uint256(int256(-offset)); return string( bytes.concat( 'data:application/json;base64,', bytes( Base64.encode( bytes.concat( '{"name": "ETH Time #', bytes(tokenId), '", "description": "ETH Time", "image": "data:image/svg+xml;base64,', bytes(_tokenImage(topHue, bottomHue, hour, minute)), '", "attributes": [{"trait_type": "top_color", "value": "hsl(', topHue, ',100%,89%)"},', '{"trait_type": "bottom_color", "value": "hsl(', bottomHue, ',77%,36%)"},', '{"trait_type": "time_offset", "value": "', offsetSign, bytes(Strings.toString(offsetUnsigned)), '"},', '{"trait_type": "time", "value": "', bytes(Strings.toString(hour)), ':', bytes(Strings.toString(minute)), '"}]}' ) ) ) ) ); } /// @dev Generate a preview of the token that will be minted. /// @param to the minter. /// @param id the NFT unique id. function tokenImagePreview(address to, uint256 id) public view returns (string memory) { (uint256 hour, uint256 minute) = _adjustedHourMinutes(id); bytes memory topHue = _computeHue(uint160(id >> 4), id); bytes memory bottomHue = _computeHue(uint160(to), id); return _tokenImage(topHue, bottomHue, hour, minute); } ////////////////////////////////////////////////////////////////////////// // // // Private Functions // // // ////////////////////////////////////////////////////////////////////////// /// @dev Update the NFT history based on the transfer to the given account. /// @param to the address that will receive the nft. /// @param id the NFT unique id. function _updateHistory(address to, uint256 id) internal { // effects: xor existing value with address bytes content. historyAccumulator[id] ^= uint160(to) << 2; } function _transferFrom(address from, address to, uint256 id) internal { // checks: sender and destination require(from == ownerOf[id], "WRONG_FROM"); require(to != address(0), "INVALID_RECIPIENT"); // checks: can transfer require( msg.sender == from || msg.sender == getApproved[id] || isApprovedForAll[from][msg.sender], "NOT_AUTHORIZED" ); // effects: update balance // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. unchecked { balanceOf[from]--; balanceOf[to]++; } // effects: update owership ownerOf[id] = to; // effects: reclaim storage delete getApproved[id]; // effects: update history _updateHistory(to, id); emit Transfer(from, to, id); } bytes constant onColor = "FFF"; bytes constant offColor = "333"; /// @dev Generate the SVG image for the given NFT. function _tokenImage(bytes memory topHue, bytes memory bottomHue, uint256 hour, uint256 minute) internal pure returns (string memory) { return Base64.encode( bytes.concat( '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1000 1000">', '<linearGradient id="bg" gradientTransform="rotate(90)">', '<stop offset="0%" stop-color="hsl(', topHue, ',100%,89%)"/>', '<stop offset="100%" stop-color="hsl(', bottomHue, ',77%,36%)"/>', '</linearGradient>', '<rect x="0" y="0" width="1000" height="1000" fill="url(#bg)"/>', _binaryHour(hour), _binaryMinute(minute), '</svg>' ) ); } function _binaryHour(uint256 hour) internal pure returns (bytes memory) { if (hour > 24) { revert EthTime__NumberOutOfRange(); } bytes[7] memory colors = _binaryColor(hour); return bytes.concat( '<circle cx="665" cy="875" r="25" fill="#', colors[0], '"/>', '<circle cx="665" cy="805" r="25" fill="#', colors[1], '"/>', // skip colors[2] '<circle cx="735" cy="875" r="25" fill="#', colors[3], '"/>', '<circle cx="735" cy="805" r="25" fill="#', colors[4], '"/>', '<circle cx="735" cy="735" r="25" fill="#', colors[5], '"/>', '<circle cx="735" cy="665" r="25" fill="#', colors[6], '"/>' ); } function _binaryMinute(uint256 minute) internal pure returns (bytes memory) { if (minute > 59) { revert EthTime__NumberOutOfRange(); } bytes[7] memory colors = _binaryColor(minute); return bytes.concat( '<circle cx="805" cy="875" r="25" fill="#', colors[0], '"/>', '<circle cx="805" cy="805" r="25" fill="#', colors[1], '"/>', '<circle cx="805" cy="735" r="25" fill="#', colors[2], '"/>', '<circle cx="875" cy="875" r="25" fill="#', colors[3], '"/>', '<circle cx="875" cy="805" r="25" fill="#', colors[4], '"/>', '<circle cx="875" cy="735" r="25" fill="#', colors[5], '"/>', '<circle cx="875" cy="665" r="25" fill="#', colors[6], '"/>' ); } /// @dev Returns the colors to be used to display the time. /// The first 3 bytes are used for the first digit, the remaining 4 bytes /// for the second digit. function _binaryColor(uint256 n) internal pure returns (bytes[7] memory) { unchecked { uint256 firstDigit = n / 10; uint256 secondDigit = n % 10; return [ (firstDigit & 0x1 != 0) ? onColor : offColor, (firstDigit & 0x2 != 0) ? onColor : offColor, (firstDigit & 0x4 != 0) ? onColor : offColor, (secondDigit & 0x1 != 0) ? onColor : offColor, (secondDigit & 0x2 != 0) ? onColor : offColor, (secondDigit & 0x4 != 0) ? onColor : offColor, (secondDigit & 0x8 != 0) ? onColor : offColor ]; } } function _computeHue(uint160 n, uint256 id) internal pure returns (bytes memory) { uint160 t = n ^ uint160(id); uint160 acc = t % 360; return bytes(Strings.toString(acc)); } function _adjustedHourMinutes(uint256 id) internal view returns (uint256 hour, uint256 minute) { int256 signedUserTimestamp = int256(block.timestamp) - 60 * timeOffsetMinutes[id]; uint256 userTimestamp; // this won't realistically ever happen if (signedUserTimestamp <= 0) { userTimestamp = 0; } else { userTimestamp = uint256(signedUserTimestamp); } hour = BokkyPooBahsDateTimeLibrary.getHour(userTimestamp); minute = BokkyPooBahsDateTimeLibrary.getMinute(userTimestamp); } }
/// @notice ETH-Time NFT contract.
NatSpecSingleLine
_tokenImage
function _tokenImage(bytes memory topHue, bytes memory bottomHue, uint256 hour, uint256 minute) internal pure returns (string memory) { return Base64.encode( bytes.concat( '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1000 1000">', '<linearGradient id="bg" gradientTransform="rotate(90)">', '<stop offset="0%" stop-color="hsl(', topHue, ',100%,89%)"/>', '<stop offset="100%" stop-color="hsl(', bottomHue, ',77%,36%)"/>', '</linearGradient>', '<rect x="0" y="0" width="1000" height="1000" fill="url(#bg)"/>', _binaryHour(hour), _binaryMinute(minute), '</svg>' ) ); }
/// @dev Generate the SVG image for the given NFT.
NatSpecSingleLine
v0.8.10+commit.fc410830
{ "func_code_index": [ 14729, 15583 ] }
8,662
EthTime
EthTime.sol
0xe339d6f5a42e581dce5a479fca0ed02248a6dca4
Solidity
EthTime
contract EthTime is ERC721, CharitySplitter, Ownable, ReentrancyGuard { ////////////////////////////////////////////////////////////////////////// // // // Constructor // // // ////////////////////////////////////////////////////////////////////////// constructor(address payable charity, uint256 charityFeeBp) ERC721("ETH Time", "ETHT") CharitySplitter(charity, charityFeeBp) { } receive() external payable {} ////////////////////////////////////////////////////////////////////////// // // // Transfer with History // // // ////////////////////////////////////////////////////////////////////////// /// @notice The state of each NFT. mapping(uint256 => uint160) public historyAccumulator; function transferFrom(address from, address to, uint256 id) public nonReentrant override { _transferFrom(from, to, id); } function safeTransferFrom(address from, address to, uint256 id) public nonReentrant override { _transferFrom(from, to, id); // interactions: check destination can handle ERC721 require( to.code.length == 0 || ERC721TokenReceiver(to).onERC721Received(msg.sender, from, id, "") == ERC721TokenReceiver.onERC721Received.selector, "UNSAFE_RECIPIENT" ); } function safeTransferFrom(address from, address to, uint256 id, bytes memory /* data */) public nonReentrant override { _transferFrom(from, to, id); // interactions: check destination can handle ERC721 require( to.code.length == 0 || ERC721TokenReceiver(to).onERC721Received(msg.sender, from, id, "") == ERC721TokenReceiver.onERC721Received.selector, "UNSAFE_RECIPIENT" ); } ////////////////////////////////////////////////////////////////////////// // // // Charity Splitter // // // ////////////////////////////////////////////////////////////////////////// /// @notice Withdraw charity balance to charity address. /// @dev Anyone can call this at any time. function withdrawCharityBalance() public nonReentrant { _withdrawCharityBalance(); } /// @notice Withdraw owner balance to the specified address. /// @param destination the address that receives the owner balance. function withdrawOwnerBalance(address payable destination) public onlyOwner nonReentrant { _withdrawOwnerBalance(destination); } /// @notice Update the address that receives the charity fee. /// @param charity the new charity address. function updateCharity(address payable charity) public onlyOwner nonReentrant { _updateCharity(charity); } ////////////////////////////////////////////////////////////////////////// // // // Timezone Management // // // ////////////////////////////////////////////////////////////////////////// mapping(uint256 => int128) public timeOffsetMinutes; event TimeOffsetUpdated(uint256 indexed id, int128 offsetMinutes); /// @notice Sets the time offset of the given token id. /// @dev Use minutes because some timezones (like IST) are offset by half an hour. /// @param id the NFT unique id. /// @param offsetMinutes the offset in minutes. function setTimeOffsetMinutes(uint256 id, int128 offsetMinutes) public { // checks: id exists if (ownerOf[id] == address(0)) { revert EthTime__DoesNotExist(); } // checks: sender is owner. if (ownerOf[id] != msg.sender) { revert EthTime__NotOwner(); } // checks: validate time offset _validateTimeOffset(offsetMinutes); // effects: update time offset timeOffsetMinutes[id] = offsetMinutes; emit TimeOffsetUpdated(id, offsetMinutes); } function _validateTimeOffset(int128 offsetMinutes) internal { int128 offsetSeconds = offsetMinutes * 60; // checks: offset is [-12, +14] hours UTC if (offsetSeconds > 14 hours || offsetSeconds < -12 hours) { revert EthTime__InvalidTimeOffset(); } } ////////////////////////////////////////////////////////////////////////// // // // Minting // // // ////////////////////////////////////////////////////////////////////////// /// @dev The number of tokens minted. uint256 public totalSupply; /// @dev The maximum number of mintable tokens. uint256 public constant maximumSupply = 100; uint256 private constant TARGET_PRICE = 1 ether; uint256 private constant PRICE_INCREMENT = TARGET_PRICE / maximumSupply * 2; /// @notice Mint a new NFT, transfering ownership to the given account. /// @dev If the token id already exists, this method fails. /// @param to the NFT ower. /// @param offsetMinutes the time offset in minutes. /// @param id the NFT unique id. function mint(address to, int128 offsetMinutes, uint256 id) public payable nonReentrant virtual { // interactions: mint. uint256 valueLeft = _mint(to, offsetMinutes, id, msg.value); // interactions: send back leftover value. if (valueLeft > 0) { (bool success, ) = msg.sender.call{value: valueLeft}(""); require(success); } } /// @notice Mint new NFTs, transfering ownership to the given account. /// @dev If any of the token ids already exists, this method fails. /// @param to the NFT ower. /// @param offsetMinutes the time offset in minutes. /// @param ids the NFT unique ids. function batchMint(address to, int128 offsetMinutes, uint256[] calldata ids) public payable nonReentrant virtual { uint256 count = ids.length; // checks: can mint count nfts _validateBatchMintCount(count); uint256 valueLeft = msg.value; for (uint256 i = 0; i < count; i++) { // interactions: mint. valueLeft = _mint(to, offsetMinutes, ids[i], valueLeft); } // interactions: send back leftover value. if (valueLeft > 0) { (bool success, ) = msg.sender.call{value: valueLeft}(""); require(success); } } /// @notice Get the price for minting the next `count` NFT. function getBatchMintPrice(uint256 count) public view returns (uint256) { // checks: can mint count nfts _validateBatchMintCount(count); uint256 supply = totalSupply; uint256 price = 0; for (uint256 i = 0; i < count; i++) { price += _priceAtSupplyLevel(supply + i); } return price; } /// @notice Get the price for minting the next NFT. function getMintPrice() public view returns (uint256) { return _priceAtSupplyLevel(totalSupply); } function _mint(address to, int128 offsetMinutes, uint256 id, uint256 value) internal returns (uint256 valueLeft) { uint256 price = _priceAtSupplyLevel(totalSupply); // checks: value is enough to mint the nft. if (value < price) { revert EthTime__InvalidMintValue(); } // checks: minting causes going over maximum supply. if (totalSupply == maximumSupply) { revert EthTime__CollectionMintClosed(); } // checks: validate offset _validateTimeOffset(offsetMinutes); // effects: seed history with unique starting value. historyAccumulator[id] = uint160(id >> 4); // effects: increment total supply. totalSupply += 1; // effects: update charity split. _updateBalance(value); // effects: set time offset timeOffsetMinutes[id] = offsetMinutes; // interactions: safe mint _safeMint(to, id); // return value left to be sent back to user. valueLeft = value - price; } function _priceAtSupplyLevel(uint256 supply) internal pure returns (uint256) { uint256 price = supply * PRICE_INCREMENT; if (supply > 50) { price = TARGET_PRICE; } return price; } function _validateBatchMintCount(uint256 count) internal view { // checks: no more than 10. if (count > 10) { revert EthTime__InvalidMintAmount(); } // checks: minting does not push over the limit. // notice that it would fail anyway. if (totalSupply + count > maximumSupply) { revert EthTime__InvalidMintAmount(); } } ////////////////////////////////////////////////////////////////////////// // // // Token URI // // // ////////////////////////////////////////////////////////////////////////// /// @notice Returns the URI with the NFT metadata. /// @dev Returns the base64 encoded metadata inline. /// @param id the NFT unique id function tokenURI(uint256 id) public view override returns (string memory) { if (ownerOf[id] == address(0)) { revert EthTime__DoesNotExist(); } string memory tokenId = Strings.toString(id); (uint256 hour, uint256 minute) = _adjustedHourMinutes(id); bytes memory topHue = _computeHue(historyAccumulator[id], id); bytes memory bottomHue = _computeHue(uint160(ownerOf[id]), id); int128 offset = timeOffsetMinutes[id]; bytes memory offsetSign = offset >= 0 ? bytes('+') : bytes('-'); uint256 offsetUnsigned = offset >= 0 ? uint256(int256(offset)) : uint256(int256(-offset)); return string( bytes.concat( 'data:application/json;base64,', bytes( Base64.encode( bytes.concat( '{"name": "ETH Time #', bytes(tokenId), '", "description": "ETH Time", "image": "data:image/svg+xml;base64,', bytes(_tokenImage(topHue, bottomHue, hour, minute)), '", "attributes": [{"trait_type": "top_color", "value": "hsl(', topHue, ',100%,89%)"},', '{"trait_type": "bottom_color", "value": "hsl(', bottomHue, ',77%,36%)"},', '{"trait_type": "time_offset", "value": "', offsetSign, bytes(Strings.toString(offsetUnsigned)), '"},', '{"trait_type": "time", "value": "', bytes(Strings.toString(hour)), ':', bytes(Strings.toString(minute)), '"}]}' ) ) ) ) ); } /// @dev Generate a preview of the token that will be minted. /// @param to the minter. /// @param id the NFT unique id. function tokenImagePreview(address to, uint256 id) public view returns (string memory) { (uint256 hour, uint256 minute) = _adjustedHourMinutes(id); bytes memory topHue = _computeHue(uint160(id >> 4), id); bytes memory bottomHue = _computeHue(uint160(to), id); return _tokenImage(topHue, bottomHue, hour, minute); } ////////////////////////////////////////////////////////////////////////// // // // Private Functions // // // ////////////////////////////////////////////////////////////////////////// /// @dev Update the NFT history based on the transfer to the given account. /// @param to the address that will receive the nft. /// @param id the NFT unique id. function _updateHistory(address to, uint256 id) internal { // effects: xor existing value with address bytes content. historyAccumulator[id] ^= uint160(to) << 2; } function _transferFrom(address from, address to, uint256 id) internal { // checks: sender and destination require(from == ownerOf[id], "WRONG_FROM"); require(to != address(0), "INVALID_RECIPIENT"); // checks: can transfer require( msg.sender == from || msg.sender == getApproved[id] || isApprovedForAll[from][msg.sender], "NOT_AUTHORIZED" ); // effects: update balance // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. unchecked { balanceOf[from]--; balanceOf[to]++; } // effects: update owership ownerOf[id] = to; // effects: reclaim storage delete getApproved[id]; // effects: update history _updateHistory(to, id); emit Transfer(from, to, id); } bytes constant onColor = "FFF"; bytes constant offColor = "333"; /// @dev Generate the SVG image for the given NFT. function _tokenImage(bytes memory topHue, bytes memory bottomHue, uint256 hour, uint256 minute) internal pure returns (string memory) { return Base64.encode( bytes.concat( '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1000 1000">', '<linearGradient id="bg" gradientTransform="rotate(90)">', '<stop offset="0%" stop-color="hsl(', topHue, ',100%,89%)"/>', '<stop offset="100%" stop-color="hsl(', bottomHue, ',77%,36%)"/>', '</linearGradient>', '<rect x="0" y="0" width="1000" height="1000" fill="url(#bg)"/>', _binaryHour(hour), _binaryMinute(minute), '</svg>' ) ); } function _binaryHour(uint256 hour) internal pure returns (bytes memory) { if (hour > 24) { revert EthTime__NumberOutOfRange(); } bytes[7] memory colors = _binaryColor(hour); return bytes.concat( '<circle cx="665" cy="875" r="25" fill="#', colors[0], '"/>', '<circle cx="665" cy="805" r="25" fill="#', colors[1], '"/>', // skip colors[2] '<circle cx="735" cy="875" r="25" fill="#', colors[3], '"/>', '<circle cx="735" cy="805" r="25" fill="#', colors[4], '"/>', '<circle cx="735" cy="735" r="25" fill="#', colors[5], '"/>', '<circle cx="735" cy="665" r="25" fill="#', colors[6], '"/>' ); } function _binaryMinute(uint256 minute) internal pure returns (bytes memory) { if (minute > 59) { revert EthTime__NumberOutOfRange(); } bytes[7] memory colors = _binaryColor(minute); return bytes.concat( '<circle cx="805" cy="875" r="25" fill="#', colors[0], '"/>', '<circle cx="805" cy="805" r="25" fill="#', colors[1], '"/>', '<circle cx="805" cy="735" r="25" fill="#', colors[2], '"/>', '<circle cx="875" cy="875" r="25" fill="#', colors[3], '"/>', '<circle cx="875" cy="805" r="25" fill="#', colors[4], '"/>', '<circle cx="875" cy="735" r="25" fill="#', colors[5], '"/>', '<circle cx="875" cy="665" r="25" fill="#', colors[6], '"/>' ); } /// @dev Returns the colors to be used to display the time. /// The first 3 bytes are used for the first digit, the remaining 4 bytes /// for the second digit. function _binaryColor(uint256 n) internal pure returns (bytes[7] memory) { unchecked { uint256 firstDigit = n / 10; uint256 secondDigit = n % 10; return [ (firstDigit & 0x1 != 0) ? onColor : offColor, (firstDigit & 0x2 != 0) ? onColor : offColor, (firstDigit & 0x4 != 0) ? onColor : offColor, (secondDigit & 0x1 != 0) ? onColor : offColor, (secondDigit & 0x2 != 0) ? onColor : offColor, (secondDigit & 0x4 != 0) ? onColor : offColor, (secondDigit & 0x8 != 0) ? onColor : offColor ]; } } function _computeHue(uint160 n, uint256 id) internal pure returns (bytes memory) { uint160 t = n ^ uint160(id); uint160 acc = t % 360; return bytes(Strings.toString(acc)); } function _adjustedHourMinutes(uint256 id) internal view returns (uint256 hour, uint256 minute) { int256 signedUserTimestamp = int256(block.timestamp) - 60 * timeOffsetMinutes[id]; uint256 userTimestamp; // this won't realistically ever happen if (signedUserTimestamp <= 0) { userTimestamp = 0; } else { userTimestamp = uint256(signedUserTimestamp); } hour = BokkyPooBahsDateTimeLibrary.getHour(userTimestamp); minute = BokkyPooBahsDateTimeLibrary.getMinute(userTimestamp); } }
/// @notice ETH-Time NFT contract.
NatSpecSingleLine
_binaryColor
function _binaryColor(uint256 n) internal pure returns (bytes[7] memory) { unchecked { uint256 firstDigit = n / 10; uint256 secondDigit = n % 10; return [ (firstDigit & 0x1 != 0) ? onColor : offColor, (firstDigit & 0x2 != 0) ? onColor : offColor, (firstDigit & 0x4 != 0) ? onColor : offColor, (secondDigit & 0x1 != 0) ? onColor : offColor, (secondDigit & 0x2 != 0) ? onColor : offColor, (secondDigit & 0x4 != 0) ? onColor : offColor, (secondDigit & 0x8 != 0) ? onColor : offColor ]; } }
/// @dev Returns the colors to be used to display the time. /// The first 3 bytes are used for the first digit, the remaining 4 bytes /// for the second digit.
NatSpecSingleLine
v0.8.10+commit.fc410830
{ "func_code_index": [ 17426, 18126 ] }
8,663
Hollow
Hollow.sol
0x1020e32c0f831f61cc5be9e16ccc2fbc6c6c8369
Solidity
Token
contract Token { /// @return total amount of tokens function totalSupply() constant returns (uint256 supply) {} /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) constant returns (uint256 balance) {} /// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _value) returns (bool success) {} /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {} /// @notice `msg.sender` approves `_addr` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of wei to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint256 _value) returns (bool success) {} /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) constant returns (uint256 remaining) {} event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); }
totalSupply
function totalSupply() constant returns (uint256 supply) {}
/// @return total amount of tokens
NatSpecSingleLine
v0.4.19+commit.c4cbbb05
bzzr://cd5168dea995829c8c8e1370022707b5cba6753761cafcf6a14d88f050325663
{ "func_code_index": [ 60, 124 ] }
8,664
Hollow
Hollow.sol
0x1020e32c0f831f61cc5be9e16ccc2fbc6c6c8369
Solidity
Token
contract Token { /// @return total amount of tokens function totalSupply() constant returns (uint256 supply) {} /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) constant returns (uint256 balance) {} /// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _value) returns (bool success) {} /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {} /// @notice `msg.sender` approves `_addr` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of wei to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint256 _value) returns (bool success) {} /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) constant returns (uint256 remaining) {} event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); }
balanceOf
function balanceOf(address _owner) constant returns (uint256 balance) {}
/// @param _owner The address from which the balance will be retrieved /// @return The balance
NatSpecSingleLine
v0.4.19+commit.c4cbbb05
bzzr://cd5168dea995829c8c8e1370022707b5cba6753761cafcf6a14d88f050325663
{ "func_code_index": [ 232, 309 ] }
8,665
Hollow
Hollow.sol
0x1020e32c0f831f61cc5be9e16ccc2fbc6c6c8369
Solidity
Token
contract Token { /// @return total amount of tokens function totalSupply() constant returns (uint256 supply) {} /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) constant returns (uint256 balance) {} /// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _value) returns (bool success) {} /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {} /// @notice `msg.sender` approves `_addr` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of wei to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint256 _value) returns (bool success) {} /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) constant returns (uint256 remaining) {} event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); }
transfer
function transfer(address _to, uint256 _value) returns (bool success) {}
/// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not
NatSpecSingleLine
v0.4.19+commit.c4cbbb05
bzzr://cd5168dea995829c8c8e1370022707b5cba6753761cafcf6a14d88f050325663
{ "func_code_index": [ 546, 623 ] }
8,666
Hollow
Hollow.sol
0x1020e32c0f831f61cc5be9e16ccc2fbc6c6c8369
Solidity
Token
contract Token { /// @return total amount of tokens function totalSupply() constant returns (uint256 supply) {} /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) constant returns (uint256 balance) {} /// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _value) returns (bool success) {} /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {} /// @notice `msg.sender` approves `_addr` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of wei to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint256 _value) returns (bool success) {} /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) constant returns (uint256 remaining) {} event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); }
transferFrom
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {}
/// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not
NatSpecSingleLine
v0.4.19+commit.c4cbbb05
bzzr://cd5168dea995829c8c8e1370022707b5cba6753761cafcf6a14d88f050325663
{ "func_code_index": [ 946, 1042 ] }
8,667
Hollow
Hollow.sol
0x1020e32c0f831f61cc5be9e16ccc2fbc6c6c8369
Solidity
Token
contract Token { /// @return total amount of tokens function totalSupply() constant returns (uint256 supply) {} /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) constant returns (uint256 balance) {} /// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _value) returns (bool success) {} /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {} /// @notice `msg.sender` approves `_addr` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of wei to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint256 _value) returns (bool success) {} /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) constant returns (uint256 remaining) {} event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); }
approve
function approve(address _spender, uint256 _value) returns (bool success) {}
/// @notice `msg.sender` approves `_addr` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of wei to be approved for transfer /// @return Whether the approval was successful or not
NatSpecSingleLine
v0.4.19+commit.c4cbbb05
bzzr://cd5168dea995829c8c8e1370022707b5cba6753761cafcf6a14d88f050325663
{ "func_code_index": [ 1326, 1407 ] }
8,668
Hollow
Hollow.sol
0x1020e32c0f831f61cc5be9e16ccc2fbc6c6c8369
Solidity
Token
contract Token { /// @return total amount of tokens function totalSupply() constant returns (uint256 supply) {} /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) constant returns (uint256 balance) {} /// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _value) returns (bool success) {} /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {} /// @notice `msg.sender` approves `_addr` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of wei to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint256 _value) returns (bool success) {} /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) constant returns (uint256 remaining) {} event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); }
allowance
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {}
/// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent
NatSpecSingleLine
v0.4.19+commit.c4cbbb05
bzzr://cd5168dea995829c8c8e1370022707b5cba6753761cafcf6a14d88f050325663
{ "func_code_index": [ 1615, 1712 ] }
8,669
Hollow
Hollow.sol
0x1020e32c0f831f61cc5be9e16ccc2fbc6c6c8369
Solidity
Hollow
contract Hollow is StandardToken { function () { //if ether is sent to this address, send it back. throw; } /* Public variables of the token */ /* NOTE: The following variables are OPTIONAL vanities. One does not have to include them. They allow one to customise the token contract & in no way influences the core functionality. Some wallets/interfaces might not even bother to look at this information. */ string public name; //fancy name: eg Simon Bucks uint8 public decimals; //How many decimals to show. ie. There could 1000 base units with 3 decimals. Meaning 0.980 SBX = 980 base units. It's like comparing 1 wei to 1 ether. string public symbol; //An identifier: eg SBX string public version = 'H1.0'; //human 0.1 standard. Just an arbitrary versioning scheme. // // CHANGE THESE VALUES FOR YOUR TOKEN // //make sure this function name matches the contract name above. So if you're token is called TutorialToken, make sure the //contract name above is also TutorialToken instead of ERC20Token function Hollow( ) { balances[msg.sender] = 1618033988749894; // Give the creator all initial tokens (100000 for example) totalSupply = 1618033988749894; // Update total supply (100000 for example) name = "Hollow Coin"; // Set the name for display purposes decimals = 8; // Amount of decimals for display purposes symbol = "HOLLOW"; // Set the symbol for display purposes } /* Approves and then calls the receiving contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); //call the receiveApproval function on the contract you want to be notified. This crafts the function signature manually so one doesn't have to include a contract in here just for this. //receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData) //it is assumed that when does this that the call *should* succeed, otherwise one would use vanilla approve instead. if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; } return true; } }
//name this contract whatever you'd like
LineComment
Hollow
function Hollow( ) { balances[msg.sender] = 1618033988749894; // Give the creator all initial tokens (100000 for example) totalSupply = 1618033988749894; // Update total supply (100000 for example) name = "Hollow Coin"; // Set the name for display purposes decimals = 8; // Amount of decimals for display purposes symbol = "HOLLOW"; // Set the symbol for display purposes }
//human 0.1 standard. Just an arbitrary versioning scheme. // // CHANGE THESE VALUES FOR YOUR TOKEN // //make sure this function name matches the contract name above. So if you're token is called TutorialToken, make sure the //contract name above is also TutorialToken instead of ERC20Token
LineComment
v0.4.19+commit.c4cbbb05
bzzr://cd5168dea995829c8c8e1370022707b5cba6753761cafcf6a14d88f050325663
{ "func_code_index": [ 1155, 1720 ] }
8,670
Hollow
Hollow.sol
0x1020e32c0f831f61cc5be9e16ccc2fbc6c6c8369
Solidity
Hollow
contract Hollow is StandardToken { function () { //if ether is sent to this address, send it back. throw; } /* Public variables of the token */ /* NOTE: The following variables are OPTIONAL vanities. One does not have to include them. They allow one to customise the token contract & in no way influences the core functionality. Some wallets/interfaces might not even bother to look at this information. */ string public name; //fancy name: eg Simon Bucks uint8 public decimals; //How many decimals to show. ie. There could 1000 base units with 3 decimals. Meaning 0.980 SBX = 980 base units. It's like comparing 1 wei to 1 ether. string public symbol; //An identifier: eg SBX string public version = 'H1.0'; //human 0.1 standard. Just an arbitrary versioning scheme. // // CHANGE THESE VALUES FOR YOUR TOKEN // //make sure this function name matches the contract name above. So if you're token is called TutorialToken, make sure the //contract name above is also TutorialToken instead of ERC20Token function Hollow( ) { balances[msg.sender] = 1618033988749894; // Give the creator all initial tokens (100000 for example) totalSupply = 1618033988749894; // Update total supply (100000 for example) name = "Hollow Coin"; // Set the name for display purposes decimals = 8; // Amount of decimals for display purposes symbol = "HOLLOW"; // Set the symbol for display purposes } /* Approves and then calls the receiving contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); //call the receiveApproval function on the contract you want to be notified. This crafts the function signature manually so one doesn't have to include a contract in here just for this. //receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData) //it is assumed that when does this that the call *should* succeed, otherwise one would use vanilla approve instead. if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; } return true; } }
//name this contract whatever you'd like
LineComment
approveAndCall
function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); //call the receiveApproval function on the contract you want to be notified. This crafts the function signature manually so one doesn't have to include a contract in here just for this. //receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData) //it is assumed that when does this that the call *should* succeed, otherwise one would use vanilla approve instead. if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; } return true; }
/* Approves and then calls the receiving contract */
Comment
v0.4.19+commit.c4cbbb05
bzzr://cd5168dea995829c8c8e1370022707b5cba6753761cafcf6a14d88f050325663
{ "func_code_index": [ 1781, 2586 ] }
8,671
Address
Address.sol
0xaaf28fc39e0dc1fa4b1c7f02b034f48b211d3792
Solidity
IERC20
interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); }
totalSupply
function totalSupply() external view returns (uint256);
/** * @dev Returns the amount of tokens in existence. */
NatSpecMultiLine
v0.6.12+commit.27d51765
MIT
ipfs://da9bea1f0f6f0a5e146550ef47bb79e6d7e0ee4d5b464330b11af0c2351c4e00
{ "func_code_index": [ 94, 154 ] }
8,672
Address
Address.sol
0xaaf28fc39e0dc1fa4b1c7f02b034f48b211d3792
Solidity
IERC20
interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); }
balanceOf
function balanceOf(address account) external view returns (uint256);
/** * @dev Returns the amount of tokens owned by `account`. */
NatSpecMultiLine
v0.6.12+commit.27d51765
MIT
ipfs://da9bea1f0f6f0a5e146550ef47bb79e6d7e0ee4d5b464330b11af0c2351c4e00
{ "func_code_index": [ 237, 310 ] }
8,673
Address
Address.sol
0xaaf28fc39e0dc1fa4b1c7f02b034f48b211d3792
Solidity
IERC20
interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); }
transfer
function transfer(address recipient, uint256 amount) external returns (bool);
/** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */
NatSpecMultiLine
v0.6.12+commit.27d51765
MIT
ipfs://da9bea1f0f6f0a5e146550ef47bb79e6d7e0ee4d5b464330b11af0c2351c4e00
{ "func_code_index": [ 534, 616 ] }
8,674
Address
Address.sol
0xaaf28fc39e0dc1fa4b1c7f02b034f48b211d3792
Solidity
IERC20
interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); }
allowance
function allowance(address owner, address spender) external view returns (uint256);
/** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */
NatSpecMultiLine
v0.6.12+commit.27d51765
MIT
ipfs://da9bea1f0f6f0a5e146550ef47bb79e6d7e0ee4d5b464330b11af0c2351c4e00
{ "func_code_index": [ 895, 983 ] }
8,675
Address
Address.sol
0xaaf28fc39e0dc1fa4b1c7f02b034f48b211d3792
Solidity
IERC20
interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); }
approve
function approve(address spender, uint256 amount) external returns (bool);
/** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */
NatSpecMultiLine
v0.6.12+commit.27d51765
MIT
ipfs://da9bea1f0f6f0a5e146550ef47bb79e6d7e0ee4d5b464330b11af0c2351c4e00
{ "func_code_index": [ 1647, 1726 ] }
8,676
Address
Address.sol
0xaaf28fc39e0dc1fa4b1c7f02b034f48b211d3792
Solidity
IERC20
interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); }
transferFrom
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */
NatSpecMultiLine
v0.6.12+commit.27d51765
MIT
ipfs://da9bea1f0f6f0a5e146550ef47bb79e6d7e0ee4d5b464330b11af0c2351c4e00
{ "func_code_index": [ 2039, 2141 ] }
8,677
Address
Address.sol
0xaaf28fc39e0dc1fa4b1c7f02b034f48b211d3792
Solidity
SafeMath
library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } }
add
function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; }
/** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */
NatSpecMultiLine
v0.6.12+commit.27d51765
MIT
ipfs://da9bea1f0f6f0a5e146550ef47bb79e6d7e0ee4d5b464330b11af0c2351c4e00
{ "func_code_index": [ 259, 445 ] }
8,678
Address
Address.sol
0xaaf28fc39e0dc1fa4b1c7f02b034f48b211d3792
Solidity
SafeMath
library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } }
sub
function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); }
/** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */
NatSpecMultiLine
v0.6.12+commit.27d51765
MIT
ipfs://da9bea1f0f6f0a5e146550ef47bb79e6d7e0ee4d5b464330b11af0c2351c4e00
{ "func_code_index": [ 723, 864 ] }
8,679
Address
Address.sol
0xaaf28fc39e0dc1fa4b1c7f02b034f48b211d3792
Solidity
SafeMath
library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } }
sub
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; }
/** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */
NatSpecMultiLine
v0.6.12+commit.27d51765
MIT
ipfs://da9bea1f0f6f0a5e146550ef47bb79e6d7e0ee4d5b464330b11af0c2351c4e00
{ "func_code_index": [ 1162, 1359 ] }
8,680
Address
Address.sol
0xaaf28fc39e0dc1fa4b1c7f02b034f48b211d3792
Solidity
SafeMath
library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } }
mul
function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; }
/** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */
NatSpecMultiLine
v0.6.12+commit.27d51765
MIT
ipfs://da9bea1f0f6f0a5e146550ef47bb79e6d7e0ee4d5b464330b11af0c2351c4e00
{ "func_code_index": [ 1613, 2089 ] }
8,681
Address
Address.sol
0xaaf28fc39e0dc1fa4b1c7f02b034f48b211d3792
Solidity
SafeMath
library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } }
div
function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); }
/** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */
NatSpecMultiLine
v0.6.12+commit.27d51765
MIT
ipfs://da9bea1f0f6f0a5e146550ef47bb79e6d7e0ee4d5b464330b11af0c2351c4e00
{ "func_code_index": [ 2560, 2697 ] }
8,682
Address
Address.sol
0xaaf28fc39e0dc1fa4b1c7f02b034f48b211d3792
Solidity
SafeMath
library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } }
div
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; }
/** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */
NatSpecMultiLine
v0.6.12+commit.27d51765
MIT
ipfs://da9bea1f0f6f0a5e146550ef47bb79e6d7e0ee4d5b464330b11af0c2351c4e00
{ "func_code_index": [ 3188, 3471 ] }
8,683
Address
Address.sol
0xaaf28fc39e0dc1fa4b1c7f02b034f48b211d3792
Solidity
SafeMath
library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } }
mod
function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); }
/** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */
NatSpecMultiLine
v0.6.12+commit.27d51765
MIT
ipfs://da9bea1f0f6f0a5e146550ef47bb79e6d7e0ee4d5b464330b11af0c2351c4e00
{ "func_code_index": [ 3931, 4066 ] }
8,684
Address
Address.sol
0xaaf28fc39e0dc1fa4b1c7f02b034f48b211d3792
Solidity
SafeMath
library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } }
mod
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; }
/** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */
NatSpecMultiLine
v0.6.12+commit.27d51765
MIT
ipfs://da9bea1f0f6f0a5e146550ef47bb79e6d7e0ee4d5b464330b11af0c2351c4e00
{ "func_code_index": [ 4546, 4717 ] }
8,685
Address
Address.sol
0xaaf28fc39e0dc1fa4b1c7f02b034f48b211d3792
Solidity
Address
library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } }
isContract
function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); }
/** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */
NatSpecMultiLine
v0.6.12+commit.27d51765
MIT
ipfs://da9bea1f0f6f0a5e146550ef47bb79e6d7e0ee4d5b464330b11af0c2351c4e00
{ "func_code_index": [ 606, 1230 ] }
8,686
Address
Address.sol
0xaaf28fc39e0dc1fa4b1c7f02b034f48b211d3792
Solidity
Address
library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } }
sendValue
function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); }
/** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */
NatSpecMultiLine
v0.6.12+commit.27d51765
MIT
ipfs://da9bea1f0f6f0a5e146550ef47bb79e6d7e0ee4d5b464330b11af0c2351c4e00
{ "func_code_index": [ 2160, 2562 ] }
8,687
Address
Address.sol
0xaaf28fc39e0dc1fa4b1c7f02b034f48b211d3792
Solidity
Address
library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } }
functionCall
function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); }
/** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */
NatSpecMultiLine
v0.6.12+commit.27d51765
MIT
ipfs://da9bea1f0f6f0a5e146550ef47bb79e6d7e0ee4d5b464330b11af0c2351c4e00
{ "func_code_index": [ 3318, 3496 ] }
8,688
Address
Address.sol
0xaaf28fc39e0dc1fa4b1c7f02b034f48b211d3792
Solidity
Address
library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } }
functionCall
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); }
/** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */
NatSpecMultiLine
v0.6.12+commit.27d51765
MIT
ipfs://da9bea1f0f6f0a5e146550ef47bb79e6d7e0ee4d5b464330b11af0c2351c4e00
{ "func_code_index": [ 3721, 3922 ] }
8,689
Address
Address.sol
0xaaf28fc39e0dc1fa4b1c7f02b034f48b211d3792
Solidity
Address
library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } }
functionCallWithValue
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); }
/** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */
NatSpecMultiLine
v0.6.12+commit.27d51765
MIT
ipfs://da9bea1f0f6f0a5e146550ef47bb79e6d7e0ee4d5b464330b11af0c2351c4e00
{ "func_code_index": [ 4292, 4523 ] }
8,690
Address
Address.sol
0xaaf28fc39e0dc1fa4b1c7f02b034f48b211d3792
Solidity
Address
library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } }
functionCallWithValue
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); }
/** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */
NatSpecMultiLine
v0.6.12+commit.27d51765
MIT
ipfs://da9bea1f0f6f0a5e146550ef47bb79e6d7e0ee4d5b464330b11af0c2351c4e00
{ "func_code_index": [ 4774, 5095 ] }
8,691
Address
Address.sol
0xaaf28fc39e0dc1fa4b1c7f02b034f48b211d3792
Solidity
Ownable
contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } }
owner
function owner() public view returns (address) { return _owner; }
/** * @dev Returns the address of the current owner. */
NatSpecMultiLine
v0.6.12+commit.27d51765
MIT
ipfs://da9bea1f0f6f0a5e146550ef47bb79e6d7e0ee4d5b464330b11af0c2351c4e00
{ "func_code_index": [ 497, 581 ] }
8,692
Address
Address.sol
0xaaf28fc39e0dc1fa4b1c7f02b034f48b211d3792
Solidity
Ownable
contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } }
renounceOwnership
function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); }
/** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */
NatSpecMultiLine
v0.6.12+commit.27d51765
MIT
ipfs://da9bea1f0f6f0a5e146550ef47bb79e6d7e0ee4d5b464330b11af0c2351c4e00
{ "func_code_index": [ 1139, 1292 ] }
8,693
Address
Address.sol
0xaaf28fc39e0dc1fa4b1c7f02b034f48b211d3792
Solidity
Ownable
contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } }
transferOwnership
function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; }
/** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */
NatSpecMultiLine
v0.6.12+commit.27d51765
MIT
ipfs://da9bea1f0f6f0a5e146550ef47bb79e6d7e0ee4d5b464330b11af0c2351c4e00
{ "func_code_index": [ 1442, 1691 ] }
8,694
DODONFTRegistry
contracts/Factory/Registries/DODONFTRegistry.sol
0xa7263eb38b9a61b72397c884b5f9bfb5c34a7840
Solidity
DODONFTRegistry
contract DODONFTRegistry is InitializableOwnable, IDODONFTRegistry { mapping (address => bool) public isAdminListed; // ============ Registry ============ // Vault -> Frag mapping(address => address) public _VAULT_FRAG_REGISTRY_; // base -> quote -> DVM address list mapping(address => mapping(address => address[])) public _REGISTRY_; // ============ Events ============ event NewRegistry( address vault, address fragment, address dvm ); event RemoveRegistry(address fragment); // ============ Admin Operation Functions ============ function addRegistry( address vault, address fragment, address quoteToken, address dvm ) override external { require(isAdminListed[msg.sender], "ACCESS_DENIED"); _VAULT_FRAG_REGISTRY_[vault] = fragment; _REGISTRY_[fragment][quoteToken].push(dvm); emit NewRegistry(vault, fragment, dvm); } function removeRegistry(address fragment) override external { require(isAdminListed[msg.sender], "ACCESS_DENIED"); address vault = IFragment(fragment)._COLLATERAL_VAULT_(); address dvm = IFragment(fragment)._DVM_(); _VAULT_FRAG_REGISTRY_[vault] = address(0); address quoteToken = IDVM(dvm)._QUOTE_TOKEN_(); address[] memory registryList = _REGISTRY_[fragment][quoteToken]; for (uint256 i = 0; i < registryList.length; i++) { if (registryList[i] == dvm) { if(i != registryList.length - 1) { _REGISTRY_[fragment][quoteToken][i] = _REGISTRY_[fragment][quoteToken][registryList.length - 1]; } _REGISTRY_[fragment][quoteToken].pop(); break; } } emit RemoveRegistry(fragment); } function addAdminList (address contractAddr) external onlyOwner { isAdminListed[contractAddr] = true; } function removeAdminList (address contractAddr) external onlyOwner { isAdminListed[contractAddr] = false; } function getDODOPool(address baseToken, address quoteToken) external view returns (address[] memory pools) { return _REGISTRY_[baseToken][quoteToken]; } function getDODOPoolBidirection(address token0, address token1) external view returns (address[] memory baseToken0Pool, address[] memory baseToken1Pool) { return (_REGISTRY_[token0][token1], _REGISTRY_[token1][token0]); } }
/** * @title DODONFT Registry * @author DODO Breeder * * @notice Register DODONFT Pools */
NatSpecMultiLine
addRegistry
function addRegistry( address vault, address fragment, address quoteToken, address dvm ) override external { require(isAdminListed[msg.sender], "ACCESS_DENIED"); _VAULT_FRAG_REGISTRY_[vault] = fragment; _REGISTRY_[fragment][quoteToken].push(dvm); emit NewRegistry(vault, fragment, dvm); }
// ============ Admin Operation Functions ============
LineComment
v0.6.9+commit.3e3065ac
Apache-2.0
ipfs://7b7bfeb5b4504088fc081b5532fb95756fccd6e62f0fcd2e0699633543130769
{ "func_code_index": [ 639, 1015 ] }
8,695
Rug
Rug.sol
0x64c8b0ec48328af632d2ee36ee3852ff98b4360c
Solidity
IERC20
interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); }
/** * @dev Interface of the ERC20 standard as defined in the EIP. */
NatSpecMultiLine
totalSupply
function totalSupply() external view returns (uint256);
/** * @dev Returns the amount of tokens in existence. */
NatSpecMultiLine
v0.6.6+commit.6c089d02
MIT
ipfs://bfb9577c6cd5404043b49b2757b59e8486f69e2b2cc6adb970a9c7c8c7e6e4e5
{ "func_code_index": [ 94, 154 ] }
8,696
Rug
Rug.sol
0x64c8b0ec48328af632d2ee36ee3852ff98b4360c
Solidity
IERC20
interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); }
/** * @dev Interface of the ERC20 standard as defined in the EIP. */
NatSpecMultiLine
balanceOf
function balanceOf(address account) external view returns (uint256);
/** * @dev Returns the amount of tokens owned by `account`. */
NatSpecMultiLine
v0.6.6+commit.6c089d02
MIT
ipfs://bfb9577c6cd5404043b49b2757b59e8486f69e2b2cc6adb970a9c7c8c7e6e4e5
{ "func_code_index": [ 237, 310 ] }
8,697
Rug
Rug.sol
0x64c8b0ec48328af632d2ee36ee3852ff98b4360c
Solidity
IERC20
interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); }
/** * @dev Interface of the ERC20 standard as defined in the EIP. */
NatSpecMultiLine
transfer
function transfer(address recipient, uint256 amount) external returns (bool);
/** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */
NatSpecMultiLine
v0.6.6+commit.6c089d02
MIT
ipfs://bfb9577c6cd5404043b49b2757b59e8486f69e2b2cc6adb970a9c7c8c7e6e4e5
{ "func_code_index": [ 534, 616 ] }
8,698
Rug
Rug.sol
0x64c8b0ec48328af632d2ee36ee3852ff98b4360c
Solidity
IERC20
interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); }
/** * @dev Interface of the ERC20 standard as defined in the EIP. */
NatSpecMultiLine
allowance
function allowance(address owner, address spender) external view returns (uint256);
/** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */
NatSpecMultiLine
v0.6.6+commit.6c089d02
MIT
ipfs://bfb9577c6cd5404043b49b2757b59e8486f69e2b2cc6adb970a9c7c8c7e6e4e5
{ "func_code_index": [ 895, 983 ] }
8,699