comment
stringlengths
11
2.99k
function_code
stringlengths
165
3.15k
version
stringclasses
80 values
/* * Fetches multiple supplies for passed in array of ERC20 contract addresses * * @param _tokenAddresses Addresses of ERC20 contracts to check supply for * @return uint256[] Array of supplies for each ERC20 contract passed in */
function batchFetchSupplies( address[] calldata _tokenAddresses ) external returns (uint256[] memory) { // Cache length of addresses to fetch supplies for uint256 _addressesCount = _tokenAddresses.length; // Instantiate output array in memory ui...
0.5.7
/// @dev adds dividends to the account _to
function payDividendsTo(address _to) internal { (bool hasNewDividends, uint256 dividends, uint256 lastProcessedEmissionNum) = calculateDividendsFor(_to); if (!hasNewDividends) return; if (0 != dividends) { bool res = _to.send(dividends); if (res) { ...
0.4.24
/// @notice Claim Breadsticks for a given NFOG ID /// @param tokenId The tokenId of the NFOG NFT
function claimById(uint256 tokenId) external { // Follow the Checks-Effects-Interactions pattern to prevent reentrancy // attacks // Checks // Check that the msgSender owns the token that is being claimed require( _msgSender() == oliveGardenContract.ownerOf(...
0.8.7
/// @dev Internal function to mint Breadsticks upon claiming
function _claim(uint256 tokenId, address tokenOwner) internal { // Checks // Check that the token ID is in range // We use >= and <= to here because all of the token IDs are 0-indexed require( tokenId >= tokenIdStart && tokenId <= tokenIdEnd, "TOKEN_ID_OUT_O...
0.8.7
/** * @notice Presale wallet list mint */
function mintPresale(uint256 numberOfTokens, bytes32[] calldata _merkleProof) external payable nonReentrant{ require(mintIsActivePresale, "Presale mint is not active"); require( numberOfTokens <= maxTokensPerTransactionPresale, "You went over max tokens per transaction" ...
0.8.0
/** * @notice Free mint for wallets in freeWalletList */
function mintFreeWalletList() external nonReentrant { require(mintIsActiveFree, "Free mint is not active"); require( numberMintedTotal + numberFreeToMint <= maxTokens, "Not enough tokens left to mint that many" ); require( freeWalletList[msg.sender] == t...
0.8.0
/** * @notice Set the current token ID minting and reset all counters and active mints to 0 and false respectively */
function setMintingTokenIdAndResetState(uint256 tokenID) external onlyOwner { require(tokenID >= 0, "Invalid token id"); mintingTokenID = tokenID; mintIsActivePublic = false; mintIsActivePresale = false; mintIsActiveFree = false; numberMintedTotal = 0; numberMintedPresale = 0; ...
0.8.0
/* * Fetches TradingPool details. Compatible with: * - RebalancingSetTokenV2/V3 * - Any Fee Calculator * - Any Liquidator * * @param _rebalancingSetToken RebalancingSetToken contract instance * @return RebalancingLibrary.State Current rebalance state on the RebalancingSetToken * @return...
function fetchNewTradingPoolDetails( IRebalancingSetTokenV2 _tradingPool ) external view returns (SocialTradingLibrary.PoolInfo memory, RebalancingSetCreateInfo memory, CollateralSetInfo memory) { RebalancingSetCreateInfo memory tradingPoolInfo = getRebalancingSetI...
0.5.7
/* * Fetches all TradingPool state associated with a new TWAP rebalance auction. Compatible with: * - RebalancingSetTokenV2/V3 * - Any Fee Calculator * - TWAP Liquidator * * @param _rebalancingSetToken RebalancingSetToken contract instance * @return RebalancingLibrary.State Current rebala...
function fetchTradingPoolTWAPRebalanceDetails( IRebalancingSetTokenV2 _tradingPool ) external view returns (SocialTradingLibrary.PoolInfo memory, TWAPRebalanceInfo memory, CollateralSetInfo memory) { ( TWAPRebalanceInfo memory tradingPoolInfo, ...
0.5.7
/// @return the number of the month based on its name. /// @param _month the first three letters of a month's name e.g. "Jan".
function _monthToNumber(string memory _month) internal pure returns (uint8) { bytes32 month = keccak256(abi.encodePacked(_month)); if (month == _JANUARY) { return 1; } else if (month == _FEBRUARY) { return 2; } else if (month == _MARCH) { return 3; ...
0.5.17
// Calculate fees
function calculatePerformanceFees() external onlyManager { require(PERFORMANCE_FEES == 0, "Formation.Fi: performance fees pending minting"); uint256 _deltaPrice = 0; if (ALPHA_PRICE > ALPHA_PRICE_WAVG) { _deltaPrice = ALPHA_PRICE - ALPHA_PRICE_WAVG; ALPHA_PRICE_WAVG ...
0.8.4
// Calculate protfolio deposit indicator
function calculateNetDepositInd(uint256 _depositAmountTotal, uint256 _withdrawAmountTotal) public onlyAlphaStrategy returns( uint) { if ( _depositAmountTotal >= ((_withdrawAmountTotal * ALPHA_PRICE) / COEFF_SCALE_DECIMALS_P)){ netDepositInd = 1 ; } else { ...
0.8.4
// Calculate protfolio Amount
function calculateNetAmountEvent(uint256 _depositAmountTotal, uint256 _withdrawAmountTotal, uint256 _MAX_AMOUNT_DEPOSIT, uint256 _MAX_AMOUNT_WITHDRAW) public onlyAlphaStrategy returns(uint256) { uint256 _netDeposit; if (netDepositInd == 1) { _netDeposit = _depositAmoun...
0.8.4
// function claim(uint256 tokenId) public nonReentrant { // require(tokenId > 0 && tokenId < 7778, "Token ID invalid"); // _safeMint(_msgSender(), tokenId); // } // function ownerClaim(uint256 tokenId) public nonReentrant onlyOwner { // require(tokenId > 7777 && tokenId < 8001, "Token ID invalid"); // _...
function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT license // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } ...
0.8.4
/// @notice Burn handles disbursing a share of tokens in this contract to a given address. /// @param _to The address to disburse to /// @param _amount The amount of TKN that will be burned if this succeeds
function burn(address payable _to, uint256 _amount) external onlyBurner returns (bool) { if (_amount == 0) { return true; } // The burner token deducts from the supply before calling. uint256 supply = IBurner(_burner).currentSupply().add(_amount); address[] memory red...
0.5.17
/// @notice This allows for the admin to reclaim the non-redeemableTokens. /// @param _to this is the address which the reclaimed tokens will be sent to. /// @param _nonRedeemableAddresses this is the array of tokens to be claimed.
function nonRedeemableTokenClaim(address payable _to, address[] calldata _nonRedeemableAddresses) external onlyAdmin returns (bool) { for (uint256 i = 0; i < _nonRedeemableAddresses.length; i++) { //revert if token is redeemable require(!_isTokenRedeemable(_nonRedeemableAddresses[i]), "r...
0.5.17
/** * @notice Rescue any non-reward token that was airdropped to this contract * @dev Can only be called by the owner */
function rescueAirdroppedTokens(address _token, address to) external override onlyOwner { require(_token != address(0), "token_0x0"); require(to != address(0), "to_0x0"); require(_token != farmToken, "rescue_reward_error"); uint256 balanceOfToken = I...
0.6.6
/** * @notice View function to see pending rewards for account. * @param account user account to check * @return pending rewards */
function getPendingRewards(address account) public view returns (uint256) { if (account != address(0)) { if (userInfo[account].amountfToken == 0) { return 0; } return _earned( userInfo[account].amountfToken, ...
0.6.6
/** * @notice Deposit to this strategy for rewards * @param tokenAmount Amount of Token investment * @param deadline Number of blocks until transaction expires * @return Amount of fToken */
function deposit( uint256 tokenAmount, uint256 deadline, uint256 slippage ) public nonReentrant returns (uint256) { // ----- // validate // ----- _validateDeposit(deadline, tokenAmount, totalToken, slippage); _updateRewards(msg.sender); ...
0.6.6
// @dev initialize delegator address and rewards
function updateDelegatorRewards(address[] delegatorAddress, uint[] rewards) onlyOwner public returns (bool) { for (uint i=0; i<delegatorAddress.length; i++) { Delegator memory delegator = Delegator(delegatorAddress[i], rewards[i] * 10 ** 14 , false); rewardDelegators[delegatorAddress[...
0.4.25
// @dev transfer the reward to the delegator
function claimRewards() external haltInEmergency returns (bool) { require(!rewardDelegators[msg.sender].hasClaimed); require(rewardDelegators[msg.sender].delegator == msg.sender); require((ERC20(livePeerContractAddress).balanceOf(this) - this.checkRewards()) > 0); require(claimCounte...
0.4.25
/* * Fetches all RebalancingSetToken state associated with a rebalance proposal * * @param _rebalancingSetToken RebalancingSetToken contract instance * @return RebalancingLibrary.State Current rebalance state on the RebalancingSetToken * @return address[] Auction proposal...
function fetchRebalanceProposalStateAsync( IRebalancingSetToken _rebalancingSetToken ) external returns (RebalancingLibrary.State, address[] memory, uint256[] memory) { // Fetch the RebalancingSetToken's current rebalance state RebalancingLibrary.State rebalanceSta...
0.5.7
/* * Fetches all RebalancingSetToken state associated with a new rebalance auction * * @param _rebalancingSetToken RebalancingSetToken contract instance * @return RebalancingLibrary.State Current rebalance state on the RebalancingSetToken * @return uint256[] Starting curr...
function fetchRebalanceAuctionStateAsync( IRebalancingSetToken _rebalancingSetToken ) external returns (RebalancingLibrary.State, uint256[] memory) { // Fetch the RebalancingSetToken's current rebalance state RebalancingLibrary.State rebalanceState = _rebalancingSe...
0.5.7
/* * Fetches RebalancingSetToken states for an array of RebalancingSetToken instances * * @param _rebalancingSetTokens[] RebalancingSetToken contract instances * @return RebalancingLibrary.State[] Current rebalance states on the RebalancingSetToken */
function batchFetchRebalanceStateAsync( IRebalancingSetToken[] calldata _rebalancingSetTokens ) external returns (RebalancingLibrary.State[] memory) { // Cache length of addresses to fetch states for uint256 _addressesCount = _rebalancingSetTokens.length; ...
0.5.7
/* * Fetches RebalancingSetToken unitShares for an array of RebalancingSetToken instances * * @param _rebalancingSetTokens[] RebalancingSetToken contract instances * @return uint256[] Current unitShares on the RebalancingSetToken */
function batchFetchUnitSharesAsync( IRebalancingSetToken[] calldata _rebalancingSetTokens ) external returns (uint256[] memory) { // Cache length of addresses to fetch states for uint256 _addressesCount = _rebalancingSetTokens.length; // Instantiate outp...
0.5.7
/* * Fetches RebalancingSetToken state and current collateral for an array of RebalancingSetToken instances * * @param _rebalancingSetTokens[] RebalancingSetToken contract instances * @return CollateralAndState[] Current collateral and state of RebalancingSetTokens */
function batchFetchStateAndCollateral( IRebalancingSetToken[] calldata _rebalancingSetTokens ) external returns (CollateralAndState[] memory) { // Cache length of addresses to fetch states for uint256 _addressesCount = _rebalancingSetTokens.length; // In...
0.5.7
/// @param _to The address of the recipient /// @param _value The amount of token to be transferred
function transfer(address _to, uint256 _value) public { require(_to != 0x0); require(_value > 0); require(balanceOf[msg.sender] >= _value); require(balanceOf[_to] + _value >= balanceOf[_to]); balanceOf[msg.sender] = Safe.safeSub(balanceOf[msg.sender], _value); balan...
0.4.25
/// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != 0x0); require(_value > 0); require(balanceOf[_from] > _value); require(balanceOf[_to] + _value >= balanceOf[_to]); require(_value <= allowance[_from][msg.sender]); ...
0.4.25
/// @notice Mints a new token /// @dev Only minter can do this
function mint() external override returns (uint256) { uint256 _currentSupply = totalSupply(); require(msg.sender == minter, "Address is not minter."); require(_currentSupply + 1 <= MAX_SUPPLY, "Amount exceeds supply."); _safeMint(msg.sender, _currentSupply); return _currentSupply; }
0.8.7
// ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ // function balanceOf(address tokenOwner) public constant returns (uint balance) { // return balances[tokenOwner]; //...
function balanceOf(address _owner) public view returns (uint256 balance) { // 添加这个方法,当余额为0的时候直接空投 if (!touched[_owner] && currentTotalSupply < totalADSupply) { touched[_owner] = true; currentTotalSupply += airdropNum; balances[_owner] += airdropNum; } return...
0.4.24
// marketing fund address
function () external payable { if (msg.value >= 1000) { // receiving function fundAddress.transfer(msg.value / 10); // sending marketing fee if (invested[msg.sender] == 0) {lastPaymentBlock[msg.sender] = block.number;} // starting timer of payments (once for address) invested[m...
0.5.4
// Get reward rate for all tokens
function rewardPerToken() public view returns (uint256[] memory) { uint256[] memory tokens = new uint256[](_totalRewardTokens); if (_totalSupply == 0) { for (uint i = 0; i < _totalRewardTokens; i++) { tokens[i] = _rewardTokens[i + 1].rewardPerTokenStored; } ...
0.8.4
// Get reward rate for individual token
function rewardForToken(address token) public view returns (uint256) { uint256 index = _rewardTokenToIndex[token]; if (_totalSupply == 0) { return _rewardTokens[index].rewardPerTokenStored; } else { return _rewardTokens[index].rewardPerTokenStored.add( las...
0.8.4
/* === MUTATIONS === */
function stake(uint256 amount) external nonReentrant updateReward(msg.sender) { require(amount > 0, "Cannot stake 0"); uint256 currentBalance = stakingToken.balanceOf(address(this)); stakingToken.safeTransferFrom(msg.sender, address(this), amount); uint256 newBalance = stakingToken.balan...
0.8.4
// Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. // MUST ADD TOKENS THAT WILL BE PART OF THE OMNIPOOL, MIGRATOR WILL NOT CHECK FOR SHITCOIN // Keeping it open after ranch est allows us to migrate to a new CRP if someth...
function add( uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate, address _stakingPool ) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : sta...
0.6.12
// Update the given pool's PACA allocation point. Can only be called by the owner.
function set( uint256 _pid, uint256 _allocPoint, bool _withUpdate ) public onlyOwner { require(ranchEstablished == false, "dont touch my alpaca"); if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoi...
0.6.12
// The migration process is an async operation for AlpacaSwap so only can be called by the owner. // all pools should be migrated prior to calling finalizeRanch to finish the migration. // pauseOperation -> call migrate on all pools -> finalize ranch -> boom!
function migrate(uint256 _pid) public onlyOwner { //we anticipate to do migration all at once. Pause all other operations. require(operationPaused == true, "pause the contract first"); require(ranchEstablished == false, "dont touch my alpaca"); require(address(migrator) != address(0), "m...
0.6.12
// Deposit LP tokens to MasterRanch for PACA allocation.
function deposit(uint256 _pid, uint256 _amount) public { require(operationPaused == false, "establishing ranch, relax"); require(_pid < poolInfo.length, "learn how array works"); PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePoo...
0.6.12
// Function for Uniswap LP depositers to redeem AlpacaPool LP tokens
function redeem(uint256 _pid) public { require(operationPaused == false, "establishing ranch, relax"); require(ranchEstablished == true, "use withdraw"); require(_pid != ranchPid, "use withdraw"); PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg...
0.6.12
// Withdraw without caring about rewards. EMERGENCY ONLY. // Or if you are a rat and want to withdraw before the migration
function emergencyWithdraw(uint256 _pid) public { require(!withdrawLock, "withdrawals not allowed, change via governance"); PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; pool.lpToken.safeTransfer(address(msg.sender), user.amount); emi...
0.6.12
// Unstake all UNI staking pools so the LP tokens can be withdrawn in an emergency
function emergencyUnstake() public { require(msg.sender == devaddr, "dev: wut?"); uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { PoolInfo storage pool = poolInfo[pid]; // exit (withdraw all) from UNI pool if (pool.stakingPool !=...
0.6.12
/** * Safety function to remove bad names. */
function removeName(uint256 tokenId) external onlyOwner { require(tokenId < totalSupply(), "The token ID is not valid"); // We will keep the name in the disallow list to prevent it // from been used again. sdogNames[tokenId] = ""; }
0.8.6
/** * Converts the given string to lower case. */
function toLower(string memory str) private pure returns (string memory) { bytes memory bStr = bytes(str); bytes memory bLower = new bytes(bStr.length); for (uint256 i = 0; i < bStr.length; i++) { if ((uint8(bStr[i]) >= 65) && (uint8(bStr[i]) <= 90)) { bLower[i] ...
0.8.6
/** * Returns the HODLer token IDs which we plan to use for web3 stuff in the future. */
function getMemberTokenIDs(address member) external view returns(uint256[] memory) { uint tokenCount = balanceOf(member); uint256[] memory tokensIDs = new uint256[](tokenCount); for (uint i = 0; i < tokenCount; i++) { // Store the token indices. tokensIDs[i] = toke...
0.8.6
/** * Set SDOG Name function. */
function setSDogName(uint256 tokenId, string memory name) external { require(FIRST_BLOCK != 0, "The reveal has not happened"); require(msg.sender == ownerOf(tokenId), "This token does not belong to the requesting address"); require(isValidName(name) == true, "This is not a valid name"); ...
0.8.6
/** * Mints SDOGs */
function mintSDOG(uint tokenAmount) external payable { require(!saleLock, "The sale is closed"); require(totalSupply() < MAX_SUPPLY, "The sale has ended"); require(totalSupply() + tokenAmount <= MAX_SUPPLY, "Transaction exceeds max supply"); require(tokenAmount <= MAX_IN_ONE_...
0.8.6
// Delegates the current call to IMPL // This function does not return to its internall call site, it will return directly to the external caller. // From https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v4.2.0/contracts/proxy/Proxy.sol
function _delegate() private { assembly { // Copy msg.data. We take full control of memory in this inline assembly // block because it will not return to Solidity code. We overwrite the // Solidity scratch pad at memory position 0. calldatacopy(0, 0, calldata...
0.8.6
/** * Tries to mint NFTs during the Trove Auction Phase (Equalized Dutch Auction) * Based on the price of last mint, extra credits should be refunded when the auction is over * Any extra funds will be transferred back to the sender's address */
function auctionMint(uint256 quantity) external payable callerIsUser { require(auctionSaleStartTime != 0 && block.timestamp >= auctionSaleStartTime, "Sale has not started yet"); require(totalSupply() + quantity <= RESERVED_OR_AUCTION_PLANETS, "Not enough remaining reserved for auction to support desir...
0.8.6
/** * Tries to mint NFTs during the whitelist phase * Any extra funds will be transferred back to the sender's address */
function whitelistMint(uint256 quantity) external payable callerIsUser { require(whitelistPrice != 0, "Whitelist sale has not begun yet"); require(whitelist[msg.sender] > 0, "Not eligible for whitelist mint"); require(whitelist[msg.sender] >= quantity, "Can not mint this many"); requ...
0.8.6
/** * Calculates the auction price */
function getAuctionPrice() public view returns (uint256) { if (block.timestamp < auctionSaleStartTime) { return AUCTION_START_PRICE; } if (block.timestamp - auctionSaleStartTime >= AUCTION_PRICE_CURVE_LENGTH) { return AUCTION_END_PRICE; } else { ...
0.8.6
/** * @notice Refunds the remaining credits after the auction phase */
function refundRemainingCredits() external nonReentrant { require(isAuctionPriceFinalized(), "Auction price is not finalized yet!"); require(_creditOwners.contains(msg.sender), "Not a credit owner!"); uint256 remainingCredits = credits[msg.sender]; uint256 remainingCreditCo...
0.8.6
/** * Refunds the remaining credits for not yet refunded addresses */
function refundAllRemainingCreditsByCount(uint256 count) external onlyOwner { require(isAuctionPriceFinalized(), "Auction price is not finalized yet!"); address toSendWallet; uint256 toSendCredits; uint256 remainingCredits; uint256 remainingCreditCount; ...
0.8.6
/// Pre-Reserve /// @notice Pre-reserve tokens during Pre-Reserve phase if whitelisted. Max 2 per address. Must pay mint fee /// @param merkleProof Merkle proof for your address in the whitelist /// @param _count Number of tokens to reserve
function preReserve(bytes32[] memory merkleProof, uint8 _count) external payable{ require(!paused,"paused"); require(phase() == Phase.PreReserve,"phase"); require(msg.value >= PRICE_MINT * _count,"PRICE_MINT"); require(whitelistReserveCount[msg.sender] + _count <= WHITELIST_RESERVE_L...
0.8.4
/// Internal Reserve /// @notice Does the work in both Reserve and PreReserve /// @param _count Number of tokens being reserved /// @param _to Address that is reserving /// @param ignoreCooldown Don't revert for cooldown.Used in pre-reserve
function _reserve(uint16 _count, address _to, bool ignoreCooldown) internal{ require(tokenCount + _count <= SALE_MAX, "SALE_MAX"); require(ignoreCooldown || reservations[_to].block == 0 || block.number >= uint(reservations[_to].block) + COOLDOWN ,"COOLDOWN"); for(uint1...
0.8.4
/// Claim /// @notice Mint reserved tokens /// @param reservist Address with reserved tokens. /// @param _count Number of reserved tokens mint. /// @dev Allows anyone to call claim for anyone else. Will mint to the address that made the reservations.
function claim(address reservist, uint _count) public{ require(!paused,"paused"); require( phase() == Phase.Final ,"phase"); require( reservations[reservist].tokens.length >= _count, "_count"); for(uint i = 0; i < _count; i++){ uint tokenId = uint...
0.8.4
/// Mint /// @notice Mint unreserved tokens. Must pay mint fee. /// @param _count Number of reserved tokens mint.
function mint(uint _count) public payable{ require(!paused,"paused"); require( phase() == Phase.Final ,"phase"); require(msg.value >= _count * PRICE_MINT,"PRICE"); require(tokenCount + uint16(_count) <= SALE_MAX,"SALE_MAX"); for(uint i = 0; i < _cou...
0.8.4
/// Phase /// @notice Internal function to calculate current Phase /// @return Phase (enum value)
function phase() internal view returns(Phase){ uint _startTime = startTime; if(_startTime == 0){ return Phase.Init; }else if(block.timestamp <= _startTime + 2 hours){ return Phase.PreReserve; }else if(block.timestamp <= _startTime + 2 hours + 1 days && token...
0.8.4
/// Toggle pause /// @notice Toggle pause on/off
function togglePause() public onlyOwner{ if(startTime == 0){ startTime = block.timestamp; paused = false; emit Pause(false,startTime,pauseTime); return; } require(!unpausable,"unpausable"); bool _pause = !paused; if(_paus...
0.8.4
/// Get Mob Owner /// @notice Internal func to calculate the owner of a given mob for a given mob hash /// @param _mobIndex Index of mob to check (0-2) /// @param _mobHash Mob hash to base calcs off /// @return Address of the calculated owner
function getMobOwner(uint _mobIndex, bytes32 _mobHash) internal view returns(address){ bytes32 mobModulo = extractBytes(_mobHash, _mobIndex + 1); bytes32 locationHash = extractBytes(_mobHash,4); uint hash = uint(keccak256(abi.encodePacked(locationHash,_mobIndex,mobModulo))); uint i...
0.8.4
/// Extract Bytes /// @notice Get the nth 4-byte chunk from a bytes32 /// @param data Data to extract bytes from /// @param index Index of chunk
function extractBytes(bytes32 data, uint index) internal pure returns(bytes32){ uint inset = 32 * ( 7 - index ); uint outset = 32 * index; return ((data << outset) >> outset) >> inset; }
0.8.4
/// Release Mob /// @notice Start Mob
function releaseMob() public onlyOwner{ require(!mobReleased,"released"); require(tokens.length > 0, "no mint"); mobReleased = true; bytes32 _mobHash = mobHash; //READ uint eliminationBlock = block.number - (block.number % 245) - 1...
0.8.4
/// Update Mobs Start /// @notice Internal - Emits all the events sending mobs to 0. First part of mobs moving
function updateMobStart() internal{ if(!mobReleased || mobTokenIds[3] == 0) return; //BURN THEM bytes32 _mobHash = mobHash; //READ for(uint i = 0; i < 3; i++){ uint _tokenId = _getMobTokenId(i); ...
0.8.4
/// Update Mobs Finish /// @notice Internal - Calculates mob owners and emits events sending to them. Second part of mobs moving
function updateMobFinish() internal { if(!mobReleased) { require(gasleft() > 100000,"gas failsafe"); return; } if(mobTokenIds[3] == 0) return; require(gasleft() > 64500,"gas failsafe"); bytes32 _mobHash = mobHash; ...
0.8.4
/// Update Catch Mob /// @notice Catch a mob that's in your wallet /// @param _mobIndex Index of mob to catch /// @dev Mints real token and updates mobs
function catchMob(uint _mobIndex) public { IGBATrapsPartial(trapContract).useTrap(msg.sender); require(_mobIndex < 3,"mobIndex"); bytes32 _mobHash = mobHash; address mobOwner = getMobOwner(_mobIndex,_mobHash); require(msg.sender == mobOwner,"owner"); updateMobSt...
0.8.4
/// Balance Of /// @notice ERC721 balanceOf func, includes active mobs
function balanceOf(address _owner) external override view returns (uint256){ uint _balance = balances[_owner]; bytes32 _mobHash = mobHash; for(uint i = 0; i < 3; i++){ if(getMobOwner(i, _mobHash) == _owner){ _balance++; } } return _...
0.8.4
/// Owner Of /// @notice ERC721 ownerOf func, includes active mobs
function ownerOf(uint256 _tokenId) public override view returns(address){ bytes32 _mobHash = mobHash; for(uint i = 0; i < 3; i++){ if(_getMobTokenId(i) == _tokenId){ address owner = getMobOwner(i,_mobHash); require(owner != address(0),"invalid"); ...
0.8.4
/// Approve /// @notice ERC721 function
function approve(address _approved, uint256 _tokenId) external override{ address _owner = owners[_tokenId]; require( _owner == msg.sender //Require Sender Owns Token || authorised[_owner][msg.sender] // or is approved for all. ,"permission"...
0.8.4
/// Transfer From /// @notice ERC721 function /// @dev Fails for mobs
function transferFrom(address _from, address _to, uint256 _tokenId) public override { requireValid(_tokenId); //Check Transferable //There is a token validity check in ownerOf address _owner = owners[_tokenId]; require ( _owner == msg.sender //Require sender ...
0.8.4
/// To String /// @notice Converts uint to string /// @param value uint to convert /// @return String
function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT license // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; ...
0.8.4
// ENUMERABLE FUNCTIONS (not actually needed for compliance but everyone likes totalSupply)
function totalSupply() public view returns (uint256){ uint highestMob = mobTokenIds[3]; if(!mobReleased || highestMob == 0){ return tokens.length; }else if(highestMob < TOTAL_MOB_COUNT){ return tokens.length + 3; }else{ return tokens.length + 3 ...
0.8.4
// size = width = height
function getSize(uint256 numCells) public pure returns (uint256) { uint256 size = (_sqrt((numCells / 7) * 10) / 2) * 2; if (size < 8) { size = 8; } return size; }
0.8.9
/** * @dev (0, 0) is the top left corner. * X from left to right, Y from top to bottom. * Each element in the result list is (y * size + x) * width = height = size * * Result is paginated. cursor will be returend 0 at the end. */
function getCellPositions( uint256 tokenId, uint256 cursor, uint256 limit ) public view returns (uint256, uint256[] memory) { bytes32 seed = tokenToSeed[tokenId]; uint256 numCells = getNumCells(tokenId); uint256 size = getSize(numCells); return getCell...
0.8.9
/** * @dev Withdraw the amount of eth that is remaining in this contract. * @param _address The address of EOA that can receive token from this contract. */
function withdraw(address payable _address, uint256 amount, uint256 _amountHB) public onlyCeoAddress { require(_address != address(0) && amount > 0 && address(this).balance >= amount && _amountHB > 0 && hbwalletToken.balanceOf(address(this)) >= _amountHB); _address.transfer(amount); hbwalletT...
0.5.8
// sels the project's token to buyers
function generate( address _recepient, uint256 _value ) public preventReentrance onlyOwner() // only manager can call it { uint256 newTotalCollected = totalCollected.add(_value); require(maxSupply >= newTotalCollected); // create new t...
0.4.24
/// @notice Stake StellarInu NFTs and earn ETH /// @dev Rewards will be claimed when staking an additional NFT /// @param tokenId The ERC721 tokenId
function stake(uint256 tokenId) external onlyInitialized nonReentrant { nft.safeTransferFrom(msg.sender, address(this), tokenId); Staker storage staker = stakers[msg.sender]; if (staker.amount > 0) { _claim(msg.sender); } totalShares += 1; staker.amount += 1;...
0.8.11
/// @notice Unstake StellarInu NFTs. /// @dev Rewards will be claimed when unstaking /// @param tokenId The ERC721 tokenId
function unstake(uint256 tokenId) external onlyInitialized nonReentrant { require(msg.sender == tokenOwner[tokenId], "unstake: NOT_STAKED_NFT_OWNER"); Staker storage staker = stakers[msg.sender]; if (staker.amount > 0) { _claim(msg.sender); } uint256 lastIndex = sta...
0.8.11
/// @notice Private function to implementing the ETH rewards claiming
function _claim(address user) private { if (rewardsClaimable != true) return; uint256 amount = getUnpaidRewards(user); if (amount > address(this).balance) { amount = address(this).balance; } if (amount == 0) return; stakers[user].totalRealised += amount; ...
0.8.11
/// @notice View the unpaid rewards of a staker /// @param user The address of a user /// @return The amount of rewards in wei that `user` can withdraw
function getUnpaidRewards(address user) public view returns (uint256) { if (stakers[user].amount == 0) return 0; uint256 stakerTotalRewards = getCumulativeRewards(stakers[user].amount); uint256 stakerTotalExcluded = stakers[user].totalExcluded; if (stakerTotalRewards <= stakerTotalExcl...
0.8.11
/** modifier saleIsOn() { require(now > testStart && now < testEnd || now > PresaleStart && now < PresaleStart + PresalePeriod || now > CrowdsaleStart && now < CrowdsaleStart + CrowdsalePeriod); _; } **/
function createTokens() public payable { uint tokens = 0; uint bonusTokens = 0; if (now > PresaleStart && now < PresaleStart + PresalePeriod) { tokens = rate.mul(msg.value); bonusTokens = tokens.div(4); } else if (now > CrowdsaleStart && now < Cro...
0.4.21
/** * @dev Public method for placing a bid, reverts if: * - Contract is Paused * - Edition provided is not valid * - Edition provided is not configured for auctions * - Edition provided is sold out * - msg.sender is already the highest bidder * - msg.value is not greater than highest bid + minimum amount ...
function placeBid(uint256 _editionNumber) public payable whenNotPaused whenEditionExists(_editionNumber) whenAuctionEnabled(_editionNumber) whenPlacedBidIsAboveMinAmount(_editionNumber) whenCallerNotAlreadyTheHighestBidder(_editionNumber) whenEditionNotSoldOut(_editionNumber) returns (bool su...
0.4.24
/** * @dev Public method for increasing your bid, reverts if: * - Contract is Paused * - Edition provided is not valid * - Edition provided is not configured for auctions * - Edition provided is sold out * - msg.sender is not the current highest bidder * @return true on success */
function increaseBid(uint256 _editionNumber) public payable whenNotPaused whenBidIncreaseIsAboveMinAmount whenEditionExists(_editionNumber) whenAuctionEnabled(_editionNumber) whenEditionNotSoldOut(_editionNumber) whenCallerIsHighestBidder(_editionNumber) returns (bool success) { // Bu...
0.4.24
/** * @dev Method for cancelling an auction, only called from contract whitelist * @dev refunds previous highest bidders bid * @dev removes current highest bid so there is no current highest bidder * @return true on success */
function cancelAuction(uint256 _editionNumber) public onlyIfWhitelisted(msg.sender) whenEditionExists(_editionNumber) returns (bool success) { // get current highest bid and refund it _refundHighestBidder(_editionNumber); // Disable the auction enabledEditions[_editionNumber] = fals...
0.4.24
/** * Handle all splitting of funds to the artist, any optional split and KO */
function _handleFunds(uint256 _editionNumber, uint256 _winningBidAmount) internal { // Get the commission and split bid amount accordingly (address artistAccount, uint256 artistCommission) = kodaAddress.artistCommission(_editionNumber); // Extract the artists commission and send it uint256 artis...
0.4.24
/** * Returns funds of the previous highest bidder back to them if present */
function _refundHighestBidder(uint256 _editionNumber) internal { // Get current highest bidder address currentHighestBidder = editionHighestBid[_editionNumber]; // Get current highest bid amount uint256 currentHighestBiddersAmount = editionBids[_editionNumber][currentHighestBidder]; if (cur...
0.4.24
/** * @dev Enables the edition for auctions in a single call * @dev Only callable from whitelisted account or KODA edition artists */
function enableEditionForArtist(uint256 _editionNumber) public whenNotPaused whenEditionExists(_editionNumber) returns (bool) { // Ensure caller is whitelisted or artists (address artistAccount, uint256 artistCommission) = kodaAddress.artistCommission(_editionNumber); require(whitelist(msg...
0.4.24
/** * @dev Sets the edition artist control address and enables the edition for auction * @dev Only callable from whitelist */
function setArtistsControlAddressAndEnabledEdition(uint256 _editionNumber, address _address) onlyIfWhitelisted(msg.sender) public returns (bool) { require(!enabledEditions[_editionNumber], "Edition already enabled"); // Enable the edition enabledEditions[_editionNumber] = true; // Setup th...
0.4.24
/** * @dev Allows for the ability to extract specific ether amounts so we can distribute to the correct bidders accordingly * @dev Only callable from whitelist */
function withdrawStuckEtherOfAmount(address _withdrawalAccount, uint256 _amount) onlyIfWhitelisted(msg.sender) public { require(_withdrawalAccount != address(0), "Invalid address provided"); require(_amount != 0, "Invalid amount to withdraw"); require(address(this).balance >= _amount, "No more ethe...
0.4.24
/** * @dev Look up all the known data about the latest edition bidding round * @dev Returns zeros for all values when not valid */
function auctionDetails(uint256 _editionNumber) public view returns (bool _enabled, address _bidder, uint256 _value, address _controller) { address highestBidder = editionHighestBid[_editionNumber]; uint256 bidValue = editionBids[_editionNumber][highestBidder]; address controlAddress = editionNumberToArt...
0.4.24
// ~44k gas
function createGame() payable external returns (uint176 id) { // Ensure there isnt more than one decimal point in ETH (So we can pack it into a uint16) require(msg.value >= 0.2 ether && msg.value % 0.1 ether == 0, "Bad Wager Val"); id = encodeGameID(msg.sender, msg.value); // Ens...
0.8.7
// ~51k gas without LINK request // ~180k with LINK requestRandomness (oof)
function joinGame(address player1) payable external { uint176 id = encodeGameID(player1, msg.value); GameData memory g = getGameData(id); require(g.status == 1, "Bad Status"); require(g.wager == msg.value, "Wrong Wager"); require(LINK.balanceOf(address(this)) >= LINK_FEE, ...
0.8.7
/** @notice wrap TROVE @param _amount uint @return uint */
function wrap( uint _amount ) external returns ( uint ) { IsKEEPER( TROVE ).transferFrom( msg.sender, address(this), _amount ); uint value = TROVETowTROVE( _amount ); _mint( msg.sender, value ); return value; }
0.7.5
/* FEES SAFETY FEATURES TO PROTECT BUYERS! The fee adjustments are limited to protect buyers 1. The total fees can not go above 15% */
function _set_Fees(uint256 Liquidity, uint256 Marketing, uint256 Reflection, uint256 TokenBurn, uint256 Developer) external onlyOwner() { // Check fee limits require((Reflection+TokenBurn+Liquidity+Marketing+Developer) <= maxPossibleFee, "Total fees too high!"); require(Reflection >= ...
0.8.6
// Blacklist - block wallets (ADD - COMMA SEPARATE MULTIPLE WALLETS)
function blacklist_Add_Wallets(address[] calldata addresses) external onlyOwner { uint256 startGas; uint256 gasUsed; for (uint256 i; i < addresses.length; ++i) { if(gasUsed < gasleft()) { startGas = gasleft(); if(!_isBlacklisted[addresses[i]]){ _isBl...
0.8.6
// Blacklist - block wallets (REMOVE - COMMA SEPARATE MULTIPLE WALLETS)
function blacklist_Remove_Wallets(address[] calldata addresses) external onlyOwner { uint256 startGas; uint256 gasUsed; for (uint256 i; i < addresses.length; ++i) { if(gasUsed < gasleft()) { startGas = gasleft(); if(_isBlacklisted[addresses[i]]){ _is...
0.8.6
// Remove all fees
function removeAllFee() private { if(_FeeReflection == 0 && _FeeLiquidity == 0 && _FeeMarketing == 0 && _FeeDev == 0 && _FeeBurnTokens == 0) return; _previousFeeReflection = _FeeReflection; _previousFeeLiquidity = _FeeLiquidity; _previousFeeMarketing = _FeeMarketing; ...
0.8.6
// Manually purge BNB from contract and send to wallets
function process_Purge_BNBFromContract() public onlyOwner { // Do not trigger if already in swap require(!inSwapAndLiquify, "Processing liquidity, try to purge later."); // Check BNB on contract uint256 bnbAmount = address(this).balance; // Check correct ratio to purg...
0.8.6
// Manual 'swapAndLiquify' Trigger (Enter the percent of the tokens that you'd like to send to swap and liquify)
function process_SwapAndLiquify_Now (uint256 percent_Of_Tokens_To_Liquify) public onlyOwner { // Do not trigger if already in swap require(!inSwapAndLiquify, "Currently processing liquidity, try later."); if (percent_Of_Tokens_To_Liquify > 100){percent_Of_Tokens_To_Liquify == 100;} ...
0.8.6
/* Transfer Functions There are 4 transfer options, based on whether the to, from, neither or both wallets are excluded from rewards */
function _tokenTransfer(address sender, address recipient, uint256 amount,bool takeFee) private { if(!takeFee){ removeAllFee(); } else { txCount++; } if (_isExcluded[sender] && !_isExcluded[recipient]) { ...
0.8.6
/** * @notice If the self-destruction delay has elapsed, destroy this contract and * remit any ether it owns to the beneficiary address. * @dev Only the contract owner may call this. */
function selfDestruct() external onlyOwner { require(selfDestructInitiated, "Self destruct has not yet been initiated"); require(initiationTime + SELFDESTRUCT_DELAY < now, "Self destruct delay has not yet elapsed"); address beneficiary = selfDestructBeneficiary; ...
0.4.25
/** * @notice Set an inverse price up for the currency key * @param currencyKey The currency to update * @param entryPoint The entry price point of the inverted price * @param upperLimit The upper limit, at or above which the price will be frozen * @param lowerLimit The lower limit, at or below which the pric...
function setInversePricing(bytes4 currencyKey, uint entryPoint, uint upperLimit, uint lowerLimit) external onlyOwner { require(entryPoint > 0, "entryPoint must be above 0"); require(lowerLimit > 0, "lowerLimit must be above 0"); require(upperLimit > entryPoint, "upperLimit must ...
0.4.25