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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
TorroDao | TorroDao.sol | 0x3cf9e9d45380b6ab61bde46b2e6cfcd7d8f6cdc1 | Solidity | TorroDao | contract TorroDao is ITorroDao, OwnableUpgradeSafe {
using EnumerableSet for EnumerableSet.AddressSet;
using EnumerableSet for EnumerableSet.UintSet;
using SafeMath for uint256;
// Structs.
/// @notice General proposal structure.
struct Proposal {
uint256 id;
address proposalAddress;
address investTokenAddress;
DaoFunction daoFunction;
uint256 amount;
address creator;
uint256 endLifetime;
EnumerableSet.AddressSet voterAddresses;
uint256 votesFor;
uint256 votesAgainst;
bool executed;
}
// Events.
/// @notice Event for dispatching on new proposal creation.
/// @param id id of the new proposal.
event NewProposal(uint256 id);
/// @notice Event for dispatching when proposal has been removed.
/// @param id id of the removed proposal.
event RemoveProposal(uint256 id);
/// @notice Event for dispatching when someone voted on a proposal.
/// @param id id of the voted proposal.
event Vote(uint256 id);
/// @notice Event for dispatching when an admin has been added to the DAO.
/// @param admin address of the admin that's been added.
event AddAdmin(address admin);
/// @notice Event for dispatching when an admin has been removed from the DAO.
/// @param admin address of the admin that's been removed.
event RemoveAdmin(address admin);
/// @notice Event for dispatching when a proposal has been executed.
/// @param id id of the executed proposal.
event ExecutedProposal(uint256 id);
/// @notice Event for dispatching when cloned DAO tokens have been bought.
event Buy();
/// @notice Event for dispatching when cloned DAO tokens have been sold.
event Sell();
/// @notice Event for dispatching when new holdings addresses have been changed.
event HoldingsAddressesChanged();
/// @notice Event for dipatching when new liquidity addresses have been changed.
event LiquidityAddressesChanged();
// Constants.
// Private data.
address private _creator;
EnumerableSet.AddressSet private _holdings;
EnumerableSet.AddressSet private _liquidityAddresses;
EnumerableSet.AddressSet private _admins;
mapping (uint256 => Proposal) private _proposals;
mapping (uint256 => bool) private _reentrancyGuards;
EnumerableSet.UintSet private _proposalIds;
ITorro private _torroToken;
ITorro private _governingToken;
address private _factory;
uint256 private _latestProposalId;
uint256 private _timeout;
uint256 private _maxCost;
uint256 private _executeMinPct;
uint256 private _votingMinHours;
uint256 private _voteWeightDivider;
uint256 private _lastWithdraw;
uint256 private _spendDivider;
bool private _isPublic;
bool private _isMain;
bool private _hasAdmins;
// ===============
IUniswapV2Router02 private _router;
// Constructor.
/// @notice Constructor for original Torro DAO.
/// @param governingToken_ Torro token address.
constructor(address governingToken_) public {
__Ownable_init();
_torroToken = ITorro(governingToken_);
_governingToken = ITorro(governingToken_);
_factory = address(0x0);
_latestProposalId = 0;
_timeout = uint256(5).mul(1 minutes);
_router = IUniswapV2Router02(address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D));
_maxCost = 0;
_executeMinPct = 5;
_votingMinHours = 6;
_voteWeightDivider = 10000;
_lastWithdraw = block.timestamp.add(1 * 1 weeks);
_spendDivider = 10;
_isMain = true;
_isPublic = true;
_hasAdmins = true;
_creator = msg.sender;
}
/// @notice Initializer for DAO clones.
/// @param torroToken_ main torro token address.
/// @param governingToken_ torro token clone that's governing this dao.
/// @param factory_ torro factory address.
/// @param creator_ creator of cloned DAO.
/// @param maxCost_ maximum cost of all governing tokens for cloned DAO.
/// @param executeMinPct_ minimum percentage of votes needed for proposal execution.
/// @param votingMinHours_ minimum lifetime of proposal before it closes.
/// @param isPublic_ whether cloned DAO has public visibility.
/// @param hasAdmins_ whether cloned DAO has admins, otherwise all stakers are treated as admins.
function initializeCustom(
address torroToken_,
address governingToken_,
address factory_,
address creator_,
uint256 maxCost_,
uint256 executeMinPct_,
uint256 votingMinHours_,
bool isPublic_,
bool hasAdmins_
) public override initializer {
__Ownable_init();
_torroToken = ITorro(torroToken_);
_governingToken = ITorro(governingToken_);
_factory = factory_;
_latestProposalId = 0;
_timeout = uint256(5).mul(1 minutes);
_router = IUniswapV2Router02(address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D));
_maxCost = maxCost_;
_voteWeightDivider = 0;
_executeMinPct = executeMinPct_;
_votingMinHours = votingMinHours_;
_lastWithdraw = block.timestamp;
_spendDivider = 0;
_isMain = false;
_isPublic = isPublic_;
_hasAdmins = hasAdmins_;
_creator = creator_;
if (_hasAdmins) {
_admins.add(creator_);
}
}
// Modifiers.
/// @notice Stops double execution of proposals.
/// @param id_ proposal id that's executing.
modifier nonReentrant(uint256 id_) {
// check that it's already not executing
require(!_reentrancyGuards[id_]);
// toggle state that proposal is currently executing
_reentrancyGuards[id_] = true;
_;
// toggle state back
_reentrancyGuards[id_] = false;
}
/// @notice Allow fund transfers to DAO contract.
receive() external payable {
// do nothing
}
// Public calls.
/// @notice Address of DAO creator.
/// @return DAO creator address.
function daoCreator() public override view returns (address) {
return _creator;
}
/// @notice Amount of tokens needed for a single vote.
/// @return uint256 token amount.
function voteWeight() public override view returns (uint256) {
uint256 weight;
if (_isMain) {
weight = _governingToken.totalSupply() / _voteWeightDivider;
} else {
weight = 10**18;
}
return weight;
}
/// @notice Amount of votes that holder has.
/// @param sender_ address of the holder.
/// @return number of votes.
function votesOf(address sender_) public override view returns (uint256) {
return _governingToken.stakedOf(sender_) / voteWeight();
}
/// @notice Address of the governing token.
/// @return address of the governing token.
function tokenAddress() public override view returns (address) {
return address(_governingToken);
}
/// @notice Saved addresses of tokens that DAO is holding.
/// @return array of holdings addresses.
function holdings() public override view returns (address[] memory) {
uint256 length = _holdings.length();
address[] memory holdingsAddresses = new address[](length);
for (uint256 i = 0; i < length; i++) {
holdingsAddresses[i] = _holdings.at(i);
}
return holdingsAddresses;
}
/// @notice Saved addresses of liquidity tokens that DAO is holding.
/// @return array of liquidity addresses.
function liquidities() public override view returns (address[] memory) {
uint256 length = _liquidityAddresses.length();
address[] memory liquidityAddresses = new address[](length);
for (uint256 i = 0; i < length; i++) {
liquidityAddresses[i] = _liquidityAddresses.at(i);
}
return liquidityAddresses;
}
/// @notice Calculates address of liquidity token from ERC-20 token address.
/// @param token_ token address to calculate liquidity address from.
/// @return address of liquidity token.
function liquidityToken(address token_) public override view returns (address) {
return UniswapV2Library.pairFor(_router.factory(), token_, _router.WETH());
}
/// @notice Gets tokens and liquidity token addresses of DAO's liquidity holdings.
/// @return Arrays of tokens and liquidity tokens, should have the same length.
function liquidityHoldings() public override view returns (address[] memory, address[] memory) {
uint256 length = _liquidityAddresses.length();
address[] memory tokens = new address[](length);
address[] memory liquidityTokens = new address[](length);
for (uint256 i = 0; i < length; i++) {
address token = _liquidityAddresses.at(i);
tokens[i] = token;
liquidityTokens[i] = liquidityToken(token);
}
return (tokens, liquidityTokens);
}
/// @notice DAO admins.
/// @return Array of admin addresses.
function admins() public override view returns (address[] memory) {
uint256 length = _admins.length();
address[] memory currentAdmins = new address[](length);
for (uint256 i = 0; i < length; i++) {
currentAdmins[i] = _admins.at(i);
}
return currentAdmins;
}
/// @notice DAO balance for specified token.
/// @param token_ token address to get balance for.
/// @return uint256 token balance.
function tokenBalance(address token_) public override view returns (uint256) {
return IERC20(token_).balanceOf(address(this));
}
/// @notice DAO balance for liquidity token.
/// @param token_ token address to get liquidity balance for.
/// @return uin256 token liquidity balance.
function liquidityBalance(address token_) public override view returns (uint256) {
return tokenBalance(liquidityToken(token_));
}
/// @notice DAO ethereum balance.
/// @return uint256 wei balance.
function availableBalance() public override view returns (uint256) {
return address(this).balance;
}
/// @notice Maximum cost for all tokens of cloned DAO.
/// @return uint256 maximum cost in wei.
function maxCost() public override view returns (uint256) {
return _maxCost;
}
/// @notice Minimum percentage of votes needed to execute a proposal.
/// @return uint256 minimum percentage of votes.
function executeMinPct() public override view returns (uint256) {
return _executeMinPct;
}
/// @notice Minimum lifetime of proposal before it closes.
/// @return uint256 minimum number of hours for proposal lifetime.
function votingMinHours() public override view returns (uint256) {
return _votingMinHours;
}
/// @notice Whether DAO is public or private.
/// @return bool true if public.
function isPublic() public override view returns (bool) {
return _isPublic;
}
/// @notice Whether DAO has admins.
/// @return bool true if DAO has admins.
function hasAdmins() public override view returns (bool) {
return _hasAdmins;
}
/// @notice Proposal ids of DAO.
/// @return array of proposal ids.
function getProposalIds() public override view returns (uint256[] memory) {
uint256 proposalsLength = _proposalIds.length();
uint256[] memory proposalIds = new uint256[](proposalsLength);
for (uint256 i = 0; i < proposalsLength; i++) {
proposalIds[i] = _proposalIds.at(i);
}
return proposalIds;
}
/// @notice Gets proposal info for proposal id.
/// @param id_ id of proposal to get info for.
/// @return proposalAddress address for proposal execution.
/// @return investTokenAddress secondary address for proposal execution, used for investment proposals if ICO and token addresses differ.
/// @return daoFunction proposal type.
/// @return amount proposal amount eth/token to use during execution.
/// @return creator address of proposal creator.
/// @return endLifetime epoch time when proposal voting ends.
/// @return votesFor amount of votes for the proposal.
/// @return votesAgainst amount of votes against the proposal.
/// @return executed whether proposal has been executed or not.
function getProposal(uint256 id_) public override view returns (
address proposalAddress,
address investTokenAddress,
DaoFunction daoFunction,
uint256 amount,
address creator,
uint256 endLifetime,
uint256 votesFor,
uint256 votesAgainst,
bool executed
) {
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
return (
currentProposal.proposalAddress,
currentProposal.investTokenAddress,
currentProposal.daoFunction,
currentProposal.amount,
currentProposal.creator,
currentProposal.endLifetime,
currentProposal.votesFor,
currentProposal.votesAgainst,
currentProposal.executed
);
}
/// @notice Whether a holder is allowed to vote for a proposal.
/// @param id_ proposal id to check whether holder is allowed to vote for.
/// @param sender_ address of the holder.
/// @return bool true if voting is allowed.
function canVote(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
return proposal.endLifetime >= block.timestamp && proposal.creator != sender_ && !proposal.voterAddresses.contains(sender_);
}
/// @notice Whether a holder is allowed to remove a proposal.
/// @param id_ proposal id to check whether holder is allowed to remove.
/// @param sender_ address of the holder.
/// @return bool true if removal is allowed.
function canRemove(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
return proposal.endLifetime >= block.timestamp && proposal.voterAddresses.length() == 1 && (proposal.creator == sender_ || owner() == sender_);
}
/// @notice Whether a holder is allowed to execute a proposal.
/// @param id_ proposal id to check whether holder is allowed to execute.
/// @param sender_ address of the holder.
/// @return bool true if execution is allowed.
function canExecute(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
// check that proposal hasn't been executed yet.
if (proposal.executed) {
return false;
}
// if custom pool has admins then only admins can execute proposals
if (!_isMain && _hasAdmins) {
if (!isAdmin(sender_)) {
return false;
}
}
if (proposal.daoFunction == DaoFunction.INVEST) {
// for invest functions only admins can execute
if (sender_ != _creator && !_admins.contains(sender_)) {
return false;
}
// check that sender is proposal creator or admin
} else if (proposal.creator != sender_ && !isAdmin(sender_)) {
return false;
}
// For main pool Buy and Sell dao functions allow instant executions if at least 10% of staked supply has voted for it
if (_isMain && (proposal.daoFunction == DaoFunction.BUY || proposal.daoFunction == DaoFunction.SELL)) {
if (proposal.votesFor.mul(voteWeight()) >= _governingToken.stakedSupply() / 10) {
if (proposal.votesFor > proposal.votesAgainst) {
// only allow admins to execute buy and sell proposals early
return isAdmin(sender_);
}
}
}
// check that proposal voting lifetime has run out.
if (proposal.endLifetime > block.timestamp) {
return false;
}
// check that votes for outweigh votes against.
bool currentCanExecute = proposal.votesFor > proposal.votesAgainst;
if (currentCanExecute && _executeMinPct > 0) {
// Check that proposal has at least _executeMinPct% of staked votes.
uint256 minVotes = _governingToken.stakedSupply() / (100 / _executeMinPct);
currentCanExecute = minVotes <= proposal.votesFor.add(proposal.votesAgainst).mul(voteWeight());
}
return currentCanExecute;
}
/// @notice Whether a holder is an admin.
/// @param sender_ address of holder.
/// @return bool true if holder is an admin (in DAO without admins all holders are treated as such).
function isAdmin(address sender_) public override view returns (bool) {
return !_hasAdmins || sender_ == _creator || _admins.contains(sender_);
}
// Public transactions.
/// @notice Saves new holdings addresses for DAO.
/// @param tokens_ token addresses that DAO has holdings of.
function addHoldingsAddresses(address[] memory tokens_) public override {
require(isAdmin(msg.sender));
for (uint256 i = 0; i < tokens_.length; i++) {
address token = tokens_[i];
if (!_holdings.contains(token)) {
_holdings.add(token);
}
}
emit HoldingsAddressesChanged();
}
/// @notice Saves new liquidity addresses for DAO.
/// @param tokens_ token addresses that DAO has liquidities of.
function addLiquidityAddresses(address[] memory tokens_) public override {
require(isAdmin(msg.sender));
for (uint256 i = 0; i < tokens_.length; i++) {
address token = tokens_[i];
if (!_liquidityAddresses.contains(token)) {
_liquidityAddresses.add(token);
}
}
emit LiquidityAddressesChanged();
}
/// @notice Creates new proposal.
/// @param proposalAddress_ main address of the proposal, in investment proposals this is the address funds are sent to.
/// @param investTokenAddress_ secondary address of the proposal, used in investment proposals to specify token address.
/// @param daoFunction_ type of the proposal.
/// @param amount_ amount of funds to use in the proposal.
/// @param hoursLifetime_ voting lifetime of the proposal.
function propose(address proposalAddress_, address investTokenAddress_, DaoFunction daoFunction_, uint256 amount_, uint256 hoursLifetime_) public override {
// check that lifetime is at least equals to min hours set for DAO.
require(hoursLifetime_ >= _votingMinHours);
// Check that proposal creator is allowed to create a proposal.
uint256 balance = _governingToken.stakedOf(msg.sender);
uint256 weight = voteWeight();
require(balance >= weight);
// For main DAO.
if (_isMain) {
if (daoFunction_ == DaoFunction.WITHDRAW || daoFunction_ == DaoFunction.INVEST || daoFunction_ == DaoFunction.BUY) {
// Limit each buy, investment and withdraw proposals to 10% of ETH funds.
require(amount_ <= (availableBalance() / _spendDivider));
}
}
// Increment proposal id counter.
_latestProposalId++;
uint256 currentId = _latestProposalId;
// Calculate end lifetime of the proposal.
uint256 endLifetime = block.timestamp.add(hoursLifetime_.mul(1 hours));
// Declare voter addresses set.
EnumerableSet.AddressSet storage voterAddresses;
// Save proposal struct.
_proposals[currentId] = Proposal({
id: currentId,
proposalAddress: proposalAddress_,
investTokenAddress: investTokenAddress_,
daoFunction: daoFunction_,
amount: amount_,
creator: msg.sender,
endLifetime: endLifetime,
voterAddresses: voterAddresses,
votesFor: balance / weight,
votesAgainst: 0,
executed: false
});
// Save id of new proposal.
_proposalIds.add(currentId);
// Emit event that new proposal has been created.
emit NewProposal(currentId);
}
/// @notice Removes existing proposal.
/// @param id_ id of proposal to remove.
function unpropose(uint256 id_) public override {
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
// Check that proposal creator, owner or an admin is removing a proposal.
require(msg.sender == currentProposal.creator || msg.sender == _creator || _admins.contains(msg.sender));
// Check that no votes have been registered for the proposal apart from the proposal creator, pool creator can remove any proposal.
if (msg.sender != _creator) {
require(currentProposal.voterAddresses.length() == 1);
}
// Remove proposal.
delete _proposals[id_];
_proposalIds.remove(id_);
// Emit event that a proposal has been removed.
emit RemoveProposal(id_);
}
/// @notice Voting for multiple proposals.
/// @param ids_ ids of proposals to vote for.
/// @param votes_ for or against votes for proposals.
function vote(uint256[] memory ids_, bool[] memory votes_) public override {
// Check that arrays of the same length have been supplied.
require(ids_.length == votes_.length);
// Check that voter has enough tokens staked to vote.
uint256 balance = _governingToken.stakedOf(msg.sender);
uint256 weight = voteWeight();
require(balance >= weight);
// Get number of votes that msg.sender has.
uint256 votesCount = balance / weight;
// Iterate over voted proposals.
for (uint256 i = 0; i < ids_.length; i++) {
uint256 id = ids_[i];
bool currentVote = votes_[i];
Proposal storage proposal = _proposals[id];
// Check that proposal hasn't been voted for by msg.sender and that it's still active.
if (!proposal.voterAddresses.contains(msg.sender) && proposal.endLifetime >= block.timestamp) {
// Add votes.
proposal.voterAddresses.add(msg.sender);
if (currentVote) {
proposal.votesFor = proposal.votesFor.add(votesCount);
} else {
proposal.votesAgainst = proposal.votesAgainst.add(votesCount);
}
}
// Emit event that a proposal has been voted for.
emit Vote(id);
}
}
/// @notice Executes a proposal.
/// @param id_ id of proposal to be executed.
function execute(uint256 id_) public override nonReentrant(id_) {
// save gas at the start of execution
uint256 remainingGasStart = gasleft();
// check whether proposal can be executed by the sender
require(canExecute(id_, msg.sender));
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
// Check that msg.sender has balance for at least 1 vote to execute a proposal.
uint256 balance = _governingToken.totalOf(msg.sender);
if (balance < voteWeight()) {
// Remove admin if his balance is not high enough.
if (_admins.contains(msg.sender)) {
_admins.remove(msg.sender);
}
revert();
}
// Call private function for proposal execution depending on the type.
if (currentProposal.daoFunction == DaoFunction.BUY) {
_executeBuy(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.SELL) {
_executeSell(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.ADD_LIQUIDITY) {
_executeAddLiquidity(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.REMOVE_LIQUIDITY) {
_executeRemoveLiquidity(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.ADD_ADMIN) {
_executeAddAdmin(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.REMOVE_ADMIN) {
_executeRemoveAdmin(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.INVEST) {
_executeInvest(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.WITHDRAW) {
_executeWithdraw(currentProposal);
}
// Mark proposal as executed.
currentProposal.executed = true;
// calculate gas used during execution
uint256 remainingGasEnd = gasleft();
uint256 usedGas = remainingGasStart.sub(remainingGasEnd).add(35000);
// max gas price allowed for refund is 200gwei
uint256 gasPrice;
if (tx.gasprice > 200000000000) {
gasPrice = 200000000000;
} else {
gasPrice = tx.gasprice;
}
// refund used gas
payable(msg.sender).transfer(usedGas.mul(gasPrice));
// Emit event that proposal has been executed.
emit ExecutedProposal(id_);
}
/// @notice Buying tokens for cloned DAO.
function buy() public override payable {
// Check that it's not the main DAO.
require(!_isMain);
// Check that msg.sender is not sending more money than max cost of dao.
require(msg.value <= _maxCost);
// Check that DAO has enough tokens to sell to msg.sender.
uint256 portion = _governingToken.totalSupply().mul(msg.value) / _maxCost;
require(_governingToken.balanceOf(address(this)) >= portion);
// Transfer tokens.
_governingToken.transfer(msg.sender, portion);
// Emit event that tokens have been bought.
emit Buy();
}
/// @notice Sell tokens back to cloned DAO.
/// @param amount_ amount of tokens to sell.
function sell(uint256 amount_) public override {
// Check that it's not the main DAO.
require(!_isMain);
// Check that msg.sender has enough tokens to sell.
require(_governingToken.balanceOf(msg.sender) >= amount_);
// Calculate the eth share holder should get back and whether pool has enough funds.
uint256 share = _supplyShare(amount_);
// Approve token transfer for DAO.
_governingToken.approveDao(msg.sender, amount_);
// Transfer tokens from msg.sender back to DAO.
_governingToken.transferFrom(msg.sender, address(this), amount_);
// Refund eth back to the msg.sender.
payable(msg.sender).transfer(share);
// Emit event that tokens have been sold back to DAO.
emit Sell();
}
// Private calls.
/// @notice Calculates cost of share of the supply.
/// @param amount_ amount of tokens to calculate eth share for.
/// @return price for specified amount share.
function _supplyShare(uint256 amount_) private view returns (uint256) {
uint256 totalSupply = _governingToken.totalSupply();
uint256 circulatingSupply = _circulatingSupply(totalSupply);
uint256 circulatingMaxCost = _circulatingMaxCost(circulatingSupply, totalSupply);
// Check whether available balance is higher than circulating max cost.
if (availableBalance() > circulatingMaxCost) {
// If true then share will equal to buy price.
return circulatingMaxCost.mul(amount_) / circulatingSupply;
} else {
// Otherwise calculate share price based on currently available balance.
return availableBalance().mul(amount_) / circulatingSupply;
}
}
/// @notice Calculates max cost for currently circulating supply.
/// @param circulatingSupply_ governing token circulating supply.
/// @param totalSupply_ governing token total supply.
/// @return uint256 eth cost of currently circulating supply.
function _circulatingMaxCost(uint256 circulatingSupply_, uint256 totalSupply_) private view returns (uint256) {
return _maxCost.mul(circulatingSupply_) / totalSupply_;
}
/// @notice Calculates circulating supply of governing token.
/// @param totalSupply_ governing token total supply.
/// @return uint256 number of tokens in circulation.
function _circulatingSupply(uint256 totalSupply_) private view returns (uint256) {
uint256 balance = _governingToken.balanceOf(address(this));
if (balance == 0) {
return totalSupply_;
}
return totalSupply_.sub(balance);
}
// Private transactions.
/// @notice Execution of BUY proposal.
/// @param proposal_ proposal.
function _executeBuy(Proposal storage proposal_) private {
// Check that DAO has enough funds to execute buy proposal.
require(availableBalance() >= proposal_.amount);
// Deposit eth funds to Uniswap router.
IWETH weth = IWETH(_router.WETH());
weth.deposit{value: proposal_.amount}();
// Create path for buying, buying is only for Token-ETH pair.
address[] memory path = new address[](2);
path[0] = address(weth);
path[1] = proposal_.proposalAddress;
// Execute uniswap buy.
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), path[0], path[1]);
uint256 amountOut = UniswapV2Library.getAmountOut(proposal_.amount, reserveA, reserveB);
_router.swapExactETHForTokens{value: proposal_.amount}(amountOut, path, address(this), block.timestamp.add(_timeout));
// If new token then save it holdings addresses.
if (!_holdings.contains(proposal_.proposalAddress)) {
_holdings.add(proposal_.proposalAddress);
// Emit event that holdings addresses changed.
emit HoldingsAddressesChanged();
}
}
/// @notice Execution of SELL proposal.
/// @param proposal_ proposal.
function _executeSell(Proposal storage proposal_) private {
// Approve uniswap router to sell tokens.
IERC20 token = IERC20(proposal_.proposalAddress);
require(token.approve(address(_router), proposal_.amount));
// Create path for selling, selling is only for Token-ETH pair.
address[] memory path = new address[](2);
path[0] = proposal_.proposalAddress;
path[1] = _router.WETH();
// Execute uniswap sell.
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), path[0], path[1]);
uint256 amountOut = UniswapV2Library.getAmountOut(proposal_.amount, reserveA, reserveB);
_router.swapExactTokensForETH(proposal_.amount, amountOut, path, address(this), block.timestamp.add(_timeout));
// If sold all tokens then remove it from holdings.
if (token.balanceOf(address(this)) == 0 && _holdings.contains(proposal_.proposalAddress)) {
_holdings.remove(proposal_.proposalAddress);
// Emit event that holdings addresses changed.
emit HoldingsAddressesChanged();
}
}
/// @notice Execution of ADD_LIQUIDITY proposal.
/// @param proposal_ proposal.
function _executeAddLiquidity(Proposal storage proposal_) private {
// Approve uniswap route to transfer tokens.
require(IERC20(proposal_.proposalAddress).approve(address(_router), proposal_.amount));
// Calculate amount of tokens and eth needed for liquidity.
IWETH weth = IWETH(_router.WETH());
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), proposal_.proposalAddress, address(weth));
uint256 wethAmount = UniswapV2Library.quote(proposal_.amount, reserveA, reserveB);
// Check that DAO has sufficient eth balance for liquidity.
require (availableBalance() > wethAmount);
// Deposit eth for liqudity.
weth.deposit{value: wethAmount}();
// Execute uniswap add liquidity.
_router.addLiquidityETH{value: wethAmount}(
proposal_.proposalAddress,
proposal_.amount,
(proposal_.amount / 100).mul(98),
(wethAmount / 100).mul(98),
address(this),
block.timestamp.add(_timeout)
);
// If new liquidity token then save it.
if (!_liquidityAddresses.contains(proposal_.proposalAddress)) {
_liquidityAddresses.add(proposal_.proposalAddress);
// Emit event that liquidity addresses changed.
emit LiquidityAddressesChanged();
}
}
/// @notice Execution of REMOVE_LIQUIDITY proposal.
/// @param proposal_ proposal.
function _executeRemoveLiquidity(Proposal storage proposal_) private {
// Approve uniswap router to transfer liquidity tokens.
address liquidityTokenAddress = liquidityToken(proposal_.proposalAddress);
require(IERC20(liquidityTokenAddress).approve(address(_router), proposal_.amount));
// Execute uniswap liquidity removal.
_router.removeLiquidityETH(
proposal_.proposalAddress,
proposal_.amount,
0,
0,
address(this),
block.timestamp.add(_timeout)
);
// If all tokens have been sold then remove liquidty address.
if (tokenBalance(liquidityTokenAddress) == 0 && _liquidityAddresses.contains(proposal_.proposalAddress)) {
_liquidityAddresses.remove(proposal_.proposalAddress);
// Emit event that liquidity addresses have changed.
emit LiquidityAddressesChanged();
}
}
/// @notice Execution of ADD_ADMIN proposal.
/// @param proposal_ propsal.
function _executeAddAdmin(Proposal storage proposal_) private {
// Check that address is not an admin already.
require(!_admins.contains(proposal_.proposalAddress));
// Check that holder has sufficient balance to be an admin.
uint256 balance = _governingToken.totalOf(proposal_.proposalAddress);
require(balance >= voteWeight());
// Add admin.
_admins.add(proposal_.proposalAddress);
// Emit event that new admin has been added.
emit AddAdmin(proposal_.proposalAddress);
}
/// @notice Execution of REMOVE_ADMIN proposal.
/// @param proposal_ proposal.
function _executeRemoveAdmin(Proposal storage proposal_) private {
// Check that address is an admin.
require(_admins.contains(proposal_.proposalAddress));
// Remove admin.
_admins.remove(proposal_.proposalAddress);
// Emit event that an admin has been removed.
emit RemoveAdmin(proposal_.proposalAddress);
}
/// @notice Execution of INVEST proposal.
/// @param proposal_ proposal.
function _executeInvest(Proposal storage proposal_) private {
// Check that DAO has sufficient balance for investment.
require(availableBalance() >= proposal_.amount);
// Transfer funds.
payable(proposal_.proposalAddress).call{value: proposal_.amount}("");
// If secondary address for invest token is specified then save it to holdings.
if(proposal_.investTokenAddress != address(0x0)) {
if (!_holdings.contains(proposal_.investTokenAddress)) {
_holdings.add(proposal_.investTokenAddress);
// Emit event that holdings addresses have changed.
emit HoldingsAddressesChanged();
}
}
}
/// @notice Execution of WITHDRAW proposal.
/// @param proposal_ proposal.
function _executeWithdraw(Proposal storage proposal_) private {
if (_isMain) {
// Main DAO only allows withdrawal once a week.
require(block.timestamp > _lastWithdraw.add(1 * 1 weeks));
_lastWithdraw = block.timestamp;
}
uint256 amount;
uint256 mainAmount;
uint256 currentBalance = availableBalance();
if (_isMain) {
mainAmount = 0;
amount = proposal_.amount;
// Check that withdrawal amount is not more than 10% of main DAO balance.
require(currentBalance / 10 >= amount);
} else {
uint256 totalSupply = _governingToken.totalSupply();
uint256 circulatingMaxCost = _circulatingMaxCost(_circulatingSupply(totalSupply), totalSupply);
// Check that cloned DAO balance is higher than circulating max cost.
require(currentBalance > circulatingMaxCost);
// Check that cloned DAO gains are enough to cover withdrawal.
require(currentBalance.sub(circulatingMaxCost) >= proposal_.amount);
// 0.25% of withdrawal will be transfered to Main DAO stakers.
mainAmount = proposal_.amount / 400;
amount = proposal_.amount.sub(mainAmount);
}
// Transfer all withdrawal funds to Torro Factory.
ITorroFactory(_factory).depositBenefits{value: proposal_.amount}(address(_governingToken));
// Divide withdrawal between governing token stakers.
_governingToken.addBenefits(amount);
// If cloned DAO withdrawal then divide 0.25% of withdrawal between main token stakers.
if (mainAmount > 0) {
_torroToken.addBenefits(mainAmount);
}
}
// Owner calls.
// Owner transactions.
/// @notice Sets factory address.
/// @param factory_ address of TorroFactory.
function setFactoryAddress(address factory_) public override onlyOwner {
_factory = factory_;
}
/// @notice Sets vote weight divider.
/// @param weight_ weight divider for a single vote.
function setVoteWeightDivider(uint256 weight_) public override onlyOwner {
_voteWeightDivider = weight_;
}
/// @notice Sets new address for router.
/// @param router_ address for router.
function setRouter(address router_) public override onlyOwner {
_router = IUniswapV2Router02(router_);
}
/// @notice Sets divider for BUY, INVEST, WITHDAW proposals.
/// @param divider_ divider for BUY, INVEST, WITHDRAW proposals.
function setSpendDivider(uint256 divider_) public override onlyOwner {
_spendDivider = divider_;
}
/// @notice Migrates balances of current DAO to a new DAO.
/// @param newDao_ address of the new DAO to migrate to.
function migrate(address newDao_) public override onlyOwner {
ITorroDao dao = ITorroDao(newDao_);
// Migrate holdings.
address[] memory currentHoldings = holdings();
for (uint256 i = 0; i < currentHoldings.length; i++) {
_migrateTransferBalance(currentHoldings[i], newDao_);
}
dao.addHoldingsAddresses(currentHoldings);
// Migrate liquidities.
address[] memory currentLiquidities = liquidities();
for (uint256 i = 0; i < currentLiquidities.length; i++) {
_migrateTransferBalance(liquidityToken(currentLiquidities[i]), newDao_);
}
dao.addLiquidityAddresses(currentLiquidities);
// Send over ETH balance.
payable(newDao_).call{value: availableBalance()}("");
}
// Private owner calls.
/// @notice Private function for migrating token balance to a new address.
/// @param token_ address of ERC-20 token to migrate.
/// @param target_ migration end point address.
function _migrateTransferBalance(address token_, address target_) private {
if (token_ != address(0x0)) {
IERC20 erc20 = IERC20(token_);
uint256 balance = erc20.balanceOf(address(this));
if (balance > 0) {
erc20.transfer(target_, balance);
}
}
}
} | /// @title DAO for proposals, voting and execution.
/// @notice Contract for creation, voting and execution of proposals.
/// @author ORayskiy - @robitnik_TorroDao | NatSpecSingleLine | _executeInvest | function _executeInvest(Proposal storage proposal_) private {
// Check that DAO has sufficient balance for investment.
require(availableBalance() >= proposal_.amount);
// Transfer funds.
payable(proposal_.proposalAddress).call{value: proposal_.amount}("");
// If secondary address for invest token is specified then save it to holdings.
if(proposal_.investTokenAddress != address(0x0)) {
if (!_holdings.contains(proposal_.investTokenAddress)) {
_holdings.add(proposal_.investTokenAddress);
// Emit event that holdings addresses have changed.
emit HoldingsAddressesChanged();
}
}
}
| /// @notice Execution of INVEST proposal.
/// @param proposal_ proposal. | NatSpecSingleLine | v0.6.6+commit.6c089d02 | Unknown | ipfs://d1c6095fcf143d951c9754f00fe8cd59d29ab460461efe53b91eb289fd0fe5ac | {
"func_code_index": [
33476,
34146
]
} | 58,561 |
TorroDao | TorroDao.sol | 0x3cf9e9d45380b6ab61bde46b2e6cfcd7d8f6cdc1 | Solidity | TorroDao | contract TorroDao is ITorroDao, OwnableUpgradeSafe {
using EnumerableSet for EnumerableSet.AddressSet;
using EnumerableSet for EnumerableSet.UintSet;
using SafeMath for uint256;
// Structs.
/// @notice General proposal structure.
struct Proposal {
uint256 id;
address proposalAddress;
address investTokenAddress;
DaoFunction daoFunction;
uint256 amount;
address creator;
uint256 endLifetime;
EnumerableSet.AddressSet voterAddresses;
uint256 votesFor;
uint256 votesAgainst;
bool executed;
}
// Events.
/// @notice Event for dispatching on new proposal creation.
/// @param id id of the new proposal.
event NewProposal(uint256 id);
/// @notice Event for dispatching when proposal has been removed.
/// @param id id of the removed proposal.
event RemoveProposal(uint256 id);
/// @notice Event for dispatching when someone voted on a proposal.
/// @param id id of the voted proposal.
event Vote(uint256 id);
/// @notice Event for dispatching when an admin has been added to the DAO.
/// @param admin address of the admin that's been added.
event AddAdmin(address admin);
/// @notice Event for dispatching when an admin has been removed from the DAO.
/// @param admin address of the admin that's been removed.
event RemoveAdmin(address admin);
/// @notice Event for dispatching when a proposal has been executed.
/// @param id id of the executed proposal.
event ExecutedProposal(uint256 id);
/// @notice Event for dispatching when cloned DAO tokens have been bought.
event Buy();
/// @notice Event for dispatching when cloned DAO tokens have been sold.
event Sell();
/// @notice Event for dispatching when new holdings addresses have been changed.
event HoldingsAddressesChanged();
/// @notice Event for dipatching when new liquidity addresses have been changed.
event LiquidityAddressesChanged();
// Constants.
// Private data.
address private _creator;
EnumerableSet.AddressSet private _holdings;
EnumerableSet.AddressSet private _liquidityAddresses;
EnumerableSet.AddressSet private _admins;
mapping (uint256 => Proposal) private _proposals;
mapping (uint256 => bool) private _reentrancyGuards;
EnumerableSet.UintSet private _proposalIds;
ITorro private _torroToken;
ITorro private _governingToken;
address private _factory;
uint256 private _latestProposalId;
uint256 private _timeout;
uint256 private _maxCost;
uint256 private _executeMinPct;
uint256 private _votingMinHours;
uint256 private _voteWeightDivider;
uint256 private _lastWithdraw;
uint256 private _spendDivider;
bool private _isPublic;
bool private _isMain;
bool private _hasAdmins;
// ===============
IUniswapV2Router02 private _router;
// Constructor.
/// @notice Constructor for original Torro DAO.
/// @param governingToken_ Torro token address.
constructor(address governingToken_) public {
__Ownable_init();
_torroToken = ITorro(governingToken_);
_governingToken = ITorro(governingToken_);
_factory = address(0x0);
_latestProposalId = 0;
_timeout = uint256(5).mul(1 minutes);
_router = IUniswapV2Router02(address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D));
_maxCost = 0;
_executeMinPct = 5;
_votingMinHours = 6;
_voteWeightDivider = 10000;
_lastWithdraw = block.timestamp.add(1 * 1 weeks);
_spendDivider = 10;
_isMain = true;
_isPublic = true;
_hasAdmins = true;
_creator = msg.sender;
}
/// @notice Initializer for DAO clones.
/// @param torroToken_ main torro token address.
/// @param governingToken_ torro token clone that's governing this dao.
/// @param factory_ torro factory address.
/// @param creator_ creator of cloned DAO.
/// @param maxCost_ maximum cost of all governing tokens for cloned DAO.
/// @param executeMinPct_ minimum percentage of votes needed for proposal execution.
/// @param votingMinHours_ minimum lifetime of proposal before it closes.
/// @param isPublic_ whether cloned DAO has public visibility.
/// @param hasAdmins_ whether cloned DAO has admins, otherwise all stakers are treated as admins.
function initializeCustom(
address torroToken_,
address governingToken_,
address factory_,
address creator_,
uint256 maxCost_,
uint256 executeMinPct_,
uint256 votingMinHours_,
bool isPublic_,
bool hasAdmins_
) public override initializer {
__Ownable_init();
_torroToken = ITorro(torroToken_);
_governingToken = ITorro(governingToken_);
_factory = factory_;
_latestProposalId = 0;
_timeout = uint256(5).mul(1 minutes);
_router = IUniswapV2Router02(address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D));
_maxCost = maxCost_;
_voteWeightDivider = 0;
_executeMinPct = executeMinPct_;
_votingMinHours = votingMinHours_;
_lastWithdraw = block.timestamp;
_spendDivider = 0;
_isMain = false;
_isPublic = isPublic_;
_hasAdmins = hasAdmins_;
_creator = creator_;
if (_hasAdmins) {
_admins.add(creator_);
}
}
// Modifiers.
/// @notice Stops double execution of proposals.
/// @param id_ proposal id that's executing.
modifier nonReentrant(uint256 id_) {
// check that it's already not executing
require(!_reentrancyGuards[id_]);
// toggle state that proposal is currently executing
_reentrancyGuards[id_] = true;
_;
// toggle state back
_reentrancyGuards[id_] = false;
}
/// @notice Allow fund transfers to DAO contract.
receive() external payable {
// do nothing
}
// Public calls.
/// @notice Address of DAO creator.
/// @return DAO creator address.
function daoCreator() public override view returns (address) {
return _creator;
}
/// @notice Amount of tokens needed for a single vote.
/// @return uint256 token amount.
function voteWeight() public override view returns (uint256) {
uint256 weight;
if (_isMain) {
weight = _governingToken.totalSupply() / _voteWeightDivider;
} else {
weight = 10**18;
}
return weight;
}
/// @notice Amount of votes that holder has.
/// @param sender_ address of the holder.
/// @return number of votes.
function votesOf(address sender_) public override view returns (uint256) {
return _governingToken.stakedOf(sender_) / voteWeight();
}
/// @notice Address of the governing token.
/// @return address of the governing token.
function tokenAddress() public override view returns (address) {
return address(_governingToken);
}
/// @notice Saved addresses of tokens that DAO is holding.
/// @return array of holdings addresses.
function holdings() public override view returns (address[] memory) {
uint256 length = _holdings.length();
address[] memory holdingsAddresses = new address[](length);
for (uint256 i = 0; i < length; i++) {
holdingsAddresses[i] = _holdings.at(i);
}
return holdingsAddresses;
}
/// @notice Saved addresses of liquidity tokens that DAO is holding.
/// @return array of liquidity addresses.
function liquidities() public override view returns (address[] memory) {
uint256 length = _liquidityAddresses.length();
address[] memory liquidityAddresses = new address[](length);
for (uint256 i = 0; i < length; i++) {
liquidityAddresses[i] = _liquidityAddresses.at(i);
}
return liquidityAddresses;
}
/// @notice Calculates address of liquidity token from ERC-20 token address.
/// @param token_ token address to calculate liquidity address from.
/// @return address of liquidity token.
function liquidityToken(address token_) public override view returns (address) {
return UniswapV2Library.pairFor(_router.factory(), token_, _router.WETH());
}
/// @notice Gets tokens and liquidity token addresses of DAO's liquidity holdings.
/// @return Arrays of tokens and liquidity tokens, should have the same length.
function liquidityHoldings() public override view returns (address[] memory, address[] memory) {
uint256 length = _liquidityAddresses.length();
address[] memory tokens = new address[](length);
address[] memory liquidityTokens = new address[](length);
for (uint256 i = 0; i < length; i++) {
address token = _liquidityAddresses.at(i);
tokens[i] = token;
liquidityTokens[i] = liquidityToken(token);
}
return (tokens, liquidityTokens);
}
/// @notice DAO admins.
/// @return Array of admin addresses.
function admins() public override view returns (address[] memory) {
uint256 length = _admins.length();
address[] memory currentAdmins = new address[](length);
for (uint256 i = 0; i < length; i++) {
currentAdmins[i] = _admins.at(i);
}
return currentAdmins;
}
/// @notice DAO balance for specified token.
/// @param token_ token address to get balance for.
/// @return uint256 token balance.
function tokenBalance(address token_) public override view returns (uint256) {
return IERC20(token_).balanceOf(address(this));
}
/// @notice DAO balance for liquidity token.
/// @param token_ token address to get liquidity balance for.
/// @return uin256 token liquidity balance.
function liquidityBalance(address token_) public override view returns (uint256) {
return tokenBalance(liquidityToken(token_));
}
/// @notice DAO ethereum balance.
/// @return uint256 wei balance.
function availableBalance() public override view returns (uint256) {
return address(this).balance;
}
/// @notice Maximum cost for all tokens of cloned DAO.
/// @return uint256 maximum cost in wei.
function maxCost() public override view returns (uint256) {
return _maxCost;
}
/// @notice Minimum percentage of votes needed to execute a proposal.
/// @return uint256 minimum percentage of votes.
function executeMinPct() public override view returns (uint256) {
return _executeMinPct;
}
/// @notice Minimum lifetime of proposal before it closes.
/// @return uint256 minimum number of hours for proposal lifetime.
function votingMinHours() public override view returns (uint256) {
return _votingMinHours;
}
/// @notice Whether DAO is public or private.
/// @return bool true if public.
function isPublic() public override view returns (bool) {
return _isPublic;
}
/// @notice Whether DAO has admins.
/// @return bool true if DAO has admins.
function hasAdmins() public override view returns (bool) {
return _hasAdmins;
}
/// @notice Proposal ids of DAO.
/// @return array of proposal ids.
function getProposalIds() public override view returns (uint256[] memory) {
uint256 proposalsLength = _proposalIds.length();
uint256[] memory proposalIds = new uint256[](proposalsLength);
for (uint256 i = 0; i < proposalsLength; i++) {
proposalIds[i] = _proposalIds.at(i);
}
return proposalIds;
}
/// @notice Gets proposal info for proposal id.
/// @param id_ id of proposal to get info for.
/// @return proposalAddress address for proposal execution.
/// @return investTokenAddress secondary address for proposal execution, used for investment proposals if ICO and token addresses differ.
/// @return daoFunction proposal type.
/// @return amount proposal amount eth/token to use during execution.
/// @return creator address of proposal creator.
/// @return endLifetime epoch time when proposal voting ends.
/// @return votesFor amount of votes for the proposal.
/// @return votesAgainst amount of votes against the proposal.
/// @return executed whether proposal has been executed or not.
function getProposal(uint256 id_) public override view returns (
address proposalAddress,
address investTokenAddress,
DaoFunction daoFunction,
uint256 amount,
address creator,
uint256 endLifetime,
uint256 votesFor,
uint256 votesAgainst,
bool executed
) {
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
return (
currentProposal.proposalAddress,
currentProposal.investTokenAddress,
currentProposal.daoFunction,
currentProposal.amount,
currentProposal.creator,
currentProposal.endLifetime,
currentProposal.votesFor,
currentProposal.votesAgainst,
currentProposal.executed
);
}
/// @notice Whether a holder is allowed to vote for a proposal.
/// @param id_ proposal id to check whether holder is allowed to vote for.
/// @param sender_ address of the holder.
/// @return bool true if voting is allowed.
function canVote(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
return proposal.endLifetime >= block.timestamp && proposal.creator != sender_ && !proposal.voterAddresses.contains(sender_);
}
/// @notice Whether a holder is allowed to remove a proposal.
/// @param id_ proposal id to check whether holder is allowed to remove.
/// @param sender_ address of the holder.
/// @return bool true if removal is allowed.
function canRemove(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
return proposal.endLifetime >= block.timestamp && proposal.voterAddresses.length() == 1 && (proposal.creator == sender_ || owner() == sender_);
}
/// @notice Whether a holder is allowed to execute a proposal.
/// @param id_ proposal id to check whether holder is allowed to execute.
/// @param sender_ address of the holder.
/// @return bool true if execution is allowed.
function canExecute(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
// check that proposal hasn't been executed yet.
if (proposal.executed) {
return false;
}
// if custom pool has admins then only admins can execute proposals
if (!_isMain && _hasAdmins) {
if (!isAdmin(sender_)) {
return false;
}
}
if (proposal.daoFunction == DaoFunction.INVEST) {
// for invest functions only admins can execute
if (sender_ != _creator && !_admins.contains(sender_)) {
return false;
}
// check that sender is proposal creator or admin
} else if (proposal.creator != sender_ && !isAdmin(sender_)) {
return false;
}
// For main pool Buy and Sell dao functions allow instant executions if at least 10% of staked supply has voted for it
if (_isMain && (proposal.daoFunction == DaoFunction.BUY || proposal.daoFunction == DaoFunction.SELL)) {
if (proposal.votesFor.mul(voteWeight()) >= _governingToken.stakedSupply() / 10) {
if (proposal.votesFor > proposal.votesAgainst) {
// only allow admins to execute buy and sell proposals early
return isAdmin(sender_);
}
}
}
// check that proposal voting lifetime has run out.
if (proposal.endLifetime > block.timestamp) {
return false;
}
// check that votes for outweigh votes against.
bool currentCanExecute = proposal.votesFor > proposal.votesAgainst;
if (currentCanExecute && _executeMinPct > 0) {
// Check that proposal has at least _executeMinPct% of staked votes.
uint256 minVotes = _governingToken.stakedSupply() / (100 / _executeMinPct);
currentCanExecute = minVotes <= proposal.votesFor.add(proposal.votesAgainst).mul(voteWeight());
}
return currentCanExecute;
}
/// @notice Whether a holder is an admin.
/// @param sender_ address of holder.
/// @return bool true if holder is an admin (in DAO without admins all holders are treated as such).
function isAdmin(address sender_) public override view returns (bool) {
return !_hasAdmins || sender_ == _creator || _admins.contains(sender_);
}
// Public transactions.
/// @notice Saves new holdings addresses for DAO.
/// @param tokens_ token addresses that DAO has holdings of.
function addHoldingsAddresses(address[] memory tokens_) public override {
require(isAdmin(msg.sender));
for (uint256 i = 0; i < tokens_.length; i++) {
address token = tokens_[i];
if (!_holdings.contains(token)) {
_holdings.add(token);
}
}
emit HoldingsAddressesChanged();
}
/// @notice Saves new liquidity addresses for DAO.
/// @param tokens_ token addresses that DAO has liquidities of.
function addLiquidityAddresses(address[] memory tokens_) public override {
require(isAdmin(msg.sender));
for (uint256 i = 0; i < tokens_.length; i++) {
address token = tokens_[i];
if (!_liquidityAddresses.contains(token)) {
_liquidityAddresses.add(token);
}
}
emit LiquidityAddressesChanged();
}
/// @notice Creates new proposal.
/// @param proposalAddress_ main address of the proposal, in investment proposals this is the address funds are sent to.
/// @param investTokenAddress_ secondary address of the proposal, used in investment proposals to specify token address.
/// @param daoFunction_ type of the proposal.
/// @param amount_ amount of funds to use in the proposal.
/// @param hoursLifetime_ voting lifetime of the proposal.
function propose(address proposalAddress_, address investTokenAddress_, DaoFunction daoFunction_, uint256 amount_, uint256 hoursLifetime_) public override {
// check that lifetime is at least equals to min hours set for DAO.
require(hoursLifetime_ >= _votingMinHours);
// Check that proposal creator is allowed to create a proposal.
uint256 balance = _governingToken.stakedOf(msg.sender);
uint256 weight = voteWeight();
require(balance >= weight);
// For main DAO.
if (_isMain) {
if (daoFunction_ == DaoFunction.WITHDRAW || daoFunction_ == DaoFunction.INVEST || daoFunction_ == DaoFunction.BUY) {
// Limit each buy, investment and withdraw proposals to 10% of ETH funds.
require(amount_ <= (availableBalance() / _spendDivider));
}
}
// Increment proposal id counter.
_latestProposalId++;
uint256 currentId = _latestProposalId;
// Calculate end lifetime of the proposal.
uint256 endLifetime = block.timestamp.add(hoursLifetime_.mul(1 hours));
// Declare voter addresses set.
EnumerableSet.AddressSet storage voterAddresses;
// Save proposal struct.
_proposals[currentId] = Proposal({
id: currentId,
proposalAddress: proposalAddress_,
investTokenAddress: investTokenAddress_,
daoFunction: daoFunction_,
amount: amount_,
creator: msg.sender,
endLifetime: endLifetime,
voterAddresses: voterAddresses,
votesFor: balance / weight,
votesAgainst: 0,
executed: false
});
// Save id of new proposal.
_proposalIds.add(currentId);
// Emit event that new proposal has been created.
emit NewProposal(currentId);
}
/// @notice Removes existing proposal.
/// @param id_ id of proposal to remove.
function unpropose(uint256 id_) public override {
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
// Check that proposal creator, owner or an admin is removing a proposal.
require(msg.sender == currentProposal.creator || msg.sender == _creator || _admins.contains(msg.sender));
// Check that no votes have been registered for the proposal apart from the proposal creator, pool creator can remove any proposal.
if (msg.sender != _creator) {
require(currentProposal.voterAddresses.length() == 1);
}
// Remove proposal.
delete _proposals[id_];
_proposalIds.remove(id_);
// Emit event that a proposal has been removed.
emit RemoveProposal(id_);
}
/// @notice Voting for multiple proposals.
/// @param ids_ ids of proposals to vote for.
/// @param votes_ for or against votes for proposals.
function vote(uint256[] memory ids_, bool[] memory votes_) public override {
// Check that arrays of the same length have been supplied.
require(ids_.length == votes_.length);
// Check that voter has enough tokens staked to vote.
uint256 balance = _governingToken.stakedOf(msg.sender);
uint256 weight = voteWeight();
require(balance >= weight);
// Get number of votes that msg.sender has.
uint256 votesCount = balance / weight;
// Iterate over voted proposals.
for (uint256 i = 0; i < ids_.length; i++) {
uint256 id = ids_[i];
bool currentVote = votes_[i];
Proposal storage proposal = _proposals[id];
// Check that proposal hasn't been voted for by msg.sender and that it's still active.
if (!proposal.voterAddresses.contains(msg.sender) && proposal.endLifetime >= block.timestamp) {
// Add votes.
proposal.voterAddresses.add(msg.sender);
if (currentVote) {
proposal.votesFor = proposal.votesFor.add(votesCount);
} else {
proposal.votesAgainst = proposal.votesAgainst.add(votesCount);
}
}
// Emit event that a proposal has been voted for.
emit Vote(id);
}
}
/// @notice Executes a proposal.
/// @param id_ id of proposal to be executed.
function execute(uint256 id_) public override nonReentrant(id_) {
// save gas at the start of execution
uint256 remainingGasStart = gasleft();
// check whether proposal can be executed by the sender
require(canExecute(id_, msg.sender));
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
// Check that msg.sender has balance for at least 1 vote to execute a proposal.
uint256 balance = _governingToken.totalOf(msg.sender);
if (balance < voteWeight()) {
// Remove admin if his balance is not high enough.
if (_admins.contains(msg.sender)) {
_admins.remove(msg.sender);
}
revert();
}
// Call private function for proposal execution depending on the type.
if (currentProposal.daoFunction == DaoFunction.BUY) {
_executeBuy(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.SELL) {
_executeSell(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.ADD_LIQUIDITY) {
_executeAddLiquidity(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.REMOVE_LIQUIDITY) {
_executeRemoveLiquidity(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.ADD_ADMIN) {
_executeAddAdmin(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.REMOVE_ADMIN) {
_executeRemoveAdmin(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.INVEST) {
_executeInvest(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.WITHDRAW) {
_executeWithdraw(currentProposal);
}
// Mark proposal as executed.
currentProposal.executed = true;
// calculate gas used during execution
uint256 remainingGasEnd = gasleft();
uint256 usedGas = remainingGasStart.sub(remainingGasEnd).add(35000);
// max gas price allowed for refund is 200gwei
uint256 gasPrice;
if (tx.gasprice > 200000000000) {
gasPrice = 200000000000;
} else {
gasPrice = tx.gasprice;
}
// refund used gas
payable(msg.sender).transfer(usedGas.mul(gasPrice));
// Emit event that proposal has been executed.
emit ExecutedProposal(id_);
}
/// @notice Buying tokens for cloned DAO.
function buy() public override payable {
// Check that it's not the main DAO.
require(!_isMain);
// Check that msg.sender is not sending more money than max cost of dao.
require(msg.value <= _maxCost);
// Check that DAO has enough tokens to sell to msg.sender.
uint256 portion = _governingToken.totalSupply().mul(msg.value) / _maxCost;
require(_governingToken.balanceOf(address(this)) >= portion);
// Transfer tokens.
_governingToken.transfer(msg.sender, portion);
// Emit event that tokens have been bought.
emit Buy();
}
/// @notice Sell tokens back to cloned DAO.
/// @param amount_ amount of tokens to sell.
function sell(uint256 amount_) public override {
// Check that it's not the main DAO.
require(!_isMain);
// Check that msg.sender has enough tokens to sell.
require(_governingToken.balanceOf(msg.sender) >= amount_);
// Calculate the eth share holder should get back and whether pool has enough funds.
uint256 share = _supplyShare(amount_);
// Approve token transfer for DAO.
_governingToken.approveDao(msg.sender, amount_);
// Transfer tokens from msg.sender back to DAO.
_governingToken.transferFrom(msg.sender, address(this), amount_);
// Refund eth back to the msg.sender.
payable(msg.sender).transfer(share);
// Emit event that tokens have been sold back to DAO.
emit Sell();
}
// Private calls.
/// @notice Calculates cost of share of the supply.
/// @param amount_ amount of tokens to calculate eth share for.
/// @return price for specified amount share.
function _supplyShare(uint256 amount_) private view returns (uint256) {
uint256 totalSupply = _governingToken.totalSupply();
uint256 circulatingSupply = _circulatingSupply(totalSupply);
uint256 circulatingMaxCost = _circulatingMaxCost(circulatingSupply, totalSupply);
// Check whether available balance is higher than circulating max cost.
if (availableBalance() > circulatingMaxCost) {
// If true then share will equal to buy price.
return circulatingMaxCost.mul(amount_) / circulatingSupply;
} else {
// Otherwise calculate share price based on currently available balance.
return availableBalance().mul(amount_) / circulatingSupply;
}
}
/// @notice Calculates max cost for currently circulating supply.
/// @param circulatingSupply_ governing token circulating supply.
/// @param totalSupply_ governing token total supply.
/// @return uint256 eth cost of currently circulating supply.
function _circulatingMaxCost(uint256 circulatingSupply_, uint256 totalSupply_) private view returns (uint256) {
return _maxCost.mul(circulatingSupply_) / totalSupply_;
}
/// @notice Calculates circulating supply of governing token.
/// @param totalSupply_ governing token total supply.
/// @return uint256 number of tokens in circulation.
function _circulatingSupply(uint256 totalSupply_) private view returns (uint256) {
uint256 balance = _governingToken.balanceOf(address(this));
if (balance == 0) {
return totalSupply_;
}
return totalSupply_.sub(balance);
}
// Private transactions.
/// @notice Execution of BUY proposal.
/// @param proposal_ proposal.
function _executeBuy(Proposal storage proposal_) private {
// Check that DAO has enough funds to execute buy proposal.
require(availableBalance() >= proposal_.amount);
// Deposit eth funds to Uniswap router.
IWETH weth = IWETH(_router.WETH());
weth.deposit{value: proposal_.amount}();
// Create path for buying, buying is only for Token-ETH pair.
address[] memory path = new address[](2);
path[0] = address(weth);
path[1] = proposal_.proposalAddress;
// Execute uniswap buy.
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), path[0], path[1]);
uint256 amountOut = UniswapV2Library.getAmountOut(proposal_.amount, reserveA, reserveB);
_router.swapExactETHForTokens{value: proposal_.amount}(amountOut, path, address(this), block.timestamp.add(_timeout));
// If new token then save it holdings addresses.
if (!_holdings.contains(proposal_.proposalAddress)) {
_holdings.add(proposal_.proposalAddress);
// Emit event that holdings addresses changed.
emit HoldingsAddressesChanged();
}
}
/// @notice Execution of SELL proposal.
/// @param proposal_ proposal.
function _executeSell(Proposal storage proposal_) private {
// Approve uniswap router to sell tokens.
IERC20 token = IERC20(proposal_.proposalAddress);
require(token.approve(address(_router), proposal_.amount));
// Create path for selling, selling is only for Token-ETH pair.
address[] memory path = new address[](2);
path[0] = proposal_.proposalAddress;
path[1] = _router.WETH();
// Execute uniswap sell.
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), path[0], path[1]);
uint256 amountOut = UniswapV2Library.getAmountOut(proposal_.amount, reserveA, reserveB);
_router.swapExactTokensForETH(proposal_.amount, amountOut, path, address(this), block.timestamp.add(_timeout));
// If sold all tokens then remove it from holdings.
if (token.balanceOf(address(this)) == 0 && _holdings.contains(proposal_.proposalAddress)) {
_holdings.remove(proposal_.proposalAddress);
// Emit event that holdings addresses changed.
emit HoldingsAddressesChanged();
}
}
/// @notice Execution of ADD_LIQUIDITY proposal.
/// @param proposal_ proposal.
function _executeAddLiquidity(Proposal storage proposal_) private {
// Approve uniswap route to transfer tokens.
require(IERC20(proposal_.proposalAddress).approve(address(_router), proposal_.amount));
// Calculate amount of tokens and eth needed for liquidity.
IWETH weth = IWETH(_router.WETH());
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), proposal_.proposalAddress, address(weth));
uint256 wethAmount = UniswapV2Library.quote(proposal_.amount, reserveA, reserveB);
// Check that DAO has sufficient eth balance for liquidity.
require (availableBalance() > wethAmount);
// Deposit eth for liqudity.
weth.deposit{value: wethAmount}();
// Execute uniswap add liquidity.
_router.addLiquidityETH{value: wethAmount}(
proposal_.proposalAddress,
proposal_.amount,
(proposal_.amount / 100).mul(98),
(wethAmount / 100).mul(98),
address(this),
block.timestamp.add(_timeout)
);
// If new liquidity token then save it.
if (!_liquidityAddresses.contains(proposal_.proposalAddress)) {
_liquidityAddresses.add(proposal_.proposalAddress);
// Emit event that liquidity addresses changed.
emit LiquidityAddressesChanged();
}
}
/// @notice Execution of REMOVE_LIQUIDITY proposal.
/// @param proposal_ proposal.
function _executeRemoveLiquidity(Proposal storage proposal_) private {
// Approve uniswap router to transfer liquidity tokens.
address liquidityTokenAddress = liquidityToken(proposal_.proposalAddress);
require(IERC20(liquidityTokenAddress).approve(address(_router), proposal_.amount));
// Execute uniswap liquidity removal.
_router.removeLiquidityETH(
proposal_.proposalAddress,
proposal_.amount,
0,
0,
address(this),
block.timestamp.add(_timeout)
);
// If all tokens have been sold then remove liquidty address.
if (tokenBalance(liquidityTokenAddress) == 0 && _liquidityAddresses.contains(proposal_.proposalAddress)) {
_liquidityAddresses.remove(proposal_.proposalAddress);
// Emit event that liquidity addresses have changed.
emit LiquidityAddressesChanged();
}
}
/// @notice Execution of ADD_ADMIN proposal.
/// @param proposal_ propsal.
function _executeAddAdmin(Proposal storage proposal_) private {
// Check that address is not an admin already.
require(!_admins.contains(proposal_.proposalAddress));
// Check that holder has sufficient balance to be an admin.
uint256 balance = _governingToken.totalOf(proposal_.proposalAddress);
require(balance >= voteWeight());
// Add admin.
_admins.add(proposal_.proposalAddress);
// Emit event that new admin has been added.
emit AddAdmin(proposal_.proposalAddress);
}
/// @notice Execution of REMOVE_ADMIN proposal.
/// @param proposal_ proposal.
function _executeRemoveAdmin(Proposal storage proposal_) private {
// Check that address is an admin.
require(_admins.contains(proposal_.proposalAddress));
// Remove admin.
_admins.remove(proposal_.proposalAddress);
// Emit event that an admin has been removed.
emit RemoveAdmin(proposal_.proposalAddress);
}
/// @notice Execution of INVEST proposal.
/// @param proposal_ proposal.
function _executeInvest(Proposal storage proposal_) private {
// Check that DAO has sufficient balance for investment.
require(availableBalance() >= proposal_.amount);
// Transfer funds.
payable(proposal_.proposalAddress).call{value: proposal_.amount}("");
// If secondary address for invest token is specified then save it to holdings.
if(proposal_.investTokenAddress != address(0x0)) {
if (!_holdings.contains(proposal_.investTokenAddress)) {
_holdings.add(proposal_.investTokenAddress);
// Emit event that holdings addresses have changed.
emit HoldingsAddressesChanged();
}
}
}
/// @notice Execution of WITHDRAW proposal.
/// @param proposal_ proposal.
function _executeWithdraw(Proposal storage proposal_) private {
if (_isMain) {
// Main DAO only allows withdrawal once a week.
require(block.timestamp > _lastWithdraw.add(1 * 1 weeks));
_lastWithdraw = block.timestamp;
}
uint256 amount;
uint256 mainAmount;
uint256 currentBalance = availableBalance();
if (_isMain) {
mainAmount = 0;
amount = proposal_.amount;
// Check that withdrawal amount is not more than 10% of main DAO balance.
require(currentBalance / 10 >= amount);
} else {
uint256 totalSupply = _governingToken.totalSupply();
uint256 circulatingMaxCost = _circulatingMaxCost(_circulatingSupply(totalSupply), totalSupply);
// Check that cloned DAO balance is higher than circulating max cost.
require(currentBalance > circulatingMaxCost);
// Check that cloned DAO gains are enough to cover withdrawal.
require(currentBalance.sub(circulatingMaxCost) >= proposal_.amount);
// 0.25% of withdrawal will be transfered to Main DAO stakers.
mainAmount = proposal_.amount / 400;
amount = proposal_.amount.sub(mainAmount);
}
// Transfer all withdrawal funds to Torro Factory.
ITorroFactory(_factory).depositBenefits{value: proposal_.amount}(address(_governingToken));
// Divide withdrawal between governing token stakers.
_governingToken.addBenefits(amount);
// If cloned DAO withdrawal then divide 0.25% of withdrawal between main token stakers.
if (mainAmount > 0) {
_torroToken.addBenefits(mainAmount);
}
}
// Owner calls.
// Owner transactions.
/// @notice Sets factory address.
/// @param factory_ address of TorroFactory.
function setFactoryAddress(address factory_) public override onlyOwner {
_factory = factory_;
}
/// @notice Sets vote weight divider.
/// @param weight_ weight divider for a single vote.
function setVoteWeightDivider(uint256 weight_) public override onlyOwner {
_voteWeightDivider = weight_;
}
/// @notice Sets new address for router.
/// @param router_ address for router.
function setRouter(address router_) public override onlyOwner {
_router = IUniswapV2Router02(router_);
}
/// @notice Sets divider for BUY, INVEST, WITHDAW proposals.
/// @param divider_ divider for BUY, INVEST, WITHDRAW proposals.
function setSpendDivider(uint256 divider_) public override onlyOwner {
_spendDivider = divider_;
}
/// @notice Migrates balances of current DAO to a new DAO.
/// @param newDao_ address of the new DAO to migrate to.
function migrate(address newDao_) public override onlyOwner {
ITorroDao dao = ITorroDao(newDao_);
// Migrate holdings.
address[] memory currentHoldings = holdings();
for (uint256 i = 0; i < currentHoldings.length; i++) {
_migrateTransferBalance(currentHoldings[i], newDao_);
}
dao.addHoldingsAddresses(currentHoldings);
// Migrate liquidities.
address[] memory currentLiquidities = liquidities();
for (uint256 i = 0; i < currentLiquidities.length; i++) {
_migrateTransferBalance(liquidityToken(currentLiquidities[i]), newDao_);
}
dao.addLiquidityAddresses(currentLiquidities);
// Send over ETH balance.
payable(newDao_).call{value: availableBalance()}("");
}
// Private owner calls.
/// @notice Private function for migrating token balance to a new address.
/// @param token_ address of ERC-20 token to migrate.
/// @param target_ migration end point address.
function _migrateTransferBalance(address token_, address target_) private {
if (token_ != address(0x0)) {
IERC20 erc20 = IERC20(token_);
uint256 balance = erc20.balanceOf(address(this));
if (balance > 0) {
erc20.transfer(target_, balance);
}
}
}
} | /// @title DAO for proposals, voting and execution.
/// @notice Contract for creation, voting and execution of proposals.
/// @author ORayskiy - @robitnik_TorroDao | NatSpecSingleLine | _executeWithdraw | function _executeWithdraw(Proposal storage proposal_) private {
if (_isMain) {
// Main DAO only allows withdrawal once a week.
require(block.timestamp > _lastWithdraw.add(1 * 1 weeks));
_lastWithdraw = block.timestamp;
}
uint256 amount;
uint256 mainAmount;
uint256 currentBalance = availableBalance();
if (_isMain) {
mainAmount = 0;
amount = proposal_.amount;
// Check that withdrawal amount is not more than 10% of main DAO balance.
require(currentBalance / 10 >= amount);
} else {
uint256 totalSupply = _governingToken.totalSupply();
uint256 circulatingMaxCost = _circulatingMaxCost(_circulatingSupply(totalSupply), totalSupply);
// Check that cloned DAO balance is higher than circulating max cost.
require(currentBalance > circulatingMaxCost);
// Check that cloned DAO gains are enough to cover withdrawal.
require(currentBalance.sub(circulatingMaxCost) >= proposal_.amount);
// 0.25% of withdrawal will be transfered to Main DAO stakers.
mainAmount = proposal_.amount / 400;
amount = proposal_.amount.sub(mainAmount);
}
// Transfer all withdrawal funds to Torro Factory.
ITorroFactory(_factory).depositBenefits{value: proposal_.amount}(address(_governingToken));
// Divide withdrawal between governing token stakers.
_governingToken.addBenefits(amount);
// If cloned DAO withdrawal then divide 0.25% of withdrawal between main token stakers.
if (mainAmount > 0) {
_torroToken.addBenefits(mainAmount);
}
}
| /// @notice Execution of WITHDRAW proposal.
/// @param proposal_ proposal. | NatSpecSingleLine | v0.6.6+commit.6c089d02 | Unknown | ipfs://d1c6095fcf143d951c9754f00fe8cd59d29ab460461efe53b91eb289fd0fe5ac | {
"func_code_index": [
34230,
35841
]
} | 58,562 |
TorroDao | TorroDao.sol | 0x3cf9e9d45380b6ab61bde46b2e6cfcd7d8f6cdc1 | Solidity | TorroDao | contract TorroDao is ITorroDao, OwnableUpgradeSafe {
using EnumerableSet for EnumerableSet.AddressSet;
using EnumerableSet for EnumerableSet.UintSet;
using SafeMath for uint256;
// Structs.
/// @notice General proposal structure.
struct Proposal {
uint256 id;
address proposalAddress;
address investTokenAddress;
DaoFunction daoFunction;
uint256 amount;
address creator;
uint256 endLifetime;
EnumerableSet.AddressSet voterAddresses;
uint256 votesFor;
uint256 votesAgainst;
bool executed;
}
// Events.
/// @notice Event for dispatching on new proposal creation.
/// @param id id of the new proposal.
event NewProposal(uint256 id);
/// @notice Event for dispatching when proposal has been removed.
/// @param id id of the removed proposal.
event RemoveProposal(uint256 id);
/// @notice Event for dispatching when someone voted on a proposal.
/// @param id id of the voted proposal.
event Vote(uint256 id);
/// @notice Event for dispatching when an admin has been added to the DAO.
/// @param admin address of the admin that's been added.
event AddAdmin(address admin);
/// @notice Event for dispatching when an admin has been removed from the DAO.
/// @param admin address of the admin that's been removed.
event RemoveAdmin(address admin);
/// @notice Event for dispatching when a proposal has been executed.
/// @param id id of the executed proposal.
event ExecutedProposal(uint256 id);
/// @notice Event for dispatching when cloned DAO tokens have been bought.
event Buy();
/// @notice Event for dispatching when cloned DAO tokens have been sold.
event Sell();
/// @notice Event for dispatching when new holdings addresses have been changed.
event HoldingsAddressesChanged();
/// @notice Event for dipatching when new liquidity addresses have been changed.
event LiquidityAddressesChanged();
// Constants.
// Private data.
address private _creator;
EnumerableSet.AddressSet private _holdings;
EnumerableSet.AddressSet private _liquidityAddresses;
EnumerableSet.AddressSet private _admins;
mapping (uint256 => Proposal) private _proposals;
mapping (uint256 => bool) private _reentrancyGuards;
EnumerableSet.UintSet private _proposalIds;
ITorro private _torroToken;
ITorro private _governingToken;
address private _factory;
uint256 private _latestProposalId;
uint256 private _timeout;
uint256 private _maxCost;
uint256 private _executeMinPct;
uint256 private _votingMinHours;
uint256 private _voteWeightDivider;
uint256 private _lastWithdraw;
uint256 private _spendDivider;
bool private _isPublic;
bool private _isMain;
bool private _hasAdmins;
// ===============
IUniswapV2Router02 private _router;
// Constructor.
/// @notice Constructor for original Torro DAO.
/// @param governingToken_ Torro token address.
constructor(address governingToken_) public {
__Ownable_init();
_torroToken = ITorro(governingToken_);
_governingToken = ITorro(governingToken_);
_factory = address(0x0);
_latestProposalId = 0;
_timeout = uint256(5).mul(1 minutes);
_router = IUniswapV2Router02(address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D));
_maxCost = 0;
_executeMinPct = 5;
_votingMinHours = 6;
_voteWeightDivider = 10000;
_lastWithdraw = block.timestamp.add(1 * 1 weeks);
_spendDivider = 10;
_isMain = true;
_isPublic = true;
_hasAdmins = true;
_creator = msg.sender;
}
/// @notice Initializer for DAO clones.
/// @param torroToken_ main torro token address.
/// @param governingToken_ torro token clone that's governing this dao.
/// @param factory_ torro factory address.
/// @param creator_ creator of cloned DAO.
/// @param maxCost_ maximum cost of all governing tokens for cloned DAO.
/// @param executeMinPct_ minimum percentage of votes needed for proposal execution.
/// @param votingMinHours_ minimum lifetime of proposal before it closes.
/// @param isPublic_ whether cloned DAO has public visibility.
/// @param hasAdmins_ whether cloned DAO has admins, otherwise all stakers are treated as admins.
function initializeCustom(
address torroToken_,
address governingToken_,
address factory_,
address creator_,
uint256 maxCost_,
uint256 executeMinPct_,
uint256 votingMinHours_,
bool isPublic_,
bool hasAdmins_
) public override initializer {
__Ownable_init();
_torroToken = ITorro(torroToken_);
_governingToken = ITorro(governingToken_);
_factory = factory_;
_latestProposalId = 0;
_timeout = uint256(5).mul(1 minutes);
_router = IUniswapV2Router02(address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D));
_maxCost = maxCost_;
_voteWeightDivider = 0;
_executeMinPct = executeMinPct_;
_votingMinHours = votingMinHours_;
_lastWithdraw = block.timestamp;
_spendDivider = 0;
_isMain = false;
_isPublic = isPublic_;
_hasAdmins = hasAdmins_;
_creator = creator_;
if (_hasAdmins) {
_admins.add(creator_);
}
}
// Modifiers.
/// @notice Stops double execution of proposals.
/// @param id_ proposal id that's executing.
modifier nonReentrant(uint256 id_) {
// check that it's already not executing
require(!_reentrancyGuards[id_]);
// toggle state that proposal is currently executing
_reentrancyGuards[id_] = true;
_;
// toggle state back
_reentrancyGuards[id_] = false;
}
/// @notice Allow fund transfers to DAO contract.
receive() external payable {
// do nothing
}
// Public calls.
/// @notice Address of DAO creator.
/// @return DAO creator address.
function daoCreator() public override view returns (address) {
return _creator;
}
/// @notice Amount of tokens needed for a single vote.
/// @return uint256 token amount.
function voteWeight() public override view returns (uint256) {
uint256 weight;
if (_isMain) {
weight = _governingToken.totalSupply() / _voteWeightDivider;
} else {
weight = 10**18;
}
return weight;
}
/// @notice Amount of votes that holder has.
/// @param sender_ address of the holder.
/// @return number of votes.
function votesOf(address sender_) public override view returns (uint256) {
return _governingToken.stakedOf(sender_) / voteWeight();
}
/// @notice Address of the governing token.
/// @return address of the governing token.
function tokenAddress() public override view returns (address) {
return address(_governingToken);
}
/// @notice Saved addresses of tokens that DAO is holding.
/// @return array of holdings addresses.
function holdings() public override view returns (address[] memory) {
uint256 length = _holdings.length();
address[] memory holdingsAddresses = new address[](length);
for (uint256 i = 0; i < length; i++) {
holdingsAddresses[i] = _holdings.at(i);
}
return holdingsAddresses;
}
/// @notice Saved addresses of liquidity tokens that DAO is holding.
/// @return array of liquidity addresses.
function liquidities() public override view returns (address[] memory) {
uint256 length = _liquidityAddresses.length();
address[] memory liquidityAddresses = new address[](length);
for (uint256 i = 0; i < length; i++) {
liquidityAddresses[i] = _liquidityAddresses.at(i);
}
return liquidityAddresses;
}
/// @notice Calculates address of liquidity token from ERC-20 token address.
/// @param token_ token address to calculate liquidity address from.
/// @return address of liquidity token.
function liquidityToken(address token_) public override view returns (address) {
return UniswapV2Library.pairFor(_router.factory(), token_, _router.WETH());
}
/// @notice Gets tokens and liquidity token addresses of DAO's liquidity holdings.
/// @return Arrays of tokens and liquidity tokens, should have the same length.
function liquidityHoldings() public override view returns (address[] memory, address[] memory) {
uint256 length = _liquidityAddresses.length();
address[] memory tokens = new address[](length);
address[] memory liquidityTokens = new address[](length);
for (uint256 i = 0; i < length; i++) {
address token = _liquidityAddresses.at(i);
tokens[i] = token;
liquidityTokens[i] = liquidityToken(token);
}
return (tokens, liquidityTokens);
}
/// @notice DAO admins.
/// @return Array of admin addresses.
function admins() public override view returns (address[] memory) {
uint256 length = _admins.length();
address[] memory currentAdmins = new address[](length);
for (uint256 i = 0; i < length; i++) {
currentAdmins[i] = _admins.at(i);
}
return currentAdmins;
}
/// @notice DAO balance for specified token.
/// @param token_ token address to get balance for.
/// @return uint256 token balance.
function tokenBalance(address token_) public override view returns (uint256) {
return IERC20(token_).balanceOf(address(this));
}
/// @notice DAO balance for liquidity token.
/// @param token_ token address to get liquidity balance for.
/// @return uin256 token liquidity balance.
function liquidityBalance(address token_) public override view returns (uint256) {
return tokenBalance(liquidityToken(token_));
}
/// @notice DAO ethereum balance.
/// @return uint256 wei balance.
function availableBalance() public override view returns (uint256) {
return address(this).balance;
}
/// @notice Maximum cost for all tokens of cloned DAO.
/// @return uint256 maximum cost in wei.
function maxCost() public override view returns (uint256) {
return _maxCost;
}
/// @notice Minimum percentage of votes needed to execute a proposal.
/// @return uint256 minimum percentage of votes.
function executeMinPct() public override view returns (uint256) {
return _executeMinPct;
}
/// @notice Minimum lifetime of proposal before it closes.
/// @return uint256 minimum number of hours for proposal lifetime.
function votingMinHours() public override view returns (uint256) {
return _votingMinHours;
}
/// @notice Whether DAO is public or private.
/// @return bool true if public.
function isPublic() public override view returns (bool) {
return _isPublic;
}
/// @notice Whether DAO has admins.
/// @return bool true if DAO has admins.
function hasAdmins() public override view returns (bool) {
return _hasAdmins;
}
/// @notice Proposal ids of DAO.
/// @return array of proposal ids.
function getProposalIds() public override view returns (uint256[] memory) {
uint256 proposalsLength = _proposalIds.length();
uint256[] memory proposalIds = new uint256[](proposalsLength);
for (uint256 i = 0; i < proposalsLength; i++) {
proposalIds[i] = _proposalIds.at(i);
}
return proposalIds;
}
/// @notice Gets proposal info for proposal id.
/// @param id_ id of proposal to get info for.
/// @return proposalAddress address for proposal execution.
/// @return investTokenAddress secondary address for proposal execution, used for investment proposals if ICO and token addresses differ.
/// @return daoFunction proposal type.
/// @return amount proposal amount eth/token to use during execution.
/// @return creator address of proposal creator.
/// @return endLifetime epoch time when proposal voting ends.
/// @return votesFor amount of votes for the proposal.
/// @return votesAgainst amount of votes against the proposal.
/// @return executed whether proposal has been executed or not.
function getProposal(uint256 id_) public override view returns (
address proposalAddress,
address investTokenAddress,
DaoFunction daoFunction,
uint256 amount,
address creator,
uint256 endLifetime,
uint256 votesFor,
uint256 votesAgainst,
bool executed
) {
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
return (
currentProposal.proposalAddress,
currentProposal.investTokenAddress,
currentProposal.daoFunction,
currentProposal.amount,
currentProposal.creator,
currentProposal.endLifetime,
currentProposal.votesFor,
currentProposal.votesAgainst,
currentProposal.executed
);
}
/// @notice Whether a holder is allowed to vote for a proposal.
/// @param id_ proposal id to check whether holder is allowed to vote for.
/// @param sender_ address of the holder.
/// @return bool true if voting is allowed.
function canVote(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
return proposal.endLifetime >= block.timestamp && proposal.creator != sender_ && !proposal.voterAddresses.contains(sender_);
}
/// @notice Whether a holder is allowed to remove a proposal.
/// @param id_ proposal id to check whether holder is allowed to remove.
/// @param sender_ address of the holder.
/// @return bool true if removal is allowed.
function canRemove(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
return proposal.endLifetime >= block.timestamp && proposal.voterAddresses.length() == 1 && (proposal.creator == sender_ || owner() == sender_);
}
/// @notice Whether a holder is allowed to execute a proposal.
/// @param id_ proposal id to check whether holder is allowed to execute.
/// @param sender_ address of the holder.
/// @return bool true if execution is allowed.
function canExecute(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
// check that proposal hasn't been executed yet.
if (proposal.executed) {
return false;
}
// if custom pool has admins then only admins can execute proposals
if (!_isMain && _hasAdmins) {
if (!isAdmin(sender_)) {
return false;
}
}
if (proposal.daoFunction == DaoFunction.INVEST) {
// for invest functions only admins can execute
if (sender_ != _creator && !_admins.contains(sender_)) {
return false;
}
// check that sender is proposal creator or admin
} else if (proposal.creator != sender_ && !isAdmin(sender_)) {
return false;
}
// For main pool Buy and Sell dao functions allow instant executions if at least 10% of staked supply has voted for it
if (_isMain && (proposal.daoFunction == DaoFunction.BUY || proposal.daoFunction == DaoFunction.SELL)) {
if (proposal.votesFor.mul(voteWeight()) >= _governingToken.stakedSupply() / 10) {
if (proposal.votesFor > proposal.votesAgainst) {
// only allow admins to execute buy and sell proposals early
return isAdmin(sender_);
}
}
}
// check that proposal voting lifetime has run out.
if (proposal.endLifetime > block.timestamp) {
return false;
}
// check that votes for outweigh votes against.
bool currentCanExecute = proposal.votesFor > proposal.votesAgainst;
if (currentCanExecute && _executeMinPct > 0) {
// Check that proposal has at least _executeMinPct% of staked votes.
uint256 minVotes = _governingToken.stakedSupply() / (100 / _executeMinPct);
currentCanExecute = minVotes <= proposal.votesFor.add(proposal.votesAgainst).mul(voteWeight());
}
return currentCanExecute;
}
/// @notice Whether a holder is an admin.
/// @param sender_ address of holder.
/// @return bool true if holder is an admin (in DAO without admins all holders are treated as such).
function isAdmin(address sender_) public override view returns (bool) {
return !_hasAdmins || sender_ == _creator || _admins.contains(sender_);
}
// Public transactions.
/// @notice Saves new holdings addresses for DAO.
/// @param tokens_ token addresses that DAO has holdings of.
function addHoldingsAddresses(address[] memory tokens_) public override {
require(isAdmin(msg.sender));
for (uint256 i = 0; i < tokens_.length; i++) {
address token = tokens_[i];
if (!_holdings.contains(token)) {
_holdings.add(token);
}
}
emit HoldingsAddressesChanged();
}
/// @notice Saves new liquidity addresses for DAO.
/// @param tokens_ token addresses that DAO has liquidities of.
function addLiquidityAddresses(address[] memory tokens_) public override {
require(isAdmin(msg.sender));
for (uint256 i = 0; i < tokens_.length; i++) {
address token = tokens_[i];
if (!_liquidityAddresses.contains(token)) {
_liquidityAddresses.add(token);
}
}
emit LiquidityAddressesChanged();
}
/// @notice Creates new proposal.
/// @param proposalAddress_ main address of the proposal, in investment proposals this is the address funds are sent to.
/// @param investTokenAddress_ secondary address of the proposal, used in investment proposals to specify token address.
/// @param daoFunction_ type of the proposal.
/// @param amount_ amount of funds to use in the proposal.
/// @param hoursLifetime_ voting lifetime of the proposal.
function propose(address proposalAddress_, address investTokenAddress_, DaoFunction daoFunction_, uint256 amount_, uint256 hoursLifetime_) public override {
// check that lifetime is at least equals to min hours set for DAO.
require(hoursLifetime_ >= _votingMinHours);
// Check that proposal creator is allowed to create a proposal.
uint256 balance = _governingToken.stakedOf(msg.sender);
uint256 weight = voteWeight();
require(balance >= weight);
// For main DAO.
if (_isMain) {
if (daoFunction_ == DaoFunction.WITHDRAW || daoFunction_ == DaoFunction.INVEST || daoFunction_ == DaoFunction.BUY) {
// Limit each buy, investment and withdraw proposals to 10% of ETH funds.
require(amount_ <= (availableBalance() / _spendDivider));
}
}
// Increment proposal id counter.
_latestProposalId++;
uint256 currentId = _latestProposalId;
// Calculate end lifetime of the proposal.
uint256 endLifetime = block.timestamp.add(hoursLifetime_.mul(1 hours));
// Declare voter addresses set.
EnumerableSet.AddressSet storage voterAddresses;
// Save proposal struct.
_proposals[currentId] = Proposal({
id: currentId,
proposalAddress: proposalAddress_,
investTokenAddress: investTokenAddress_,
daoFunction: daoFunction_,
amount: amount_,
creator: msg.sender,
endLifetime: endLifetime,
voterAddresses: voterAddresses,
votesFor: balance / weight,
votesAgainst: 0,
executed: false
});
// Save id of new proposal.
_proposalIds.add(currentId);
// Emit event that new proposal has been created.
emit NewProposal(currentId);
}
/// @notice Removes existing proposal.
/// @param id_ id of proposal to remove.
function unpropose(uint256 id_) public override {
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
// Check that proposal creator, owner or an admin is removing a proposal.
require(msg.sender == currentProposal.creator || msg.sender == _creator || _admins.contains(msg.sender));
// Check that no votes have been registered for the proposal apart from the proposal creator, pool creator can remove any proposal.
if (msg.sender != _creator) {
require(currentProposal.voterAddresses.length() == 1);
}
// Remove proposal.
delete _proposals[id_];
_proposalIds.remove(id_);
// Emit event that a proposal has been removed.
emit RemoveProposal(id_);
}
/// @notice Voting for multiple proposals.
/// @param ids_ ids of proposals to vote for.
/// @param votes_ for or against votes for proposals.
function vote(uint256[] memory ids_, bool[] memory votes_) public override {
// Check that arrays of the same length have been supplied.
require(ids_.length == votes_.length);
// Check that voter has enough tokens staked to vote.
uint256 balance = _governingToken.stakedOf(msg.sender);
uint256 weight = voteWeight();
require(balance >= weight);
// Get number of votes that msg.sender has.
uint256 votesCount = balance / weight;
// Iterate over voted proposals.
for (uint256 i = 0; i < ids_.length; i++) {
uint256 id = ids_[i];
bool currentVote = votes_[i];
Proposal storage proposal = _proposals[id];
// Check that proposal hasn't been voted for by msg.sender and that it's still active.
if (!proposal.voterAddresses.contains(msg.sender) && proposal.endLifetime >= block.timestamp) {
// Add votes.
proposal.voterAddresses.add(msg.sender);
if (currentVote) {
proposal.votesFor = proposal.votesFor.add(votesCount);
} else {
proposal.votesAgainst = proposal.votesAgainst.add(votesCount);
}
}
// Emit event that a proposal has been voted for.
emit Vote(id);
}
}
/// @notice Executes a proposal.
/// @param id_ id of proposal to be executed.
function execute(uint256 id_) public override nonReentrant(id_) {
// save gas at the start of execution
uint256 remainingGasStart = gasleft();
// check whether proposal can be executed by the sender
require(canExecute(id_, msg.sender));
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
// Check that msg.sender has balance for at least 1 vote to execute a proposal.
uint256 balance = _governingToken.totalOf(msg.sender);
if (balance < voteWeight()) {
// Remove admin if his balance is not high enough.
if (_admins.contains(msg.sender)) {
_admins.remove(msg.sender);
}
revert();
}
// Call private function for proposal execution depending on the type.
if (currentProposal.daoFunction == DaoFunction.BUY) {
_executeBuy(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.SELL) {
_executeSell(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.ADD_LIQUIDITY) {
_executeAddLiquidity(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.REMOVE_LIQUIDITY) {
_executeRemoveLiquidity(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.ADD_ADMIN) {
_executeAddAdmin(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.REMOVE_ADMIN) {
_executeRemoveAdmin(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.INVEST) {
_executeInvest(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.WITHDRAW) {
_executeWithdraw(currentProposal);
}
// Mark proposal as executed.
currentProposal.executed = true;
// calculate gas used during execution
uint256 remainingGasEnd = gasleft();
uint256 usedGas = remainingGasStart.sub(remainingGasEnd).add(35000);
// max gas price allowed for refund is 200gwei
uint256 gasPrice;
if (tx.gasprice > 200000000000) {
gasPrice = 200000000000;
} else {
gasPrice = tx.gasprice;
}
// refund used gas
payable(msg.sender).transfer(usedGas.mul(gasPrice));
// Emit event that proposal has been executed.
emit ExecutedProposal(id_);
}
/// @notice Buying tokens for cloned DAO.
function buy() public override payable {
// Check that it's not the main DAO.
require(!_isMain);
// Check that msg.sender is not sending more money than max cost of dao.
require(msg.value <= _maxCost);
// Check that DAO has enough tokens to sell to msg.sender.
uint256 portion = _governingToken.totalSupply().mul(msg.value) / _maxCost;
require(_governingToken.balanceOf(address(this)) >= portion);
// Transfer tokens.
_governingToken.transfer(msg.sender, portion);
// Emit event that tokens have been bought.
emit Buy();
}
/// @notice Sell tokens back to cloned DAO.
/// @param amount_ amount of tokens to sell.
function sell(uint256 amount_) public override {
// Check that it's not the main DAO.
require(!_isMain);
// Check that msg.sender has enough tokens to sell.
require(_governingToken.balanceOf(msg.sender) >= amount_);
// Calculate the eth share holder should get back and whether pool has enough funds.
uint256 share = _supplyShare(amount_);
// Approve token transfer for DAO.
_governingToken.approveDao(msg.sender, amount_);
// Transfer tokens from msg.sender back to DAO.
_governingToken.transferFrom(msg.sender, address(this), amount_);
// Refund eth back to the msg.sender.
payable(msg.sender).transfer(share);
// Emit event that tokens have been sold back to DAO.
emit Sell();
}
// Private calls.
/// @notice Calculates cost of share of the supply.
/// @param amount_ amount of tokens to calculate eth share for.
/// @return price for specified amount share.
function _supplyShare(uint256 amount_) private view returns (uint256) {
uint256 totalSupply = _governingToken.totalSupply();
uint256 circulatingSupply = _circulatingSupply(totalSupply);
uint256 circulatingMaxCost = _circulatingMaxCost(circulatingSupply, totalSupply);
// Check whether available balance is higher than circulating max cost.
if (availableBalance() > circulatingMaxCost) {
// If true then share will equal to buy price.
return circulatingMaxCost.mul(amount_) / circulatingSupply;
} else {
// Otherwise calculate share price based on currently available balance.
return availableBalance().mul(amount_) / circulatingSupply;
}
}
/// @notice Calculates max cost for currently circulating supply.
/// @param circulatingSupply_ governing token circulating supply.
/// @param totalSupply_ governing token total supply.
/// @return uint256 eth cost of currently circulating supply.
function _circulatingMaxCost(uint256 circulatingSupply_, uint256 totalSupply_) private view returns (uint256) {
return _maxCost.mul(circulatingSupply_) / totalSupply_;
}
/// @notice Calculates circulating supply of governing token.
/// @param totalSupply_ governing token total supply.
/// @return uint256 number of tokens in circulation.
function _circulatingSupply(uint256 totalSupply_) private view returns (uint256) {
uint256 balance = _governingToken.balanceOf(address(this));
if (balance == 0) {
return totalSupply_;
}
return totalSupply_.sub(balance);
}
// Private transactions.
/// @notice Execution of BUY proposal.
/// @param proposal_ proposal.
function _executeBuy(Proposal storage proposal_) private {
// Check that DAO has enough funds to execute buy proposal.
require(availableBalance() >= proposal_.amount);
// Deposit eth funds to Uniswap router.
IWETH weth = IWETH(_router.WETH());
weth.deposit{value: proposal_.amount}();
// Create path for buying, buying is only for Token-ETH pair.
address[] memory path = new address[](2);
path[0] = address(weth);
path[1] = proposal_.proposalAddress;
// Execute uniswap buy.
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), path[0], path[1]);
uint256 amountOut = UniswapV2Library.getAmountOut(proposal_.amount, reserveA, reserveB);
_router.swapExactETHForTokens{value: proposal_.amount}(amountOut, path, address(this), block.timestamp.add(_timeout));
// If new token then save it holdings addresses.
if (!_holdings.contains(proposal_.proposalAddress)) {
_holdings.add(proposal_.proposalAddress);
// Emit event that holdings addresses changed.
emit HoldingsAddressesChanged();
}
}
/// @notice Execution of SELL proposal.
/// @param proposal_ proposal.
function _executeSell(Proposal storage proposal_) private {
// Approve uniswap router to sell tokens.
IERC20 token = IERC20(proposal_.proposalAddress);
require(token.approve(address(_router), proposal_.amount));
// Create path for selling, selling is only for Token-ETH pair.
address[] memory path = new address[](2);
path[0] = proposal_.proposalAddress;
path[1] = _router.WETH();
// Execute uniswap sell.
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), path[0], path[1]);
uint256 amountOut = UniswapV2Library.getAmountOut(proposal_.amount, reserveA, reserveB);
_router.swapExactTokensForETH(proposal_.amount, amountOut, path, address(this), block.timestamp.add(_timeout));
// If sold all tokens then remove it from holdings.
if (token.balanceOf(address(this)) == 0 && _holdings.contains(proposal_.proposalAddress)) {
_holdings.remove(proposal_.proposalAddress);
// Emit event that holdings addresses changed.
emit HoldingsAddressesChanged();
}
}
/// @notice Execution of ADD_LIQUIDITY proposal.
/// @param proposal_ proposal.
function _executeAddLiquidity(Proposal storage proposal_) private {
// Approve uniswap route to transfer tokens.
require(IERC20(proposal_.proposalAddress).approve(address(_router), proposal_.amount));
// Calculate amount of tokens and eth needed for liquidity.
IWETH weth = IWETH(_router.WETH());
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), proposal_.proposalAddress, address(weth));
uint256 wethAmount = UniswapV2Library.quote(proposal_.amount, reserveA, reserveB);
// Check that DAO has sufficient eth balance for liquidity.
require (availableBalance() > wethAmount);
// Deposit eth for liqudity.
weth.deposit{value: wethAmount}();
// Execute uniswap add liquidity.
_router.addLiquidityETH{value: wethAmount}(
proposal_.proposalAddress,
proposal_.amount,
(proposal_.amount / 100).mul(98),
(wethAmount / 100).mul(98),
address(this),
block.timestamp.add(_timeout)
);
// If new liquidity token then save it.
if (!_liquidityAddresses.contains(proposal_.proposalAddress)) {
_liquidityAddresses.add(proposal_.proposalAddress);
// Emit event that liquidity addresses changed.
emit LiquidityAddressesChanged();
}
}
/// @notice Execution of REMOVE_LIQUIDITY proposal.
/// @param proposal_ proposal.
function _executeRemoveLiquidity(Proposal storage proposal_) private {
// Approve uniswap router to transfer liquidity tokens.
address liquidityTokenAddress = liquidityToken(proposal_.proposalAddress);
require(IERC20(liquidityTokenAddress).approve(address(_router), proposal_.amount));
// Execute uniswap liquidity removal.
_router.removeLiquidityETH(
proposal_.proposalAddress,
proposal_.amount,
0,
0,
address(this),
block.timestamp.add(_timeout)
);
// If all tokens have been sold then remove liquidty address.
if (tokenBalance(liquidityTokenAddress) == 0 && _liquidityAddresses.contains(proposal_.proposalAddress)) {
_liquidityAddresses.remove(proposal_.proposalAddress);
// Emit event that liquidity addresses have changed.
emit LiquidityAddressesChanged();
}
}
/// @notice Execution of ADD_ADMIN proposal.
/// @param proposal_ propsal.
function _executeAddAdmin(Proposal storage proposal_) private {
// Check that address is not an admin already.
require(!_admins.contains(proposal_.proposalAddress));
// Check that holder has sufficient balance to be an admin.
uint256 balance = _governingToken.totalOf(proposal_.proposalAddress);
require(balance >= voteWeight());
// Add admin.
_admins.add(proposal_.proposalAddress);
// Emit event that new admin has been added.
emit AddAdmin(proposal_.proposalAddress);
}
/// @notice Execution of REMOVE_ADMIN proposal.
/// @param proposal_ proposal.
function _executeRemoveAdmin(Proposal storage proposal_) private {
// Check that address is an admin.
require(_admins.contains(proposal_.proposalAddress));
// Remove admin.
_admins.remove(proposal_.proposalAddress);
// Emit event that an admin has been removed.
emit RemoveAdmin(proposal_.proposalAddress);
}
/// @notice Execution of INVEST proposal.
/// @param proposal_ proposal.
function _executeInvest(Proposal storage proposal_) private {
// Check that DAO has sufficient balance for investment.
require(availableBalance() >= proposal_.amount);
// Transfer funds.
payable(proposal_.proposalAddress).call{value: proposal_.amount}("");
// If secondary address for invest token is specified then save it to holdings.
if(proposal_.investTokenAddress != address(0x0)) {
if (!_holdings.contains(proposal_.investTokenAddress)) {
_holdings.add(proposal_.investTokenAddress);
// Emit event that holdings addresses have changed.
emit HoldingsAddressesChanged();
}
}
}
/// @notice Execution of WITHDRAW proposal.
/// @param proposal_ proposal.
function _executeWithdraw(Proposal storage proposal_) private {
if (_isMain) {
// Main DAO only allows withdrawal once a week.
require(block.timestamp > _lastWithdraw.add(1 * 1 weeks));
_lastWithdraw = block.timestamp;
}
uint256 amount;
uint256 mainAmount;
uint256 currentBalance = availableBalance();
if (_isMain) {
mainAmount = 0;
amount = proposal_.amount;
// Check that withdrawal amount is not more than 10% of main DAO balance.
require(currentBalance / 10 >= amount);
} else {
uint256 totalSupply = _governingToken.totalSupply();
uint256 circulatingMaxCost = _circulatingMaxCost(_circulatingSupply(totalSupply), totalSupply);
// Check that cloned DAO balance is higher than circulating max cost.
require(currentBalance > circulatingMaxCost);
// Check that cloned DAO gains are enough to cover withdrawal.
require(currentBalance.sub(circulatingMaxCost) >= proposal_.amount);
// 0.25% of withdrawal will be transfered to Main DAO stakers.
mainAmount = proposal_.amount / 400;
amount = proposal_.amount.sub(mainAmount);
}
// Transfer all withdrawal funds to Torro Factory.
ITorroFactory(_factory).depositBenefits{value: proposal_.amount}(address(_governingToken));
// Divide withdrawal between governing token stakers.
_governingToken.addBenefits(amount);
// If cloned DAO withdrawal then divide 0.25% of withdrawal between main token stakers.
if (mainAmount > 0) {
_torroToken.addBenefits(mainAmount);
}
}
// Owner calls.
// Owner transactions.
/// @notice Sets factory address.
/// @param factory_ address of TorroFactory.
function setFactoryAddress(address factory_) public override onlyOwner {
_factory = factory_;
}
/// @notice Sets vote weight divider.
/// @param weight_ weight divider for a single vote.
function setVoteWeightDivider(uint256 weight_) public override onlyOwner {
_voteWeightDivider = weight_;
}
/// @notice Sets new address for router.
/// @param router_ address for router.
function setRouter(address router_) public override onlyOwner {
_router = IUniswapV2Router02(router_);
}
/// @notice Sets divider for BUY, INVEST, WITHDAW proposals.
/// @param divider_ divider for BUY, INVEST, WITHDRAW proposals.
function setSpendDivider(uint256 divider_) public override onlyOwner {
_spendDivider = divider_;
}
/// @notice Migrates balances of current DAO to a new DAO.
/// @param newDao_ address of the new DAO to migrate to.
function migrate(address newDao_) public override onlyOwner {
ITorroDao dao = ITorroDao(newDao_);
// Migrate holdings.
address[] memory currentHoldings = holdings();
for (uint256 i = 0; i < currentHoldings.length; i++) {
_migrateTransferBalance(currentHoldings[i], newDao_);
}
dao.addHoldingsAddresses(currentHoldings);
// Migrate liquidities.
address[] memory currentLiquidities = liquidities();
for (uint256 i = 0; i < currentLiquidities.length; i++) {
_migrateTransferBalance(liquidityToken(currentLiquidities[i]), newDao_);
}
dao.addLiquidityAddresses(currentLiquidities);
// Send over ETH balance.
payable(newDao_).call{value: availableBalance()}("");
}
// Private owner calls.
/// @notice Private function for migrating token balance to a new address.
/// @param token_ address of ERC-20 token to migrate.
/// @param target_ migration end point address.
function _migrateTransferBalance(address token_, address target_) private {
if (token_ != address(0x0)) {
IERC20 erc20 = IERC20(token_);
uint256 balance = erc20.balanceOf(address(this));
if (balance > 0) {
erc20.transfer(target_, balance);
}
}
}
} | /// @title DAO for proposals, voting and execution.
/// @notice Contract for creation, voting and execution of proposals.
/// @author ORayskiy - @robitnik_TorroDao | NatSpecSingleLine | setFactoryAddress | function setFactoryAddress(address factory_) public override onlyOwner {
_factory = factory_;
}
| /// @notice Sets factory address.
/// @param factory_ address of TorroFactory. | NatSpecSingleLine | v0.6.6+commit.6c089d02 | Unknown | ipfs://d1c6095fcf143d951c9754f00fe8cd59d29ab460461efe53b91eb289fd0fe5ac | {
"func_code_index": [
35978,
36084
]
} | 58,563 |
TorroDao | TorroDao.sol | 0x3cf9e9d45380b6ab61bde46b2e6cfcd7d8f6cdc1 | Solidity | TorroDao | contract TorroDao is ITorroDao, OwnableUpgradeSafe {
using EnumerableSet for EnumerableSet.AddressSet;
using EnumerableSet for EnumerableSet.UintSet;
using SafeMath for uint256;
// Structs.
/// @notice General proposal structure.
struct Proposal {
uint256 id;
address proposalAddress;
address investTokenAddress;
DaoFunction daoFunction;
uint256 amount;
address creator;
uint256 endLifetime;
EnumerableSet.AddressSet voterAddresses;
uint256 votesFor;
uint256 votesAgainst;
bool executed;
}
// Events.
/// @notice Event for dispatching on new proposal creation.
/// @param id id of the new proposal.
event NewProposal(uint256 id);
/// @notice Event for dispatching when proposal has been removed.
/// @param id id of the removed proposal.
event RemoveProposal(uint256 id);
/// @notice Event for dispatching when someone voted on a proposal.
/// @param id id of the voted proposal.
event Vote(uint256 id);
/// @notice Event for dispatching when an admin has been added to the DAO.
/// @param admin address of the admin that's been added.
event AddAdmin(address admin);
/// @notice Event for dispatching when an admin has been removed from the DAO.
/// @param admin address of the admin that's been removed.
event RemoveAdmin(address admin);
/// @notice Event for dispatching when a proposal has been executed.
/// @param id id of the executed proposal.
event ExecutedProposal(uint256 id);
/// @notice Event for dispatching when cloned DAO tokens have been bought.
event Buy();
/// @notice Event for dispatching when cloned DAO tokens have been sold.
event Sell();
/// @notice Event for dispatching when new holdings addresses have been changed.
event HoldingsAddressesChanged();
/// @notice Event for dipatching when new liquidity addresses have been changed.
event LiquidityAddressesChanged();
// Constants.
// Private data.
address private _creator;
EnumerableSet.AddressSet private _holdings;
EnumerableSet.AddressSet private _liquidityAddresses;
EnumerableSet.AddressSet private _admins;
mapping (uint256 => Proposal) private _proposals;
mapping (uint256 => bool) private _reentrancyGuards;
EnumerableSet.UintSet private _proposalIds;
ITorro private _torroToken;
ITorro private _governingToken;
address private _factory;
uint256 private _latestProposalId;
uint256 private _timeout;
uint256 private _maxCost;
uint256 private _executeMinPct;
uint256 private _votingMinHours;
uint256 private _voteWeightDivider;
uint256 private _lastWithdraw;
uint256 private _spendDivider;
bool private _isPublic;
bool private _isMain;
bool private _hasAdmins;
// ===============
IUniswapV2Router02 private _router;
// Constructor.
/// @notice Constructor for original Torro DAO.
/// @param governingToken_ Torro token address.
constructor(address governingToken_) public {
__Ownable_init();
_torroToken = ITorro(governingToken_);
_governingToken = ITorro(governingToken_);
_factory = address(0x0);
_latestProposalId = 0;
_timeout = uint256(5).mul(1 minutes);
_router = IUniswapV2Router02(address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D));
_maxCost = 0;
_executeMinPct = 5;
_votingMinHours = 6;
_voteWeightDivider = 10000;
_lastWithdraw = block.timestamp.add(1 * 1 weeks);
_spendDivider = 10;
_isMain = true;
_isPublic = true;
_hasAdmins = true;
_creator = msg.sender;
}
/// @notice Initializer for DAO clones.
/// @param torroToken_ main torro token address.
/// @param governingToken_ torro token clone that's governing this dao.
/// @param factory_ torro factory address.
/// @param creator_ creator of cloned DAO.
/// @param maxCost_ maximum cost of all governing tokens for cloned DAO.
/// @param executeMinPct_ minimum percentage of votes needed for proposal execution.
/// @param votingMinHours_ minimum lifetime of proposal before it closes.
/// @param isPublic_ whether cloned DAO has public visibility.
/// @param hasAdmins_ whether cloned DAO has admins, otherwise all stakers are treated as admins.
function initializeCustom(
address torroToken_,
address governingToken_,
address factory_,
address creator_,
uint256 maxCost_,
uint256 executeMinPct_,
uint256 votingMinHours_,
bool isPublic_,
bool hasAdmins_
) public override initializer {
__Ownable_init();
_torroToken = ITorro(torroToken_);
_governingToken = ITorro(governingToken_);
_factory = factory_;
_latestProposalId = 0;
_timeout = uint256(5).mul(1 minutes);
_router = IUniswapV2Router02(address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D));
_maxCost = maxCost_;
_voteWeightDivider = 0;
_executeMinPct = executeMinPct_;
_votingMinHours = votingMinHours_;
_lastWithdraw = block.timestamp;
_spendDivider = 0;
_isMain = false;
_isPublic = isPublic_;
_hasAdmins = hasAdmins_;
_creator = creator_;
if (_hasAdmins) {
_admins.add(creator_);
}
}
// Modifiers.
/// @notice Stops double execution of proposals.
/// @param id_ proposal id that's executing.
modifier nonReentrant(uint256 id_) {
// check that it's already not executing
require(!_reentrancyGuards[id_]);
// toggle state that proposal is currently executing
_reentrancyGuards[id_] = true;
_;
// toggle state back
_reentrancyGuards[id_] = false;
}
/// @notice Allow fund transfers to DAO contract.
receive() external payable {
// do nothing
}
// Public calls.
/// @notice Address of DAO creator.
/// @return DAO creator address.
function daoCreator() public override view returns (address) {
return _creator;
}
/// @notice Amount of tokens needed for a single vote.
/// @return uint256 token amount.
function voteWeight() public override view returns (uint256) {
uint256 weight;
if (_isMain) {
weight = _governingToken.totalSupply() / _voteWeightDivider;
} else {
weight = 10**18;
}
return weight;
}
/// @notice Amount of votes that holder has.
/// @param sender_ address of the holder.
/// @return number of votes.
function votesOf(address sender_) public override view returns (uint256) {
return _governingToken.stakedOf(sender_) / voteWeight();
}
/// @notice Address of the governing token.
/// @return address of the governing token.
function tokenAddress() public override view returns (address) {
return address(_governingToken);
}
/// @notice Saved addresses of tokens that DAO is holding.
/// @return array of holdings addresses.
function holdings() public override view returns (address[] memory) {
uint256 length = _holdings.length();
address[] memory holdingsAddresses = new address[](length);
for (uint256 i = 0; i < length; i++) {
holdingsAddresses[i] = _holdings.at(i);
}
return holdingsAddresses;
}
/// @notice Saved addresses of liquidity tokens that DAO is holding.
/// @return array of liquidity addresses.
function liquidities() public override view returns (address[] memory) {
uint256 length = _liquidityAddresses.length();
address[] memory liquidityAddresses = new address[](length);
for (uint256 i = 0; i < length; i++) {
liquidityAddresses[i] = _liquidityAddresses.at(i);
}
return liquidityAddresses;
}
/// @notice Calculates address of liquidity token from ERC-20 token address.
/// @param token_ token address to calculate liquidity address from.
/// @return address of liquidity token.
function liquidityToken(address token_) public override view returns (address) {
return UniswapV2Library.pairFor(_router.factory(), token_, _router.WETH());
}
/// @notice Gets tokens and liquidity token addresses of DAO's liquidity holdings.
/// @return Arrays of tokens and liquidity tokens, should have the same length.
function liquidityHoldings() public override view returns (address[] memory, address[] memory) {
uint256 length = _liquidityAddresses.length();
address[] memory tokens = new address[](length);
address[] memory liquidityTokens = new address[](length);
for (uint256 i = 0; i < length; i++) {
address token = _liquidityAddresses.at(i);
tokens[i] = token;
liquidityTokens[i] = liquidityToken(token);
}
return (tokens, liquidityTokens);
}
/// @notice DAO admins.
/// @return Array of admin addresses.
function admins() public override view returns (address[] memory) {
uint256 length = _admins.length();
address[] memory currentAdmins = new address[](length);
for (uint256 i = 0; i < length; i++) {
currentAdmins[i] = _admins.at(i);
}
return currentAdmins;
}
/// @notice DAO balance for specified token.
/// @param token_ token address to get balance for.
/// @return uint256 token balance.
function tokenBalance(address token_) public override view returns (uint256) {
return IERC20(token_).balanceOf(address(this));
}
/// @notice DAO balance for liquidity token.
/// @param token_ token address to get liquidity balance for.
/// @return uin256 token liquidity balance.
function liquidityBalance(address token_) public override view returns (uint256) {
return tokenBalance(liquidityToken(token_));
}
/// @notice DAO ethereum balance.
/// @return uint256 wei balance.
function availableBalance() public override view returns (uint256) {
return address(this).balance;
}
/// @notice Maximum cost for all tokens of cloned DAO.
/// @return uint256 maximum cost in wei.
function maxCost() public override view returns (uint256) {
return _maxCost;
}
/// @notice Minimum percentage of votes needed to execute a proposal.
/// @return uint256 minimum percentage of votes.
function executeMinPct() public override view returns (uint256) {
return _executeMinPct;
}
/// @notice Minimum lifetime of proposal before it closes.
/// @return uint256 minimum number of hours for proposal lifetime.
function votingMinHours() public override view returns (uint256) {
return _votingMinHours;
}
/// @notice Whether DAO is public or private.
/// @return bool true if public.
function isPublic() public override view returns (bool) {
return _isPublic;
}
/// @notice Whether DAO has admins.
/// @return bool true if DAO has admins.
function hasAdmins() public override view returns (bool) {
return _hasAdmins;
}
/// @notice Proposal ids of DAO.
/// @return array of proposal ids.
function getProposalIds() public override view returns (uint256[] memory) {
uint256 proposalsLength = _proposalIds.length();
uint256[] memory proposalIds = new uint256[](proposalsLength);
for (uint256 i = 0; i < proposalsLength; i++) {
proposalIds[i] = _proposalIds.at(i);
}
return proposalIds;
}
/// @notice Gets proposal info for proposal id.
/// @param id_ id of proposal to get info for.
/// @return proposalAddress address for proposal execution.
/// @return investTokenAddress secondary address for proposal execution, used for investment proposals if ICO and token addresses differ.
/// @return daoFunction proposal type.
/// @return amount proposal amount eth/token to use during execution.
/// @return creator address of proposal creator.
/// @return endLifetime epoch time when proposal voting ends.
/// @return votesFor amount of votes for the proposal.
/// @return votesAgainst amount of votes against the proposal.
/// @return executed whether proposal has been executed or not.
function getProposal(uint256 id_) public override view returns (
address proposalAddress,
address investTokenAddress,
DaoFunction daoFunction,
uint256 amount,
address creator,
uint256 endLifetime,
uint256 votesFor,
uint256 votesAgainst,
bool executed
) {
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
return (
currentProposal.proposalAddress,
currentProposal.investTokenAddress,
currentProposal.daoFunction,
currentProposal.amount,
currentProposal.creator,
currentProposal.endLifetime,
currentProposal.votesFor,
currentProposal.votesAgainst,
currentProposal.executed
);
}
/// @notice Whether a holder is allowed to vote for a proposal.
/// @param id_ proposal id to check whether holder is allowed to vote for.
/// @param sender_ address of the holder.
/// @return bool true if voting is allowed.
function canVote(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
return proposal.endLifetime >= block.timestamp && proposal.creator != sender_ && !proposal.voterAddresses.contains(sender_);
}
/// @notice Whether a holder is allowed to remove a proposal.
/// @param id_ proposal id to check whether holder is allowed to remove.
/// @param sender_ address of the holder.
/// @return bool true if removal is allowed.
function canRemove(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
return proposal.endLifetime >= block.timestamp && proposal.voterAddresses.length() == 1 && (proposal.creator == sender_ || owner() == sender_);
}
/// @notice Whether a holder is allowed to execute a proposal.
/// @param id_ proposal id to check whether holder is allowed to execute.
/// @param sender_ address of the holder.
/// @return bool true if execution is allowed.
function canExecute(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
// check that proposal hasn't been executed yet.
if (proposal.executed) {
return false;
}
// if custom pool has admins then only admins can execute proposals
if (!_isMain && _hasAdmins) {
if (!isAdmin(sender_)) {
return false;
}
}
if (proposal.daoFunction == DaoFunction.INVEST) {
// for invest functions only admins can execute
if (sender_ != _creator && !_admins.contains(sender_)) {
return false;
}
// check that sender is proposal creator or admin
} else if (proposal.creator != sender_ && !isAdmin(sender_)) {
return false;
}
// For main pool Buy and Sell dao functions allow instant executions if at least 10% of staked supply has voted for it
if (_isMain && (proposal.daoFunction == DaoFunction.BUY || proposal.daoFunction == DaoFunction.SELL)) {
if (proposal.votesFor.mul(voteWeight()) >= _governingToken.stakedSupply() / 10) {
if (proposal.votesFor > proposal.votesAgainst) {
// only allow admins to execute buy and sell proposals early
return isAdmin(sender_);
}
}
}
// check that proposal voting lifetime has run out.
if (proposal.endLifetime > block.timestamp) {
return false;
}
// check that votes for outweigh votes against.
bool currentCanExecute = proposal.votesFor > proposal.votesAgainst;
if (currentCanExecute && _executeMinPct > 0) {
// Check that proposal has at least _executeMinPct% of staked votes.
uint256 minVotes = _governingToken.stakedSupply() / (100 / _executeMinPct);
currentCanExecute = minVotes <= proposal.votesFor.add(proposal.votesAgainst).mul(voteWeight());
}
return currentCanExecute;
}
/// @notice Whether a holder is an admin.
/// @param sender_ address of holder.
/// @return bool true if holder is an admin (in DAO without admins all holders are treated as such).
function isAdmin(address sender_) public override view returns (bool) {
return !_hasAdmins || sender_ == _creator || _admins.contains(sender_);
}
// Public transactions.
/// @notice Saves new holdings addresses for DAO.
/// @param tokens_ token addresses that DAO has holdings of.
function addHoldingsAddresses(address[] memory tokens_) public override {
require(isAdmin(msg.sender));
for (uint256 i = 0; i < tokens_.length; i++) {
address token = tokens_[i];
if (!_holdings.contains(token)) {
_holdings.add(token);
}
}
emit HoldingsAddressesChanged();
}
/// @notice Saves new liquidity addresses for DAO.
/// @param tokens_ token addresses that DAO has liquidities of.
function addLiquidityAddresses(address[] memory tokens_) public override {
require(isAdmin(msg.sender));
for (uint256 i = 0; i < tokens_.length; i++) {
address token = tokens_[i];
if (!_liquidityAddresses.contains(token)) {
_liquidityAddresses.add(token);
}
}
emit LiquidityAddressesChanged();
}
/// @notice Creates new proposal.
/// @param proposalAddress_ main address of the proposal, in investment proposals this is the address funds are sent to.
/// @param investTokenAddress_ secondary address of the proposal, used in investment proposals to specify token address.
/// @param daoFunction_ type of the proposal.
/// @param amount_ amount of funds to use in the proposal.
/// @param hoursLifetime_ voting lifetime of the proposal.
function propose(address proposalAddress_, address investTokenAddress_, DaoFunction daoFunction_, uint256 amount_, uint256 hoursLifetime_) public override {
// check that lifetime is at least equals to min hours set for DAO.
require(hoursLifetime_ >= _votingMinHours);
// Check that proposal creator is allowed to create a proposal.
uint256 balance = _governingToken.stakedOf(msg.sender);
uint256 weight = voteWeight();
require(balance >= weight);
// For main DAO.
if (_isMain) {
if (daoFunction_ == DaoFunction.WITHDRAW || daoFunction_ == DaoFunction.INVEST || daoFunction_ == DaoFunction.BUY) {
// Limit each buy, investment and withdraw proposals to 10% of ETH funds.
require(amount_ <= (availableBalance() / _spendDivider));
}
}
// Increment proposal id counter.
_latestProposalId++;
uint256 currentId = _latestProposalId;
// Calculate end lifetime of the proposal.
uint256 endLifetime = block.timestamp.add(hoursLifetime_.mul(1 hours));
// Declare voter addresses set.
EnumerableSet.AddressSet storage voterAddresses;
// Save proposal struct.
_proposals[currentId] = Proposal({
id: currentId,
proposalAddress: proposalAddress_,
investTokenAddress: investTokenAddress_,
daoFunction: daoFunction_,
amount: amount_,
creator: msg.sender,
endLifetime: endLifetime,
voterAddresses: voterAddresses,
votesFor: balance / weight,
votesAgainst: 0,
executed: false
});
// Save id of new proposal.
_proposalIds.add(currentId);
// Emit event that new proposal has been created.
emit NewProposal(currentId);
}
/// @notice Removes existing proposal.
/// @param id_ id of proposal to remove.
function unpropose(uint256 id_) public override {
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
// Check that proposal creator, owner or an admin is removing a proposal.
require(msg.sender == currentProposal.creator || msg.sender == _creator || _admins.contains(msg.sender));
// Check that no votes have been registered for the proposal apart from the proposal creator, pool creator can remove any proposal.
if (msg.sender != _creator) {
require(currentProposal.voterAddresses.length() == 1);
}
// Remove proposal.
delete _proposals[id_];
_proposalIds.remove(id_);
// Emit event that a proposal has been removed.
emit RemoveProposal(id_);
}
/// @notice Voting for multiple proposals.
/// @param ids_ ids of proposals to vote for.
/// @param votes_ for or against votes for proposals.
function vote(uint256[] memory ids_, bool[] memory votes_) public override {
// Check that arrays of the same length have been supplied.
require(ids_.length == votes_.length);
// Check that voter has enough tokens staked to vote.
uint256 balance = _governingToken.stakedOf(msg.sender);
uint256 weight = voteWeight();
require(balance >= weight);
// Get number of votes that msg.sender has.
uint256 votesCount = balance / weight;
// Iterate over voted proposals.
for (uint256 i = 0; i < ids_.length; i++) {
uint256 id = ids_[i];
bool currentVote = votes_[i];
Proposal storage proposal = _proposals[id];
// Check that proposal hasn't been voted for by msg.sender and that it's still active.
if (!proposal.voterAddresses.contains(msg.sender) && proposal.endLifetime >= block.timestamp) {
// Add votes.
proposal.voterAddresses.add(msg.sender);
if (currentVote) {
proposal.votesFor = proposal.votesFor.add(votesCount);
} else {
proposal.votesAgainst = proposal.votesAgainst.add(votesCount);
}
}
// Emit event that a proposal has been voted for.
emit Vote(id);
}
}
/// @notice Executes a proposal.
/// @param id_ id of proposal to be executed.
function execute(uint256 id_) public override nonReentrant(id_) {
// save gas at the start of execution
uint256 remainingGasStart = gasleft();
// check whether proposal can be executed by the sender
require(canExecute(id_, msg.sender));
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
// Check that msg.sender has balance for at least 1 vote to execute a proposal.
uint256 balance = _governingToken.totalOf(msg.sender);
if (balance < voteWeight()) {
// Remove admin if his balance is not high enough.
if (_admins.contains(msg.sender)) {
_admins.remove(msg.sender);
}
revert();
}
// Call private function for proposal execution depending on the type.
if (currentProposal.daoFunction == DaoFunction.BUY) {
_executeBuy(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.SELL) {
_executeSell(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.ADD_LIQUIDITY) {
_executeAddLiquidity(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.REMOVE_LIQUIDITY) {
_executeRemoveLiquidity(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.ADD_ADMIN) {
_executeAddAdmin(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.REMOVE_ADMIN) {
_executeRemoveAdmin(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.INVEST) {
_executeInvest(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.WITHDRAW) {
_executeWithdraw(currentProposal);
}
// Mark proposal as executed.
currentProposal.executed = true;
// calculate gas used during execution
uint256 remainingGasEnd = gasleft();
uint256 usedGas = remainingGasStart.sub(remainingGasEnd).add(35000);
// max gas price allowed for refund is 200gwei
uint256 gasPrice;
if (tx.gasprice > 200000000000) {
gasPrice = 200000000000;
} else {
gasPrice = tx.gasprice;
}
// refund used gas
payable(msg.sender).transfer(usedGas.mul(gasPrice));
// Emit event that proposal has been executed.
emit ExecutedProposal(id_);
}
/// @notice Buying tokens for cloned DAO.
function buy() public override payable {
// Check that it's not the main DAO.
require(!_isMain);
// Check that msg.sender is not sending more money than max cost of dao.
require(msg.value <= _maxCost);
// Check that DAO has enough tokens to sell to msg.sender.
uint256 portion = _governingToken.totalSupply().mul(msg.value) / _maxCost;
require(_governingToken.balanceOf(address(this)) >= portion);
// Transfer tokens.
_governingToken.transfer(msg.sender, portion);
// Emit event that tokens have been bought.
emit Buy();
}
/// @notice Sell tokens back to cloned DAO.
/// @param amount_ amount of tokens to sell.
function sell(uint256 amount_) public override {
// Check that it's not the main DAO.
require(!_isMain);
// Check that msg.sender has enough tokens to sell.
require(_governingToken.balanceOf(msg.sender) >= amount_);
// Calculate the eth share holder should get back and whether pool has enough funds.
uint256 share = _supplyShare(amount_);
// Approve token transfer for DAO.
_governingToken.approveDao(msg.sender, amount_);
// Transfer tokens from msg.sender back to DAO.
_governingToken.transferFrom(msg.sender, address(this), amount_);
// Refund eth back to the msg.sender.
payable(msg.sender).transfer(share);
// Emit event that tokens have been sold back to DAO.
emit Sell();
}
// Private calls.
/// @notice Calculates cost of share of the supply.
/// @param amount_ amount of tokens to calculate eth share for.
/// @return price for specified amount share.
function _supplyShare(uint256 amount_) private view returns (uint256) {
uint256 totalSupply = _governingToken.totalSupply();
uint256 circulatingSupply = _circulatingSupply(totalSupply);
uint256 circulatingMaxCost = _circulatingMaxCost(circulatingSupply, totalSupply);
// Check whether available balance is higher than circulating max cost.
if (availableBalance() > circulatingMaxCost) {
// If true then share will equal to buy price.
return circulatingMaxCost.mul(amount_) / circulatingSupply;
} else {
// Otherwise calculate share price based on currently available balance.
return availableBalance().mul(amount_) / circulatingSupply;
}
}
/// @notice Calculates max cost for currently circulating supply.
/// @param circulatingSupply_ governing token circulating supply.
/// @param totalSupply_ governing token total supply.
/// @return uint256 eth cost of currently circulating supply.
function _circulatingMaxCost(uint256 circulatingSupply_, uint256 totalSupply_) private view returns (uint256) {
return _maxCost.mul(circulatingSupply_) / totalSupply_;
}
/// @notice Calculates circulating supply of governing token.
/// @param totalSupply_ governing token total supply.
/// @return uint256 number of tokens in circulation.
function _circulatingSupply(uint256 totalSupply_) private view returns (uint256) {
uint256 balance = _governingToken.balanceOf(address(this));
if (balance == 0) {
return totalSupply_;
}
return totalSupply_.sub(balance);
}
// Private transactions.
/// @notice Execution of BUY proposal.
/// @param proposal_ proposal.
function _executeBuy(Proposal storage proposal_) private {
// Check that DAO has enough funds to execute buy proposal.
require(availableBalance() >= proposal_.amount);
// Deposit eth funds to Uniswap router.
IWETH weth = IWETH(_router.WETH());
weth.deposit{value: proposal_.amount}();
// Create path for buying, buying is only for Token-ETH pair.
address[] memory path = new address[](2);
path[0] = address(weth);
path[1] = proposal_.proposalAddress;
// Execute uniswap buy.
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), path[0], path[1]);
uint256 amountOut = UniswapV2Library.getAmountOut(proposal_.amount, reserveA, reserveB);
_router.swapExactETHForTokens{value: proposal_.amount}(amountOut, path, address(this), block.timestamp.add(_timeout));
// If new token then save it holdings addresses.
if (!_holdings.contains(proposal_.proposalAddress)) {
_holdings.add(proposal_.proposalAddress);
// Emit event that holdings addresses changed.
emit HoldingsAddressesChanged();
}
}
/// @notice Execution of SELL proposal.
/// @param proposal_ proposal.
function _executeSell(Proposal storage proposal_) private {
// Approve uniswap router to sell tokens.
IERC20 token = IERC20(proposal_.proposalAddress);
require(token.approve(address(_router), proposal_.amount));
// Create path for selling, selling is only for Token-ETH pair.
address[] memory path = new address[](2);
path[0] = proposal_.proposalAddress;
path[1] = _router.WETH();
// Execute uniswap sell.
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), path[0], path[1]);
uint256 amountOut = UniswapV2Library.getAmountOut(proposal_.amount, reserveA, reserveB);
_router.swapExactTokensForETH(proposal_.amount, amountOut, path, address(this), block.timestamp.add(_timeout));
// If sold all tokens then remove it from holdings.
if (token.balanceOf(address(this)) == 0 && _holdings.contains(proposal_.proposalAddress)) {
_holdings.remove(proposal_.proposalAddress);
// Emit event that holdings addresses changed.
emit HoldingsAddressesChanged();
}
}
/// @notice Execution of ADD_LIQUIDITY proposal.
/// @param proposal_ proposal.
function _executeAddLiquidity(Proposal storage proposal_) private {
// Approve uniswap route to transfer tokens.
require(IERC20(proposal_.proposalAddress).approve(address(_router), proposal_.amount));
// Calculate amount of tokens and eth needed for liquidity.
IWETH weth = IWETH(_router.WETH());
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), proposal_.proposalAddress, address(weth));
uint256 wethAmount = UniswapV2Library.quote(proposal_.amount, reserveA, reserveB);
// Check that DAO has sufficient eth balance for liquidity.
require (availableBalance() > wethAmount);
// Deposit eth for liqudity.
weth.deposit{value: wethAmount}();
// Execute uniswap add liquidity.
_router.addLiquidityETH{value: wethAmount}(
proposal_.proposalAddress,
proposal_.amount,
(proposal_.amount / 100).mul(98),
(wethAmount / 100).mul(98),
address(this),
block.timestamp.add(_timeout)
);
// If new liquidity token then save it.
if (!_liquidityAddresses.contains(proposal_.proposalAddress)) {
_liquidityAddresses.add(proposal_.proposalAddress);
// Emit event that liquidity addresses changed.
emit LiquidityAddressesChanged();
}
}
/// @notice Execution of REMOVE_LIQUIDITY proposal.
/// @param proposal_ proposal.
function _executeRemoveLiquidity(Proposal storage proposal_) private {
// Approve uniswap router to transfer liquidity tokens.
address liquidityTokenAddress = liquidityToken(proposal_.proposalAddress);
require(IERC20(liquidityTokenAddress).approve(address(_router), proposal_.amount));
// Execute uniswap liquidity removal.
_router.removeLiquidityETH(
proposal_.proposalAddress,
proposal_.amount,
0,
0,
address(this),
block.timestamp.add(_timeout)
);
// If all tokens have been sold then remove liquidty address.
if (tokenBalance(liquidityTokenAddress) == 0 && _liquidityAddresses.contains(proposal_.proposalAddress)) {
_liquidityAddresses.remove(proposal_.proposalAddress);
// Emit event that liquidity addresses have changed.
emit LiquidityAddressesChanged();
}
}
/// @notice Execution of ADD_ADMIN proposal.
/// @param proposal_ propsal.
function _executeAddAdmin(Proposal storage proposal_) private {
// Check that address is not an admin already.
require(!_admins.contains(proposal_.proposalAddress));
// Check that holder has sufficient balance to be an admin.
uint256 balance = _governingToken.totalOf(proposal_.proposalAddress);
require(balance >= voteWeight());
// Add admin.
_admins.add(proposal_.proposalAddress);
// Emit event that new admin has been added.
emit AddAdmin(proposal_.proposalAddress);
}
/// @notice Execution of REMOVE_ADMIN proposal.
/// @param proposal_ proposal.
function _executeRemoveAdmin(Proposal storage proposal_) private {
// Check that address is an admin.
require(_admins.contains(proposal_.proposalAddress));
// Remove admin.
_admins.remove(proposal_.proposalAddress);
// Emit event that an admin has been removed.
emit RemoveAdmin(proposal_.proposalAddress);
}
/// @notice Execution of INVEST proposal.
/// @param proposal_ proposal.
function _executeInvest(Proposal storage proposal_) private {
// Check that DAO has sufficient balance for investment.
require(availableBalance() >= proposal_.amount);
// Transfer funds.
payable(proposal_.proposalAddress).call{value: proposal_.amount}("");
// If secondary address for invest token is specified then save it to holdings.
if(proposal_.investTokenAddress != address(0x0)) {
if (!_holdings.contains(proposal_.investTokenAddress)) {
_holdings.add(proposal_.investTokenAddress);
// Emit event that holdings addresses have changed.
emit HoldingsAddressesChanged();
}
}
}
/// @notice Execution of WITHDRAW proposal.
/// @param proposal_ proposal.
function _executeWithdraw(Proposal storage proposal_) private {
if (_isMain) {
// Main DAO only allows withdrawal once a week.
require(block.timestamp > _lastWithdraw.add(1 * 1 weeks));
_lastWithdraw = block.timestamp;
}
uint256 amount;
uint256 mainAmount;
uint256 currentBalance = availableBalance();
if (_isMain) {
mainAmount = 0;
amount = proposal_.amount;
// Check that withdrawal amount is not more than 10% of main DAO balance.
require(currentBalance / 10 >= amount);
} else {
uint256 totalSupply = _governingToken.totalSupply();
uint256 circulatingMaxCost = _circulatingMaxCost(_circulatingSupply(totalSupply), totalSupply);
// Check that cloned DAO balance is higher than circulating max cost.
require(currentBalance > circulatingMaxCost);
// Check that cloned DAO gains are enough to cover withdrawal.
require(currentBalance.sub(circulatingMaxCost) >= proposal_.amount);
// 0.25% of withdrawal will be transfered to Main DAO stakers.
mainAmount = proposal_.amount / 400;
amount = proposal_.amount.sub(mainAmount);
}
// Transfer all withdrawal funds to Torro Factory.
ITorroFactory(_factory).depositBenefits{value: proposal_.amount}(address(_governingToken));
// Divide withdrawal between governing token stakers.
_governingToken.addBenefits(amount);
// If cloned DAO withdrawal then divide 0.25% of withdrawal between main token stakers.
if (mainAmount > 0) {
_torroToken.addBenefits(mainAmount);
}
}
// Owner calls.
// Owner transactions.
/// @notice Sets factory address.
/// @param factory_ address of TorroFactory.
function setFactoryAddress(address factory_) public override onlyOwner {
_factory = factory_;
}
/// @notice Sets vote weight divider.
/// @param weight_ weight divider for a single vote.
function setVoteWeightDivider(uint256 weight_) public override onlyOwner {
_voteWeightDivider = weight_;
}
/// @notice Sets new address for router.
/// @param router_ address for router.
function setRouter(address router_) public override onlyOwner {
_router = IUniswapV2Router02(router_);
}
/// @notice Sets divider for BUY, INVEST, WITHDAW proposals.
/// @param divider_ divider for BUY, INVEST, WITHDRAW proposals.
function setSpendDivider(uint256 divider_) public override onlyOwner {
_spendDivider = divider_;
}
/// @notice Migrates balances of current DAO to a new DAO.
/// @param newDao_ address of the new DAO to migrate to.
function migrate(address newDao_) public override onlyOwner {
ITorroDao dao = ITorroDao(newDao_);
// Migrate holdings.
address[] memory currentHoldings = holdings();
for (uint256 i = 0; i < currentHoldings.length; i++) {
_migrateTransferBalance(currentHoldings[i], newDao_);
}
dao.addHoldingsAddresses(currentHoldings);
// Migrate liquidities.
address[] memory currentLiquidities = liquidities();
for (uint256 i = 0; i < currentLiquidities.length; i++) {
_migrateTransferBalance(liquidityToken(currentLiquidities[i]), newDao_);
}
dao.addLiquidityAddresses(currentLiquidities);
// Send over ETH balance.
payable(newDao_).call{value: availableBalance()}("");
}
// Private owner calls.
/// @notice Private function for migrating token balance to a new address.
/// @param token_ address of ERC-20 token to migrate.
/// @param target_ migration end point address.
function _migrateTransferBalance(address token_, address target_) private {
if (token_ != address(0x0)) {
IERC20 erc20 = IERC20(token_);
uint256 balance = erc20.balanceOf(address(this));
if (balance > 0) {
erc20.transfer(target_, balance);
}
}
}
} | /// @title DAO for proposals, voting and execution.
/// @notice Contract for creation, voting and execution of proposals.
/// @author ORayskiy - @robitnik_TorroDao | NatSpecSingleLine | setVoteWeightDivider | function setVoteWeightDivider(uint256 weight_) public override onlyOwner {
_voteWeightDivider = weight_;
}
| /// @notice Sets vote weight divider.
/// @param weight_ weight divider for a single vote. | NatSpecSingleLine | v0.6.6+commit.6c089d02 | Unknown | ipfs://d1c6095fcf143d951c9754f00fe8cd59d29ab460461efe53b91eb289fd0fe5ac | {
"func_code_index": [
36184,
36301
]
} | 58,564 |
TorroDao | TorroDao.sol | 0x3cf9e9d45380b6ab61bde46b2e6cfcd7d8f6cdc1 | Solidity | TorroDao | contract TorroDao is ITorroDao, OwnableUpgradeSafe {
using EnumerableSet for EnumerableSet.AddressSet;
using EnumerableSet for EnumerableSet.UintSet;
using SafeMath for uint256;
// Structs.
/// @notice General proposal structure.
struct Proposal {
uint256 id;
address proposalAddress;
address investTokenAddress;
DaoFunction daoFunction;
uint256 amount;
address creator;
uint256 endLifetime;
EnumerableSet.AddressSet voterAddresses;
uint256 votesFor;
uint256 votesAgainst;
bool executed;
}
// Events.
/// @notice Event for dispatching on new proposal creation.
/// @param id id of the new proposal.
event NewProposal(uint256 id);
/// @notice Event for dispatching when proposal has been removed.
/// @param id id of the removed proposal.
event RemoveProposal(uint256 id);
/// @notice Event for dispatching when someone voted on a proposal.
/// @param id id of the voted proposal.
event Vote(uint256 id);
/// @notice Event for dispatching when an admin has been added to the DAO.
/// @param admin address of the admin that's been added.
event AddAdmin(address admin);
/// @notice Event for dispatching when an admin has been removed from the DAO.
/// @param admin address of the admin that's been removed.
event RemoveAdmin(address admin);
/// @notice Event for dispatching when a proposal has been executed.
/// @param id id of the executed proposal.
event ExecutedProposal(uint256 id);
/// @notice Event for dispatching when cloned DAO tokens have been bought.
event Buy();
/// @notice Event for dispatching when cloned DAO tokens have been sold.
event Sell();
/// @notice Event for dispatching when new holdings addresses have been changed.
event HoldingsAddressesChanged();
/// @notice Event for dipatching when new liquidity addresses have been changed.
event LiquidityAddressesChanged();
// Constants.
// Private data.
address private _creator;
EnumerableSet.AddressSet private _holdings;
EnumerableSet.AddressSet private _liquidityAddresses;
EnumerableSet.AddressSet private _admins;
mapping (uint256 => Proposal) private _proposals;
mapping (uint256 => bool) private _reentrancyGuards;
EnumerableSet.UintSet private _proposalIds;
ITorro private _torroToken;
ITorro private _governingToken;
address private _factory;
uint256 private _latestProposalId;
uint256 private _timeout;
uint256 private _maxCost;
uint256 private _executeMinPct;
uint256 private _votingMinHours;
uint256 private _voteWeightDivider;
uint256 private _lastWithdraw;
uint256 private _spendDivider;
bool private _isPublic;
bool private _isMain;
bool private _hasAdmins;
// ===============
IUniswapV2Router02 private _router;
// Constructor.
/// @notice Constructor for original Torro DAO.
/// @param governingToken_ Torro token address.
constructor(address governingToken_) public {
__Ownable_init();
_torroToken = ITorro(governingToken_);
_governingToken = ITorro(governingToken_);
_factory = address(0x0);
_latestProposalId = 0;
_timeout = uint256(5).mul(1 minutes);
_router = IUniswapV2Router02(address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D));
_maxCost = 0;
_executeMinPct = 5;
_votingMinHours = 6;
_voteWeightDivider = 10000;
_lastWithdraw = block.timestamp.add(1 * 1 weeks);
_spendDivider = 10;
_isMain = true;
_isPublic = true;
_hasAdmins = true;
_creator = msg.sender;
}
/// @notice Initializer for DAO clones.
/// @param torroToken_ main torro token address.
/// @param governingToken_ torro token clone that's governing this dao.
/// @param factory_ torro factory address.
/// @param creator_ creator of cloned DAO.
/// @param maxCost_ maximum cost of all governing tokens for cloned DAO.
/// @param executeMinPct_ minimum percentage of votes needed for proposal execution.
/// @param votingMinHours_ minimum lifetime of proposal before it closes.
/// @param isPublic_ whether cloned DAO has public visibility.
/// @param hasAdmins_ whether cloned DAO has admins, otherwise all stakers are treated as admins.
function initializeCustom(
address torroToken_,
address governingToken_,
address factory_,
address creator_,
uint256 maxCost_,
uint256 executeMinPct_,
uint256 votingMinHours_,
bool isPublic_,
bool hasAdmins_
) public override initializer {
__Ownable_init();
_torroToken = ITorro(torroToken_);
_governingToken = ITorro(governingToken_);
_factory = factory_;
_latestProposalId = 0;
_timeout = uint256(5).mul(1 minutes);
_router = IUniswapV2Router02(address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D));
_maxCost = maxCost_;
_voteWeightDivider = 0;
_executeMinPct = executeMinPct_;
_votingMinHours = votingMinHours_;
_lastWithdraw = block.timestamp;
_spendDivider = 0;
_isMain = false;
_isPublic = isPublic_;
_hasAdmins = hasAdmins_;
_creator = creator_;
if (_hasAdmins) {
_admins.add(creator_);
}
}
// Modifiers.
/// @notice Stops double execution of proposals.
/// @param id_ proposal id that's executing.
modifier nonReentrant(uint256 id_) {
// check that it's already not executing
require(!_reentrancyGuards[id_]);
// toggle state that proposal is currently executing
_reentrancyGuards[id_] = true;
_;
// toggle state back
_reentrancyGuards[id_] = false;
}
/// @notice Allow fund transfers to DAO contract.
receive() external payable {
// do nothing
}
// Public calls.
/// @notice Address of DAO creator.
/// @return DAO creator address.
function daoCreator() public override view returns (address) {
return _creator;
}
/// @notice Amount of tokens needed for a single vote.
/// @return uint256 token amount.
function voteWeight() public override view returns (uint256) {
uint256 weight;
if (_isMain) {
weight = _governingToken.totalSupply() / _voteWeightDivider;
} else {
weight = 10**18;
}
return weight;
}
/// @notice Amount of votes that holder has.
/// @param sender_ address of the holder.
/// @return number of votes.
function votesOf(address sender_) public override view returns (uint256) {
return _governingToken.stakedOf(sender_) / voteWeight();
}
/// @notice Address of the governing token.
/// @return address of the governing token.
function tokenAddress() public override view returns (address) {
return address(_governingToken);
}
/// @notice Saved addresses of tokens that DAO is holding.
/// @return array of holdings addresses.
function holdings() public override view returns (address[] memory) {
uint256 length = _holdings.length();
address[] memory holdingsAddresses = new address[](length);
for (uint256 i = 0; i < length; i++) {
holdingsAddresses[i] = _holdings.at(i);
}
return holdingsAddresses;
}
/// @notice Saved addresses of liquidity tokens that DAO is holding.
/// @return array of liquidity addresses.
function liquidities() public override view returns (address[] memory) {
uint256 length = _liquidityAddresses.length();
address[] memory liquidityAddresses = new address[](length);
for (uint256 i = 0; i < length; i++) {
liquidityAddresses[i] = _liquidityAddresses.at(i);
}
return liquidityAddresses;
}
/// @notice Calculates address of liquidity token from ERC-20 token address.
/// @param token_ token address to calculate liquidity address from.
/// @return address of liquidity token.
function liquidityToken(address token_) public override view returns (address) {
return UniswapV2Library.pairFor(_router.factory(), token_, _router.WETH());
}
/// @notice Gets tokens and liquidity token addresses of DAO's liquidity holdings.
/// @return Arrays of tokens and liquidity tokens, should have the same length.
function liquidityHoldings() public override view returns (address[] memory, address[] memory) {
uint256 length = _liquidityAddresses.length();
address[] memory tokens = new address[](length);
address[] memory liquidityTokens = new address[](length);
for (uint256 i = 0; i < length; i++) {
address token = _liquidityAddresses.at(i);
tokens[i] = token;
liquidityTokens[i] = liquidityToken(token);
}
return (tokens, liquidityTokens);
}
/// @notice DAO admins.
/// @return Array of admin addresses.
function admins() public override view returns (address[] memory) {
uint256 length = _admins.length();
address[] memory currentAdmins = new address[](length);
for (uint256 i = 0; i < length; i++) {
currentAdmins[i] = _admins.at(i);
}
return currentAdmins;
}
/// @notice DAO balance for specified token.
/// @param token_ token address to get balance for.
/// @return uint256 token balance.
function tokenBalance(address token_) public override view returns (uint256) {
return IERC20(token_).balanceOf(address(this));
}
/// @notice DAO balance for liquidity token.
/// @param token_ token address to get liquidity balance for.
/// @return uin256 token liquidity balance.
function liquidityBalance(address token_) public override view returns (uint256) {
return tokenBalance(liquidityToken(token_));
}
/// @notice DAO ethereum balance.
/// @return uint256 wei balance.
function availableBalance() public override view returns (uint256) {
return address(this).balance;
}
/// @notice Maximum cost for all tokens of cloned DAO.
/// @return uint256 maximum cost in wei.
function maxCost() public override view returns (uint256) {
return _maxCost;
}
/// @notice Minimum percentage of votes needed to execute a proposal.
/// @return uint256 minimum percentage of votes.
function executeMinPct() public override view returns (uint256) {
return _executeMinPct;
}
/// @notice Minimum lifetime of proposal before it closes.
/// @return uint256 minimum number of hours for proposal lifetime.
function votingMinHours() public override view returns (uint256) {
return _votingMinHours;
}
/// @notice Whether DAO is public or private.
/// @return bool true if public.
function isPublic() public override view returns (bool) {
return _isPublic;
}
/// @notice Whether DAO has admins.
/// @return bool true if DAO has admins.
function hasAdmins() public override view returns (bool) {
return _hasAdmins;
}
/// @notice Proposal ids of DAO.
/// @return array of proposal ids.
function getProposalIds() public override view returns (uint256[] memory) {
uint256 proposalsLength = _proposalIds.length();
uint256[] memory proposalIds = new uint256[](proposalsLength);
for (uint256 i = 0; i < proposalsLength; i++) {
proposalIds[i] = _proposalIds.at(i);
}
return proposalIds;
}
/// @notice Gets proposal info for proposal id.
/// @param id_ id of proposal to get info for.
/// @return proposalAddress address for proposal execution.
/// @return investTokenAddress secondary address for proposal execution, used for investment proposals if ICO and token addresses differ.
/// @return daoFunction proposal type.
/// @return amount proposal amount eth/token to use during execution.
/// @return creator address of proposal creator.
/// @return endLifetime epoch time when proposal voting ends.
/// @return votesFor amount of votes for the proposal.
/// @return votesAgainst amount of votes against the proposal.
/// @return executed whether proposal has been executed or not.
function getProposal(uint256 id_) public override view returns (
address proposalAddress,
address investTokenAddress,
DaoFunction daoFunction,
uint256 amount,
address creator,
uint256 endLifetime,
uint256 votesFor,
uint256 votesAgainst,
bool executed
) {
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
return (
currentProposal.proposalAddress,
currentProposal.investTokenAddress,
currentProposal.daoFunction,
currentProposal.amount,
currentProposal.creator,
currentProposal.endLifetime,
currentProposal.votesFor,
currentProposal.votesAgainst,
currentProposal.executed
);
}
/// @notice Whether a holder is allowed to vote for a proposal.
/// @param id_ proposal id to check whether holder is allowed to vote for.
/// @param sender_ address of the holder.
/// @return bool true if voting is allowed.
function canVote(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
return proposal.endLifetime >= block.timestamp && proposal.creator != sender_ && !proposal.voterAddresses.contains(sender_);
}
/// @notice Whether a holder is allowed to remove a proposal.
/// @param id_ proposal id to check whether holder is allowed to remove.
/// @param sender_ address of the holder.
/// @return bool true if removal is allowed.
function canRemove(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
return proposal.endLifetime >= block.timestamp && proposal.voterAddresses.length() == 1 && (proposal.creator == sender_ || owner() == sender_);
}
/// @notice Whether a holder is allowed to execute a proposal.
/// @param id_ proposal id to check whether holder is allowed to execute.
/// @param sender_ address of the holder.
/// @return bool true if execution is allowed.
function canExecute(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
// check that proposal hasn't been executed yet.
if (proposal.executed) {
return false;
}
// if custom pool has admins then only admins can execute proposals
if (!_isMain && _hasAdmins) {
if (!isAdmin(sender_)) {
return false;
}
}
if (proposal.daoFunction == DaoFunction.INVEST) {
// for invest functions only admins can execute
if (sender_ != _creator && !_admins.contains(sender_)) {
return false;
}
// check that sender is proposal creator or admin
} else if (proposal.creator != sender_ && !isAdmin(sender_)) {
return false;
}
// For main pool Buy and Sell dao functions allow instant executions if at least 10% of staked supply has voted for it
if (_isMain && (proposal.daoFunction == DaoFunction.BUY || proposal.daoFunction == DaoFunction.SELL)) {
if (proposal.votesFor.mul(voteWeight()) >= _governingToken.stakedSupply() / 10) {
if (proposal.votesFor > proposal.votesAgainst) {
// only allow admins to execute buy and sell proposals early
return isAdmin(sender_);
}
}
}
// check that proposal voting lifetime has run out.
if (proposal.endLifetime > block.timestamp) {
return false;
}
// check that votes for outweigh votes against.
bool currentCanExecute = proposal.votesFor > proposal.votesAgainst;
if (currentCanExecute && _executeMinPct > 0) {
// Check that proposal has at least _executeMinPct% of staked votes.
uint256 minVotes = _governingToken.stakedSupply() / (100 / _executeMinPct);
currentCanExecute = minVotes <= proposal.votesFor.add(proposal.votesAgainst).mul(voteWeight());
}
return currentCanExecute;
}
/// @notice Whether a holder is an admin.
/// @param sender_ address of holder.
/// @return bool true if holder is an admin (in DAO without admins all holders are treated as such).
function isAdmin(address sender_) public override view returns (bool) {
return !_hasAdmins || sender_ == _creator || _admins.contains(sender_);
}
// Public transactions.
/// @notice Saves new holdings addresses for DAO.
/// @param tokens_ token addresses that DAO has holdings of.
function addHoldingsAddresses(address[] memory tokens_) public override {
require(isAdmin(msg.sender));
for (uint256 i = 0; i < tokens_.length; i++) {
address token = tokens_[i];
if (!_holdings.contains(token)) {
_holdings.add(token);
}
}
emit HoldingsAddressesChanged();
}
/// @notice Saves new liquidity addresses for DAO.
/// @param tokens_ token addresses that DAO has liquidities of.
function addLiquidityAddresses(address[] memory tokens_) public override {
require(isAdmin(msg.sender));
for (uint256 i = 0; i < tokens_.length; i++) {
address token = tokens_[i];
if (!_liquidityAddresses.contains(token)) {
_liquidityAddresses.add(token);
}
}
emit LiquidityAddressesChanged();
}
/// @notice Creates new proposal.
/// @param proposalAddress_ main address of the proposal, in investment proposals this is the address funds are sent to.
/// @param investTokenAddress_ secondary address of the proposal, used in investment proposals to specify token address.
/// @param daoFunction_ type of the proposal.
/// @param amount_ amount of funds to use in the proposal.
/// @param hoursLifetime_ voting lifetime of the proposal.
function propose(address proposalAddress_, address investTokenAddress_, DaoFunction daoFunction_, uint256 amount_, uint256 hoursLifetime_) public override {
// check that lifetime is at least equals to min hours set for DAO.
require(hoursLifetime_ >= _votingMinHours);
// Check that proposal creator is allowed to create a proposal.
uint256 balance = _governingToken.stakedOf(msg.sender);
uint256 weight = voteWeight();
require(balance >= weight);
// For main DAO.
if (_isMain) {
if (daoFunction_ == DaoFunction.WITHDRAW || daoFunction_ == DaoFunction.INVEST || daoFunction_ == DaoFunction.BUY) {
// Limit each buy, investment and withdraw proposals to 10% of ETH funds.
require(amount_ <= (availableBalance() / _spendDivider));
}
}
// Increment proposal id counter.
_latestProposalId++;
uint256 currentId = _latestProposalId;
// Calculate end lifetime of the proposal.
uint256 endLifetime = block.timestamp.add(hoursLifetime_.mul(1 hours));
// Declare voter addresses set.
EnumerableSet.AddressSet storage voterAddresses;
// Save proposal struct.
_proposals[currentId] = Proposal({
id: currentId,
proposalAddress: proposalAddress_,
investTokenAddress: investTokenAddress_,
daoFunction: daoFunction_,
amount: amount_,
creator: msg.sender,
endLifetime: endLifetime,
voterAddresses: voterAddresses,
votesFor: balance / weight,
votesAgainst: 0,
executed: false
});
// Save id of new proposal.
_proposalIds.add(currentId);
// Emit event that new proposal has been created.
emit NewProposal(currentId);
}
/// @notice Removes existing proposal.
/// @param id_ id of proposal to remove.
function unpropose(uint256 id_) public override {
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
// Check that proposal creator, owner or an admin is removing a proposal.
require(msg.sender == currentProposal.creator || msg.sender == _creator || _admins.contains(msg.sender));
// Check that no votes have been registered for the proposal apart from the proposal creator, pool creator can remove any proposal.
if (msg.sender != _creator) {
require(currentProposal.voterAddresses.length() == 1);
}
// Remove proposal.
delete _proposals[id_];
_proposalIds.remove(id_);
// Emit event that a proposal has been removed.
emit RemoveProposal(id_);
}
/// @notice Voting for multiple proposals.
/// @param ids_ ids of proposals to vote for.
/// @param votes_ for or against votes for proposals.
function vote(uint256[] memory ids_, bool[] memory votes_) public override {
// Check that arrays of the same length have been supplied.
require(ids_.length == votes_.length);
// Check that voter has enough tokens staked to vote.
uint256 balance = _governingToken.stakedOf(msg.sender);
uint256 weight = voteWeight();
require(balance >= weight);
// Get number of votes that msg.sender has.
uint256 votesCount = balance / weight;
// Iterate over voted proposals.
for (uint256 i = 0; i < ids_.length; i++) {
uint256 id = ids_[i];
bool currentVote = votes_[i];
Proposal storage proposal = _proposals[id];
// Check that proposal hasn't been voted for by msg.sender and that it's still active.
if (!proposal.voterAddresses.contains(msg.sender) && proposal.endLifetime >= block.timestamp) {
// Add votes.
proposal.voterAddresses.add(msg.sender);
if (currentVote) {
proposal.votesFor = proposal.votesFor.add(votesCount);
} else {
proposal.votesAgainst = proposal.votesAgainst.add(votesCount);
}
}
// Emit event that a proposal has been voted for.
emit Vote(id);
}
}
/// @notice Executes a proposal.
/// @param id_ id of proposal to be executed.
function execute(uint256 id_) public override nonReentrant(id_) {
// save gas at the start of execution
uint256 remainingGasStart = gasleft();
// check whether proposal can be executed by the sender
require(canExecute(id_, msg.sender));
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
// Check that msg.sender has balance for at least 1 vote to execute a proposal.
uint256 balance = _governingToken.totalOf(msg.sender);
if (balance < voteWeight()) {
// Remove admin if his balance is not high enough.
if (_admins.contains(msg.sender)) {
_admins.remove(msg.sender);
}
revert();
}
// Call private function for proposal execution depending on the type.
if (currentProposal.daoFunction == DaoFunction.BUY) {
_executeBuy(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.SELL) {
_executeSell(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.ADD_LIQUIDITY) {
_executeAddLiquidity(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.REMOVE_LIQUIDITY) {
_executeRemoveLiquidity(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.ADD_ADMIN) {
_executeAddAdmin(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.REMOVE_ADMIN) {
_executeRemoveAdmin(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.INVEST) {
_executeInvest(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.WITHDRAW) {
_executeWithdraw(currentProposal);
}
// Mark proposal as executed.
currentProposal.executed = true;
// calculate gas used during execution
uint256 remainingGasEnd = gasleft();
uint256 usedGas = remainingGasStart.sub(remainingGasEnd).add(35000);
// max gas price allowed for refund is 200gwei
uint256 gasPrice;
if (tx.gasprice > 200000000000) {
gasPrice = 200000000000;
} else {
gasPrice = tx.gasprice;
}
// refund used gas
payable(msg.sender).transfer(usedGas.mul(gasPrice));
// Emit event that proposal has been executed.
emit ExecutedProposal(id_);
}
/// @notice Buying tokens for cloned DAO.
function buy() public override payable {
// Check that it's not the main DAO.
require(!_isMain);
// Check that msg.sender is not sending more money than max cost of dao.
require(msg.value <= _maxCost);
// Check that DAO has enough tokens to sell to msg.sender.
uint256 portion = _governingToken.totalSupply().mul(msg.value) / _maxCost;
require(_governingToken.balanceOf(address(this)) >= portion);
// Transfer tokens.
_governingToken.transfer(msg.sender, portion);
// Emit event that tokens have been bought.
emit Buy();
}
/// @notice Sell tokens back to cloned DAO.
/// @param amount_ amount of tokens to sell.
function sell(uint256 amount_) public override {
// Check that it's not the main DAO.
require(!_isMain);
// Check that msg.sender has enough tokens to sell.
require(_governingToken.balanceOf(msg.sender) >= amount_);
// Calculate the eth share holder should get back and whether pool has enough funds.
uint256 share = _supplyShare(amount_);
// Approve token transfer for DAO.
_governingToken.approveDao(msg.sender, amount_);
// Transfer tokens from msg.sender back to DAO.
_governingToken.transferFrom(msg.sender, address(this), amount_);
// Refund eth back to the msg.sender.
payable(msg.sender).transfer(share);
// Emit event that tokens have been sold back to DAO.
emit Sell();
}
// Private calls.
/// @notice Calculates cost of share of the supply.
/// @param amount_ amount of tokens to calculate eth share for.
/// @return price for specified amount share.
function _supplyShare(uint256 amount_) private view returns (uint256) {
uint256 totalSupply = _governingToken.totalSupply();
uint256 circulatingSupply = _circulatingSupply(totalSupply);
uint256 circulatingMaxCost = _circulatingMaxCost(circulatingSupply, totalSupply);
// Check whether available balance is higher than circulating max cost.
if (availableBalance() > circulatingMaxCost) {
// If true then share will equal to buy price.
return circulatingMaxCost.mul(amount_) / circulatingSupply;
} else {
// Otherwise calculate share price based on currently available balance.
return availableBalance().mul(amount_) / circulatingSupply;
}
}
/// @notice Calculates max cost for currently circulating supply.
/// @param circulatingSupply_ governing token circulating supply.
/// @param totalSupply_ governing token total supply.
/// @return uint256 eth cost of currently circulating supply.
function _circulatingMaxCost(uint256 circulatingSupply_, uint256 totalSupply_) private view returns (uint256) {
return _maxCost.mul(circulatingSupply_) / totalSupply_;
}
/// @notice Calculates circulating supply of governing token.
/// @param totalSupply_ governing token total supply.
/// @return uint256 number of tokens in circulation.
function _circulatingSupply(uint256 totalSupply_) private view returns (uint256) {
uint256 balance = _governingToken.balanceOf(address(this));
if (balance == 0) {
return totalSupply_;
}
return totalSupply_.sub(balance);
}
// Private transactions.
/// @notice Execution of BUY proposal.
/// @param proposal_ proposal.
function _executeBuy(Proposal storage proposal_) private {
// Check that DAO has enough funds to execute buy proposal.
require(availableBalance() >= proposal_.amount);
// Deposit eth funds to Uniswap router.
IWETH weth = IWETH(_router.WETH());
weth.deposit{value: proposal_.amount}();
// Create path for buying, buying is only for Token-ETH pair.
address[] memory path = new address[](2);
path[0] = address(weth);
path[1] = proposal_.proposalAddress;
// Execute uniswap buy.
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), path[0], path[1]);
uint256 amountOut = UniswapV2Library.getAmountOut(proposal_.amount, reserveA, reserveB);
_router.swapExactETHForTokens{value: proposal_.amount}(amountOut, path, address(this), block.timestamp.add(_timeout));
// If new token then save it holdings addresses.
if (!_holdings.contains(proposal_.proposalAddress)) {
_holdings.add(proposal_.proposalAddress);
// Emit event that holdings addresses changed.
emit HoldingsAddressesChanged();
}
}
/// @notice Execution of SELL proposal.
/// @param proposal_ proposal.
function _executeSell(Proposal storage proposal_) private {
// Approve uniswap router to sell tokens.
IERC20 token = IERC20(proposal_.proposalAddress);
require(token.approve(address(_router), proposal_.amount));
// Create path for selling, selling is only for Token-ETH pair.
address[] memory path = new address[](2);
path[0] = proposal_.proposalAddress;
path[1] = _router.WETH();
// Execute uniswap sell.
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), path[0], path[1]);
uint256 amountOut = UniswapV2Library.getAmountOut(proposal_.amount, reserveA, reserveB);
_router.swapExactTokensForETH(proposal_.amount, amountOut, path, address(this), block.timestamp.add(_timeout));
// If sold all tokens then remove it from holdings.
if (token.balanceOf(address(this)) == 0 && _holdings.contains(proposal_.proposalAddress)) {
_holdings.remove(proposal_.proposalAddress);
// Emit event that holdings addresses changed.
emit HoldingsAddressesChanged();
}
}
/// @notice Execution of ADD_LIQUIDITY proposal.
/// @param proposal_ proposal.
function _executeAddLiquidity(Proposal storage proposal_) private {
// Approve uniswap route to transfer tokens.
require(IERC20(proposal_.proposalAddress).approve(address(_router), proposal_.amount));
// Calculate amount of tokens and eth needed for liquidity.
IWETH weth = IWETH(_router.WETH());
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), proposal_.proposalAddress, address(weth));
uint256 wethAmount = UniswapV2Library.quote(proposal_.amount, reserveA, reserveB);
// Check that DAO has sufficient eth balance for liquidity.
require (availableBalance() > wethAmount);
// Deposit eth for liqudity.
weth.deposit{value: wethAmount}();
// Execute uniswap add liquidity.
_router.addLiquidityETH{value: wethAmount}(
proposal_.proposalAddress,
proposal_.amount,
(proposal_.amount / 100).mul(98),
(wethAmount / 100).mul(98),
address(this),
block.timestamp.add(_timeout)
);
// If new liquidity token then save it.
if (!_liquidityAddresses.contains(proposal_.proposalAddress)) {
_liquidityAddresses.add(proposal_.proposalAddress);
// Emit event that liquidity addresses changed.
emit LiquidityAddressesChanged();
}
}
/// @notice Execution of REMOVE_LIQUIDITY proposal.
/// @param proposal_ proposal.
function _executeRemoveLiquidity(Proposal storage proposal_) private {
// Approve uniswap router to transfer liquidity tokens.
address liquidityTokenAddress = liquidityToken(proposal_.proposalAddress);
require(IERC20(liquidityTokenAddress).approve(address(_router), proposal_.amount));
// Execute uniswap liquidity removal.
_router.removeLiquidityETH(
proposal_.proposalAddress,
proposal_.amount,
0,
0,
address(this),
block.timestamp.add(_timeout)
);
// If all tokens have been sold then remove liquidty address.
if (tokenBalance(liquidityTokenAddress) == 0 && _liquidityAddresses.contains(proposal_.proposalAddress)) {
_liquidityAddresses.remove(proposal_.proposalAddress);
// Emit event that liquidity addresses have changed.
emit LiquidityAddressesChanged();
}
}
/// @notice Execution of ADD_ADMIN proposal.
/// @param proposal_ propsal.
function _executeAddAdmin(Proposal storage proposal_) private {
// Check that address is not an admin already.
require(!_admins.contains(proposal_.proposalAddress));
// Check that holder has sufficient balance to be an admin.
uint256 balance = _governingToken.totalOf(proposal_.proposalAddress);
require(balance >= voteWeight());
// Add admin.
_admins.add(proposal_.proposalAddress);
// Emit event that new admin has been added.
emit AddAdmin(proposal_.proposalAddress);
}
/// @notice Execution of REMOVE_ADMIN proposal.
/// @param proposal_ proposal.
function _executeRemoveAdmin(Proposal storage proposal_) private {
// Check that address is an admin.
require(_admins.contains(proposal_.proposalAddress));
// Remove admin.
_admins.remove(proposal_.proposalAddress);
// Emit event that an admin has been removed.
emit RemoveAdmin(proposal_.proposalAddress);
}
/// @notice Execution of INVEST proposal.
/// @param proposal_ proposal.
function _executeInvest(Proposal storage proposal_) private {
// Check that DAO has sufficient balance for investment.
require(availableBalance() >= proposal_.amount);
// Transfer funds.
payable(proposal_.proposalAddress).call{value: proposal_.amount}("");
// If secondary address for invest token is specified then save it to holdings.
if(proposal_.investTokenAddress != address(0x0)) {
if (!_holdings.contains(proposal_.investTokenAddress)) {
_holdings.add(proposal_.investTokenAddress);
// Emit event that holdings addresses have changed.
emit HoldingsAddressesChanged();
}
}
}
/// @notice Execution of WITHDRAW proposal.
/// @param proposal_ proposal.
function _executeWithdraw(Proposal storage proposal_) private {
if (_isMain) {
// Main DAO only allows withdrawal once a week.
require(block.timestamp > _lastWithdraw.add(1 * 1 weeks));
_lastWithdraw = block.timestamp;
}
uint256 amount;
uint256 mainAmount;
uint256 currentBalance = availableBalance();
if (_isMain) {
mainAmount = 0;
amount = proposal_.amount;
// Check that withdrawal amount is not more than 10% of main DAO balance.
require(currentBalance / 10 >= amount);
} else {
uint256 totalSupply = _governingToken.totalSupply();
uint256 circulatingMaxCost = _circulatingMaxCost(_circulatingSupply(totalSupply), totalSupply);
// Check that cloned DAO balance is higher than circulating max cost.
require(currentBalance > circulatingMaxCost);
// Check that cloned DAO gains are enough to cover withdrawal.
require(currentBalance.sub(circulatingMaxCost) >= proposal_.amount);
// 0.25% of withdrawal will be transfered to Main DAO stakers.
mainAmount = proposal_.amount / 400;
amount = proposal_.amount.sub(mainAmount);
}
// Transfer all withdrawal funds to Torro Factory.
ITorroFactory(_factory).depositBenefits{value: proposal_.amount}(address(_governingToken));
// Divide withdrawal between governing token stakers.
_governingToken.addBenefits(amount);
// If cloned DAO withdrawal then divide 0.25% of withdrawal between main token stakers.
if (mainAmount > 0) {
_torroToken.addBenefits(mainAmount);
}
}
// Owner calls.
// Owner transactions.
/// @notice Sets factory address.
/// @param factory_ address of TorroFactory.
function setFactoryAddress(address factory_) public override onlyOwner {
_factory = factory_;
}
/// @notice Sets vote weight divider.
/// @param weight_ weight divider for a single vote.
function setVoteWeightDivider(uint256 weight_) public override onlyOwner {
_voteWeightDivider = weight_;
}
/// @notice Sets new address for router.
/// @param router_ address for router.
function setRouter(address router_) public override onlyOwner {
_router = IUniswapV2Router02(router_);
}
/// @notice Sets divider for BUY, INVEST, WITHDAW proposals.
/// @param divider_ divider for BUY, INVEST, WITHDRAW proposals.
function setSpendDivider(uint256 divider_) public override onlyOwner {
_spendDivider = divider_;
}
/// @notice Migrates balances of current DAO to a new DAO.
/// @param newDao_ address of the new DAO to migrate to.
function migrate(address newDao_) public override onlyOwner {
ITorroDao dao = ITorroDao(newDao_);
// Migrate holdings.
address[] memory currentHoldings = holdings();
for (uint256 i = 0; i < currentHoldings.length; i++) {
_migrateTransferBalance(currentHoldings[i], newDao_);
}
dao.addHoldingsAddresses(currentHoldings);
// Migrate liquidities.
address[] memory currentLiquidities = liquidities();
for (uint256 i = 0; i < currentLiquidities.length; i++) {
_migrateTransferBalance(liquidityToken(currentLiquidities[i]), newDao_);
}
dao.addLiquidityAddresses(currentLiquidities);
// Send over ETH balance.
payable(newDao_).call{value: availableBalance()}("");
}
// Private owner calls.
/// @notice Private function for migrating token balance to a new address.
/// @param token_ address of ERC-20 token to migrate.
/// @param target_ migration end point address.
function _migrateTransferBalance(address token_, address target_) private {
if (token_ != address(0x0)) {
IERC20 erc20 = IERC20(token_);
uint256 balance = erc20.balanceOf(address(this));
if (balance > 0) {
erc20.transfer(target_, balance);
}
}
}
} | /// @title DAO for proposals, voting and execution.
/// @notice Contract for creation, voting and execution of proposals.
/// @author ORayskiy - @robitnik_TorroDao | NatSpecSingleLine | setRouter | function setRouter(address router_) public override onlyOwner {
_router = IUniswapV2Router02(router_);
}
| /// @notice Sets new address for router.
/// @param router_ address for router. | NatSpecSingleLine | v0.6.6+commit.6c089d02 | Unknown | ipfs://d1c6095fcf143d951c9754f00fe8cd59d29ab460461efe53b91eb289fd0fe5ac | {
"func_code_index": [
36390,
36505
]
} | 58,565 |
TorroDao | TorroDao.sol | 0x3cf9e9d45380b6ab61bde46b2e6cfcd7d8f6cdc1 | Solidity | TorroDao | contract TorroDao is ITorroDao, OwnableUpgradeSafe {
using EnumerableSet for EnumerableSet.AddressSet;
using EnumerableSet for EnumerableSet.UintSet;
using SafeMath for uint256;
// Structs.
/// @notice General proposal structure.
struct Proposal {
uint256 id;
address proposalAddress;
address investTokenAddress;
DaoFunction daoFunction;
uint256 amount;
address creator;
uint256 endLifetime;
EnumerableSet.AddressSet voterAddresses;
uint256 votesFor;
uint256 votesAgainst;
bool executed;
}
// Events.
/// @notice Event for dispatching on new proposal creation.
/// @param id id of the new proposal.
event NewProposal(uint256 id);
/// @notice Event for dispatching when proposal has been removed.
/// @param id id of the removed proposal.
event RemoveProposal(uint256 id);
/// @notice Event for dispatching when someone voted on a proposal.
/// @param id id of the voted proposal.
event Vote(uint256 id);
/// @notice Event for dispatching when an admin has been added to the DAO.
/// @param admin address of the admin that's been added.
event AddAdmin(address admin);
/// @notice Event for dispatching when an admin has been removed from the DAO.
/// @param admin address of the admin that's been removed.
event RemoveAdmin(address admin);
/// @notice Event for dispatching when a proposal has been executed.
/// @param id id of the executed proposal.
event ExecutedProposal(uint256 id);
/// @notice Event for dispatching when cloned DAO tokens have been bought.
event Buy();
/// @notice Event for dispatching when cloned DAO tokens have been sold.
event Sell();
/// @notice Event for dispatching when new holdings addresses have been changed.
event HoldingsAddressesChanged();
/// @notice Event for dipatching when new liquidity addresses have been changed.
event LiquidityAddressesChanged();
// Constants.
// Private data.
address private _creator;
EnumerableSet.AddressSet private _holdings;
EnumerableSet.AddressSet private _liquidityAddresses;
EnumerableSet.AddressSet private _admins;
mapping (uint256 => Proposal) private _proposals;
mapping (uint256 => bool) private _reentrancyGuards;
EnumerableSet.UintSet private _proposalIds;
ITorro private _torroToken;
ITorro private _governingToken;
address private _factory;
uint256 private _latestProposalId;
uint256 private _timeout;
uint256 private _maxCost;
uint256 private _executeMinPct;
uint256 private _votingMinHours;
uint256 private _voteWeightDivider;
uint256 private _lastWithdraw;
uint256 private _spendDivider;
bool private _isPublic;
bool private _isMain;
bool private _hasAdmins;
// ===============
IUniswapV2Router02 private _router;
// Constructor.
/// @notice Constructor for original Torro DAO.
/// @param governingToken_ Torro token address.
constructor(address governingToken_) public {
__Ownable_init();
_torroToken = ITorro(governingToken_);
_governingToken = ITorro(governingToken_);
_factory = address(0x0);
_latestProposalId = 0;
_timeout = uint256(5).mul(1 minutes);
_router = IUniswapV2Router02(address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D));
_maxCost = 0;
_executeMinPct = 5;
_votingMinHours = 6;
_voteWeightDivider = 10000;
_lastWithdraw = block.timestamp.add(1 * 1 weeks);
_spendDivider = 10;
_isMain = true;
_isPublic = true;
_hasAdmins = true;
_creator = msg.sender;
}
/// @notice Initializer for DAO clones.
/// @param torroToken_ main torro token address.
/// @param governingToken_ torro token clone that's governing this dao.
/// @param factory_ torro factory address.
/// @param creator_ creator of cloned DAO.
/// @param maxCost_ maximum cost of all governing tokens for cloned DAO.
/// @param executeMinPct_ minimum percentage of votes needed for proposal execution.
/// @param votingMinHours_ minimum lifetime of proposal before it closes.
/// @param isPublic_ whether cloned DAO has public visibility.
/// @param hasAdmins_ whether cloned DAO has admins, otherwise all stakers are treated as admins.
function initializeCustom(
address torroToken_,
address governingToken_,
address factory_,
address creator_,
uint256 maxCost_,
uint256 executeMinPct_,
uint256 votingMinHours_,
bool isPublic_,
bool hasAdmins_
) public override initializer {
__Ownable_init();
_torroToken = ITorro(torroToken_);
_governingToken = ITorro(governingToken_);
_factory = factory_;
_latestProposalId = 0;
_timeout = uint256(5).mul(1 minutes);
_router = IUniswapV2Router02(address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D));
_maxCost = maxCost_;
_voteWeightDivider = 0;
_executeMinPct = executeMinPct_;
_votingMinHours = votingMinHours_;
_lastWithdraw = block.timestamp;
_spendDivider = 0;
_isMain = false;
_isPublic = isPublic_;
_hasAdmins = hasAdmins_;
_creator = creator_;
if (_hasAdmins) {
_admins.add(creator_);
}
}
// Modifiers.
/// @notice Stops double execution of proposals.
/// @param id_ proposal id that's executing.
modifier nonReentrant(uint256 id_) {
// check that it's already not executing
require(!_reentrancyGuards[id_]);
// toggle state that proposal is currently executing
_reentrancyGuards[id_] = true;
_;
// toggle state back
_reentrancyGuards[id_] = false;
}
/// @notice Allow fund transfers to DAO contract.
receive() external payable {
// do nothing
}
// Public calls.
/// @notice Address of DAO creator.
/// @return DAO creator address.
function daoCreator() public override view returns (address) {
return _creator;
}
/// @notice Amount of tokens needed for a single vote.
/// @return uint256 token amount.
function voteWeight() public override view returns (uint256) {
uint256 weight;
if (_isMain) {
weight = _governingToken.totalSupply() / _voteWeightDivider;
} else {
weight = 10**18;
}
return weight;
}
/// @notice Amount of votes that holder has.
/// @param sender_ address of the holder.
/// @return number of votes.
function votesOf(address sender_) public override view returns (uint256) {
return _governingToken.stakedOf(sender_) / voteWeight();
}
/// @notice Address of the governing token.
/// @return address of the governing token.
function tokenAddress() public override view returns (address) {
return address(_governingToken);
}
/// @notice Saved addresses of tokens that DAO is holding.
/// @return array of holdings addresses.
function holdings() public override view returns (address[] memory) {
uint256 length = _holdings.length();
address[] memory holdingsAddresses = new address[](length);
for (uint256 i = 0; i < length; i++) {
holdingsAddresses[i] = _holdings.at(i);
}
return holdingsAddresses;
}
/// @notice Saved addresses of liquidity tokens that DAO is holding.
/// @return array of liquidity addresses.
function liquidities() public override view returns (address[] memory) {
uint256 length = _liquidityAddresses.length();
address[] memory liquidityAddresses = new address[](length);
for (uint256 i = 0; i < length; i++) {
liquidityAddresses[i] = _liquidityAddresses.at(i);
}
return liquidityAddresses;
}
/// @notice Calculates address of liquidity token from ERC-20 token address.
/// @param token_ token address to calculate liquidity address from.
/// @return address of liquidity token.
function liquidityToken(address token_) public override view returns (address) {
return UniswapV2Library.pairFor(_router.factory(), token_, _router.WETH());
}
/// @notice Gets tokens and liquidity token addresses of DAO's liquidity holdings.
/// @return Arrays of tokens and liquidity tokens, should have the same length.
function liquidityHoldings() public override view returns (address[] memory, address[] memory) {
uint256 length = _liquidityAddresses.length();
address[] memory tokens = new address[](length);
address[] memory liquidityTokens = new address[](length);
for (uint256 i = 0; i < length; i++) {
address token = _liquidityAddresses.at(i);
tokens[i] = token;
liquidityTokens[i] = liquidityToken(token);
}
return (tokens, liquidityTokens);
}
/// @notice DAO admins.
/// @return Array of admin addresses.
function admins() public override view returns (address[] memory) {
uint256 length = _admins.length();
address[] memory currentAdmins = new address[](length);
for (uint256 i = 0; i < length; i++) {
currentAdmins[i] = _admins.at(i);
}
return currentAdmins;
}
/// @notice DAO balance for specified token.
/// @param token_ token address to get balance for.
/// @return uint256 token balance.
function tokenBalance(address token_) public override view returns (uint256) {
return IERC20(token_).balanceOf(address(this));
}
/// @notice DAO balance for liquidity token.
/// @param token_ token address to get liquidity balance for.
/// @return uin256 token liquidity balance.
function liquidityBalance(address token_) public override view returns (uint256) {
return tokenBalance(liquidityToken(token_));
}
/// @notice DAO ethereum balance.
/// @return uint256 wei balance.
function availableBalance() public override view returns (uint256) {
return address(this).balance;
}
/// @notice Maximum cost for all tokens of cloned DAO.
/// @return uint256 maximum cost in wei.
function maxCost() public override view returns (uint256) {
return _maxCost;
}
/// @notice Minimum percentage of votes needed to execute a proposal.
/// @return uint256 minimum percentage of votes.
function executeMinPct() public override view returns (uint256) {
return _executeMinPct;
}
/// @notice Minimum lifetime of proposal before it closes.
/// @return uint256 minimum number of hours for proposal lifetime.
function votingMinHours() public override view returns (uint256) {
return _votingMinHours;
}
/// @notice Whether DAO is public or private.
/// @return bool true if public.
function isPublic() public override view returns (bool) {
return _isPublic;
}
/// @notice Whether DAO has admins.
/// @return bool true if DAO has admins.
function hasAdmins() public override view returns (bool) {
return _hasAdmins;
}
/// @notice Proposal ids of DAO.
/// @return array of proposal ids.
function getProposalIds() public override view returns (uint256[] memory) {
uint256 proposalsLength = _proposalIds.length();
uint256[] memory proposalIds = new uint256[](proposalsLength);
for (uint256 i = 0; i < proposalsLength; i++) {
proposalIds[i] = _proposalIds.at(i);
}
return proposalIds;
}
/// @notice Gets proposal info for proposal id.
/// @param id_ id of proposal to get info for.
/// @return proposalAddress address for proposal execution.
/// @return investTokenAddress secondary address for proposal execution, used for investment proposals if ICO and token addresses differ.
/// @return daoFunction proposal type.
/// @return amount proposal amount eth/token to use during execution.
/// @return creator address of proposal creator.
/// @return endLifetime epoch time when proposal voting ends.
/// @return votesFor amount of votes for the proposal.
/// @return votesAgainst amount of votes against the proposal.
/// @return executed whether proposal has been executed or not.
function getProposal(uint256 id_) public override view returns (
address proposalAddress,
address investTokenAddress,
DaoFunction daoFunction,
uint256 amount,
address creator,
uint256 endLifetime,
uint256 votesFor,
uint256 votesAgainst,
bool executed
) {
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
return (
currentProposal.proposalAddress,
currentProposal.investTokenAddress,
currentProposal.daoFunction,
currentProposal.amount,
currentProposal.creator,
currentProposal.endLifetime,
currentProposal.votesFor,
currentProposal.votesAgainst,
currentProposal.executed
);
}
/// @notice Whether a holder is allowed to vote for a proposal.
/// @param id_ proposal id to check whether holder is allowed to vote for.
/// @param sender_ address of the holder.
/// @return bool true if voting is allowed.
function canVote(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
return proposal.endLifetime >= block.timestamp && proposal.creator != sender_ && !proposal.voterAddresses.contains(sender_);
}
/// @notice Whether a holder is allowed to remove a proposal.
/// @param id_ proposal id to check whether holder is allowed to remove.
/// @param sender_ address of the holder.
/// @return bool true if removal is allowed.
function canRemove(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
return proposal.endLifetime >= block.timestamp && proposal.voterAddresses.length() == 1 && (proposal.creator == sender_ || owner() == sender_);
}
/// @notice Whether a holder is allowed to execute a proposal.
/// @param id_ proposal id to check whether holder is allowed to execute.
/// @param sender_ address of the holder.
/// @return bool true if execution is allowed.
function canExecute(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
// check that proposal hasn't been executed yet.
if (proposal.executed) {
return false;
}
// if custom pool has admins then only admins can execute proposals
if (!_isMain && _hasAdmins) {
if (!isAdmin(sender_)) {
return false;
}
}
if (proposal.daoFunction == DaoFunction.INVEST) {
// for invest functions only admins can execute
if (sender_ != _creator && !_admins.contains(sender_)) {
return false;
}
// check that sender is proposal creator or admin
} else if (proposal.creator != sender_ && !isAdmin(sender_)) {
return false;
}
// For main pool Buy and Sell dao functions allow instant executions if at least 10% of staked supply has voted for it
if (_isMain && (proposal.daoFunction == DaoFunction.BUY || proposal.daoFunction == DaoFunction.SELL)) {
if (proposal.votesFor.mul(voteWeight()) >= _governingToken.stakedSupply() / 10) {
if (proposal.votesFor > proposal.votesAgainst) {
// only allow admins to execute buy and sell proposals early
return isAdmin(sender_);
}
}
}
// check that proposal voting lifetime has run out.
if (proposal.endLifetime > block.timestamp) {
return false;
}
// check that votes for outweigh votes against.
bool currentCanExecute = proposal.votesFor > proposal.votesAgainst;
if (currentCanExecute && _executeMinPct > 0) {
// Check that proposal has at least _executeMinPct% of staked votes.
uint256 minVotes = _governingToken.stakedSupply() / (100 / _executeMinPct);
currentCanExecute = minVotes <= proposal.votesFor.add(proposal.votesAgainst).mul(voteWeight());
}
return currentCanExecute;
}
/// @notice Whether a holder is an admin.
/// @param sender_ address of holder.
/// @return bool true if holder is an admin (in DAO without admins all holders are treated as such).
function isAdmin(address sender_) public override view returns (bool) {
return !_hasAdmins || sender_ == _creator || _admins.contains(sender_);
}
// Public transactions.
/// @notice Saves new holdings addresses for DAO.
/// @param tokens_ token addresses that DAO has holdings of.
function addHoldingsAddresses(address[] memory tokens_) public override {
require(isAdmin(msg.sender));
for (uint256 i = 0; i < tokens_.length; i++) {
address token = tokens_[i];
if (!_holdings.contains(token)) {
_holdings.add(token);
}
}
emit HoldingsAddressesChanged();
}
/// @notice Saves new liquidity addresses for DAO.
/// @param tokens_ token addresses that DAO has liquidities of.
function addLiquidityAddresses(address[] memory tokens_) public override {
require(isAdmin(msg.sender));
for (uint256 i = 0; i < tokens_.length; i++) {
address token = tokens_[i];
if (!_liquidityAddresses.contains(token)) {
_liquidityAddresses.add(token);
}
}
emit LiquidityAddressesChanged();
}
/// @notice Creates new proposal.
/// @param proposalAddress_ main address of the proposal, in investment proposals this is the address funds are sent to.
/// @param investTokenAddress_ secondary address of the proposal, used in investment proposals to specify token address.
/// @param daoFunction_ type of the proposal.
/// @param amount_ amount of funds to use in the proposal.
/// @param hoursLifetime_ voting lifetime of the proposal.
function propose(address proposalAddress_, address investTokenAddress_, DaoFunction daoFunction_, uint256 amount_, uint256 hoursLifetime_) public override {
// check that lifetime is at least equals to min hours set for DAO.
require(hoursLifetime_ >= _votingMinHours);
// Check that proposal creator is allowed to create a proposal.
uint256 balance = _governingToken.stakedOf(msg.sender);
uint256 weight = voteWeight();
require(balance >= weight);
// For main DAO.
if (_isMain) {
if (daoFunction_ == DaoFunction.WITHDRAW || daoFunction_ == DaoFunction.INVEST || daoFunction_ == DaoFunction.BUY) {
// Limit each buy, investment and withdraw proposals to 10% of ETH funds.
require(amount_ <= (availableBalance() / _spendDivider));
}
}
// Increment proposal id counter.
_latestProposalId++;
uint256 currentId = _latestProposalId;
// Calculate end lifetime of the proposal.
uint256 endLifetime = block.timestamp.add(hoursLifetime_.mul(1 hours));
// Declare voter addresses set.
EnumerableSet.AddressSet storage voterAddresses;
// Save proposal struct.
_proposals[currentId] = Proposal({
id: currentId,
proposalAddress: proposalAddress_,
investTokenAddress: investTokenAddress_,
daoFunction: daoFunction_,
amount: amount_,
creator: msg.sender,
endLifetime: endLifetime,
voterAddresses: voterAddresses,
votesFor: balance / weight,
votesAgainst: 0,
executed: false
});
// Save id of new proposal.
_proposalIds.add(currentId);
// Emit event that new proposal has been created.
emit NewProposal(currentId);
}
/// @notice Removes existing proposal.
/// @param id_ id of proposal to remove.
function unpropose(uint256 id_) public override {
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
// Check that proposal creator, owner or an admin is removing a proposal.
require(msg.sender == currentProposal.creator || msg.sender == _creator || _admins.contains(msg.sender));
// Check that no votes have been registered for the proposal apart from the proposal creator, pool creator can remove any proposal.
if (msg.sender != _creator) {
require(currentProposal.voterAddresses.length() == 1);
}
// Remove proposal.
delete _proposals[id_];
_proposalIds.remove(id_);
// Emit event that a proposal has been removed.
emit RemoveProposal(id_);
}
/// @notice Voting for multiple proposals.
/// @param ids_ ids of proposals to vote for.
/// @param votes_ for or against votes for proposals.
function vote(uint256[] memory ids_, bool[] memory votes_) public override {
// Check that arrays of the same length have been supplied.
require(ids_.length == votes_.length);
// Check that voter has enough tokens staked to vote.
uint256 balance = _governingToken.stakedOf(msg.sender);
uint256 weight = voteWeight();
require(balance >= weight);
// Get number of votes that msg.sender has.
uint256 votesCount = balance / weight;
// Iterate over voted proposals.
for (uint256 i = 0; i < ids_.length; i++) {
uint256 id = ids_[i];
bool currentVote = votes_[i];
Proposal storage proposal = _proposals[id];
// Check that proposal hasn't been voted for by msg.sender and that it's still active.
if (!proposal.voterAddresses.contains(msg.sender) && proposal.endLifetime >= block.timestamp) {
// Add votes.
proposal.voterAddresses.add(msg.sender);
if (currentVote) {
proposal.votesFor = proposal.votesFor.add(votesCount);
} else {
proposal.votesAgainst = proposal.votesAgainst.add(votesCount);
}
}
// Emit event that a proposal has been voted for.
emit Vote(id);
}
}
/// @notice Executes a proposal.
/// @param id_ id of proposal to be executed.
function execute(uint256 id_) public override nonReentrant(id_) {
// save gas at the start of execution
uint256 remainingGasStart = gasleft();
// check whether proposal can be executed by the sender
require(canExecute(id_, msg.sender));
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
// Check that msg.sender has balance for at least 1 vote to execute a proposal.
uint256 balance = _governingToken.totalOf(msg.sender);
if (balance < voteWeight()) {
// Remove admin if his balance is not high enough.
if (_admins.contains(msg.sender)) {
_admins.remove(msg.sender);
}
revert();
}
// Call private function for proposal execution depending on the type.
if (currentProposal.daoFunction == DaoFunction.BUY) {
_executeBuy(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.SELL) {
_executeSell(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.ADD_LIQUIDITY) {
_executeAddLiquidity(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.REMOVE_LIQUIDITY) {
_executeRemoveLiquidity(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.ADD_ADMIN) {
_executeAddAdmin(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.REMOVE_ADMIN) {
_executeRemoveAdmin(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.INVEST) {
_executeInvest(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.WITHDRAW) {
_executeWithdraw(currentProposal);
}
// Mark proposal as executed.
currentProposal.executed = true;
// calculate gas used during execution
uint256 remainingGasEnd = gasleft();
uint256 usedGas = remainingGasStart.sub(remainingGasEnd).add(35000);
// max gas price allowed for refund is 200gwei
uint256 gasPrice;
if (tx.gasprice > 200000000000) {
gasPrice = 200000000000;
} else {
gasPrice = tx.gasprice;
}
// refund used gas
payable(msg.sender).transfer(usedGas.mul(gasPrice));
// Emit event that proposal has been executed.
emit ExecutedProposal(id_);
}
/// @notice Buying tokens for cloned DAO.
function buy() public override payable {
// Check that it's not the main DAO.
require(!_isMain);
// Check that msg.sender is not sending more money than max cost of dao.
require(msg.value <= _maxCost);
// Check that DAO has enough tokens to sell to msg.sender.
uint256 portion = _governingToken.totalSupply().mul(msg.value) / _maxCost;
require(_governingToken.balanceOf(address(this)) >= portion);
// Transfer tokens.
_governingToken.transfer(msg.sender, portion);
// Emit event that tokens have been bought.
emit Buy();
}
/// @notice Sell tokens back to cloned DAO.
/// @param amount_ amount of tokens to sell.
function sell(uint256 amount_) public override {
// Check that it's not the main DAO.
require(!_isMain);
// Check that msg.sender has enough tokens to sell.
require(_governingToken.balanceOf(msg.sender) >= amount_);
// Calculate the eth share holder should get back and whether pool has enough funds.
uint256 share = _supplyShare(amount_);
// Approve token transfer for DAO.
_governingToken.approveDao(msg.sender, amount_);
// Transfer tokens from msg.sender back to DAO.
_governingToken.transferFrom(msg.sender, address(this), amount_);
// Refund eth back to the msg.sender.
payable(msg.sender).transfer(share);
// Emit event that tokens have been sold back to DAO.
emit Sell();
}
// Private calls.
/// @notice Calculates cost of share of the supply.
/// @param amount_ amount of tokens to calculate eth share for.
/// @return price for specified amount share.
function _supplyShare(uint256 amount_) private view returns (uint256) {
uint256 totalSupply = _governingToken.totalSupply();
uint256 circulatingSupply = _circulatingSupply(totalSupply);
uint256 circulatingMaxCost = _circulatingMaxCost(circulatingSupply, totalSupply);
// Check whether available balance is higher than circulating max cost.
if (availableBalance() > circulatingMaxCost) {
// If true then share will equal to buy price.
return circulatingMaxCost.mul(amount_) / circulatingSupply;
} else {
// Otherwise calculate share price based on currently available balance.
return availableBalance().mul(amount_) / circulatingSupply;
}
}
/// @notice Calculates max cost for currently circulating supply.
/// @param circulatingSupply_ governing token circulating supply.
/// @param totalSupply_ governing token total supply.
/// @return uint256 eth cost of currently circulating supply.
function _circulatingMaxCost(uint256 circulatingSupply_, uint256 totalSupply_) private view returns (uint256) {
return _maxCost.mul(circulatingSupply_) / totalSupply_;
}
/// @notice Calculates circulating supply of governing token.
/// @param totalSupply_ governing token total supply.
/// @return uint256 number of tokens in circulation.
function _circulatingSupply(uint256 totalSupply_) private view returns (uint256) {
uint256 balance = _governingToken.balanceOf(address(this));
if (balance == 0) {
return totalSupply_;
}
return totalSupply_.sub(balance);
}
// Private transactions.
/// @notice Execution of BUY proposal.
/// @param proposal_ proposal.
function _executeBuy(Proposal storage proposal_) private {
// Check that DAO has enough funds to execute buy proposal.
require(availableBalance() >= proposal_.amount);
// Deposit eth funds to Uniswap router.
IWETH weth = IWETH(_router.WETH());
weth.deposit{value: proposal_.amount}();
// Create path for buying, buying is only for Token-ETH pair.
address[] memory path = new address[](2);
path[0] = address(weth);
path[1] = proposal_.proposalAddress;
// Execute uniswap buy.
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), path[0], path[1]);
uint256 amountOut = UniswapV2Library.getAmountOut(proposal_.amount, reserveA, reserveB);
_router.swapExactETHForTokens{value: proposal_.amount}(amountOut, path, address(this), block.timestamp.add(_timeout));
// If new token then save it holdings addresses.
if (!_holdings.contains(proposal_.proposalAddress)) {
_holdings.add(proposal_.proposalAddress);
// Emit event that holdings addresses changed.
emit HoldingsAddressesChanged();
}
}
/// @notice Execution of SELL proposal.
/// @param proposal_ proposal.
function _executeSell(Proposal storage proposal_) private {
// Approve uniswap router to sell tokens.
IERC20 token = IERC20(proposal_.proposalAddress);
require(token.approve(address(_router), proposal_.amount));
// Create path for selling, selling is only for Token-ETH pair.
address[] memory path = new address[](2);
path[0] = proposal_.proposalAddress;
path[1] = _router.WETH();
// Execute uniswap sell.
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), path[0], path[1]);
uint256 amountOut = UniswapV2Library.getAmountOut(proposal_.amount, reserveA, reserveB);
_router.swapExactTokensForETH(proposal_.amount, amountOut, path, address(this), block.timestamp.add(_timeout));
// If sold all tokens then remove it from holdings.
if (token.balanceOf(address(this)) == 0 && _holdings.contains(proposal_.proposalAddress)) {
_holdings.remove(proposal_.proposalAddress);
// Emit event that holdings addresses changed.
emit HoldingsAddressesChanged();
}
}
/// @notice Execution of ADD_LIQUIDITY proposal.
/// @param proposal_ proposal.
function _executeAddLiquidity(Proposal storage proposal_) private {
// Approve uniswap route to transfer tokens.
require(IERC20(proposal_.proposalAddress).approve(address(_router), proposal_.amount));
// Calculate amount of tokens and eth needed for liquidity.
IWETH weth = IWETH(_router.WETH());
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), proposal_.proposalAddress, address(weth));
uint256 wethAmount = UniswapV2Library.quote(proposal_.amount, reserveA, reserveB);
// Check that DAO has sufficient eth balance for liquidity.
require (availableBalance() > wethAmount);
// Deposit eth for liqudity.
weth.deposit{value: wethAmount}();
// Execute uniswap add liquidity.
_router.addLiquidityETH{value: wethAmount}(
proposal_.proposalAddress,
proposal_.amount,
(proposal_.amount / 100).mul(98),
(wethAmount / 100).mul(98),
address(this),
block.timestamp.add(_timeout)
);
// If new liquidity token then save it.
if (!_liquidityAddresses.contains(proposal_.proposalAddress)) {
_liquidityAddresses.add(proposal_.proposalAddress);
// Emit event that liquidity addresses changed.
emit LiquidityAddressesChanged();
}
}
/// @notice Execution of REMOVE_LIQUIDITY proposal.
/// @param proposal_ proposal.
function _executeRemoveLiquidity(Proposal storage proposal_) private {
// Approve uniswap router to transfer liquidity tokens.
address liquidityTokenAddress = liquidityToken(proposal_.proposalAddress);
require(IERC20(liquidityTokenAddress).approve(address(_router), proposal_.amount));
// Execute uniswap liquidity removal.
_router.removeLiquidityETH(
proposal_.proposalAddress,
proposal_.amount,
0,
0,
address(this),
block.timestamp.add(_timeout)
);
// If all tokens have been sold then remove liquidty address.
if (tokenBalance(liquidityTokenAddress) == 0 && _liquidityAddresses.contains(proposal_.proposalAddress)) {
_liquidityAddresses.remove(proposal_.proposalAddress);
// Emit event that liquidity addresses have changed.
emit LiquidityAddressesChanged();
}
}
/// @notice Execution of ADD_ADMIN proposal.
/// @param proposal_ propsal.
function _executeAddAdmin(Proposal storage proposal_) private {
// Check that address is not an admin already.
require(!_admins.contains(proposal_.proposalAddress));
// Check that holder has sufficient balance to be an admin.
uint256 balance = _governingToken.totalOf(proposal_.proposalAddress);
require(balance >= voteWeight());
// Add admin.
_admins.add(proposal_.proposalAddress);
// Emit event that new admin has been added.
emit AddAdmin(proposal_.proposalAddress);
}
/// @notice Execution of REMOVE_ADMIN proposal.
/// @param proposal_ proposal.
function _executeRemoveAdmin(Proposal storage proposal_) private {
// Check that address is an admin.
require(_admins.contains(proposal_.proposalAddress));
// Remove admin.
_admins.remove(proposal_.proposalAddress);
// Emit event that an admin has been removed.
emit RemoveAdmin(proposal_.proposalAddress);
}
/// @notice Execution of INVEST proposal.
/// @param proposal_ proposal.
function _executeInvest(Proposal storage proposal_) private {
// Check that DAO has sufficient balance for investment.
require(availableBalance() >= proposal_.amount);
// Transfer funds.
payable(proposal_.proposalAddress).call{value: proposal_.amount}("");
// If secondary address for invest token is specified then save it to holdings.
if(proposal_.investTokenAddress != address(0x0)) {
if (!_holdings.contains(proposal_.investTokenAddress)) {
_holdings.add(proposal_.investTokenAddress);
// Emit event that holdings addresses have changed.
emit HoldingsAddressesChanged();
}
}
}
/// @notice Execution of WITHDRAW proposal.
/// @param proposal_ proposal.
function _executeWithdraw(Proposal storage proposal_) private {
if (_isMain) {
// Main DAO only allows withdrawal once a week.
require(block.timestamp > _lastWithdraw.add(1 * 1 weeks));
_lastWithdraw = block.timestamp;
}
uint256 amount;
uint256 mainAmount;
uint256 currentBalance = availableBalance();
if (_isMain) {
mainAmount = 0;
amount = proposal_.amount;
// Check that withdrawal amount is not more than 10% of main DAO balance.
require(currentBalance / 10 >= amount);
} else {
uint256 totalSupply = _governingToken.totalSupply();
uint256 circulatingMaxCost = _circulatingMaxCost(_circulatingSupply(totalSupply), totalSupply);
// Check that cloned DAO balance is higher than circulating max cost.
require(currentBalance > circulatingMaxCost);
// Check that cloned DAO gains are enough to cover withdrawal.
require(currentBalance.sub(circulatingMaxCost) >= proposal_.amount);
// 0.25% of withdrawal will be transfered to Main DAO stakers.
mainAmount = proposal_.amount / 400;
amount = proposal_.amount.sub(mainAmount);
}
// Transfer all withdrawal funds to Torro Factory.
ITorroFactory(_factory).depositBenefits{value: proposal_.amount}(address(_governingToken));
// Divide withdrawal between governing token stakers.
_governingToken.addBenefits(amount);
// If cloned DAO withdrawal then divide 0.25% of withdrawal between main token stakers.
if (mainAmount > 0) {
_torroToken.addBenefits(mainAmount);
}
}
// Owner calls.
// Owner transactions.
/// @notice Sets factory address.
/// @param factory_ address of TorroFactory.
function setFactoryAddress(address factory_) public override onlyOwner {
_factory = factory_;
}
/// @notice Sets vote weight divider.
/// @param weight_ weight divider for a single vote.
function setVoteWeightDivider(uint256 weight_) public override onlyOwner {
_voteWeightDivider = weight_;
}
/// @notice Sets new address for router.
/// @param router_ address for router.
function setRouter(address router_) public override onlyOwner {
_router = IUniswapV2Router02(router_);
}
/// @notice Sets divider for BUY, INVEST, WITHDAW proposals.
/// @param divider_ divider for BUY, INVEST, WITHDRAW proposals.
function setSpendDivider(uint256 divider_) public override onlyOwner {
_spendDivider = divider_;
}
/// @notice Migrates balances of current DAO to a new DAO.
/// @param newDao_ address of the new DAO to migrate to.
function migrate(address newDao_) public override onlyOwner {
ITorroDao dao = ITorroDao(newDao_);
// Migrate holdings.
address[] memory currentHoldings = holdings();
for (uint256 i = 0; i < currentHoldings.length; i++) {
_migrateTransferBalance(currentHoldings[i], newDao_);
}
dao.addHoldingsAddresses(currentHoldings);
// Migrate liquidities.
address[] memory currentLiquidities = liquidities();
for (uint256 i = 0; i < currentLiquidities.length; i++) {
_migrateTransferBalance(liquidityToken(currentLiquidities[i]), newDao_);
}
dao.addLiquidityAddresses(currentLiquidities);
// Send over ETH balance.
payable(newDao_).call{value: availableBalance()}("");
}
// Private owner calls.
/// @notice Private function for migrating token balance to a new address.
/// @param token_ address of ERC-20 token to migrate.
/// @param target_ migration end point address.
function _migrateTransferBalance(address token_, address target_) private {
if (token_ != address(0x0)) {
IERC20 erc20 = IERC20(token_);
uint256 balance = erc20.balanceOf(address(this));
if (balance > 0) {
erc20.transfer(target_, balance);
}
}
}
} | /// @title DAO for proposals, voting and execution.
/// @notice Contract for creation, voting and execution of proposals.
/// @author ORayskiy - @robitnik_TorroDao | NatSpecSingleLine | setSpendDivider | function setSpendDivider(uint256 divider_) public override onlyOwner {
_spendDivider = divider_;
}
| /// @notice Sets divider for BUY, INVEST, WITHDAW proposals.
/// @param divider_ divider for BUY, INVEST, WITHDRAW proposals. | NatSpecSingleLine | v0.6.6+commit.6c089d02 | Unknown | ipfs://d1c6095fcf143d951c9754f00fe8cd59d29ab460461efe53b91eb289fd0fe5ac | {
"func_code_index": [
36640,
36749
]
} | 58,566 |
TorroDao | TorroDao.sol | 0x3cf9e9d45380b6ab61bde46b2e6cfcd7d8f6cdc1 | Solidity | TorroDao | contract TorroDao is ITorroDao, OwnableUpgradeSafe {
using EnumerableSet for EnumerableSet.AddressSet;
using EnumerableSet for EnumerableSet.UintSet;
using SafeMath for uint256;
// Structs.
/// @notice General proposal structure.
struct Proposal {
uint256 id;
address proposalAddress;
address investTokenAddress;
DaoFunction daoFunction;
uint256 amount;
address creator;
uint256 endLifetime;
EnumerableSet.AddressSet voterAddresses;
uint256 votesFor;
uint256 votesAgainst;
bool executed;
}
// Events.
/// @notice Event for dispatching on new proposal creation.
/// @param id id of the new proposal.
event NewProposal(uint256 id);
/// @notice Event for dispatching when proposal has been removed.
/// @param id id of the removed proposal.
event RemoveProposal(uint256 id);
/// @notice Event for dispatching when someone voted on a proposal.
/// @param id id of the voted proposal.
event Vote(uint256 id);
/// @notice Event for dispatching when an admin has been added to the DAO.
/// @param admin address of the admin that's been added.
event AddAdmin(address admin);
/// @notice Event for dispatching when an admin has been removed from the DAO.
/// @param admin address of the admin that's been removed.
event RemoveAdmin(address admin);
/// @notice Event for dispatching when a proposal has been executed.
/// @param id id of the executed proposal.
event ExecutedProposal(uint256 id);
/// @notice Event for dispatching when cloned DAO tokens have been bought.
event Buy();
/// @notice Event for dispatching when cloned DAO tokens have been sold.
event Sell();
/// @notice Event for dispatching when new holdings addresses have been changed.
event HoldingsAddressesChanged();
/// @notice Event for dipatching when new liquidity addresses have been changed.
event LiquidityAddressesChanged();
// Constants.
// Private data.
address private _creator;
EnumerableSet.AddressSet private _holdings;
EnumerableSet.AddressSet private _liquidityAddresses;
EnumerableSet.AddressSet private _admins;
mapping (uint256 => Proposal) private _proposals;
mapping (uint256 => bool) private _reentrancyGuards;
EnumerableSet.UintSet private _proposalIds;
ITorro private _torroToken;
ITorro private _governingToken;
address private _factory;
uint256 private _latestProposalId;
uint256 private _timeout;
uint256 private _maxCost;
uint256 private _executeMinPct;
uint256 private _votingMinHours;
uint256 private _voteWeightDivider;
uint256 private _lastWithdraw;
uint256 private _spendDivider;
bool private _isPublic;
bool private _isMain;
bool private _hasAdmins;
// ===============
IUniswapV2Router02 private _router;
// Constructor.
/// @notice Constructor for original Torro DAO.
/// @param governingToken_ Torro token address.
constructor(address governingToken_) public {
__Ownable_init();
_torroToken = ITorro(governingToken_);
_governingToken = ITorro(governingToken_);
_factory = address(0x0);
_latestProposalId = 0;
_timeout = uint256(5).mul(1 minutes);
_router = IUniswapV2Router02(address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D));
_maxCost = 0;
_executeMinPct = 5;
_votingMinHours = 6;
_voteWeightDivider = 10000;
_lastWithdraw = block.timestamp.add(1 * 1 weeks);
_spendDivider = 10;
_isMain = true;
_isPublic = true;
_hasAdmins = true;
_creator = msg.sender;
}
/// @notice Initializer for DAO clones.
/// @param torroToken_ main torro token address.
/// @param governingToken_ torro token clone that's governing this dao.
/// @param factory_ torro factory address.
/// @param creator_ creator of cloned DAO.
/// @param maxCost_ maximum cost of all governing tokens for cloned DAO.
/// @param executeMinPct_ minimum percentage of votes needed for proposal execution.
/// @param votingMinHours_ minimum lifetime of proposal before it closes.
/// @param isPublic_ whether cloned DAO has public visibility.
/// @param hasAdmins_ whether cloned DAO has admins, otherwise all stakers are treated as admins.
function initializeCustom(
address torroToken_,
address governingToken_,
address factory_,
address creator_,
uint256 maxCost_,
uint256 executeMinPct_,
uint256 votingMinHours_,
bool isPublic_,
bool hasAdmins_
) public override initializer {
__Ownable_init();
_torroToken = ITorro(torroToken_);
_governingToken = ITorro(governingToken_);
_factory = factory_;
_latestProposalId = 0;
_timeout = uint256(5).mul(1 minutes);
_router = IUniswapV2Router02(address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D));
_maxCost = maxCost_;
_voteWeightDivider = 0;
_executeMinPct = executeMinPct_;
_votingMinHours = votingMinHours_;
_lastWithdraw = block.timestamp;
_spendDivider = 0;
_isMain = false;
_isPublic = isPublic_;
_hasAdmins = hasAdmins_;
_creator = creator_;
if (_hasAdmins) {
_admins.add(creator_);
}
}
// Modifiers.
/// @notice Stops double execution of proposals.
/// @param id_ proposal id that's executing.
modifier nonReentrant(uint256 id_) {
// check that it's already not executing
require(!_reentrancyGuards[id_]);
// toggle state that proposal is currently executing
_reentrancyGuards[id_] = true;
_;
// toggle state back
_reentrancyGuards[id_] = false;
}
/// @notice Allow fund transfers to DAO contract.
receive() external payable {
// do nothing
}
// Public calls.
/// @notice Address of DAO creator.
/// @return DAO creator address.
function daoCreator() public override view returns (address) {
return _creator;
}
/// @notice Amount of tokens needed for a single vote.
/// @return uint256 token amount.
function voteWeight() public override view returns (uint256) {
uint256 weight;
if (_isMain) {
weight = _governingToken.totalSupply() / _voteWeightDivider;
} else {
weight = 10**18;
}
return weight;
}
/// @notice Amount of votes that holder has.
/// @param sender_ address of the holder.
/// @return number of votes.
function votesOf(address sender_) public override view returns (uint256) {
return _governingToken.stakedOf(sender_) / voteWeight();
}
/// @notice Address of the governing token.
/// @return address of the governing token.
function tokenAddress() public override view returns (address) {
return address(_governingToken);
}
/// @notice Saved addresses of tokens that DAO is holding.
/// @return array of holdings addresses.
function holdings() public override view returns (address[] memory) {
uint256 length = _holdings.length();
address[] memory holdingsAddresses = new address[](length);
for (uint256 i = 0; i < length; i++) {
holdingsAddresses[i] = _holdings.at(i);
}
return holdingsAddresses;
}
/// @notice Saved addresses of liquidity tokens that DAO is holding.
/// @return array of liquidity addresses.
function liquidities() public override view returns (address[] memory) {
uint256 length = _liquidityAddresses.length();
address[] memory liquidityAddresses = new address[](length);
for (uint256 i = 0; i < length; i++) {
liquidityAddresses[i] = _liquidityAddresses.at(i);
}
return liquidityAddresses;
}
/// @notice Calculates address of liquidity token from ERC-20 token address.
/// @param token_ token address to calculate liquidity address from.
/// @return address of liquidity token.
function liquidityToken(address token_) public override view returns (address) {
return UniswapV2Library.pairFor(_router.factory(), token_, _router.WETH());
}
/// @notice Gets tokens and liquidity token addresses of DAO's liquidity holdings.
/// @return Arrays of tokens and liquidity tokens, should have the same length.
function liquidityHoldings() public override view returns (address[] memory, address[] memory) {
uint256 length = _liquidityAddresses.length();
address[] memory tokens = new address[](length);
address[] memory liquidityTokens = new address[](length);
for (uint256 i = 0; i < length; i++) {
address token = _liquidityAddresses.at(i);
tokens[i] = token;
liquidityTokens[i] = liquidityToken(token);
}
return (tokens, liquidityTokens);
}
/// @notice DAO admins.
/// @return Array of admin addresses.
function admins() public override view returns (address[] memory) {
uint256 length = _admins.length();
address[] memory currentAdmins = new address[](length);
for (uint256 i = 0; i < length; i++) {
currentAdmins[i] = _admins.at(i);
}
return currentAdmins;
}
/// @notice DAO balance for specified token.
/// @param token_ token address to get balance for.
/// @return uint256 token balance.
function tokenBalance(address token_) public override view returns (uint256) {
return IERC20(token_).balanceOf(address(this));
}
/// @notice DAO balance for liquidity token.
/// @param token_ token address to get liquidity balance for.
/// @return uin256 token liquidity balance.
function liquidityBalance(address token_) public override view returns (uint256) {
return tokenBalance(liquidityToken(token_));
}
/// @notice DAO ethereum balance.
/// @return uint256 wei balance.
function availableBalance() public override view returns (uint256) {
return address(this).balance;
}
/// @notice Maximum cost for all tokens of cloned DAO.
/// @return uint256 maximum cost in wei.
function maxCost() public override view returns (uint256) {
return _maxCost;
}
/// @notice Minimum percentage of votes needed to execute a proposal.
/// @return uint256 minimum percentage of votes.
function executeMinPct() public override view returns (uint256) {
return _executeMinPct;
}
/// @notice Minimum lifetime of proposal before it closes.
/// @return uint256 minimum number of hours for proposal lifetime.
function votingMinHours() public override view returns (uint256) {
return _votingMinHours;
}
/// @notice Whether DAO is public or private.
/// @return bool true if public.
function isPublic() public override view returns (bool) {
return _isPublic;
}
/// @notice Whether DAO has admins.
/// @return bool true if DAO has admins.
function hasAdmins() public override view returns (bool) {
return _hasAdmins;
}
/// @notice Proposal ids of DAO.
/// @return array of proposal ids.
function getProposalIds() public override view returns (uint256[] memory) {
uint256 proposalsLength = _proposalIds.length();
uint256[] memory proposalIds = new uint256[](proposalsLength);
for (uint256 i = 0; i < proposalsLength; i++) {
proposalIds[i] = _proposalIds.at(i);
}
return proposalIds;
}
/// @notice Gets proposal info for proposal id.
/// @param id_ id of proposal to get info for.
/// @return proposalAddress address for proposal execution.
/// @return investTokenAddress secondary address for proposal execution, used for investment proposals if ICO and token addresses differ.
/// @return daoFunction proposal type.
/// @return amount proposal amount eth/token to use during execution.
/// @return creator address of proposal creator.
/// @return endLifetime epoch time when proposal voting ends.
/// @return votesFor amount of votes for the proposal.
/// @return votesAgainst amount of votes against the proposal.
/// @return executed whether proposal has been executed or not.
function getProposal(uint256 id_) public override view returns (
address proposalAddress,
address investTokenAddress,
DaoFunction daoFunction,
uint256 amount,
address creator,
uint256 endLifetime,
uint256 votesFor,
uint256 votesAgainst,
bool executed
) {
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
return (
currentProposal.proposalAddress,
currentProposal.investTokenAddress,
currentProposal.daoFunction,
currentProposal.amount,
currentProposal.creator,
currentProposal.endLifetime,
currentProposal.votesFor,
currentProposal.votesAgainst,
currentProposal.executed
);
}
/// @notice Whether a holder is allowed to vote for a proposal.
/// @param id_ proposal id to check whether holder is allowed to vote for.
/// @param sender_ address of the holder.
/// @return bool true if voting is allowed.
function canVote(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
return proposal.endLifetime >= block.timestamp && proposal.creator != sender_ && !proposal.voterAddresses.contains(sender_);
}
/// @notice Whether a holder is allowed to remove a proposal.
/// @param id_ proposal id to check whether holder is allowed to remove.
/// @param sender_ address of the holder.
/// @return bool true if removal is allowed.
function canRemove(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
return proposal.endLifetime >= block.timestamp && proposal.voterAddresses.length() == 1 && (proposal.creator == sender_ || owner() == sender_);
}
/// @notice Whether a holder is allowed to execute a proposal.
/// @param id_ proposal id to check whether holder is allowed to execute.
/// @param sender_ address of the holder.
/// @return bool true if execution is allowed.
function canExecute(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
// check that proposal hasn't been executed yet.
if (proposal.executed) {
return false;
}
// if custom pool has admins then only admins can execute proposals
if (!_isMain && _hasAdmins) {
if (!isAdmin(sender_)) {
return false;
}
}
if (proposal.daoFunction == DaoFunction.INVEST) {
// for invest functions only admins can execute
if (sender_ != _creator && !_admins.contains(sender_)) {
return false;
}
// check that sender is proposal creator or admin
} else if (proposal.creator != sender_ && !isAdmin(sender_)) {
return false;
}
// For main pool Buy and Sell dao functions allow instant executions if at least 10% of staked supply has voted for it
if (_isMain && (proposal.daoFunction == DaoFunction.BUY || proposal.daoFunction == DaoFunction.SELL)) {
if (proposal.votesFor.mul(voteWeight()) >= _governingToken.stakedSupply() / 10) {
if (proposal.votesFor > proposal.votesAgainst) {
// only allow admins to execute buy and sell proposals early
return isAdmin(sender_);
}
}
}
// check that proposal voting lifetime has run out.
if (proposal.endLifetime > block.timestamp) {
return false;
}
// check that votes for outweigh votes against.
bool currentCanExecute = proposal.votesFor > proposal.votesAgainst;
if (currentCanExecute && _executeMinPct > 0) {
// Check that proposal has at least _executeMinPct% of staked votes.
uint256 minVotes = _governingToken.stakedSupply() / (100 / _executeMinPct);
currentCanExecute = minVotes <= proposal.votesFor.add(proposal.votesAgainst).mul(voteWeight());
}
return currentCanExecute;
}
/// @notice Whether a holder is an admin.
/// @param sender_ address of holder.
/// @return bool true if holder is an admin (in DAO without admins all holders are treated as such).
function isAdmin(address sender_) public override view returns (bool) {
return !_hasAdmins || sender_ == _creator || _admins.contains(sender_);
}
// Public transactions.
/// @notice Saves new holdings addresses for DAO.
/// @param tokens_ token addresses that DAO has holdings of.
function addHoldingsAddresses(address[] memory tokens_) public override {
require(isAdmin(msg.sender));
for (uint256 i = 0; i < tokens_.length; i++) {
address token = tokens_[i];
if (!_holdings.contains(token)) {
_holdings.add(token);
}
}
emit HoldingsAddressesChanged();
}
/// @notice Saves new liquidity addresses for DAO.
/// @param tokens_ token addresses that DAO has liquidities of.
function addLiquidityAddresses(address[] memory tokens_) public override {
require(isAdmin(msg.sender));
for (uint256 i = 0; i < tokens_.length; i++) {
address token = tokens_[i];
if (!_liquidityAddresses.contains(token)) {
_liquidityAddresses.add(token);
}
}
emit LiquidityAddressesChanged();
}
/// @notice Creates new proposal.
/// @param proposalAddress_ main address of the proposal, in investment proposals this is the address funds are sent to.
/// @param investTokenAddress_ secondary address of the proposal, used in investment proposals to specify token address.
/// @param daoFunction_ type of the proposal.
/// @param amount_ amount of funds to use in the proposal.
/// @param hoursLifetime_ voting lifetime of the proposal.
function propose(address proposalAddress_, address investTokenAddress_, DaoFunction daoFunction_, uint256 amount_, uint256 hoursLifetime_) public override {
// check that lifetime is at least equals to min hours set for DAO.
require(hoursLifetime_ >= _votingMinHours);
// Check that proposal creator is allowed to create a proposal.
uint256 balance = _governingToken.stakedOf(msg.sender);
uint256 weight = voteWeight();
require(balance >= weight);
// For main DAO.
if (_isMain) {
if (daoFunction_ == DaoFunction.WITHDRAW || daoFunction_ == DaoFunction.INVEST || daoFunction_ == DaoFunction.BUY) {
// Limit each buy, investment and withdraw proposals to 10% of ETH funds.
require(amount_ <= (availableBalance() / _spendDivider));
}
}
// Increment proposal id counter.
_latestProposalId++;
uint256 currentId = _latestProposalId;
// Calculate end lifetime of the proposal.
uint256 endLifetime = block.timestamp.add(hoursLifetime_.mul(1 hours));
// Declare voter addresses set.
EnumerableSet.AddressSet storage voterAddresses;
// Save proposal struct.
_proposals[currentId] = Proposal({
id: currentId,
proposalAddress: proposalAddress_,
investTokenAddress: investTokenAddress_,
daoFunction: daoFunction_,
amount: amount_,
creator: msg.sender,
endLifetime: endLifetime,
voterAddresses: voterAddresses,
votesFor: balance / weight,
votesAgainst: 0,
executed: false
});
// Save id of new proposal.
_proposalIds.add(currentId);
// Emit event that new proposal has been created.
emit NewProposal(currentId);
}
/// @notice Removes existing proposal.
/// @param id_ id of proposal to remove.
function unpropose(uint256 id_) public override {
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
// Check that proposal creator, owner or an admin is removing a proposal.
require(msg.sender == currentProposal.creator || msg.sender == _creator || _admins.contains(msg.sender));
// Check that no votes have been registered for the proposal apart from the proposal creator, pool creator can remove any proposal.
if (msg.sender != _creator) {
require(currentProposal.voterAddresses.length() == 1);
}
// Remove proposal.
delete _proposals[id_];
_proposalIds.remove(id_);
// Emit event that a proposal has been removed.
emit RemoveProposal(id_);
}
/// @notice Voting for multiple proposals.
/// @param ids_ ids of proposals to vote for.
/// @param votes_ for or against votes for proposals.
function vote(uint256[] memory ids_, bool[] memory votes_) public override {
// Check that arrays of the same length have been supplied.
require(ids_.length == votes_.length);
// Check that voter has enough tokens staked to vote.
uint256 balance = _governingToken.stakedOf(msg.sender);
uint256 weight = voteWeight();
require(balance >= weight);
// Get number of votes that msg.sender has.
uint256 votesCount = balance / weight;
// Iterate over voted proposals.
for (uint256 i = 0; i < ids_.length; i++) {
uint256 id = ids_[i];
bool currentVote = votes_[i];
Proposal storage proposal = _proposals[id];
// Check that proposal hasn't been voted for by msg.sender and that it's still active.
if (!proposal.voterAddresses.contains(msg.sender) && proposal.endLifetime >= block.timestamp) {
// Add votes.
proposal.voterAddresses.add(msg.sender);
if (currentVote) {
proposal.votesFor = proposal.votesFor.add(votesCount);
} else {
proposal.votesAgainst = proposal.votesAgainst.add(votesCount);
}
}
// Emit event that a proposal has been voted for.
emit Vote(id);
}
}
/// @notice Executes a proposal.
/// @param id_ id of proposal to be executed.
function execute(uint256 id_) public override nonReentrant(id_) {
// save gas at the start of execution
uint256 remainingGasStart = gasleft();
// check whether proposal can be executed by the sender
require(canExecute(id_, msg.sender));
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
// Check that msg.sender has balance for at least 1 vote to execute a proposal.
uint256 balance = _governingToken.totalOf(msg.sender);
if (balance < voteWeight()) {
// Remove admin if his balance is not high enough.
if (_admins.contains(msg.sender)) {
_admins.remove(msg.sender);
}
revert();
}
// Call private function for proposal execution depending on the type.
if (currentProposal.daoFunction == DaoFunction.BUY) {
_executeBuy(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.SELL) {
_executeSell(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.ADD_LIQUIDITY) {
_executeAddLiquidity(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.REMOVE_LIQUIDITY) {
_executeRemoveLiquidity(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.ADD_ADMIN) {
_executeAddAdmin(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.REMOVE_ADMIN) {
_executeRemoveAdmin(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.INVEST) {
_executeInvest(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.WITHDRAW) {
_executeWithdraw(currentProposal);
}
// Mark proposal as executed.
currentProposal.executed = true;
// calculate gas used during execution
uint256 remainingGasEnd = gasleft();
uint256 usedGas = remainingGasStart.sub(remainingGasEnd).add(35000);
// max gas price allowed for refund is 200gwei
uint256 gasPrice;
if (tx.gasprice > 200000000000) {
gasPrice = 200000000000;
} else {
gasPrice = tx.gasprice;
}
// refund used gas
payable(msg.sender).transfer(usedGas.mul(gasPrice));
// Emit event that proposal has been executed.
emit ExecutedProposal(id_);
}
/// @notice Buying tokens for cloned DAO.
function buy() public override payable {
// Check that it's not the main DAO.
require(!_isMain);
// Check that msg.sender is not sending more money than max cost of dao.
require(msg.value <= _maxCost);
// Check that DAO has enough tokens to sell to msg.sender.
uint256 portion = _governingToken.totalSupply().mul(msg.value) / _maxCost;
require(_governingToken.balanceOf(address(this)) >= portion);
// Transfer tokens.
_governingToken.transfer(msg.sender, portion);
// Emit event that tokens have been bought.
emit Buy();
}
/// @notice Sell tokens back to cloned DAO.
/// @param amount_ amount of tokens to sell.
function sell(uint256 amount_) public override {
// Check that it's not the main DAO.
require(!_isMain);
// Check that msg.sender has enough tokens to sell.
require(_governingToken.balanceOf(msg.sender) >= amount_);
// Calculate the eth share holder should get back and whether pool has enough funds.
uint256 share = _supplyShare(amount_);
// Approve token transfer for DAO.
_governingToken.approveDao(msg.sender, amount_);
// Transfer tokens from msg.sender back to DAO.
_governingToken.transferFrom(msg.sender, address(this), amount_);
// Refund eth back to the msg.sender.
payable(msg.sender).transfer(share);
// Emit event that tokens have been sold back to DAO.
emit Sell();
}
// Private calls.
/// @notice Calculates cost of share of the supply.
/// @param amount_ amount of tokens to calculate eth share for.
/// @return price for specified amount share.
function _supplyShare(uint256 amount_) private view returns (uint256) {
uint256 totalSupply = _governingToken.totalSupply();
uint256 circulatingSupply = _circulatingSupply(totalSupply);
uint256 circulatingMaxCost = _circulatingMaxCost(circulatingSupply, totalSupply);
// Check whether available balance is higher than circulating max cost.
if (availableBalance() > circulatingMaxCost) {
// If true then share will equal to buy price.
return circulatingMaxCost.mul(amount_) / circulatingSupply;
} else {
// Otherwise calculate share price based on currently available balance.
return availableBalance().mul(amount_) / circulatingSupply;
}
}
/// @notice Calculates max cost for currently circulating supply.
/// @param circulatingSupply_ governing token circulating supply.
/// @param totalSupply_ governing token total supply.
/// @return uint256 eth cost of currently circulating supply.
function _circulatingMaxCost(uint256 circulatingSupply_, uint256 totalSupply_) private view returns (uint256) {
return _maxCost.mul(circulatingSupply_) / totalSupply_;
}
/// @notice Calculates circulating supply of governing token.
/// @param totalSupply_ governing token total supply.
/// @return uint256 number of tokens in circulation.
function _circulatingSupply(uint256 totalSupply_) private view returns (uint256) {
uint256 balance = _governingToken.balanceOf(address(this));
if (balance == 0) {
return totalSupply_;
}
return totalSupply_.sub(balance);
}
// Private transactions.
/// @notice Execution of BUY proposal.
/// @param proposal_ proposal.
function _executeBuy(Proposal storage proposal_) private {
// Check that DAO has enough funds to execute buy proposal.
require(availableBalance() >= proposal_.amount);
// Deposit eth funds to Uniswap router.
IWETH weth = IWETH(_router.WETH());
weth.deposit{value: proposal_.amount}();
// Create path for buying, buying is only for Token-ETH pair.
address[] memory path = new address[](2);
path[0] = address(weth);
path[1] = proposal_.proposalAddress;
// Execute uniswap buy.
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), path[0], path[1]);
uint256 amountOut = UniswapV2Library.getAmountOut(proposal_.amount, reserveA, reserveB);
_router.swapExactETHForTokens{value: proposal_.amount}(amountOut, path, address(this), block.timestamp.add(_timeout));
// If new token then save it holdings addresses.
if (!_holdings.contains(proposal_.proposalAddress)) {
_holdings.add(proposal_.proposalAddress);
// Emit event that holdings addresses changed.
emit HoldingsAddressesChanged();
}
}
/// @notice Execution of SELL proposal.
/// @param proposal_ proposal.
function _executeSell(Proposal storage proposal_) private {
// Approve uniswap router to sell tokens.
IERC20 token = IERC20(proposal_.proposalAddress);
require(token.approve(address(_router), proposal_.amount));
// Create path for selling, selling is only for Token-ETH pair.
address[] memory path = new address[](2);
path[0] = proposal_.proposalAddress;
path[1] = _router.WETH();
// Execute uniswap sell.
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), path[0], path[1]);
uint256 amountOut = UniswapV2Library.getAmountOut(proposal_.amount, reserveA, reserveB);
_router.swapExactTokensForETH(proposal_.amount, amountOut, path, address(this), block.timestamp.add(_timeout));
// If sold all tokens then remove it from holdings.
if (token.balanceOf(address(this)) == 0 && _holdings.contains(proposal_.proposalAddress)) {
_holdings.remove(proposal_.proposalAddress);
// Emit event that holdings addresses changed.
emit HoldingsAddressesChanged();
}
}
/// @notice Execution of ADD_LIQUIDITY proposal.
/// @param proposal_ proposal.
function _executeAddLiquidity(Proposal storage proposal_) private {
// Approve uniswap route to transfer tokens.
require(IERC20(proposal_.proposalAddress).approve(address(_router), proposal_.amount));
// Calculate amount of tokens and eth needed for liquidity.
IWETH weth = IWETH(_router.WETH());
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), proposal_.proposalAddress, address(weth));
uint256 wethAmount = UniswapV2Library.quote(proposal_.amount, reserveA, reserveB);
// Check that DAO has sufficient eth balance for liquidity.
require (availableBalance() > wethAmount);
// Deposit eth for liqudity.
weth.deposit{value: wethAmount}();
// Execute uniswap add liquidity.
_router.addLiquidityETH{value: wethAmount}(
proposal_.proposalAddress,
proposal_.amount,
(proposal_.amount / 100).mul(98),
(wethAmount / 100).mul(98),
address(this),
block.timestamp.add(_timeout)
);
// If new liquidity token then save it.
if (!_liquidityAddresses.contains(proposal_.proposalAddress)) {
_liquidityAddresses.add(proposal_.proposalAddress);
// Emit event that liquidity addresses changed.
emit LiquidityAddressesChanged();
}
}
/// @notice Execution of REMOVE_LIQUIDITY proposal.
/// @param proposal_ proposal.
function _executeRemoveLiquidity(Proposal storage proposal_) private {
// Approve uniswap router to transfer liquidity tokens.
address liquidityTokenAddress = liquidityToken(proposal_.proposalAddress);
require(IERC20(liquidityTokenAddress).approve(address(_router), proposal_.amount));
// Execute uniswap liquidity removal.
_router.removeLiquidityETH(
proposal_.proposalAddress,
proposal_.amount,
0,
0,
address(this),
block.timestamp.add(_timeout)
);
// If all tokens have been sold then remove liquidty address.
if (tokenBalance(liquidityTokenAddress) == 0 && _liquidityAddresses.contains(proposal_.proposalAddress)) {
_liquidityAddresses.remove(proposal_.proposalAddress);
// Emit event that liquidity addresses have changed.
emit LiquidityAddressesChanged();
}
}
/// @notice Execution of ADD_ADMIN proposal.
/// @param proposal_ propsal.
function _executeAddAdmin(Proposal storage proposal_) private {
// Check that address is not an admin already.
require(!_admins.contains(proposal_.proposalAddress));
// Check that holder has sufficient balance to be an admin.
uint256 balance = _governingToken.totalOf(proposal_.proposalAddress);
require(balance >= voteWeight());
// Add admin.
_admins.add(proposal_.proposalAddress);
// Emit event that new admin has been added.
emit AddAdmin(proposal_.proposalAddress);
}
/// @notice Execution of REMOVE_ADMIN proposal.
/// @param proposal_ proposal.
function _executeRemoveAdmin(Proposal storage proposal_) private {
// Check that address is an admin.
require(_admins.contains(proposal_.proposalAddress));
// Remove admin.
_admins.remove(proposal_.proposalAddress);
// Emit event that an admin has been removed.
emit RemoveAdmin(proposal_.proposalAddress);
}
/// @notice Execution of INVEST proposal.
/// @param proposal_ proposal.
function _executeInvest(Proposal storage proposal_) private {
// Check that DAO has sufficient balance for investment.
require(availableBalance() >= proposal_.amount);
// Transfer funds.
payable(proposal_.proposalAddress).call{value: proposal_.amount}("");
// If secondary address for invest token is specified then save it to holdings.
if(proposal_.investTokenAddress != address(0x0)) {
if (!_holdings.contains(proposal_.investTokenAddress)) {
_holdings.add(proposal_.investTokenAddress);
// Emit event that holdings addresses have changed.
emit HoldingsAddressesChanged();
}
}
}
/// @notice Execution of WITHDRAW proposal.
/// @param proposal_ proposal.
function _executeWithdraw(Proposal storage proposal_) private {
if (_isMain) {
// Main DAO only allows withdrawal once a week.
require(block.timestamp > _lastWithdraw.add(1 * 1 weeks));
_lastWithdraw = block.timestamp;
}
uint256 amount;
uint256 mainAmount;
uint256 currentBalance = availableBalance();
if (_isMain) {
mainAmount = 0;
amount = proposal_.amount;
// Check that withdrawal amount is not more than 10% of main DAO balance.
require(currentBalance / 10 >= amount);
} else {
uint256 totalSupply = _governingToken.totalSupply();
uint256 circulatingMaxCost = _circulatingMaxCost(_circulatingSupply(totalSupply), totalSupply);
// Check that cloned DAO balance is higher than circulating max cost.
require(currentBalance > circulatingMaxCost);
// Check that cloned DAO gains are enough to cover withdrawal.
require(currentBalance.sub(circulatingMaxCost) >= proposal_.amount);
// 0.25% of withdrawal will be transfered to Main DAO stakers.
mainAmount = proposal_.amount / 400;
amount = proposal_.amount.sub(mainAmount);
}
// Transfer all withdrawal funds to Torro Factory.
ITorroFactory(_factory).depositBenefits{value: proposal_.amount}(address(_governingToken));
// Divide withdrawal between governing token stakers.
_governingToken.addBenefits(amount);
// If cloned DAO withdrawal then divide 0.25% of withdrawal between main token stakers.
if (mainAmount > 0) {
_torroToken.addBenefits(mainAmount);
}
}
// Owner calls.
// Owner transactions.
/// @notice Sets factory address.
/// @param factory_ address of TorroFactory.
function setFactoryAddress(address factory_) public override onlyOwner {
_factory = factory_;
}
/// @notice Sets vote weight divider.
/// @param weight_ weight divider for a single vote.
function setVoteWeightDivider(uint256 weight_) public override onlyOwner {
_voteWeightDivider = weight_;
}
/// @notice Sets new address for router.
/// @param router_ address for router.
function setRouter(address router_) public override onlyOwner {
_router = IUniswapV2Router02(router_);
}
/// @notice Sets divider for BUY, INVEST, WITHDAW proposals.
/// @param divider_ divider for BUY, INVEST, WITHDRAW proposals.
function setSpendDivider(uint256 divider_) public override onlyOwner {
_spendDivider = divider_;
}
/// @notice Migrates balances of current DAO to a new DAO.
/// @param newDao_ address of the new DAO to migrate to.
function migrate(address newDao_) public override onlyOwner {
ITorroDao dao = ITorroDao(newDao_);
// Migrate holdings.
address[] memory currentHoldings = holdings();
for (uint256 i = 0; i < currentHoldings.length; i++) {
_migrateTransferBalance(currentHoldings[i], newDao_);
}
dao.addHoldingsAddresses(currentHoldings);
// Migrate liquidities.
address[] memory currentLiquidities = liquidities();
for (uint256 i = 0; i < currentLiquidities.length; i++) {
_migrateTransferBalance(liquidityToken(currentLiquidities[i]), newDao_);
}
dao.addLiquidityAddresses(currentLiquidities);
// Send over ETH balance.
payable(newDao_).call{value: availableBalance()}("");
}
// Private owner calls.
/// @notice Private function for migrating token balance to a new address.
/// @param token_ address of ERC-20 token to migrate.
/// @param target_ migration end point address.
function _migrateTransferBalance(address token_, address target_) private {
if (token_ != address(0x0)) {
IERC20 erc20 = IERC20(token_);
uint256 balance = erc20.balanceOf(address(this));
if (balance > 0) {
erc20.transfer(target_, balance);
}
}
}
} | /// @title DAO for proposals, voting and execution.
/// @notice Contract for creation, voting and execution of proposals.
/// @author ORayskiy - @robitnik_TorroDao | NatSpecSingleLine | migrate | function migrate(address newDao_) public override onlyOwner {
ITorroDao dao = ITorroDao(newDao_);
// Migrate holdings.
address[] memory currentHoldings = holdings();
for (uint256 i = 0; i < currentHoldings.length; i++) {
_migrateTransferBalance(currentHoldings[i], newDao_);
}
dao.addHoldingsAddresses(currentHoldings);
// Migrate liquidities.
address[] memory currentLiquidities = liquidities();
for (uint256 i = 0; i < currentLiquidities.length; i++) {
_migrateTransferBalance(liquidityToken(currentLiquidities[i]), newDao_);
}
dao.addLiquidityAddresses(currentLiquidities);
// Send over ETH balance.
payable(newDao_).call{value: availableBalance()}("");
}
| /// @notice Migrates balances of current DAO to a new DAO.
/// @param newDao_ address of the new DAO to migrate to. | NatSpecSingleLine | v0.6.6+commit.6c089d02 | Unknown | ipfs://d1c6095fcf143d951c9754f00fe8cd59d29ab460461efe53b91eb289fd0fe5ac | {
"func_code_index": [
36874,
37627
]
} | 58,567 |
TorroDao | TorroDao.sol | 0x3cf9e9d45380b6ab61bde46b2e6cfcd7d8f6cdc1 | Solidity | TorroDao | contract TorroDao is ITorroDao, OwnableUpgradeSafe {
using EnumerableSet for EnumerableSet.AddressSet;
using EnumerableSet for EnumerableSet.UintSet;
using SafeMath for uint256;
// Structs.
/// @notice General proposal structure.
struct Proposal {
uint256 id;
address proposalAddress;
address investTokenAddress;
DaoFunction daoFunction;
uint256 amount;
address creator;
uint256 endLifetime;
EnumerableSet.AddressSet voterAddresses;
uint256 votesFor;
uint256 votesAgainst;
bool executed;
}
// Events.
/// @notice Event for dispatching on new proposal creation.
/// @param id id of the new proposal.
event NewProposal(uint256 id);
/// @notice Event for dispatching when proposal has been removed.
/// @param id id of the removed proposal.
event RemoveProposal(uint256 id);
/// @notice Event for dispatching when someone voted on a proposal.
/// @param id id of the voted proposal.
event Vote(uint256 id);
/// @notice Event for dispatching when an admin has been added to the DAO.
/// @param admin address of the admin that's been added.
event AddAdmin(address admin);
/// @notice Event for dispatching when an admin has been removed from the DAO.
/// @param admin address of the admin that's been removed.
event RemoveAdmin(address admin);
/// @notice Event for dispatching when a proposal has been executed.
/// @param id id of the executed proposal.
event ExecutedProposal(uint256 id);
/// @notice Event for dispatching when cloned DAO tokens have been bought.
event Buy();
/// @notice Event for dispatching when cloned DAO tokens have been sold.
event Sell();
/// @notice Event for dispatching when new holdings addresses have been changed.
event HoldingsAddressesChanged();
/// @notice Event for dipatching when new liquidity addresses have been changed.
event LiquidityAddressesChanged();
// Constants.
// Private data.
address private _creator;
EnumerableSet.AddressSet private _holdings;
EnumerableSet.AddressSet private _liquidityAddresses;
EnumerableSet.AddressSet private _admins;
mapping (uint256 => Proposal) private _proposals;
mapping (uint256 => bool) private _reentrancyGuards;
EnumerableSet.UintSet private _proposalIds;
ITorro private _torroToken;
ITorro private _governingToken;
address private _factory;
uint256 private _latestProposalId;
uint256 private _timeout;
uint256 private _maxCost;
uint256 private _executeMinPct;
uint256 private _votingMinHours;
uint256 private _voteWeightDivider;
uint256 private _lastWithdraw;
uint256 private _spendDivider;
bool private _isPublic;
bool private _isMain;
bool private _hasAdmins;
// ===============
IUniswapV2Router02 private _router;
// Constructor.
/// @notice Constructor for original Torro DAO.
/// @param governingToken_ Torro token address.
constructor(address governingToken_) public {
__Ownable_init();
_torroToken = ITorro(governingToken_);
_governingToken = ITorro(governingToken_);
_factory = address(0x0);
_latestProposalId = 0;
_timeout = uint256(5).mul(1 minutes);
_router = IUniswapV2Router02(address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D));
_maxCost = 0;
_executeMinPct = 5;
_votingMinHours = 6;
_voteWeightDivider = 10000;
_lastWithdraw = block.timestamp.add(1 * 1 weeks);
_spendDivider = 10;
_isMain = true;
_isPublic = true;
_hasAdmins = true;
_creator = msg.sender;
}
/// @notice Initializer for DAO clones.
/// @param torroToken_ main torro token address.
/// @param governingToken_ torro token clone that's governing this dao.
/// @param factory_ torro factory address.
/// @param creator_ creator of cloned DAO.
/// @param maxCost_ maximum cost of all governing tokens for cloned DAO.
/// @param executeMinPct_ minimum percentage of votes needed for proposal execution.
/// @param votingMinHours_ minimum lifetime of proposal before it closes.
/// @param isPublic_ whether cloned DAO has public visibility.
/// @param hasAdmins_ whether cloned DAO has admins, otherwise all stakers are treated as admins.
function initializeCustom(
address torroToken_,
address governingToken_,
address factory_,
address creator_,
uint256 maxCost_,
uint256 executeMinPct_,
uint256 votingMinHours_,
bool isPublic_,
bool hasAdmins_
) public override initializer {
__Ownable_init();
_torroToken = ITorro(torroToken_);
_governingToken = ITorro(governingToken_);
_factory = factory_;
_latestProposalId = 0;
_timeout = uint256(5).mul(1 minutes);
_router = IUniswapV2Router02(address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D));
_maxCost = maxCost_;
_voteWeightDivider = 0;
_executeMinPct = executeMinPct_;
_votingMinHours = votingMinHours_;
_lastWithdraw = block.timestamp;
_spendDivider = 0;
_isMain = false;
_isPublic = isPublic_;
_hasAdmins = hasAdmins_;
_creator = creator_;
if (_hasAdmins) {
_admins.add(creator_);
}
}
// Modifiers.
/// @notice Stops double execution of proposals.
/// @param id_ proposal id that's executing.
modifier nonReentrant(uint256 id_) {
// check that it's already not executing
require(!_reentrancyGuards[id_]);
// toggle state that proposal is currently executing
_reentrancyGuards[id_] = true;
_;
// toggle state back
_reentrancyGuards[id_] = false;
}
/// @notice Allow fund transfers to DAO contract.
receive() external payable {
// do nothing
}
// Public calls.
/// @notice Address of DAO creator.
/// @return DAO creator address.
function daoCreator() public override view returns (address) {
return _creator;
}
/// @notice Amount of tokens needed for a single vote.
/// @return uint256 token amount.
function voteWeight() public override view returns (uint256) {
uint256 weight;
if (_isMain) {
weight = _governingToken.totalSupply() / _voteWeightDivider;
} else {
weight = 10**18;
}
return weight;
}
/// @notice Amount of votes that holder has.
/// @param sender_ address of the holder.
/// @return number of votes.
function votesOf(address sender_) public override view returns (uint256) {
return _governingToken.stakedOf(sender_) / voteWeight();
}
/// @notice Address of the governing token.
/// @return address of the governing token.
function tokenAddress() public override view returns (address) {
return address(_governingToken);
}
/// @notice Saved addresses of tokens that DAO is holding.
/// @return array of holdings addresses.
function holdings() public override view returns (address[] memory) {
uint256 length = _holdings.length();
address[] memory holdingsAddresses = new address[](length);
for (uint256 i = 0; i < length; i++) {
holdingsAddresses[i] = _holdings.at(i);
}
return holdingsAddresses;
}
/// @notice Saved addresses of liquidity tokens that DAO is holding.
/// @return array of liquidity addresses.
function liquidities() public override view returns (address[] memory) {
uint256 length = _liquidityAddresses.length();
address[] memory liquidityAddresses = new address[](length);
for (uint256 i = 0; i < length; i++) {
liquidityAddresses[i] = _liquidityAddresses.at(i);
}
return liquidityAddresses;
}
/// @notice Calculates address of liquidity token from ERC-20 token address.
/// @param token_ token address to calculate liquidity address from.
/// @return address of liquidity token.
function liquidityToken(address token_) public override view returns (address) {
return UniswapV2Library.pairFor(_router.factory(), token_, _router.WETH());
}
/// @notice Gets tokens and liquidity token addresses of DAO's liquidity holdings.
/// @return Arrays of tokens and liquidity tokens, should have the same length.
function liquidityHoldings() public override view returns (address[] memory, address[] memory) {
uint256 length = _liquidityAddresses.length();
address[] memory tokens = new address[](length);
address[] memory liquidityTokens = new address[](length);
for (uint256 i = 0; i < length; i++) {
address token = _liquidityAddresses.at(i);
tokens[i] = token;
liquidityTokens[i] = liquidityToken(token);
}
return (tokens, liquidityTokens);
}
/// @notice DAO admins.
/// @return Array of admin addresses.
function admins() public override view returns (address[] memory) {
uint256 length = _admins.length();
address[] memory currentAdmins = new address[](length);
for (uint256 i = 0; i < length; i++) {
currentAdmins[i] = _admins.at(i);
}
return currentAdmins;
}
/// @notice DAO balance for specified token.
/// @param token_ token address to get balance for.
/// @return uint256 token balance.
function tokenBalance(address token_) public override view returns (uint256) {
return IERC20(token_).balanceOf(address(this));
}
/// @notice DAO balance for liquidity token.
/// @param token_ token address to get liquidity balance for.
/// @return uin256 token liquidity balance.
function liquidityBalance(address token_) public override view returns (uint256) {
return tokenBalance(liquidityToken(token_));
}
/// @notice DAO ethereum balance.
/// @return uint256 wei balance.
function availableBalance() public override view returns (uint256) {
return address(this).balance;
}
/// @notice Maximum cost for all tokens of cloned DAO.
/// @return uint256 maximum cost in wei.
function maxCost() public override view returns (uint256) {
return _maxCost;
}
/// @notice Minimum percentage of votes needed to execute a proposal.
/// @return uint256 minimum percentage of votes.
function executeMinPct() public override view returns (uint256) {
return _executeMinPct;
}
/// @notice Minimum lifetime of proposal before it closes.
/// @return uint256 minimum number of hours for proposal lifetime.
function votingMinHours() public override view returns (uint256) {
return _votingMinHours;
}
/// @notice Whether DAO is public or private.
/// @return bool true if public.
function isPublic() public override view returns (bool) {
return _isPublic;
}
/// @notice Whether DAO has admins.
/// @return bool true if DAO has admins.
function hasAdmins() public override view returns (bool) {
return _hasAdmins;
}
/// @notice Proposal ids of DAO.
/// @return array of proposal ids.
function getProposalIds() public override view returns (uint256[] memory) {
uint256 proposalsLength = _proposalIds.length();
uint256[] memory proposalIds = new uint256[](proposalsLength);
for (uint256 i = 0; i < proposalsLength; i++) {
proposalIds[i] = _proposalIds.at(i);
}
return proposalIds;
}
/// @notice Gets proposal info for proposal id.
/// @param id_ id of proposal to get info for.
/// @return proposalAddress address for proposal execution.
/// @return investTokenAddress secondary address for proposal execution, used for investment proposals if ICO and token addresses differ.
/// @return daoFunction proposal type.
/// @return amount proposal amount eth/token to use during execution.
/// @return creator address of proposal creator.
/// @return endLifetime epoch time when proposal voting ends.
/// @return votesFor amount of votes for the proposal.
/// @return votesAgainst amount of votes against the proposal.
/// @return executed whether proposal has been executed or not.
function getProposal(uint256 id_) public override view returns (
address proposalAddress,
address investTokenAddress,
DaoFunction daoFunction,
uint256 amount,
address creator,
uint256 endLifetime,
uint256 votesFor,
uint256 votesAgainst,
bool executed
) {
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
return (
currentProposal.proposalAddress,
currentProposal.investTokenAddress,
currentProposal.daoFunction,
currentProposal.amount,
currentProposal.creator,
currentProposal.endLifetime,
currentProposal.votesFor,
currentProposal.votesAgainst,
currentProposal.executed
);
}
/// @notice Whether a holder is allowed to vote for a proposal.
/// @param id_ proposal id to check whether holder is allowed to vote for.
/// @param sender_ address of the holder.
/// @return bool true if voting is allowed.
function canVote(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
return proposal.endLifetime >= block.timestamp && proposal.creator != sender_ && !proposal.voterAddresses.contains(sender_);
}
/// @notice Whether a holder is allowed to remove a proposal.
/// @param id_ proposal id to check whether holder is allowed to remove.
/// @param sender_ address of the holder.
/// @return bool true if removal is allowed.
function canRemove(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
return proposal.endLifetime >= block.timestamp && proposal.voterAddresses.length() == 1 && (proposal.creator == sender_ || owner() == sender_);
}
/// @notice Whether a holder is allowed to execute a proposal.
/// @param id_ proposal id to check whether holder is allowed to execute.
/// @param sender_ address of the holder.
/// @return bool true if execution is allowed.
function canExecute(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
// check that proposal hasn't been executed yet.
if (proposal.executed) {
return false;
}
// if custom pool has admins then only admins can execute proposals
if (!_isMain && _hasAdmins) {
if (!isAdmin(sender_)) {
return false;
}
}
if (proposal.daoFunction == DaoFunction.INVEST) {
// for invest functions only admins can execute
if (sender_ != _creator && !_admins.contains(sender_)) {
return false;
}
// check that sender is proposal creator or admin
} else if (proposal.creator != sender_ && !isAdmin(sender_)) {
return false;
}
// For main pool Buy and Sell dao functions allow instant executions if at least 10% of staked supply has voted for it
if (_isMain && (proposal.daoFunction == DaoFunction.BUY || proposal.daoFunction == DaoFunction.SELL)) {
if (proposal.votesFor.mul(voteWeight()) >= _governingToken.stakedSupply() / 10) {
if (proposal.votesFor > proposal.votesAgainst) {
// only allow admins to execute buy and sell proposals early
return isAdmin(sender_);
}
}
}
// check that proposal voting lifetime has run out.
if (proposal.endLifetime > block.timestamp) {
return false;
}
// check that votes for outweigh votes against.
bool currentCanExecute = proposal.votesFor > proposal.votesAgainst;
if (currentCanExecute && _executeMinPct > 0) {
// Check that proposal has at least _executeMinPct% of staked votes.
uint256 minVotes = _governingToken.stakedSupply() / (100 / _executeMinPct);
currentCanExecute = minVotes <= proposal.votesFor.add(proposal.votesAgainst).mul(voteWeight());
}
return currentCanExecute;
}
/// @notice Whether a holder is an admin.
/// @param sender_ address of holder.
/// @return bool true if holder is an admin (in DAO without admins all holders are treated as such).
function isAdmin(address sender_) public override view returns (bool) {
return !_hasAdmins || sender_ == _creator || _admins.contains(sender_);
}
// Public transactions.
/// @notice Saves new holdings addresses for DAO.
/// @param tokens_ token addresses that DAO has holdings of.
function addHoldingsAddresses(address[] memory tokens_) public override {
require(isAdmin(msg.sender));
for (uint256 i = 0; i < tokens_.length; i++) {
address token = tokens_[i];
if (!_holdings.contains(token)) {
_holdings.add(token);
}
}
emit HoldingsAddressesChanged();
}
/// @notice Saves new liquidity addresses for DAO.
/// @param tokens_ token addresses that DAO has liquidities of.
function addLiquidityAddresses(address[] memory tokens_) public override {
require(isAdmin(msg.sender));
for (uint256 i = 0; i < tokens_.length; i++) {
address token = tokens_[i];
if (!_liquidityAddresses.contains(token)) {
_liquidityAddresses.add(token);
}
}
emit LiquidityAddressesChanged();
}
/// @notice Creates new proposal.
/// @param proposalAddress_ main address of the proposal, in investment proposals this is the address funds are sent to.
/// @param investTokenAddress_ secondary address of the proposal, used in investment proposals to specify token address.
/// @param daoFunction_ type of the proposal.
/// @param amount_ amount of funds to use in the proposal.
/// @param hoursLifetime_ voting lifetime of the proposal.
function propose(address proposalAddress_, address investTokenAddress_, DaoFunction daoFunction_, uint256 amount_, uint256 hoursLifetime_) public override {
// check that lifetime is at least equals to min hours set for DAO.
require(hoursLifetime_ >= _votingMinHours);
// Check that proposal creator is allowed to create a proposal.
uint256 balance = _governingToken.stakedOf(msg.sender);
uint256 weight = voteWeight();
require(balance >= weight);
// For main DAO.
if (_isMain) {
if (daoFunction_ == DaoFunction.WITHDRAW || daoFunction_ == DaoFunction.INVEST || daoFunction_ == DaoFunction.BUY) {
// Limit each buy, investment and withdraw proposals to 10% of ETH funds.
require(amount_ <= (availableBalance() / _spendDivider));
}
}
// Increment proposal id counter.
_latestProposalId++;
uint256 currentId = _latestProposalId;
// Calculate end lifetime of the proposal.
uint256 endLifetime = block.timestamp.add(hoursLifetime_.mul(1 hours));
// Declare voter addresses set.
EnumerableSet.AddressSet storage voterAddresses;
// Save proposal struct.
_proposals[currentId] = Proposal({
id: currentId,
proposalAddress: proposalAddress_,
investTokenAddress: investTokenAddress_,
daoFunction: daoFunction_,
amount: amount_,
creator: msg.sender,
endLifetime: endLifetime,
voterAddresses: voterAddresses,
votesFor: balance / weight,
votesAgainst: 0,
executed: false
});
// Save id of new proposal.
_proposalIds.add(currentId);
// Emit event that new proposal has been created.
emit NewProposal(currentId);
}
/// @notice Removes existing proposal.
/// @param id_ id of proposal to remove.
function unpropose(uint256 id_) public override {
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
// Check that proposal creator, owner or an admin is removing a proposal.
require(msg.sender == currentProposal.creator || msg.sender == _creator || _admins.contains(msg.sender));
// Check that no votes have been registered for the proposal apart from the proposal creator, pool creator can remove any proposal.
if (msg.sender != _creator) {
require(currentProposal.voterAddresses.length() == 1);
}
// Remove proposal.
delete _proposals[id_];
_proposalIds.remove(id_);
// Emit event that a proposal has been removed.
emit RemoveProposal(id_);
}
/// @notice Voting for multiple proposals.
/// @param ids_ ids of proposals to vote for.
/// @param votes_ for or against votes for proposals.
function vote(uint256[] memory ids_, bool[] memory votes_) public override {
// Check that arrays of the same length have been supplied.
require(ids_.length == votes_.length);
// Check that voter has enough tokens staked to vote.
uint256 balance = _governingToken.stakedOf(msg.sender);
uint256 weight = voteWeight();
require(balance >= weight);
// Get number of votes that msg.sender has.
uint256 votesCount = balance / weight;
// Iterate over voted proposals.
for (uint256 i = 0; i < ids_.length; i++) {
uint256 id = ids_[i];
bool currentVote = votes_[i];
Proposal storage proposal = _proposals[id];
// Check that proposal hasn't been voted for by msg.sender and that it's still active.
if (!proposal.voterAddresses.contains(msg.sender) && proposal.endLifetime >= block.timestamp) {
// Add votes.
proposal.voterAddresses.add(msg.sender);
if (currentVote) {
proposal.votesFor = proposal.votesFor.add(votesCount);
} else {
proposal.votesAgainst = proposal.votesAgainst.add(votesCount);
}
}
// Emit event that a proposal has been voted for.
emit Vote(id);
}
}
/// @notice Executes a proposal.
/// @param id_ id of proposal to be executed.
function execute(uint256 id_) public override nonReentrant(id_) {
// save gas at the start of execution
uint256 remainingGasStart = gasleft();
// check whether proposal can be executed by the sender
require(canExecute(id_, msg.sender));
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
// Check that msg.sender has balance for at least 1 vote to execute a proposal.
uint256 balance = _governingToken.totalOf(msg.sender);
if (balance < voteWeight()) {
// Remove admin if his balance is not high enough.
if (_admins.contains(msg.sender)) {
_admins.remove(msg.sender);
}
revert();
}
// Call private function for proposal execution depending on the type.
if (currentProposal.daoFunction == DaoFunction.BUY) {
_executeBuy(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.SELL) {
_executeSell(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.ADD_LIQUIDITY) {
_executeAddLiquidity(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.REMOVE_LIQUIDITY) {
_executeRemoveLiquidity(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.ADD_ADMIN) {
_executeAddAdmin(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.REMOVE_ADMIN) {
_executeRemoveAdmin(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.INVEST) {
_executeInvest(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.WITHDRAW) {
_executeWithdraw(currentProposal);
}
// Mark proposal as executed.
currentProposal.executed = true;
// calculate gas used during execution
uint256 remainingGasEnd = gasleft();
uint256 usedGas = remainingGasStart.sub(remainingGasEnd).add(35000);
// max gas price allowed for refund is 200gwei
uint256 gasPrice;
if (tx.gasprice > 200000000000) {
gasPrice = 200000000000;
} else {
gasPrice = tx.gasprice;
}
// refund used gas
payable(msg.sender).transfer(usedGas.mul(gasPrice));
// Emit event that proposal has been executed.
emit ExecutedProposal(id_);
}
/// @notice Buying tokens for cloned DAO.
function buy() public override payable {
// Check that it's not the main DAO.
require(!_isMain);
// Check that msg.sender is not sending more money than max cost of dao.
require(msg.value <= _maxCost);
// Check that DAO has enough tokens to sell to msg.sender.
uint256 portion = _governingToken.totalSupply().mul(msg.value) / _maxCost;
require(_governingToken.balanceOf(address(this)) >= portion);
// Transfer tokens.
_governingToken.transfer(msg.sender, portion);
// Emit event that tokens have been bought.
emit Buy();
}
/// @notice Sell tokens back to cloned DAO.
/// @param amount_ amount of tokens to sell.
function sell(uint256 amount_) public override {
// Check that it's not the main DAO.
require(!_isMain);
// Check that msg.sender has enough tokens to sell.
require(_governingToken.balanceOf(msg.sender) >= amount_);
// Calculate the eth share holder should get back and whether pool has enough funds.
uint256 share = _supplyShare(amount_);
// Approve token transfer for DAO.
_governingToken.approveDao(msg.sender, amount_);
// Transfer tokens from msg.sender back to DAO.
_governingToken.transferFrom(msg.sender, address(this), amount_);
// Refund eth back to the msg.sender.
payable(msg.sender).transfer(share);
// Emit event that tokens have been sold back to DAO.
emit Sell();
}
// Private calls.
/// @notice Calculates cost of share of the supply.
/// @param amount_ amount of tokens to calculate eth share for.
/// @return price for specified amount share.
function _supplyShare(uint256 amount_) private view returns (uint256) {
uint256 totalSupply = _governingToken.totalSupply();
uint256 circulatingSupply = _circulatingSupply(totalSupply);
uint256 circulatingMaxCost = _circulatingMaxCost(circulatingSupply, totalSupply);
// Check whether available balance is higher than circulating max cost.
if (availableBalance() > circulatingMaxCost) {
// If true then share will equal to buy price.
return circulatingMaxCost.mul(amount_) / circulatingSupply;
} else {
// Otherwise calculate share price based on currently available balance.
return availableBalance().mul(amount_) / circulatingSupply;
}
}
/// @notice Calculates max cost for currently circulating supply.
/// @param circulatingSupply_ governing token circulating supply.
/// @param totalSupply_ governing token total supply.
/// @return uint256 eth cost of currently circulating supply.
function _circulatingMaxCost(uint256 circulatingSupply_, uint256 totalSupply_) private view returns (uint256) {
return _maxCost.mul(circulatingSupply_) / totalSupply_;
}
/// @notice Calculates circulating supply of governing token.
/// @param totalSupply_ governing token total supply.
/// @return uint256 number of tokens in circulation.
function _circulatingSupply(uint256 totalSupply_) private view returns (uint256) {
uint256 balance = _governingToken.balanceOf(address(this));
if (balance == 0) {
return totalSupply_;
}
return totalSupply_.sub(balance);
}
// Private transactions.
/// @notice Execution of BUY proposal.
/// @param proposal_ proposal.
function _executeBuy(Proposal storage proposal_) private {
// Check that DAO has enough funds to execute buy proposal.
require(availableBalance() >= proposal_.amount);
// Deposit eth funds to Uniswap router.
IWETH weth = IWETH(_router.WETH());
weth.deposit{value: proposal_.amount}();
// Create path for buying, buying is only for Token-ETH pair.
address[] memory path = new address[](2);
path[0] = address(weth);
path[1] = proposal_.proposalAddress;
// Execute uniswap buy.
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), path[0], path[1]);
uint256 amountOut = UniswapV2Library.getAmountOut(proposal_.amount, reserveA, reserveB);
_router.swapExactETHForTokens{value: proposal_.amount}(amountOut, path, address(this), block.timestamp.add(_timeout));
// If new token then save it holdings addresses.
if (!_holdings.contains(proposal_.proposalAddress)) {
_holdings.add(proposal_.proposalAddress);
// Emit event that holdings addresses changed.
emit HoldingsAddressesChanged();
}
}
/// @notice Execution of SELL proposal.
/// @param proposal_ proposal.
function _executeSell(Proposal storage proposal_) private {
// Approve uniswap router to sell tokens.
IERC20 token = IERC20(proposal_.proposalAddress);
require(token.approve(address(_router), proposal_.amount));
// Create path for selling, selling is only for Token-ETH pair.
address[] memory path = new address[](2);
path[0] = proposal_.proposalAddress;
path[1] = _router.WETH();
// Execute uniswap sell.
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), path[0], path[1]);
uint256 amountOut = UniswapV2Library.getAmountOut(proposal_.amount, reserveA, reserveB);
_router.swapExactTokensForETH(proposal_.amount, amountOut, path, address(this), block.timestamp.add(_timeout));
// If sold all tokens then remove it from holdings.
if (token.balanceOf(address(this)) == 0 && _holdings.contains(proposal_.proposalAddress)) {
_holdings.remove(proposal_.proposalAddress);
// Emit event that holdings addresses changed.
emit HoldingsAddressesChanged();
}
}
/// @notice Execution of ADD_LIQUIDITY proposal.
/// @param proposal_ proposal.
function _executeAddLiquidity(Proposal storage proposal_) private {
// Approve uniswap route to transfer tokens.
require(IERC20(proposal_.proposalAddress).approve(address(_router), proposal_.amount));
// Calculate amount of tokens and eth needed for liquidity.
IWETH weth = IWETH(_router.WETH());
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), proposal_.proposalAddress, address(weth));
uint256 wethAmount = UniswapV2Library.quote(proposal_.amount, reserveA, reserveB);
// Check that DAO has sufficient eth balance for liquidity.
require (availableBalance() > wethAmount);
// Deposit eth for liqudity.
weth.deposit{value: wethAmount}();
// Execute uniswap add liquidity.
_router.addLiquidityETH{value: wethAmount}(
proposal_.proposalAddress,
proposal_.amount,
(proposal_.amount / 100).mul(98),
(wethAmount / 100).mul(98),
address(this),
block.timestamp.add(_timeout)
);
// If new liquidity token then save it.
if (!_liquidityAddresses.contains(proposal_.proposalAddress)) {
_liquidityAddresses.add(proposal_.proposalAddress);
// Emit event that liquidity addresses changed.
emit LiquidityAddressesChanged();
}
}
/// @notice Execution of REMOVE_LIQUIDITY proposal.
/// @param proposal_ proposal.
function _executeRemoveLiquidity(Proposal storage proposal_) private {
// Approve uniswap router to transfer liquidity tokens.
address liquidityTokenAddress = liquidityToken(proposal_.proposalAddress);
require(IERC20(liquidityTokenAddress).approve(address(_router), proposal_.amount));
// Execute uniswap liquidity removal.
_router.removeLiquidityETH(
proposal_.proposalAddress,
proposal_.amount,
0,
0,
address(this),
block.timestamp.add(_timeout)
);
// If all tokens have been sold then remove liquidty address.
if (tokenBalance(liquidityTokenAddress) == 0 && _liquidityAddresses.contains(proposal_.proposalAddress)) {
_liquidityAddresses.remove(proposal_.proposalAddress);
// Emit event that liquidity addresses have changed.
emit LiquidityAddressesChanged();
}
}
/// @notice Execution of ADD_ADMIN proposal.
/// @param proposal_ propsal.
function _executeAddAdmin(Proposal storage proposal_) private {
// Check that address is not an admin already.
require(!_admins.contains(proposal_.proposalAddress));
// Check that holder has sufficient balance to be an admin.
uint256 balance = _governingToken.totalOf(proposal_.proposalAddress);
require(balance >= voteWeight());
// Add admin.
_admins.add(proposal_.proposalAddress);
// Emit event that new admin has been added.
emit AddAdmin(proposal_.proposalAddress);
}
/// @notice Execution of REMOVE_ADMIN proposal.
/// @param proposal_ proposal.
function _executeRemoveAdmin(Proposal storage proposal_) private {
// Check that address is an admin.
require(_admins.contains(proposal_.proposalAddress));
// Remove admin.
_admins.remove(proposal_.proposalAddress);
// Emit event that an admin has been removed.
emit RemoveAdmin(proposal_.proposalAddress);
}
/// @notice Execution of INVEST proposal.
/// @param proposal_ proposal.
function _executeInvest(Proposal storage proposal_) private {
// Check that DAO has sufficient balance for investment.
require(availableBalance() >= proposal_.amount);
// Transfer funds.
payable(proposal_.proposalAddress).call{value: proposal_.amount}("");
// If secondary address for invest token is specified then save it to holdings.
if(proposal_.investTokenAddress != address(0x0)) {
if (!_holdings.contains(proposal_.investTokenAddress)) {
_holdings.add(proposal_.investTokenAddress);
// Emit event that holdings addresses have changed.
emit HoldingsAddressesChanged();
}
}
}
/// @notice Execution of WITHDRAW proposal.
/// @param proposal_ proposal.
function _executeWithdraw(Proposal storage proposal_) private {
if (_isMain) {
// Main DAO only allows withdrawal once a week.
require(block.timestamp > _lastWithdraw.add(1 * 1 weeks));
_lastWithdraw = block.timestamp;
}
uint256 amount;
uint256 mainAmount;
uint256 currentBalance = availableBalance();
if (_isMain) {
mainAmount = 0;
amount = proposal_.amount;
// Check that withdrawal amount is not more than 10% of main DAO balance.
require(currentBalance / 10 >= amount);
} else {
uint256 totalSupply = _governingToken.totalSupply();
uint256 circulatingMaxCost = _circulatingMaxCost(_circulatingSupply(totalSupply), totalSupply);
// Check that cloned DAO balance is higher than circulating max cost.
require(currentBalance > circulatingMaxCost);
// Check that cloned DAO gains are enough to cover withdrawal.
require(currentBalance.sub(circulatingMaxCost) >= proposal_.amount);
// 0.25% of withdrawal will be transfered to Main DAO stakers.
mainAmount = proposal_.amount / 400;
amount = proposal_.amount.sub(mainAmount);
}
// Transfer all withdrawal funds to Torro Factory.
ITorroFactory(_factory).depositBenefits{value: proposal_.amount}(address(_governingToken));
// Divide withdrawal between governing token stakers.
_governingToken.addBenefits(amount);
// If cloned DAO withdrawal then divide 0.25% of withdrawal between main token stakers.
if (mainAmount > 0) {
_torroToken.addBenefits(mainAmount);
}
}
// Owner calls.
// Owner transactions.
/// @notice Sets factory address.
/// @param factory_ address of TorroFactory.
function setFactoryAddress(address factory_) public override onlyOwner {
_factory = factory_;
}
/// @notice Sets vote weight divider.
/// @param weight_ weight divider for a single vote.
function setVoteWeightDivider(uint256 weight_) public override onlyOwner {
_voteWeightDivider = weight_;
}
/// @notice Sets new address for router.
/// @param router_ address for router.
function setRouter(address router_) public override onlyOwner {
_router = IUniswapV2Router02(router_);
}
/// @notice Sets divider for BUY, INVEST, WITHDAW proposals.
/// @param divider_ divider for BUY, INVEST, WITHDRAW proposals.
function setSpendDivider(uint256 divider_) public override onlyOwner {
_spendDivider = divider_;
}
/// @notice Migrates balances of current DAO to a new DAO.
/// @param newDao_ address of the new DAO to migrate to.
function migrate(address newDao_) public override onlyOwner {
ITorroDao dao = ITorroDao(newDao_);
// Migrate holdings.
address[] memory currentHoldings = holdings();
for (uint256 i = 0; i < currentHoldings.length; i++) {
_migrateTransferBalance(currentHoldings[i], newDao_);
}
dao.addHoldingsAddresses(currentHoldings);
// Migrate liquidities.
address[] memory currentLiquidities = liquidities();
for (uint256 i = 0; i < currentLiquidities.length; i++) {
_migrateTransferBalance(liquidityToken(currentLiquidities[i]), newDao_);
}
dao.addLiquidityAddresses(currentLiquidities);
// Send over ETH balance.
payable(newDao_).call{value: availableBalance()}("");
}
// Private owner calls.
/// @notice Private function for migrating token balance to a new address.
/// @param token_ address of ERC-20 token to migrate.
/// @param target_ migration end point address.
function _migrateTransferBalance(address token_, address target_) private {
if (token_ != address(0x0)) {
IERC20 erc20 = IERC20(token_);
uint256 balance = erc20.balanceOf(address(this));
if (balance > 0) {
erc20.transfer(target_, balance);
}
}
}
} | /// @title DAO for proposals, voting and execution.
/// @notice Contract for creation, voting and execution of proposals.
/// @author ORayskiy - @robitnik_TorroDao | NatSpecSingleLine | _migrateTransferBalance | function _migrateTransferBalance(address token_, address target_) private {
if (token_ != address(0x0)) {
IERC20 erc20 = IERC20(token_);
uint256 balance = erc20.balanceOf(address(this));
if (balance > 0) {
erc20.transfer(target_, balance);
}
}
}
| /// @notice Private function for migrating token balance to a new address.
/// @param token_ address of ERC-20 token to migrate.
/// @param target_ migration end point address. | NatSpecSingleLine | v0.6.6+commit.6c089d02 | Unknown | ipfs://d1c6095fcf143d951c9754f00fe8cd59d29ab460461efe53b91eb289fd0fe5ac | {
"func_code_index": [
37847,
38145
]
} | 58,568 |
MegaMilionsGangstarApes | MegaMilionsGangstarApes.sol | 0x3af32fd45224c502469af10e8fff285c18a978bc | Solidity | IERC2981Royalties | interface IERC2981Royalties {
/// @notice Called with the sale price to determine how much royalty
// is owed and to whom.
/// @param _tokenId - the NFT asset queried for royalty information
/// @param _value - the sale price of the NFT asset specified by _tokenId
/// @return _receiver - address of who should be sent the royalty payment
/// @return _royaltyAmount - the royalty payment amount for value sale price
function royaltyInfo(uint256 _tokenId, uint256 _value)
external
view
returns (address _receiver, uint256 _royaltyAmount);
} | /// @title IERC2981Royalties
/// @dev Interface for the ERC2981 - Token Royalty standard | NatSpecSingleLine | royaltyInfo | function royaltyInfo(uint256 _tokenId, uint256 _value)
external
view
returns (address _receiver, uint256 _royaltyAmount);
| /// @param _tokenId - the NFT asset queried for royalty information
/// @param _value - the sale price of the NFT asset specified by _tokenId
/// @return _receiver - address of who should be sent the royalty payment
/// @return _royaltyAmount - the royalty payment amount for value sale price | NatSpecSingleLine | v0.8.7+commit.e28d00a7 | MIT | ipfs://414d9951eb094e9f3eecc45ff7dcf1c7de317858d1ad8616b1355e70b4b69e2c | {
"func_code_index": [
456,
609
]
} | 58,569 |
MegaMilionsGangstarApes | MegaMilionsGangstarApes.sol | 0x3af32fd45224c502469af10e8fff285c18a978bc | Solidity | SafeMath | library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
} | /**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler
* now has built in overflow checking.
*/ | NatSpecMultiLine | tryAdd | function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
| /**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/ | NatSpecMultiLine | v0.8.7+commit.e28d00a7 | MIT | ipfs://414d9951eb094e9f3eecc45ff7dcf1c7de317858d1ad8616b1355e70b4b69e2c | {
"func_code_index": [
161,
388
]
} | 58,570 |
MegaMilionsGangstarApes | MegaMilionsGangstarApes.sol | 0x3af32fd45224c502469af10e8fff285c18a978bc | Solidity | SafeMath | library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
} | /**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler
* now has built in overflow checking.
*/ | NatSpecMultiLine | trySub | function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
| /**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/ | NatSpecMultiLine | v0.8.7+commit.e28d00a7 | MIT | ipfs://414d9951eb094e9f3eecc45ff7dcf1c7de317858d1ad8616b1355e70b4b69e2c | {
"func_code_index": [
536,
735
]
} | 58,571 |
MegaMilionsGangstarApes | MegaMilionsGangstarApes.sol | 0x3af32fd45224c502469af10e8fff285c18a978bc | Solidity | SafeMath | library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
} | /**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler
* now has built in overflow checking.
*/ | NatSpecMultiLine | tryMul | function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
| /**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/ | NatSpecMultiLine | v0.8.7+commit.e28d00a7 | MIT | ipfs://414d9951eb094e9f3eecc45ff7dcf1c7de317858d1ad8616b1355e70b4b69e2c | {
"func_code_index": [
885,
1393
]
} | 58,572 |
MegaMilionsGangstarApes | MegaMilionsGangstarApes.sol | 0x3af32fd45224c502469af10e8fff285c18a978bc | Solidity | SafeMath | library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
} | /**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler
* now has built in overflow checking.
*/ | NatSpecMultiLine | tryDiv | function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
| /**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/ | NatSpecMultiLine | v0.8.7+commit.e28d00a7 | MIT | ipfs://414d9951eb094e9f3eecc45ff7dcf1c7de317858d1ad8616b1355e70b4b69e2c | {
"func_code_index": [
1544,
1744
]
} | 58,573 |
MegaMilionsGangstarApes | MegaMilionsGangstarApes.sol | 0x3af32fd45224c502469af10e8fff285c18a978bc | Solidity | SafeMath | library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
} | /**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler
* now has built in overflow checking.
*/ | NatSpecMultiLine | tryMod | function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
| /**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/ | NatSpecMultiLine | v0.8.7+commit.e28d00a7 | MIT | ipfs://414d9951eb094e9f3eecc45ff7dcf1c7de317858d1ad8616b1355e70b4b69e2c | {
"func_code_index": [
1905,
2105
]
} | 58,574 |
MegaMilionsGangstarApes | MegaMilionsGangstarApes.sol | 0x3af32fd45224c502469af10e8fff285c18a978bc | Solidity | SafeMath | library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
} | /**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler
* now has built in overflow checking.
*/ | NatSpecMultiLine | add | function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
| /**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/ | NatSpecMultiLine | v0.8.7+commit.e28d00a7 | MIT | ipfs://414d9951eb094e9f3eecc45ff7dcf1c7de317858d1ad8616b1355e70b4b69e2c | {
"func_code_index": [
2347,
2450
]
} | 58,575 |
MegaMilionsGangstarApes | MegaMilionsGangstarApes.sol | 0x3af32fd45224c502469af10e8fff285c18a978bc | Solidity | SafeMath | library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
} | /**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler
* now has built in overflow checking.
*/ | NatSpecMultiLine | sub | function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
| /**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/ | NatSpecMultiLine | v0.8.7+commit.e28d00a7 | MIT | ipfs://414d9951eb094e9f3eecc45ff7dcf1c7de317858d1ad8616b1355e70b4b69e2c | {
"func_code_index": [
2728,
2831
]
} | 58,576 |
MegaMilionsGangstarApes | MegaMilionsGangstarApes.sol | 0x3af32fd45224c502469af10e8fff285c18a978bc | Solidity | SafeMath | library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
} | /**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler
* now has built in overflow checking.
*/ | NatSpecMultiLine | mul | function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
| /**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/ | NatSpecMultiLine | v0.8.7+commit.e28d00a7 | MIT | ipfs://414d9951eb094e9f3eecc45ff7dcf1c7de317858d1ad8616b1355e70b4b69e2c | {
"func_code_index": [
3085,
3188
]
} | 58,577 |
MegaMilionsGangstarApes | MegaMilionsGangstarApes.sol | 0x3af32fd45224c502469af10e8fff285c18a978bc | Solidity | SafeMath | library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
} | /**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler
* now has built in overflow checking.
*/ | NatSpecMultiLine | div | function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
| /**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/ | NatSpecMultiLine | v0.8.7+commit.e28d00a7 | MIT | ipfs://414d9951eb094e9f3eecc45ff7dcf1c7de317858d1ad8616b1355e70b4b69e2c | {
"func_code_index": [
3484,
3587
]
} | 58,578 |
MegaMilionsGangstarApes | MegaMilionsGangstarApes.sol | 0x3af32fd45224c502469af10e8fff285c18a978bc | Solidity | SafeMath | library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
} | /**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler
* now has built in overflow checking.
*/ | NatSpecMultiLine | mod | function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
| /**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/ | NatSpecMultiLine | v0.8.7+commit.e28d00a7 | MIT | ipfs://414d9951eb094e9f3eecc45ff7dcf1c7de317858d1ad8616b1355e70b4b69e2c | {
"func_code_index": [
4049,
4152
]
} | 58,579 |
MegaMilionsGangstarApes | MegaMilionsGangstarApes.sol | 0x3af32fd45224c502469af10e8fff285c18a978bc | Solidity | SafeMath | library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
} | /**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler
* now has built in overflow checking.
*/ | NatSpecMultiLine | sub | function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
| /**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/ | NatSpecMultiLine | v0.8.7+commit.e28d00a7 | MIT | ipfs://414d9951eb094e9f3eecc45ff7dcf1c7de317858d1ad8616b1355e70b4b69e2c | {
"func_code_index": [
4626,
4871
]
} | 58,580 |
MegaMilionsGangstarApes | MegaMilionsGangstarApes.sol | 0x3af32fd45224c502469af10e8fff285c18a978bc | Solidity | SafeMath | library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
} | /**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler
* now has built in overflow checking.
*/ | NatSpecMultiLine | div | function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
| /**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/ | NatSpecMultiLine | v0.8.7+commit.e28d00a7 | MIT | ipfs://414d9951eb094e9f3eecc45ff7dcf1c7de317858d1ad8616b1355e70b4b69e2c | {
"func_code_index": [
5364,
5608
]
} | 58,581 |
MegaMilionsGangstarApes | MegaMilionsGangstarApes.sol | 0x3af32fd45224c502469af10e8fff285c18a978bc | Solidity | SafeMath | library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
} | /**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler
* now has built in overflow checking.
*/ | NatSpecMultiLine | mod | function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
| /**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/ | NatSpecMultiLine | v0.8.7+commit.e28d00a7 | MIT | ipfs://414d9951eb094e9f3eecc45ff7dcf1c7de317858d1ad8616b1355e70b4b69e2c | {
"func_code_index": [
6266,
6510
]
} | 58,582 |
MegaMilionsGangstarApes | MegaMilionsGangstarApes.sol | 0x3af32fd45224c502469af10e8fff285c18a978bc | Solidity | Math | library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds up instead
* of rounding down.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b - 1) / b can overflow on addition, so we distribute.
return a / b + (a % b == 0 ? 0 : 1);
}
} | /**
* @dev Standard math utilities missing in the Solidity language.
*/ | NatSpecMultiLine | max | function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
| /**
* @dev Returns the largest of two numbers.
*/ | NatSpecMultiLine | v0.8.7+commit.e28d00a7 | MIT | ipfs://414d9951eb094e9f3eecc45ff7dcf1c7de317858d1ad8616b1355e70b4b69e2c | {
"func_code_index": [
83,
195
]
} | 58,583 |
MegaMilionsGangstarApes | MegaMilionsGangstarApes.sol | 0x3af32fd45224c502469af10e8fff285c18a978bc | Solidity | Math | library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds up instead
* of rounding down.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b - 1) / b can overflow on addition, so we distribute.
return a / b + (a % b == 0 ? 0 : 1);
}
} | /**
* @dev Standard math utilities missing in the Solidity language.
*/ | NatSpecMultiLine | min | function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
| /**
* @dev Returns the smallest of two numbers.
*/ | NatSpecMultiLine | v0.8.7+commit.e28d00a7 | MIT | ipfs://414d9951eb094e9f3eecc45ff7dcf1c7de317858d1ad8616b1355e70b4b69e2c | {
"func_code_index": [
266,
377
]
} | 58,584 |
MegaMilionsGangstarApes | MegaMilionsGangstarApes.sol | 0x3af32fd45224c502469af10e8fff285c18a978bc | Solidity | Math | library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds up instead
* of rounding down.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b - 1) / b can overflow on addition, so we distribute.
return a / b + (a % b == 0 ? 0 : 1);
}
} | /**
* @dev Standard math utilities missing in the Solidity language.
*/ | NatSpecMultiLine | average | function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
| /**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/ | NatSpecMultiLine | v0.8.7+commit.e28d00a7 | MIT | ipfs://414d9951eb094e9f3eecc45ff7dcf1c7de317858d1ad8616b1355e70b4b69e2c | {
"func_code_index": [
491,
652
]
} | 58,585 |
MegaMilionsGangstarApes | MegaMilionsGangstarApes.sol | 0x3af32fd45224c502469af10e8fff285c18a978bc | Solidity | Math | library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds up instead
* of rounding down.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b - 1) / b can overflow on addition, so we distribute.
return a / b + (a % b == 0 ? 0 : 1);
}
} | /**
* @dev Standard math utilities missing in the Solidity language.
*/ | NatSpecMultiLine | ceilDiv | function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b - 1) / b can overflow on addition, so we distribute.
return a / b + (a % b == 0 ? 0 : 1);
}
| /**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds up instead
* of rounding down.
*/ | NatSpecMultiLine | v0.8.7+commit.e28d00a7 | MIT | ipfs://414d9951eb094e9f3eecc45ff7dcf1c7de317858d1ad8616b1355e70b4b69e2c | {
"func_code_index": [
854,
1056
]
} | 58,586 |
MegaMilionsGangstarApes | MegaMilionsGangstarApes.sol | 0x3af32fd45224c502469af10e8fff285c18a978bc | 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.7+commit.e28d00a7 | MIT | ipfs://414d9951eb094e9f3eecc45ff7dcf1c7de317858d1ad8616b1355e70b4b69e2c | {
"func_code_index": [
184,
912
]
} | 58,587 |
MegaMilionsGangstarApes | MegaMilionsGangstarApes.sol | 0x3af32fd45224c502469af10e8fff285c18a978bc | 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.7+commit.e28d00a7 | MIT | ipfs://414d9951eb094e9f3eecc45ff7dcf1c7de317858d1ad8616b1355e70b4b69e2c | {
"func_code_index": [
1017,
1362
]
} | 58,588 |
MegaMilionsGangstarApes | MegaMilionsGangstarApes.sol | 0x3af32fd45224c502469af10e8fff285c18a978bc | 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.7+commit.e28d00a7 | MIT | ipfs://414d9951eb094e9f3eecc45ff7dcf1c7de317858d1ad8616b1355e70b4b69e2c | {
"func_code_index": [
1485,
1941
]
} | 58,589 |
MegaMilionsGangstarApes | MegaMilionsGangstarApes.sol | 0x3af32fd45224c502469af10e8fff285c18a978bc | 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() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
} | /**
* @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.7+commit.e28d00a7 | MIT | ipfs://414d9951eb094e9f3eecc45ff7dcf1c7de317858d1ad8616b1355e70b4b69e2c | {
"func_code_index": [
399,
491
]
} | 58,590 |
MegaMilionsGangstarApes | MegaMilionsGangstarApes.sol | 0x3af32fd45224c502469af10e8fff285c18a978bc | 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() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
} | /**
* @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 {
_setOwner(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.7+commit.e28d00a7 | MIT | ipfs://414d9951eb094e9f3eecc45ff7dcf1c7de317858d1ad8616b1355e70b4b69e2c | {
"func_code_index": [
1050,
1149
]
} | 58,591 |
MegaMilionsGangstarApes | MegaMilionsGangstarApes.sol | 0x3af32fd45224c502469af10e8fff285c18a978bc | 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() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
} | /**
* @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");
_setOwner(newOwner);
}
| /**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/ | NatSpecMultiLine | v0.8.7+commit.e28d00a7 | MIT | ipfs://414d9951eb094e9f3eecc45ff7dcf1c7de317858d1ad8616b1355e70b4b69e2c | {
"func_code_index": [
1299,
1496
]
} | 58,592 |
MegaMilionsGangstarApes | MegaMilionsGangstarApes.sol | 0x3af32fd45224c502469af10e8fff285c18a978bc | 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) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
} | /**
* @dev Collection of functions related to the address type
*/ | NatSpecMultiLine | isContract | function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
| /**
* @dev 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.8.7+commit.e28d00a7 | MIT | ipfs://414d9951eb094e9f3eecc45ff7dcf1c7de317858d1ad8616b1355e70b4b69e2c | {
"func_code_index": [
606,
998
]
} | 58,593 |
MegaMilionsGangstarApes | MegaMilionsGangstarApes.sol | 0x3af32fd45224c502469af10e8fff285c18a978bc | 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) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
} | /**
* @dev Collection of functions related to the address type
*/ | NatSpecMultiLine | sendValue | function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
| /**
* @dev 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.8.7+commit.e28d00a7 | MIT | ipfs://414d9951eb094e9f3eecc45ff7dcf1c7de317858d1ad8616b1355e70b4b69e2c | {
"func_code_index": [
1928,
2250
]
} | 58,594 |
MegaMilionsGangstarApes | MegaMilionsGangstarApes.sol | 0x3af32fd45224c502469af10e8fff285c18a978bc | 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) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
} | /**
* @dev Collection of functions related to the address type
*/ | NatSpecMultiLine | 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.8.7+commit.e28d00a7 | MIT | ipfs://414d9951eb094e9f3eecc45ff7dcf1c7de317858d1ad8616b1355e70b4b69e2c | {
"func_code_index": [
3007,
3187
]
} | 58,595 |
MegaMilionsGangstarApes | MegaMilionsGangstarApes.sol | 0x3af32fd45224c502469af10e8fff285c18a978bc | 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) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
} | /**
* @dev Collection of functions related to the address type
*/ | NatSpecMultiLine | 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.8.7+commit.e28d00a7 | MIT | ipfs://414d9951eb094e9f3eecc45ff7dcf1c7de317858d1ad8616b1355e70b4b69e2c | {
"func_code_index": [
3412,
3646
]
} | 58,596 |
MegaMilionsGangstarApes | MegaMilionsGangstarApes.sol | 0x3af32fd45224c502469af10e8fff285c18a978bc | 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) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
} | /**
* @dev Collection of functions related to the address type
*/ | NatSpecMultiLine | 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.8.7+commit.e28d00a7 | MIT | ipfs://414d9951eb094e9f3eecc45ff7dcf1c7de317858d1ad8616b1355e70b4b69e2c | {
"func_code_index": [
4016,
4281
]
} | 58,597 |
MegaMilionsGangstarApes | MegaMilionsGangstarApes.sol | 0x3af32fd45224c502469af10e8fff285c18a978bc | 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) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
} | /**
* @dev Collection of functions related to the address type
*/ | NatSpecMultiLine | 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");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
| /**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/ | NatSpecMultiLine | v0.8.7+commit.e28d00a7 | MIT | ipfs://414d9951eb094e9f3eecc45ff7dcf1c7de317858d1ad8616b1355e70b4b69e2c | {
"func_code_index": [
4532,
5047
]
} | 58,598 |
MegaMilionsGangstarApes | MegaMilionsGangstarApes.sol | 0x3af32fd45224c502469af10e8fff285c18a978bc | 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) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
} | /**
* @dev Collection of functions related to the address type
*/ | NatSpecMultiLine | functionStaticCall | function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
| /**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/ | NatSpecMultiLine | v0.8.7+commit.e28d00a7 | MIT | ipfs://414d9951eb094e9f3eecc45ff7dcf1c7de317858d1ad8616b1355e70b4b69e2c | {
"func_code_index": [
5227,
5431
]
} | 58,599 |
MegaMilionsGangstarApes | MegaMilionsGangstarApes.sol | 0x3af32fd45224c502469af10e8fff285c18a978bc | 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) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
} | /**
* @dev Collection of functions related to the address type
*/ | NatSpecMultiLine | functionStaticCall | function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
| /**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/ | NatSpecMultiLine | v0.8.7+commit.e28d00a7 | MIT | ipfs://414d9951eb094e9f3eecc45ff7dcf1c7de317858d1ad8616b1355e70b4b69e2c | {
"func_code_index": [
5618,
6018
]
} | 58,600 |
MegaMilionsGangstarApes | MegaMilionsGangstarApes.sol | 0x3af32fd45224c502469af10e8fff285c18a978bc | 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) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
} | /**
* @dev Collection of functions related to the address type
*/ | NatSpecMultiLine | functionDelegateCall | function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
| /**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/ | NatSpecMultiLine | v0.8.7+commit.e28d00a7 | MIT | ipfs://414d9951eb094e9f3eecc45ff7dcf1c7de317858d1ad8616b1355e70b4b69e2c | {
"func_code_index": [
6200,
6405
]
} | 58,601 |
MegaMilionsGangstarApes | MegaMilionsGangstarApes.sol | 0x3af32fd45224c502469af10e8fff285c18a978bc | 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) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
} | /**
* @dev Collection of functions related to the address type
*/ | NatSpecMultiLine | functionDelegateCall | function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
| /**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/ | NatSpecMultiLine | v0.8.7+commit.e28d00a7 | MIT | ipfs://414d9951eb094e9f3eecc45ff7dcf1c7de317858d1ad8616b1355e70b4b69e2c | {
"func_code_index": [
6594,
6995
]
} | 58,602 |
MegaMilionsGangstarApes | MegaMilionsGangstarApes.sol | 0x3af32fd45224c502469af10e8fff285c18a978bc | 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) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
} | /**
* @dev Collection of functions related to the address type
*/ | NatSpecMultiLine | verifyCallResult | function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
| /**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/ | NatSpecMultiLine | v0.8.7+commit.e28d00a7 | MIT | ipfs://414d9951eb094e9f3eecc45ff7dcf1c7de317858d1ad8616b1355e70b4b69e2c | {
"func_code_index": [
7218,
7935
]
} | 58,603 |
MegaMilionsGangstarApes | MegaMilionsGangstarApes.sol | 0x3af32fd45224c502469af10e8fff285c18a978bc | Solidity | IERC721Receiver | interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
} | /**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/ | NatSpecMultiLine | onERC721Received | function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
| /**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/ | NatSpecMultiLine | v0.8.7+commit.e28d00a7 | MIT | ipfs://414d9951eb094e9f3eecc45ff7dcf1c7de317858d1ad8616b1355e70b4b69e2c | {
"func_code_index": [
528,
698
]
} | 58,604 |
MegaMilionsGangstarApes | MegaMilionsGangstarApes.sol | 0x3af32fd45224c502469af10e8fff285c18a978bc | Solidity | IERC165 | interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
} | /**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/ | NatSpecMultiLine | supportsInterface | function supportsInterface(bytes4 interfaceId) external view returns (bool);
| /**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/ | NatSpecMultiLine | v0.8.7+commit.e28d00a7 | MIT | ipfs://414d9951eb094e9f3eecc45ff7dcf1c7de317858d1ad8616b1355e70b4b69e2c | {
"func_code_index": [
374,
455
]
} | 58,605 |
MegaMilionsGangstarApes | MegaMilionsGangstarApes.sol | 0x3af32fd45224c502469af10e8fff285c18a978bc | Solidity | ERC165 | abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
} | /**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/ | NatSpecMultiLine | supportsInterface | function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
| /**
* @dev See {IERC165-supportsInterface}.
*/ | NatSpecMultiLine | v0.8.7+commit.e28d00a7 | MIT | ipfs://414d9951eb094e9f3eecc45ff7dcf1c7de317858d1ad8616b1355e70b4b69e2c | {
"func_code_index": [
103,
265
]
} | 58,606 |
MegaMilionsGangstarApes | MegaMilionsGangstarApes.sol | 0x3af32fd45224c502469af10e8fff285c18a978bc | Solidity | ERC2981Base | abstract contract ERC2981Base is ERC165, IERC2981Royalties {
struct RoyaltyInfo {
address recipient;
uint24 amount;
}
/// @inheritdoc ERC165
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override
returns (bool)
{
return
interfaceId == type(IERC2981Royalties).interfaceId ||
super.supportsInterface(interfaceId);
}
} | /// @dev This is a contract used to add ERC2981 support to ERC721 and 1155 | NatSpecSingleLine | supportsInterface | function supportsInterface(bytes4 interfaceId)
public
view
virtual
override
returns (bool)
{
return
interfaceId == type(IERC2981Royalties).interfaceId ||
super.supportsInterface(interfaceId);
}
| /// @inheritdoc ERC165 | NatSpecSingleLine | v0.8.7+commit.e28d00a7 | MIT | ipfs://414d9951eb094e9f3eecc45ff7dcf1c7de317858d1ad8616b1355e70b4b69e2c | {
"func_code_index": [
177,
465
]
} | 58,607 |
MegaMilionsGangstarApes | MegaMilionsGangstarApes.sol | 0x3af32fd45224c502469af10e8fff285c18a978bc | Solidity | ERC2981ContractWideRoyalties | abstract contract ERC2981ContractWideRoyalties is ERC2981Base {
RoyaltyInfo private _royalties;
/// @dev Sets token royalties
/// @param recipient recipient of the royalties
/// @param value percentage (using 2 decimals - 10000 = 100, 0 = 0)
function _setRoyalties(address recipient, uint256 value) internal {
require(value <= 10000, 'ERC2981Royalties: Too high');
_royalties = RoyaltyInfo(recipient, uint24(value));
}
/// @inheritdoc IERC2981Royalties
function royaltyInfo(uint256, uint256 value)
external
view
override
returns (address receiver, uint256 royaltyAmount)
{
RoyaltyInfo memory royalties = _royalties;
receiver = royalties.recipient;
royaltyAmount = (value * royalties.amount) / 10000;
}
} | /// @dev This is a contract used to add ERC2981 support to ERC721 and 1155
/// @dev This implementation has the same royalties for each and every tokens | NatSpecSingleLine | _setRoyalties | function _setRoyalties(address recipient, uint256 value) internal {
require(value <= 10000, 'ERC2981Royalties: Too high');
_royalties = RoyaltyInfo(recipient, uint24(value));
}
| /// @dev Sets token royalties
/// @param recipient recipient of the royalties
/// @param value percentage (using 2 decimals - 10000 = 100, 0 = 0) | NatSpecSingleLine | v0.8.7+commit.e28d00a7 | MIT | ipfs://414d9951eb094e9f3eecc45ff7dcf1c7de317858d1ad8616b1355e70b4b69e2c | {
"func_code_index": [
265,
469
]
} | 58,608 |
MegaMilionsGangstarApes | MegaMilionsGangstarApes.sol | 0x3af32fd45224c502469af10e8fff285c18a978bc | Solidity | ERC2981ContractWideRoyalties | abstract contract ERC2981ContractWideRoyalties is ERC2981Base {
RoyaltyInfo private _royalties;
/// @dev Sets token royalties
/// @param recipient recipient of the royalties
/// @param value percentage (using 2 decimals - 10000 = 100, 0 = 0)
function _setRoyalties(address recipient, uint256 value) internal {
require(value <= 10000, 'ERC2981Royalties: Too high');
_royalties = RoyaltyInfo(recipient, uint24(value));
}
/// @inheritdoc IERC2981Royalties
function royaltyInfo(uint256, uint256 value)
external
view
override
returns (address receiver, uint256 royaltyAmount)
{
RoyaltyInfo memory royalties = _royalties;
receiver = royalties.recipient;
royaltyAmount = (value * royalties.amount) / 10000;
}
} | /// @dev This is a contract used to add ERC2981 support to ERC721 and 1155
/// @dev This implementation has the same royalties for each and every tokens | NatSpecSingleLine | royaltyInfo | function royaltyInfo(uint256, uint256 value)
external
view
override
returns (address receiver, uint256 royaltyAmount)
{
RoyaltyInfo memory royalties = _royalties;
receiver = royalties.recipient;
royaltyAmount = (value * royalties.amount) / 10000;
}
| /// @inheritdoc IERC2981Royalties | NatSpecSingleLine | v0.8.7+commit.e28d00a7 | MIT | ipfs://414d9951eb094e9f3eecc45ff7dcf1c7de317858d1ad8616b1355e70b4b69e2c | {
"func_code_index": [
511,
837
]
} | 58,609 |
MegaMilionsGangstarApes | MegaMilionsGangstarApes.sol | 0x3af32fd45224c502469af10e8fff285c18a978bc | Solidity | IERC721 | interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
} | /**
* @dev Required interface of an ERC721 compliant contract.
*/ | NatSpecMultiLine | balanceOf | function balanceOf(address owner) external view returns (uint256 balance);
| /**
* @dev Returns the number of tokens in ``owner``'s account.
*/ | NatSpecMultiLine | v0.8.7+commit.e28d00a7 | MIT | ipfs://414d9951eb094e9f3eecc45ff7dcf1c7de317858d1ad8616b1355e70b4b69e2c | {
"func_code_index": [
719,
798
]
} | 58,610 |
MegaMilionsGangstarApes | MegaMilionsGangstarApes.sol | 0x3af32fd45224c502469af10e8fff285c18a978bc | Solidity | IERC721 | interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
} | /**
* @dev Required interface of an ERC721 compliant contract.
*/ | NatSpecMultiLine | ownerOf | function ownerOf(uint256 tokenId) external view returns (address owner);
| /**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/ | NatSpecMultiLine | v0.8.7+commit.e28d00a7 | MIT | ipfs://414d9951eb094e9f3eecc45ff7dcf1c7de317858d1ad8616b1355e70b4b69e2c | {
"func_code_index": [
944,
1021
]
} | 58,611 |
MegaMilionsGangstarApes | MegaMilionsGangstarApes.sol | 0x3af32fd45224c502469af10e8fff285c18a978bc | Solidity | IERC721 | interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
} | /**
* @dev Required interface of an ERC721 compliant contract.
*/ | NatSpecMultiLine | safeTransferFrom | function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
| /**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/ | NatSpecMultiLine | v0.8.7+commit.e28d00a7 | MIT | ipfs://414d9951eb094e9f3eecc45ff7dcf1c7de317858d1ad8616b1355e70b4b69e2c | {
"func_code_index": [
1733,
1850
]
} | 58,612 |
MegaMilionsGangstarApes | MegaMilionsGangstarApes.sol | 0x3af32fd45224c502469af10e8fff285c18a978bc | Solidity | IERC721 | interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
} | /**
* @dev Required interface of an ERC721 compliant contract.
*/ | NatSpecMultiLine | transferFrom | function transferFrom(
address from,
address to,
uint256 tokenId
) external;
| /**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/ | NatSpecMultiLine | v0.8.7+commit.e28d00a7 | MIT | ipfs://414d9951eb094e9f3eecc45ff7dcf1c7de317858d1ad8616b1355e70b4b69e2c | {
"func_code_index": [
2376,
2489
]
} | 58,613 |
MegaMilionsGangstarApes | MegaMilionsGangstarApes.sol | 0x3af32fd45224c502469af10e8fff285c18a978bc | Solidity | IERC721 | interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
} | /**
* @dev Required interface of an ERC721 compliant contract.
*/ | NatSpecMultiLine | approve | function approve(address to, uint256 tokenId) external;
| /**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/ | NatSpecMultiLine | v0.8.7+commit.e28d00a7 | MIT | ipfs://414d9951eb094e9f3eecc45ff7dcf1c7de317858d1ad8616b1355e70b4b69e2c | {
"func_code_index": [
2962,
3022
]
} | 58,614 |
MegaMilionsGangstarApes | MegaMilionsGangstarApes.sol | 0x3af32fd45224c502469af10e8fff285c18a978bc | Solidity | IERC721 | interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
} | /**
* @dev Required interface of an ERC721 compliant contract.
*/ | NatSpecMultiLine | getApproved | function getApproved(uint256 tokenId) external view returns (address operator);
| /**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/ | NatSpecMultiLine | v0.8.7+commit.e28d00a7 | MIT | ipfs://414d9951eb094e9f3eecc45ff7dcf1c7de317858d1ad8616b1355e70b4b69e2c | {
"func_code_index": [
3176,
3260
]
} | 58,615 |
MegaMilionsGangstarApes | MegaMilionsGangstarApes.sol | 0x3af32fd45224c502469af10e8fff285c18a978bc | Solidity | IERC721 | interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
} | /**
* @dev Required interface of an ERC721 compliant contract.
*/ | NatSpecMultiLine | setApprovalForAll | function setApprovalForAll(address operator, bool _approved) external;
| /**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/ | NatSpecMultiLine | v0.8.7+commit.e28d00a7 | MIT | ipfs://414d9951eb094e9f3eecc45ff7dcf1c7de317858d1ad8616b1355e70b4b69e2c | {
"func_code_index": [
3587,
3662
]
} | 58,616 |
MegaMilionsGangstarApes | MegaMilionsGangstarApes.sol | 0x3af32fd45224c502469af10e8fff285c18a978bc | Solidity | IERC721 | interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
} | /**
* @dev Required interface of an ERC721 compliant contract.
*/ | NatSpecMultiLine | isApprovedForAll | function isApprovedForAll(address owner, address operator) external view returns (bool);
| /**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/ | NatSpecMultiLine | v0.8.7+commit.e28d00a7 | MIT | ipfs://414d9951eb094e9f3eecc45ff7dcf1c7de317858d1ad8616b1355e70b4b69e2c | {
"func_code_index": [
3813,
3906
]
} | 58,617 |
MegaMilionsGangstarApes | MegaMilionsGangstarApes.sol | 0x3af32fd45224c502469af10e8fff285c18a978bc | Solidity | IERC721 | interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
} | /**
* @dev Required interface of an ERC721 compliant contract.
*/ | NatSpecMultiLine | safeTransferFrom | function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
| /**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/ | NatSpecMultiLine | v0.8.7+commit.e28d00a7 | MIT | ipfs://414d9951eb094e9f3eecc45ff7dcf1c7de317858d1ad8616b1355e70b4b69e2c | {
"func_code_index": [
4483,
4630
]
} | 58,618 |
MegaMilionsGangstarApes | MegaMilionsGangstarApes.sol | 0x3af32fd45224c502469af10e8fff285c18a978bc | Solidity | IERC721Enumerable | interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
} | /**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/ | NatSpecMultiLine | totalSupply | function totalSupply() external view returns (uint256);
| /**
* @dev Returns the total amount of tokens stored by the contract.
*/ | NatSpecMultiLine | v0.8.7+commit.e28d00a7 | MIT | ipfs://414d9951eb094e9f3eecc45ff7dcf1c7de317858d1ad8616b1355e70b4b69e2c | {
"func_code_index": [
132,
192
]
} | 58,619 |
MegaMilionsGangstarApes | MegaMilionsGangstarApes.sol | 0x3af32fd45224c502469af10e8fff285c18a978bc | Solidity | IERC721Enumerable | interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
} | /**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/ | NatSpecMultiLine | tokenOfOwnerByIndex | function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
| /**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/ | NatSpecMultiLine | v0.8.7+commit.e28d00a7 | MIT | ipfs://414d9951eb094e9f3eecc45ff7dcf1c7de317858d1ad8616b1355e70b4b69e2c | {
"func_code_index": [
375,
479
]
} | 58,620 |
MegaMilionsGangstarApes | MegaMilionsGangstarApes.sol | 0x3af32fd45224c502469af10e8fff285c18a978bc | Solidity | IERC721Enumerable | interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
} | /**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/ | NatSpecMultiLine | tokenByIndex | function tokenByIndex(uint256 index) external view returns (uint256);
| /**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/ | NatSpecMultiLine | v0.8.7+commit.e28d00a7 | MIT | ipfs://414d9951eb094e9f3eecc45ff7dcf1c7de317858d1ad8616b1355e70b4b69e2c | {
"func_code_index": [
655,
729
]
} | 58,621 |
MegaMilionsGangstarApes | MegaMilionsGangstarApes.sol | 0x3af32fd45224c502469af10e8fff285c18a978bc | Solidity | IERC721Metadata | interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
} | /**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/ | NatSpecMultiLine | name | function name() external view returns (string memory);
| /**
* @dev Returns the token collection name.
*/ | NatSpecMultiLine | v0.8.7+commit.e28d00a7 | MIT | ipfs://414d9951eb094e9f3eecc45ff7dcf1c7de317858d1ad8616b1355e70b4b69e2c | {
"func_code_index": [
106,
165
]
} | 58,622 |
MegaMilionsGangstarApes | MegaMilionsGangstarApes.sol | 0x3af32fd45224c502469af10e8fff285c18a978bc | Solidity | IERC721Metadata | interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
} | /**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/ | NatSpecMultiLine | symbol | function symbol() external view returns (string memory);
| /**
* @dev Returns the token collection symbol.
*/ | NatSpecMultiLine | v0.8.7+commit.e28d00a7 | MIT | ipfs://414d9951eb094e9f3eecc45ff7dcf1c7de317858d1ad8616b1355e70b4b69e2c | {
"func_code_index": [
236,
297
]
} | 58,623 |
MegaMilionsGangstarApes | MegaMilionsGangstarApes.sol | 0x3af32fd45224c502469af10e8fff285c18a978bc | Solidity | IERC721Metadata | interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
} | /**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/ | NatSpecMultiLine | tokenURI | function tokenURI(uint256 tokenId) external view returns (string memory);
| /**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/ | NatSpecMultiLine | v0.8.7+commit.e28d00a7 | MIT | ipfs://414d9951eb094e9f3eecc45ff7dcf1c7de317858d1ad8616b1355e70b4b69e2c | {
"func_code_index": [
398,
476
]
} | 58,624 |
MegaMilionsGangstarApes | MegaMilionsGangstarApes.sol | 0x3af32fd45224c502469af10e8fff285c18a978bc | 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);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
} | /**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/ | NatSpecMultiLine | 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://414d9951eb094e9f3eecc45ff7dcf1c7de317858d1ad8616b1355e70b4b69e2c | {
"func_code_index": [
971,
1281
]
} | 58,625 |
MegaMilionsGangstarApes | MegaMilionsGangstarApes.sol | 0x3af32fd45224c502469af10e8fff285c18a978bc | 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);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
} | /**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/ | NatSpecMultiLine | 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://414d9951eb094e9f3eecc45ff7dcf1c7de317858d1ad8616b1355e70b4b69e2c | {
"func_code_index": [
1340,
1553
]
} | 58,626 |
MegaMilionsGangstarApes | MegaMilionsGangstarApes.sol | 0x3af32fd45224c502469af10e8fff285c18a978bc | 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);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
} | /**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/ | NatSpecMultiLine | 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://414d9951eb094e9f3eecc45ff7dcf1c7de317858d1ad8616b1355e70b4b69e2c | {
"func_code_index": [
1610,
1854
]
} | 58,627 |
MegaMilionsGangstarApes | MegaMilionsGangstarApes.sol | 0x3af32fd45224c502469af10e8fff285c18a978bc | 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);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
} | /**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/ | NatSpecMultiLine | name | function name() public view virtual override returns (string memory) {
return _name;
}
| /**
* @dev See {IERC721Metadata-name}.
*/ | NatSpecMultiLine | v0.8.7+commit.e28d00a7 | MIT | ipfs://414d9951eb094e9f3eecc45ff7dcf1c7de317858d1ad8616b1355e70b4b69e2c | {
"func_code_index": [
1916,
2021
]
} | 58,628 |
MegaMilionsGangstarApes | MegaMilionsGangstarApes.sol | 0x3af32fd45224c502469af10e8fff285c18a978bc | 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);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
} | /**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/ | NatSpecMultiLine | symbol | function symbol() public view virtual override returns (string memory) {
return _symbol;
}
| /**
* @dev See {IERC721Metadata-symbol}.
*/ | NatSpecMultiLine | v0.8.7+commit.e28d00a7 | MIT | ipfs://414d9951eb094e9f3eecc45ff7dcf1c7de317858d1ad8616b1355e70b4b69e2c | {
"func_code_index": [
2085,
2194
]
} | 58,629 |
MegaMilionsGangstarApes | MegaMilionsGangstarApes.sol | 0x3af32fd45224c502469af10e8fff285c18a978bc | 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);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
} | /**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/ | NatSpecMultiLine | 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://414d9951eb094e9f3eecc45ff7dcf1c7de317858d1ad8616b1355e70b4b69e2c | {
"func_code_index": [
2260,
2599
]
} | 58,630 |
MegaMilionsGangstarApes | MegaMilionsGangstarApes.sol | 0x3af32fd45224c502469af10e8fff285c18a978bc | 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);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
} | /**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/ | NatSpecMultiLine | _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://414d9951eb094e9f3eecc45ff7dcf1c7de317858d1ad8616b1355e70b4b69e2c | {
"func_code_index": [
2842,
2941
]
} | 58,631 |
MegaMilionsGangstarApes | MegaMilionsGangstarApes.sol | 0x3af32fd45224c502469af10e8fff285c18a978bc | 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);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
} | /**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/ | NatSpecMultiLine | 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://414d9951eb094e9f3eecc45ff7dcf1c7de317858d1ad8616b1355e70b4b69e2c | {
"func_code_index": [
2998,
3414
]
} | 58,632 |
MegaMilionsGangstarApes | MegaMilionsGangstarApes.sol | 0x3af32fd45224c502469af10e8fff285c18a978bc | 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);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
} | /**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/ | NatSpecMultiLine | 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://414d9951eb094e9f3eecc45ff7dcf1c7de317858d1ad8616b1355e70b4b69e2c | {
"func_code_index": [
3475,
3701
]
} | 58,633 |
MegaMilionsGangstarApes | MegaMilionsGangstarApes.sol | 0x3af32fd45224c502469af10e8fff285c18a978bc | 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);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
} | /**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/ | NatSpecMultiLine | 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://414d9951eb094e9f3eecc45ff7dcf1c7de317858d1ad8616b1355e70b4b69e2c | {
"func_code_index": [
3768,
4068
]
} | 58,634 |
MegaMilionsGangstarApes | MegaMilionsGangstarApes.sol | 0x3af32fd45224c502469af10e8fff285c18a978bc | 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);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
} | /**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/ | NatSpecMultiLine | 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://414d9951eb094e9f3eecc45ff7dcf1c7de317858d1ad8616b1355e70b4b69e2c | {
"func_code_index": [
4134,
4303
]
} | 58,635 |
MegaMilionsGangstarApes | MegaMilionsGangstarApes.sol | 0x3af32fd45224c502469af10e8fff285c18a978bc | 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);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
} | /**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/ | NatSpecMultiLine | 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://414d9951eb094e9f3eecc45ff7dcf1c7de317858d1ad8616b1355e70b4b69e2c | {
"func_code_index": [
4365,
4709
]
} | 58,636 |
MegaMilionsGangstarApes | MegaMilionsGangstarApes.sol | 0x3af32fd45224c502469af10e8fff285c18a978bc | 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);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
} | /**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/ | NatSpecMultiLine | 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://414d9951eb094e9f3eecc45ff7dcf1c7de317858d1ad8616b1355e70b4b69e2c | {
"func_code_index": [
4775,
4965
]
} | 58,637 |
MegaMilionsGangstarApes | MegaMilionsGangstarApes.sol | 0x3af32fd45224c502469af10e8fff285c18a978bc | 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);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
} | /**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/ | NatSpecMultiLine | 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://414d9951eb094e9f3eecc45ff7dcf1c7de317858d1ad8616b1355e70b4b69e2c | {
"func_code_index": [
5031,
5364
]
} | 58,638 |
MegaMilionsGangstarApes | MegaMilionsGangstarApes.sol | 0x3af32fd45224c502469af10e8fff285c18a978bc | 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);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
} | /**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/ | NatSpecMultiLine | _safeTransfer | function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
| /**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/ | NatSpecMultiLine | v0.8.7+commit.e28d00a7 | MIT | ipfs://414d9951eb094e9f3eecc45ff7dcf1c7de317858d1ad8616b1355e70b4b69e2c | {
"func_code_index": [
6241,
6561
]
} | 58,639 |
MegaMilionsGangstarApes | MegaMilionsGangstarApes.sol | 0x3af32fd45224c502469af10e8fff285c18a978bc | 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);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
} | /**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/ | NatSpecMultiLine | _exists | function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
| /**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/ | NatSpecMultiLine | v0.8.7+commit.e28d00a7 | MIT | ipfs://414d9951eb094e9f3eecc45ff7dcf1c7de317858d1ad8616b1355e70b4b69e2c | {
"func_code_index": [
6869,
7001
]
} | 58,640 |
MegaMilionsGangstarApes | MegaMilionsGangstarApes.sol | 0x3af32fd45224c502469af10e8fff285c18a978bc | 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);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
} | /**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/ | NatSpecMultiLine | _isApprovedOrOwner | function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
| /**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/ | NatSpecMultiLine | v0.8.7+commit.e28d00a7 | MIT | ipfs://414d9951eb094e9f3eecc45ff7dcf1c7de317858d1ad8616b1355e70b4b69e2c | {
"func_code_index": [
7163,
7516
]
} | 58,641 |
MegaMilionsGangstarApes | MegaMilionsGangstarApes.sol | 0x3af32fd45224c502469af10e8fff285c18a978bc | 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);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
} | /**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/ | NatSpecMultiLine | _safeMint | function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
| /**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/ | NatSpecMultiLine | v0.8.7+commit.e28d00a7 | MIT | ipfs://414d9951eb094e9f3eecc45ff7dcf1c7de317858d1ad8616b1355e70b4b69e2c | {
"func_code_index": [
7853,
7968
]
} | 58,642 |
MegaMilionsGangstarApes | MegaMilionsGangstarApes.sol | 0x3af32fd45224c502469af10e8fff285c18a978bc | 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);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
} | /**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/ | NatSpecMultiLine | _safeMint | function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
| /**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/ | NatSpecMultiLine | v0.8.7+commit.e28d00a7 | MIT | ipfs://414d9951eb094e9f3eecc45ff7dcf1c7de317858d1ad8616b1355e70b4b69e2c | {
"func_code_index": [
8190,
8516
]
} | 58,643 |
MegaMilionsGangstarApes | MegaMilionsGangstarApes.sol | 0x3af32fd45224c502469af10e8fff285c18a978bc | 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);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
} | /**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/ | NatSpecMultiLine | _mint | function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
| /**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/ | NatSpecMultiLine | v0.8.7+commit.e28d00a7 | MIT | ipfs://414d9951eb094e9f3eecc45ff7dcf1c7de317858d1ad8616b1355e70b4b69e2c | {
"func_code_index": [
8847,
9234
]
} | 58,644 |
MegaMilionsGangstarApes | MegaMilionsGangstarApes.sol | 0x3af32fd45224c502469af10e8fff285c18a978bc | 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);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
} | /**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/ | NatSpecMultiLine | _burn | function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
| /**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/ | NatSpecMultiLine | v0.8.7+commit.e28d00a7 | MIT | ipfs://414d9951eb094e9f3eecc45ff7dcf1c7de317858d1ad8616b1355e70b4b69e2c | {
"func_code_index": [
9458,
9823
]
} | 58,645 |
MegaMilionsGangstarApes | MegaMilionsGangstarApes.sol | 0x3af32fd45224c502469af10e8fff285c18a978bc | 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);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
} | /**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/ | NatSpecMultiLine | _transfer | 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 Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/ | NatSpecMultiLine | v0.8.7+commit.e28d00a7 | MIT | ipfs://414d9951eb094e9f3eecc45ff7dcf1c7de317858d1ad8616b1355e70b4b69e2c | {
"func_code_index": [
10155,
10738
]
} | 58,646 |
MegaMilionsGangstarApes | MegaMilionsGangstarApes.sol | 0x3af32fd45224c502469af10e8fff285c18a978bc | 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);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
} | /**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/ | NatSpecMultiLine | _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://414d9951eb094e9f3eecc45ff7dcf1c7de317858d1ad8616b1355e70b4b69e2c | {
"func_code_index": [
10851,
11030
]
} | 58,647 |
MegaMilionsGangstarApes | MegaMilionsGangstarApes.sol | 0x3af32fd45224c502469af10e8fff285c18a978bc | 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);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
} | /**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/ | NatSpecMultiLine | _checkOnERC721Received | function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
| /**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/ | NatSpecMultiLine | v0.8.7+commit.e28d00a7 | MIT | ipfs://414d9951eb094e9f3eecc45ff7dcf1c7de317858d1ad8616b1355e70b4b69e2c | {
"func_code_index": [
11590,
12394
]
} | 58,648 |
MegaMilionsGangstarApes | MegaMilionsGangstarApes.sol | 0x3af32fd45224c502469af10e8fff285c18a978bc | 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);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
} | /**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/ | NatSpecMultiLine | _beforeTokenTransfer | function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
| /**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/ | NatSpecMultiLine | v0.8.7+commit.e28d00a7 | MIT | ipfs://414d9951eb094e9f3eecc45ff7dcf1c7de317858d1ad8616b1355e70b4b69e2c | {
"func_code_index": [
12961,
13092
]
} | 58,649 |
MegaMilionsGangstarApes | MegaMilionsGangstarApes.sol | 0x3af32fd45224c502469af10e8fff285c18a978bc | Solidity | ERC721URIStorage | abstract contract ERC721URIStorage is ERC721 {
using Strings for uint256;
// Optional mapping for token URIs
mapping(uint256 => string) private _tokenURIs;
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721URIStorage: URI query for nonexistent token");
string memory _tokenURI = _tokenURIs[tokenId];
string memory base = _baseURI();
// If there is no base URI, return the token URI.
if (bytes(base).length == 0) {
return _tokenURI;
}
// If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked).
if (bytes(_tokenURI).length > 0) {
return string(abi.encodePacked(base, _tokenURI));
}
return super.tokenURI(tokenId);
}
/**
* @dev Sets `_tokenURI` as the tokenURI of `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {
require(_exists(tokenId), "ERC721URIStorage: URI set of nonexistent token");
_tokenURIs[tokenId] = _tokenURI;
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual override {
super._burn(tokenId);
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
}
} | /**
* @dev ERC721 token with storage based token URI management.
*/ | NatSpecMultiLine | tokenURI | function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721URIStorage: URI query for nonexistent token");
string memory _tokenURI = _tokenURIs[tokenId];
string memory base = _baseURI();
// If there is no base URI, return the token URI.
if (bytes(base).length == 0) {
return _tokenURI;
}
// If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked).
if (bytes(_tokenURI).length > 0) {
return string(abi.encodePacked(base, _tokenURI));
}
return super.tokenURI(tokenId);
}
| /**
* @dev See {IERC721Metadata-tokenURI}.
*/ | NatSpecMultiLine | v0.8.7+commit.e28d00a7 | MIT | ipfs://414d9951eb094e9f3eecc45ff7dcf1c7de317858d1ad8616b1355e70b4b69e2c | {
"func_code_index": [
239,
923
]
} | 58,650 |
MegaMilionsGangstarApes | MegaMilionsGangstarApes.sol | 0x3af32fd45224c502469af10e8fff285c18a978bc | Solidity | ERC721URIStorage | abstract contract ERC721URIStorage is ERC721 {
using Strings for uint256;
// Optional mapping for token URIs
mapping(uint256 => string) private _tokenURIs;
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721URIStorage: URI query for nonexistent token");
string memory _tokenURI = _tokenURIs[tokenId];
string memory base = _baseURI();
// If there is no base URI, return the token URI.
if (bytes(base).length == 0) {
return _tokenURI;
}
// If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked).
if (bytes(_tokenURI).length > 0) {
return string(abi.encodePacked(base, _tokenURI));
}
return super.tokenURI(tokenId);
}
/**
* @dev Sets `_tokenURI` as the tokenURI of `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {
require(_exists(tokenId), "ERC721URIStorage: URI set of nonexistent token");
_tokenURIs[tokenId] = _tokenURI;
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual override {
super._burn(tokenId);
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
}
} | /**
* @dev ERC721 token with storage based token URI management.
*/ | NatSpecMultiLine | _setTokenURI | function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {
require(_exists(tokenId), "ERC721URIStorage: URI set of nonexistent token");
_tokenURIs[tokenId] = _tokenURI;
}
| /**
* @dev Sets `_tokenURI` as the tokenURI of `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/ | NatSpecMultiLine | v0.8.7+commit.e28d00a7 | MIT | ipfs://414d9951eb094e9f3eecc45ff7dcf1c7de317858d1ad8616b1355e70b4b69e2c | {
"func_code_index": [
1074,
1296
]
} | 58,651 |
MegaMilionsGangstarApes | MegaMilionsGangstarApes.sol | 0x3af32fd45224c502469af10e8fff285c18a978bc | Solidity | ERC721URIStorage | abstract contract ERC721URIStorage is ERC721 {
using Strings for uint256;
// Optional mapping for token URIs
mapping(uint256 => string) private _tokenURIs;
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721URIStorage: URI query for nonexistent token");
string memory _tokenURI = _tokenURIs[tokenId];
string memory base = _baseURI();
// If there is no base URI, return the token URI.
if (bytes(base).length == 0) {
return _tokenURI;
}
// If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked).
if (bytes(_tokenURI).length > 0) {
return string(abi.encodePacked(base, _tokenURI));
}
return super.tokenURI(tokenId);
}
/**
* @dev Sets `_tokenURI` as the tokenURI of `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {
require(_exists(tokenId), "ERC721URIStorage: URI set of nonexistent token");
_tokenURIs[tokenId] = _tokenURI;
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual override {
super._burn(tokenId);
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
}
} | /**
* @dev ERC721 token with storage based token URI management.
*/ | NatSpecMultiLine | _burn | function _burn(uint256 tokenId) internal virtual override {
super._burn(tokenId);
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
}
| /**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/ | NatSpecMultiLine | v0.8.7+commit.e28d00a7 | MIT | ipfs://414d9951eb094e9f3eecc45ff7dcf1c7de317858d1ad8616b1355e70b4b69e2c | {
"func_code_index": [
1520,
1731
]
} | 58,652 |
MegaMilionsGangstarApes | MegaMilionsGangstarApes.sol | 0x3af32fd45224c502469af10e8fff285c18a978bc | Solidity | ERC721Enumerable | abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
} | /**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/ | NatSpecMultiLine | supportsInterface | function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
| /**
* @dev See {IERC165-supportsInterface}.
*/ | NatSpecMultiLine | v0.8.7+commit.e28d00a7 | MIT | ipfs://414d9951eb094e9f3eecc45ff7dcf1c7de317858d1ad8616b1355e70b4b69e2c | {
"func_code_index": [
605,
834
]
} | 58,653 |
MegaMilionsGangstarApes | MegaMilionsGangstarApes.sol | 0x3af32fd45224c502469af10e8fff285c18a978bc | Solidity | ERC721Enumerable | abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
} | /**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/ | NatSpecMultiLine | tokenOfOwnerByIndex | function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
| /**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/ | NatSpecMultiLine | v0.8.7+commit.e28d00a7 | MIT | ipfs://414d9951eb094e9f3eecc45ff7dcf1c7de317858d1ad8616b1355e70b4b69e2c | {
"func_code_index": [
913,
1174
]
} | 58,654 |
MegaMilionsGangstarApes | MegaMilionsGangstarApes.sol | 0x3af32fd45224c502469af10e8fff285c18a978bc | Solidity | ERC721Enumerable | abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
} | /**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/ | NatSpecMultiLine | totalSupply | function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
| /**
* @dev See {IERC721Enumerable-totalSupply}.
*/ | NatSpecMultiLine | v0.8.7+commit.e28d00a7 | MIT | ipfs://414d9951eb094e9f3eecc45ff7dcf1c7de317858d1ad8616b1355e70b4b69e2c | {
"func_code_index": [
1245,
1363
]
} | 58,655 |
MegaMilionsGangstarApes | MegaMilionsGangstarApes.sol | 0x3af32fd45224c502469af10e8fff285c18a978bc | Solidity | ERC721Enumerable | abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
} | /**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/ | NatSpecMultiLine | tokenByIndex | function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
| /**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/ | NatSpecMultiLine | v0.8.7+commit.e28d00a7 | MIT | ipfs://414d9951eb094e9f3eecc45ff7dcf1c7de317858d1ad8616b1355e70b4b69e2c | {
"func_code_index": [
1435,
1673
]
} | 58,656 |
MegaMilionsGangstarApes | MegaMilionsGangstarApes.sol | 0x3af32fd45224c502469af10e8fff285c18a978bc | Solidity | ERC721Enumerable | abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
} | /**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/ | NatSpecMultiLine | _beforeTokenTransfer | function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
| /**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/ | NatSpecMultiLine | v0.8.7+commit.e28d00a7 | MIT | ipfs://414d9951eb094e9f3eecc45ff7dcf1c7de317858d1ad8616b1355e70b4b69e2c | {
"func_code_index": [
2281,
2875
]
} | 58,657 |
MegaMilionsGangstarApes | MegaMilionsGangstarApes.sol | 0x3af32fd45224c502469af10e8fff285c18a978bc | Solidity | ERC721Enumerable | abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
} | /**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/ | NatSpecMultiLine | _addTokenToOwnerEnumeration | function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
| /**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/ | NatSpecMultiLine | v0.8.7+commit.e28d00a7 | MIT | ipfs://414d9951eb094e9f3eecc45ff7dcf1c7de317858d1ad8616b1355e70b4b69e2c | {
"func_code_index": [
3171,
3397
]
} | 58,658 |
MegaMilionsGangstarApes | MegaMilionsGangstarApes.sol | 0x3af32fd45224c502469af10e8fff285c18a978bc | Solidity | ERC721Enumerable | abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
} | /**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/ | NatSpecMultiLine | _addTokenToAllTokensEnumeration | function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
| /**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/ | NatSpecMultiLine | v0.8.7+commit.e28d00a7 | MIT | ipfs://414d9951eb094e9f3eecc45ff7dcf1c7de317858d1ad8616b1355e70b4b69e2c | {
"func_code_index": [
3593,
3762
]
} | 58,659 |
MegaMilionsGangstarApes | MegaMilionsGangstarApes.sol | 0x3af32fd45224c502469af10e8fff285c18a978bc | Solidity | ERC721Enumerable | abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
} | /**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/ | NatSpecMultiLine | _removeTokenFromOwnerEnumeration | function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
| /**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/ | NatSpecMultiLine | v0.8.7+commit.e28d00a7 | MIT | ipfs://414d9951eb094e9f3eecc45ff7dcf1c7de317858d1ad8616b1355e70b4b69e2c | {
"func_code_index": [
4384,
5377
]
} | 58,660 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.