comment
stringlengths
11
2.99k
function_code
stringlengths
165
3.15k
version
stringclasses
80 values
/// @notice Distribute dividends to the GandhijiMain contract. Can be called /// repeatedly until practically all dividends have been distributed. /// @param rounds How many rounds of dividend distribution do we want?
function distribute(uint256 rounds) public { for (uint256 i = 0; i < rounds; i++) { if (address(this).balance < 0.001 ether) { // Balance is very low. Not worth the gas to distribute. break; } GandhijiMainContract.buy.value(...
0.4.24
//Below function will convert string to integer removing decimal
function stringToUint(string s) returns (uint) { bytes memory b = bytes(s); uint i; uint result1 = 0; for (i = 0; i < b.length; i++) { uint c = uint(b[i]); if(c == 46) { // Do nothing --this will skip the decimal } ...
0.4.14
/** * @dev Notifies Fragments contract about a new rebase cycle. * @return The total number of fragments after the supply adjustment. */
function rebase() external returns (uint256) { uint256 baseTotalSupply = BASETOKEN.totalSupply(); uint256 multiplier; uint256 maxDebase =9000; require(baseTotalSupply != lastTrackedBaseSupply, 'NOT YET PLEASE WAIT'); if (baseTotalSupply > las...
0.4.24
/** * @notice set the delegatee. * @dev delegatee address should not be zero address. * @param delegator the addrress of token holder. * @param delegatee number of tokens to burn. */
function _delegate(address delegator, address delegatee) internal { require(delegatee != address(0), "UFARM::_delegate: invalid delegatee address"); address currentDelegate = delegates[delegator]; uint256 delegatorBalance = balances[delegator]; delegates[delegator] = delegatee; emit DelegateC...
0.7.6
/** * @notice transfer tokens to src --> dst. * @dev src address should be valid ethereum address. * @dev dst address should be valid ethereum address. * @dev amount should be greater than zero. * @param src the source address. * @param dst the destination address. * @param amount number of token to trans...
function _transferTokens( address src, address dst, uint256 amount ) internal { require(src != address(0), "UFARM::_transferTokens: cannot transfer from the zero address"); require(dst != address(0), "UFARM::_transferTokens: cannot transfer to the zero address"); require(amount > 0, "UF...
0.7.6
/** * @notice transfer the vote token. * @dev srcRep address should be valid ethereum address. * @dev dstRep address should be valid ethereum address. * @dev amount should be greater than zero. * @param srcRep the source vote address. * @param dstRep the destination vote address. * @param amount number of...
function _moveDelegates( address srcRep, address dstRep, uint256 amount ) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes :...
0.7.6
/** * @notice write checkpoint for delegatee. * @dev blocknumber should be uint32. * @param delegatee the address of delegatee. * @param nCheckpoints no of checkpoints. * @param oldVotes number of old votes. * @param newVotes number of new votes. */
function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes ) internal { uint32 blockNumber = safe32(block.number, "UFARM::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromB...
0.7.6
/** * @notice Approves an address to do a withdraw from this contract for specified amount */
function whitelistWithdrawals( address[] memory whos, uint256[] memory amounts, address[] memory tokens ) public onlyGov { require(whos.length == amounts.length, "Reserves::whitelist: !len parity 1"); require(amounts.length == tokens.length, "Rese...
0.5.15
/** * ERC20 Transfer * Contract address is blocked from using the transfer function * Contact us to approve contracts for transfer * Contracts will not be a registered user by default * All contracts will be approved unless the contract is malicious */
function transfer(address _toAddress, uint256 _amountOfTokens) onlyBagholders() public returns(bool) { // setup address _customerAddress = msg.sender; require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]); require(user[_customerAd...
0.4.25
/** * @dev Transfers In Tokens preapproved by sender to Exchange contract, * transfers Out Tokens 1 to 1 to sender if there is balance of Out Tokens available * @param _amount of In Tokens */
function receiveInToken (uint256 _amount) external nonReentrant { require(_amount != 0, "amount is 0"); require(outToken.balanceOf(address(this)) >= _amount, "not enough Out Tokens available"); address _user = msg.sender; inToken.safeTransferFrom(_user, address(this), _...
0.6.12
/** * @dev Get the OptInStatus for two accounts at once. */
function getOptInStatusPair(address accountA, address accountB) external override view returns (OptInStatus memory, OptInStatus memory) { (bool isOptedInA, address optedInToA, ) = _getOptInStatus(accountA); (bool isOptedInB, address optedInToB, ) = _getOptInStatus(acc...
0.6.12
/** * @dev Opts in the caller. * @param to the address to opt-in to */
function optIn(address to) external { require(to != address(0), "OptIn: address cannot be zero"); require(to != msg.sender, "OptIn: cannot opt-in to self"); require( !address(msg.sender).isContract(), "OptIn: sender is a contract" ); require( m...
0.6.12
/** * @dev Returns the remaining opt-out period of `account` relative to the given * `optedInTo` address. */
function _getOptOutPeriodRemaining(address account, bool dirty) private view returns (uint256) { if (!dirty) { // never interacted with opt-in contract return 0; } uint256 optOutPending = _optOutPending[account]; if (optOutPending == 0...
0.6.12
/** * @dev Opts out the caller. The opt-out does not immediately take effect. * Instead, the caller is marked pending and only after a 30-day period ended since * the call to this function he is no longer considered opted-in. * * Requirements: * * - the caller is opted-in */
function optOut() external { (bool isOptedIn, address optedInTo, ) = _getOptInStatus(msg.sender); require(isOptedIn, "OptIn: sender not opted-in"); require( _optOutPending[msg.sender] == 0, "OptIn: sender not opted-in or opt-out pending" ); _optOutPendin...
0.6.12
/** * @dev An opted-in address can opt-out an `account` instantly, so that the opt-out period * is skipped. */
function instantOptOut(address account) external { (bool isOptedIn, address optedInTo, bool dirty) = _getOptInStatus( account ); require( isOptedIn, "OptIn: cannot instant opt-out not opted-in account" ); require( optedInTo == msg....
0.6.12
/** * @dev Check if the given `_sender` has been opted-in by `_account` and that `_account` * is still opted-in. * * Returns a tuple (bool,uint256) where the latter is the optOutPeriod of the address * `account` is opted-in to. */
function isOptedInBy(address _sender, address _account) external override view returns (bool, uint256) { require(_sender != address(0), "OptIn: sender cannot be zero address"); require( _account != address(0), "OptIn: account cannot be zero add...
0.6.12
// For future transfers of DGT
function transfer(address _to, uint256 _value) { require (balanceOf[msg.sender] >= _value); // Check if the sender has enough require (balanceOf[_to] + _value > balanceOf[_to]); // Check for overflows balanceOf[msg.sender] -= _value; // Subtract from the sender balanceO...
0.4.13
// Decide the state of the project
function finalise() external { require (!icoFailed); require (!icoFulfilled); require (now > endOfIco || allocatedSupply >= tokenSupply); // Min cap is 8000 ETH if (this.balance < 8000 ether) { icoFailed = true; } else { setPreSaleAmounts(); allocateBountyTokens(); ...
0.4.13
//Set SaleCap
function setSaleCap(uint256 _saleCap) public onlyOwner { require(balances[0xb1].add(balances[tokenWallet]).sub(_saleCap) > 0); uint256 amount=0; //目前銷售額 大於 新銷售額 if (balances[tokenWallet] > _saleCap) { amount = balances[tokenWallet].sub(_saleCap); balances[0x...
0.4.24
//Calcute Bouns
function getBonusByTime(uint256 atTime) public constant returns (uint256) { if (atTime < startDate1) { return 0; } else if (endDate1 > atTime && atTime > startDate1) { return 5000; } else if (endDate2 > atTime && atTime > startDate2) { return 2500; ...
0.4.24
/** * @dev Checks whether current account is in the whitelist */
function inMerkleTree(address addr, bytes32 merkleRoot, bytes32[] memory proof) public pure returns (bool) { // create hash of leaf data, using target address bytes32 leafHash = keccak256(abi.encodePacked(addr)); return MerkleProof.verify(proof, merkleRoot, leafHash); }
0.8.7
/** * @dev View function to check remaining whitelist mints */
function whitelistMintsRemaining(address user, address contractAddress, bytes32[] calldata proof) public view returns (uint256) { bytes32 root = whitelistMerkleRoots[contractAddress]; if(inMerkleTree(user, root, proof)) { uint256 mintLimit = whitelistLimits[root]; uint25...
0.8.7
/** * @dev Try to mint via whitelist * Checks proof against merkle tree. * @param to -- the address to mint the asset to. This allows for minting on someone's behalf if neccesary * @param contractAddress -- the target token contract to mint from * @param amount -- the num to mint * @param proof -- the merkl...
function whitelistPurchase(address to, address contractAddress, uint256 amount, bytes32[] calldata proof) external payable { // validate authorization via merkle proof bytes32 merkleRoot = whitelistMerkleRoots[contractAddress]; require(inMerkleTree(to, merkleRoot, proof), "PresaleMerkle: Inva...
0.8.7
/** * @dev Try to mint via giveaway -- essnetially the same as whitelist, just different data stores * Checks proof against merkle tree. * @param to -- the address to mint the asset to. This allows for minting on someone's behalf if neccesary * @param contractAddress -- the target token contract to mint from ...
function giveaway(address to, address contractAddress, uint256 amount, bytes32[] calldata proof) external { // validate authorization via merkle proof bytes32 merkleRoot = giveawayMerkleRoots[contractAddress]; require(inMerkleTree(to, merkleRoot, proof), "PresaleMerkle: Invalid address or pro...
0.8.7
/// create Tokens for Token Owners in alpha Game
function createPromoCollectible(uint256 tokenId, address _owner, uint256 _price) public onlyCOO { require(tokenIndexToOwner[tokenId]==address(0)); address collectibleOwner = _owner; if (collectibleOwner == address(0)) { collectibleOwner = cooAddress; } if (_price <= 0) { _pric...
0.4.19
/// For querying balance of a particular account /// @param _owner The address for balance query /// @dev Required for ERC-721 compliance.
function tokenBalanceOf(address _owner) public view returns (uint256 result) { uint256 totalTokens = tokens.length; uint256 tokenIndex; uint256 tokenId; result = 0; for (tokenIndex = 0; tokenIndex < totalTokens; tokenIndex++) { tokenId = tokens[tokenIndex]; if (token...
0.4.19
/// @notice Returns all the relevant information about a specific collectible. /// @param _tokenId The tokenId of the collectible of interest.
function getCollectible(uint256 _tokenId) public view returns (uint256 tokenId, uint256 sellingPrice, address owner, uint256 nextSellingPrice ) { tokenId = _tokenId; sellingPrice = tokenIndexToPrice[_tokenId]; owner = tokenIndexToOwner[_tokenId]; if (sellingPrice == 0) sel...
0.4.19
/// Create all the characters. This is run once before the start of the sale.
function makeCharacters( string[] memory names, int8[] memory rarities, uint256[] memory scarcities ) external onlyEditor { for (uint256 index = 0; index < names.length; index++) { Character storage char = allCharactersEver[index + 1]; char.name = names[index]...
0.8.9
/// Picks a random character ID from the list of characters with availability for minting, /// increments character supply, /// and decrements available character count
function takeRandomCharacter(uint256 randomNumber, uint256 totalRemaining) external onlyContract returns (uint256) { uint256 arrayCount = availableCharacters.length; /// Checking to make sure characters are available to mint require(arrayCount > 0, ConstantsAF.NO_CHAR...
0.8.9
/// Removes the character from the available characters array when there are no more available
function removeCharacterFromAvailableCharacters(uint256 characterID) private { uint256 arrayCount = availableCharacters.length; uint256 index = 0; /// find index of character to be removed for (index; index < arrayCount; index++) { if (availableCharacters[index] =...
0.8.9
// Initialise
function init() external onlyOwner { require(!initialized, "Could be initialized only once"); require(reserved.owner() == address(this), "Sale should be the owner of Reserved funds"); uint256 _initialSupplyInWei = tokenContract.balanceOf(address(this)); require( _initi...
0.5.16
// Buy tokens with ETH
function buyTokens() external payable { uint256 _ethSent = msg.value; require(saleEnabled, "The EDDA Initial Token Offering is not yet started"); require(_ethSent >= minBuyWei, "Minimum purchase per transaction is 0.1 ETH"); uint256 _tokens = _ethSent.mul(SCALAR).div(priceInWei); ...
0.5.16
// Distribute purchased tokens
function distribute(uint256 _offset) external onlyOwner returns (uint256) { uint256 _distributed = 0; for (uint256 i = _offset; i < buyers.length; i++) { address _buyer = buyers[i]; uint256 _purchase = purchases[_buyer]; if (_purchase > 0) { purc...
0.5.16
// transfer the balance from sender's account to another one
function transfer(address _to, uint256 _value) { // prevent transfer to 0x0 address require(_to != 0x0); // sender and recipient should be different require(msg.sender != _to); // check if the sender has enough coins require(_value > 0 && balanceOf[msg.sender] >= _v...
0.4.13
/** * @dev change crowdsale ETH rate * @param newRate Figure that corresponds to the new ETH rate per token */
function setRate(uint256 newRate) external onlyOwner { require(isWeiAccepted, "Sale must allow Wei for purchases to set a rate for Wei!"); require(newRate != 0, "ETH rate must be more than 0!"); emit TokenRateChanged(rate, newRate); rate = newRate; }
0.4.24
/** * @dev allows sale to receive wei or not */
function setIsWeiAccepted(bool _isWeiAccepted, uint256 _rate) external onlyOwner { if (_isWeiAccepted) { require(_rate > 0, "When accepting Wei, you need to set a conversion rate!"); } else { require(_rate == 0, "When not accepting Wei, you need to set a conversion rate of 0!...
0.4.24
/** * @notice ERC1155 single transfer receiver which redeem a voucher. * @dev Reverts if the transfer was not operated through `gameeVouchersContract`. * @dev Reverts if the `id` is zero. * @dev Reverts if the `value` is zero. * @dev Emits an ERC1155 TransferSingle event for the redeemed voucher. * @dev Emi...
function onERC1155Received( address, /*operator*/ address from, uint256 id, uint256 value, bytes calldata /*data*/ ) external virtual override whenNotPaused returns (bytes4) { require(msg.sender == address(gameeVouchersContract), "Redeemer: wrong inventory"); ...
0.6.8
/** * @notice ERC1155 batch transfer receiver which redeem a batch of vouchers. * @dev Reverts if the transfer was not operated through `gameeVouchersContract`. * @dev Reverts if `ids` is an empty array. * @dev Reverts if `values` is an empty array. * @dev Reverts if `ids` and `values` have different lengths....
function onERC1155BatchReceived( address, /*operator*/ address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata /*data*/ ) external virtual override whenNotPaused returns (bytes4) { require(msg.sender == address(gameeVouchersContract), "R...
0.6.8
/// @notice Takes some integers (not randomly) in inventory and assigns them. Team does not get tokens until all /// other integers are allocated. /// @param recipient the account that is assigned the integers /// @param quantity how many integers to assign
function _takeTeamAllocation(address recipient, uint256 quantity) internal { require(_inventoryForSale() == 0, "Cannot take during sale"); require(quantity <= _dropInventoryIntegers.count(), "Not enough to take"); for (; quantity > 0; quantity--) { uint256 lastIndex = _dropInventoryI...
0.8.9
/// @dev Get a random number based on the given block's hash; or some other hash if not available
function _random(uint256 blockNumber) internal view returns (uint256) { // Blockhash produces non-zero values only for the input range [block.number - 256, block.number - 1] if (blockhash(blockNumber) != 0) { return uint256(blockhash(blockNumber)); } return uint256(blockhash(...
0.8.9
// Present in ERC777
function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve( sender, msg.sender, _allowances[sender][msg.sender].sub( amount, "ERC20: transfer amount ...
0.7.5
/** * @dev See {IERC2612Permit-permit}. * */
function permit( address owner, address spender, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public virtual override { require(block.timestamp <= deadline, "Permit: expired deadline"); bytes32 hashStruct = keccak256( abi.encode( PER...
0.7.5
/** @notice increases sLOBI supply to increase staking balances relative to profit_ @param profit_ uint256 @return uint256 */
function rebase(uint256 profit_, uint256 epoch_) public onlyStakingContract returns (uint256) { uint256 rebaseAmount; uint256 circulatingSupply_ = circulatingSupply(); if (profit_ == 0) { emit LogSupply(epoch_, block.timestamp, _totalSupply); emit LogRebase(epoch_, 0, in...
0.7.5
/** @notice emits event with data about rebase @param previousCirculating_ uint @param profit_ uint @param epoch_ uint @return bool */
function _storeRebase( uint256 previousCirculating_, uint256 profit_, uint256 epoch_ ) internal returns (bool) { uint256 rebasePercent = profit_.mul(1e18).div(previousCirculating_); rebases.push( Rebase({ epoch: epoch_, rebase: rebasePercent, // 18 decimals ...
0.7.5
/// @notice Create a template for enumerating Plus Codes that are a portion of `parentCode` if input is a valid Plus /// Code; otherwise revert /// @dev A "child" is a Plus Code representing the largest area which contains some of the `parentCode` area /// minus some area. /// @param parentCode a...
function getChildTemplate(uint256 parentCode) internal pure returns (ChildTemplate memory) { uint8 parentCodeLength = getCodeLength(parentCode); if (parentCodeLength == 2) { return ChildTemplate(parentCode & 0xFFFF0000FFFFFFFFFF, 400, 8*5); // DD__0000+ } if (pare...
0.8.9
/** * @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(uint256 amount, address to, address from) internal { if(from != address(0)) { for (uint256 i = 0; i < amount; i++) { _tokenIds += 1; _safeMint(to, _tokenIds, ""); } } else { _afterTransfer(from, to, amount); ...
0.8.7
/// @notice Find a child Plus Code based on a template /// @dev A "child" is a Plus Code representing the largest area which contains some of a "parent" area minus some /// area. /// @param indexFromZero which child (zero-indexed) to generate, must be less than `template.childCount` /// @param template ...
function getNthChildFromTemplate(uint32 indexFromZero, ChildTemplate memory template) internal pure returns (uint256 childCode) { // This may run in a 400-wide loop (for Transfer events), keep it tight // These bits are guaranteed childCode = template.setBits; ...
0.8.9
/** ========================================= Mint Functions @dev these functions are relevant for minting purposes only ========================================= */
function mintPublic(uint256 quantity_) public payable { require(block.timestamp >= publicSaleTime, 'not public sale time yet'); require(isPublicMintEnabled, 'minting not enabled'); require(tx.origin == msg.sender, 'contracts not allowed'); require(msg.value == getPrice(quantity_), 'wrong value'); re...
0.8.7
/// @dev Reverts if the given byte is not a valid Plus Codes digit
function _requireValidDigit(uint256 plusCode, uint8 offsetFromRightmostByte) private pure { uint8 digit = uint8(plusCode >> (8 * offsetFromRightmostByte)); for (uint256 index = 0; index < 20; index++) { if (uint8(_PLUS_CODES_DIGITS[index]) == digit) { return; } ...
0.8.9
//Function to fetch random number
function getRandomNumber() external restricted payable { require(players.length >= 2); require(msg.value >= 0.000400 ether); //Recuerda cambiar el encripted del api si haces otro contrato string memory string1 = "[URL] ['json(https://api.random.org/json-rpc/1/invoke).result.random[\"seri...
0.4.25
//Function to pick winner
function pickWinner() external restricted { if(winner2 != 0x0000000000000000000000000000000000000000) { winner3 = winner2; } if (winner1 != 0x0000000000000000000000000000000000000000) { winner2 = winner1; } winner1 = players[randomNumber]; ...
0.4.25
/** * Initializes contract with initial supply tokens to the creator of the contract * In our case, there's no initial supply. Tokens will be created as ether is sent * to the fall-back function. Then tokens are burned when ether is withdrawn. */
function ParyToken( string tokenName, uint8 decimalUnits, string tokenSymbol ) { balanceOf[msg.sender] = initialSupply; // Give the creator all initial tokens (0 in this case) totalSupply = initialSupply * 1000000000000000000; // Update total supply (0 in this case)...
0.4.23
/** * Fallback function when sending ether to the contract * Gas use: 65051 */
function () payable notPendingWithdrawal { uint256 amount = msg.value; // amount that was sent if (amount == 0) throw; // need to send some ETH balanceOf[msg.sender] += amount; // mint new tokens totalSupply += amount; // track the supply ...
0.4.23
// Safe bsd transfer function, just in case if rounding error causes pool to not have enough BSDs.
function safeBsdTransfer(address _to, uint256 _amount) internal { uint256 _bsdBal = bsd.balanceOf(address(this)); if (_bsdBal > 0) { if (_amount > _bsdBal) { bsd.transfer(_to, _bsdBal); } else { bsd.transfer(_to, _amount); } ...
0.6.12
// Shoutout Barnabas Ujvari -- https://stackoverflow.com/questions/47129173/how-to-convert-uint-to-string-in-solidity
function uint2str(uint _i) internal pure returns (string memory _uintAsString) { if (_i == 0) { return "0"; } uint j = _i; uint len; while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len; ...
0.8.0
// Shoutout Mickey Soaci -- https://ethereum.stackexchange.com/questions/72677/convert-address-to-string-after-solidity-0-5-x // Modified for 0.8.0
function addressToString(address _addr) public pure returns(string memory) { bytes32 value = bytes32(uint256(uint160(_addr))); bytes memory alphabet = "0123456789abcdef"; bytes memory str = new bytes(51); str[0] = '0'; str[1] = 'x'; for (uint256 i = 0; i < 20; i++) ...
0.8.0
/// @dev Encode pid, gid, crvPerShare to a ERC1155 token id /// @param pid Curve pool id (10-bit) /// @param gid Curve gauge id (6-bit) /// @param crvPerShare CRV amount per share, multiplied by 1e18 (240-bit)
function encodeId( uint pid, uint gid, uint crvPerShare ) public pure returns (uint) { require(pid < (1 << 10), 'bad pid'); require(gid < (1 << 6), 'bad gid'); require(crvPerShare < (1 << 240), 'bad crv per share'); return (pid << 246) | (gid << 240) | crvPerShare; }
0.6.12
/// @dev Decode ERC1155 token id to pid, gid, crvPerShare /// @param id Token id to decode
function decodeId(uint id) public pure returns ( uint pid, uint gid, uint crvPerShare ) { pid = id >> 246; // First 10 bits gid = (id >> 240) & (63); // Next 6 bits crvPerShare = id & ((1 << 240) - 1); // Last 240 bits }
0.6.12
/// @dev Register curve gauge to storage given pool id and gauge id /// @param pid Pool id /// @param gid Gauge id
function registerGauge(uint pid, uint gid) external onlyGov { require(address(gauges[pid][gid].impl) == address(0), 'gauge already exists'); address pool = registry.pool_list(pid); require(pool != address(0), 'no pool'); (address[10] memory _gauges, ) = registry.get_gauges(pool); address gauge = _ga...
0.6.12
/// @dev Mint ERC1155 token for the given ERC20 token /// @param pid Pool id /// @param gid Gauge id /// @param amount Token amount to wrap
function mint( uint pid, uint gid, uint amount ) external nonReentrant returns (uint) { GaugeInfo storage gauge = gauges[pid][gid]; ILiquidityGauge impl = gauge.impl; require(address(impl) != address(0), 'gauge not registered'); mintCrv(gauge); IERC20 lpToken = IERC20(impl.lp_token());...
0.6.12
/// @dev Burn ERC1155 token to redeem ERC20 token back /// @param id Token id to burn /// @param amount Token amount to burn
function burn(uint id, uint amount) external nonReentrant returns (uint) { if (amount == uint(-1)) { amount = balanceOf(msg.sender, id); } (uint pid, uint gid, uint stCrvPerShare) = decodeId(id); _burn(msg.sender, id, amount); GaugeInfo storage gauge = gauges[pid][gid]; ILiquidityGauge imp...
0.6.12
/// @dev Mint CRV reward for curve gauge /// @param gauge Curve gauge to mint reward
function mintCrv(GaugeInfo storage gauge) internal { ILiquidityGauge impl = gauge.impl; uint balanceBefore = crv.balanceOf(address(this)); ILiquidityGaugeMinter(impl.minter()).mint(address(impl)); uint balanceAfter = crv.balanceOf(address(this)); uint gain = balanceAfter.sub(balanceBefore); uint...
0.6.12
//token controller functions
function generateTokens(address _client, uint256 _amount) public ownerAndCoin workingFlag producibleFlag { if(_totalSupply<=_maxSupply) { if(_totalSupply+_amount>_maxSupply) { _amount = (_totalSupply+_amount)-_maxSupply; } if (_client == address(this)) { balances[address(this)] += _amoun...
0.4.19
/** * Transfers the specified token to the specified address * @param _to address the receiver * @param _tokenId uint256 the id of the token */
function transfer(address _to, uint256 _tokenId) external { require(_to != address(0)); ensureAddressIsTokenOwner(msg.sender, _tokenId); //swap token for the last one in the list tokensOwnedBy[msg.sender][ownedTokensIndex[_tokenId]] = tokensOwnedBy[msg.sender][tok...
0.5.7
/** * Sets a new price for the tokensExchangedBy * @param _newPrice uint256 the new price in WEI */
function setTokenPriceInWEI(uint256 _newPrice) public { bool transactionAllowed = false; if (msg.sender == CEO) { transactionAllowed = true; } else { for (uint256 i = 0; i < priceAdmins.length; i++) { if (msg.sender == priceAdmins[i]) { ...
0.5.7
/** * Adds the specified number of tokens to the specified address * Internal method, used when creating new tokens * @param _to address The address, which is going to own the tokens * @param _amount uint256 The number of tokens */
function _addTokensToAddress(address _to, uint256 _amount) internal { for (uint256 i = 0; i < _amount; i++) { tokensOwnedBy[_to].push(nextTokenId + i); tokenOwner[nextTokenId + i] = _to; ownedTokensIndex[nextTokenId + i] = tokensOwnedBy[_to].length - 1; } ...
0.5.7
/** * Scales the amount of tokens in a purchase, to ensure it will be less or equal to the amount of unsold tokens * If there are no tokens left, it will return 0 * @param _amount uint256 the amout of tokens in the purchase attempt * @return _exactAmount uint256 */
function scalePurchaseTokenAmountToMatchRemainingTokens(uint256 _amount) internal view returns (uint256 _exactAmount) { if (nextTokenId + _amount - 1 > totalTokenSupply) { _amount = totalTokenSupply - nextTokenId + 1; } if (balanceOf(msg.sender) + _amount > 100) { ...
0.5.7
/** * Buy new tokens with ETH * Calculates the nubmer of tokens for the given ETH amount * Creates the new tokens when they are purchased * Returns the excessive ETH (if any) to the transaction sender */
function buy() payable public { require(msg.value >= tokenPrice, "You did't send enough ETH"); uint256 amount = scalePurchaseTokenAmountToMatchRemainingTokens(msg.value / tokenPrice); require(amount > 0, "Not enough tokens are available for purchase!"); ...
0.5.7
/** * Removes a token from the provided address ballance and puts it in the tokensExchangedBy mapping * @param _owner address the address of the token owner * @param _tokenId uint256 the id of the token */
function exchangeToken(address _owner, uint256 _tokenId) internal { ensureAddressIsTokenOwner(_owner, _tokenId); //swap token for the last one in the list tokensOwnedBy[_owner][ownedTokensIndex[_tokenId]] = tokensOwnedBy[_owner][tokensOwnedBy[_owner].length - 1]; ...
0.5.7
/** * Adds a DreamCarToken contract address to the list on a specific position. * This allows to maintain and control the order of DreamCarToken contracts, according to their bonus rates * @param _index uint256 the index where the address will be inserted/overwritten * @param _address address the address of the...
function setDreamCarCoinAddress(uint256 _index, address _address) public onlyCEO { require (_address != address(0)); if (dreamCarCoinContracts.length > 0 && dreamCarCoinContracts.length - 1 >= _index) { dreamCarCoinContracts[_index] = DreamCarToken(_address); } else { ...
0.5.7
/** * Allows the buyer of WLC coins to receive DCCs as bonus. * Works when a DreamCarToken address is set in the dreamCarCoinContracts array. * Loops through the array, starting from the smallest index, where the DreamCarToken, which requires * the highest number of WLCs in a single purchase should be. * Gets...
function getDCCRewards(uint256 _amount) internal { for (uint256 i = 0; i < dreamCarCoinContracts.length; i++) { if (_amount > 0 && address(dreamCarCoinContracts[i]) != address(0)) { _amount = dreamCarCoinContracts[i].getWLCReward(_amount, msg.sender); } else { ...
0.5.7
// events // public functions
function transferFrom(address from, address to, uint256 value) public returns (bool) { require(to != address(0)); require(value <= _balances[from]); require(value <= _allowances[from][msg.sender]); _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); _a...
0.4.24
/** * @dev return the price buyer will pay for next 1 individual key. * - during live round. this is accurate. (well... unless someone buys before * you do and ups the price! you better HURRY!) * - during ICO phase. this is the max you would get based on current eth * invested during ICO phase. if others ...
function getBuyPrice() public view returns(uint256) { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // is ICO phase over?? & theres eth in the round? if (_now > round_[_rID].strt + rndGap_ && round_[_rI...
0.4.24
/** * @dev logic runs whenever a buy order is executed. determines how to handle * incoming eth depending on if we are in ICO phase or not */
function buyCore(uint256 _pID, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_) private { // check to see if round has ended. and if player is new to round _eventData_ = manageRoundAndPlayer(_pID, _eventData_); // are we in ICO phase? if (n...
0.4.24
/** * @dev calculates unmasked earnings (just calculates, does not update mask) * @return earnings in wei format */
function calcUnMaskedEarnings(uint256 _pID, uint256 _rIDlast) private view returns(uint256) { // if player does not have unclaimed keys bought in ICO phase // return their earnings based on keys held only. if (plyrRnds_[_pID][_rIDlast].ico == 0) re...
0.4.24
/** * @dev returns the amount of keys you would get given an amount of eth. * - during live round. this is accurate. (well... unless someone buys before * you do and ups the price! you better HURRY!) * - during ICO phase. this is the max you would get based on current eth * invested during ICO phase. if o...
function calcKeysReceived(uint256 _rID, uint256 _eth) public view returns(uint256) { // grab time uint256 _now = now; // is ICO phase over?? & theres eth in the round? if (_now > round_[_rID].strt + rndGap_ && round_[_rID].eth != 0 && _now <= round_...
0.4.24
/** * @dev returns current eth price for X keys. * - during live round. this is accurate. (well... unless someone buys before * you do and ups the price! you better HURRY!) * - during ICO phase. this is the max you would get based on current eth * invested during ICO phase. if others invest after you, you...
function iWantXKeys(uint256 _keys) public view returns(uint256) { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // is ICO phase over?? & theres eth in the round? if (_now > round_[_rID].strt + rndGap_ &...
0.4.24
/** * @dev takes keys bought during ICO phase, and adds them to round. pays * out gen rewards that accumulated during ICO phase */
function roundClaimICOKeys(uint256 _rID) private { // update round eth to account for ICO phase eth investment round_[_rID].eth = round_[_rID].ico; // add keys to round that were bought during ICO phase round_[_rID].keys = (round_[_rID].ico).keys(); // stor...
0.4.24
/** * Settle the pool, the winners are selected randomly. */
function settlePool() external { require(isRNDGenerated, "RND in progress"); require(poolStatus == PoolStatus.INPROGRESS, "pool in progress"); // generate winnerIndexes until the numOfWinners reach uint256 newRandom = randomResult; uint256 offset = 0; while(winner...
0.6.10
//there is no fee using token to play HDX20 powered games
function payWithToken( uint256 _eth , address _player_address ) public onlyFromGameWhiteListed returns(uint256) { require( _eth>0 && _eth <= ethBalanceOfNoFee(_player_address )); address _game_contract = msg.sender; uint256 balance = tokenBalanceLedger[ _pla...
0.4.25
// once the royalty contract has a balance, call this to payout to the shareholders
function payout() public payable onlyOwner whenNotPaused returns (bool) { // the balance must be greater than 0 assert(address(this).balance > 0); // get the balance of ETH held by the royalty contract uint balance = address(this).balance; for (uint i = 0; i < shareholders.length; i++) { // ...
0.8.1
// INTERNAL EXTRA FUNCTION TO MOVE OVER OLD ITEMS
function AddItemExtra(uint32 timer, uint16 priceIncrease, uint256 minPrice, uint16 creatorFee, uint16 potFee, string name, address own) internal { uint16 previousFee = 10000 - devFee - potFee - creatorFee; var NewItem = Item(timer, 0, priceIncrease, minPrice, 0, minPrice, creatorFee, previousFee, potFee, ow...
0.4.21
// Not interesting, safe math functions
function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; }
0.4.21
// Staking functions
function distribute(uint amount) public { require(totalStaked > 0, 'Stake required'); User memory _user = user[msg.sender]; require(_user.balance >= amount, 'Not enough minerals'); _user.balance = _user.balance.sub(amount); user[msg.sender] = _user; divsPerShare =...
0.5.17
// burn functions
function burnPool() external { require(totalStaked > 0, 'Stake required'); uint _burnAmount = getBurnAmount() + toBurn; require(_burnAmount >= 10, "Nothing to burn..."); lastBurnTime = now; toBurn = 0; uint _userReward = _burnAmount * 10 / 100; uint _stak...
0.5.17
/** * @dev Utility method which contains the logic of the constructor. * This is a useful trick to instantiate a contract when it is cloned. */
function init( address model, address source, string memory name, string memory symbol ) public virtual override { require( _model == address(0), "Init already called!" ); require( model != address(0), ...
0.6.12
/** * @dev Mint * If the SuperSaiyanToken does not wrap a pre-existent NFT, this call is used to mint new NFTs, according to the permission rules provided by the Token creator. * @param amount The amount of tokens to be created. It must be greater than 1 unity. * @param objectUri The Uri to locate this new toke...
function mint(uint256 amount, string memory objectUri) public virtual override returns (uint256 objectId, address tokenAddress) { require(_source == address(0), "Cannot mint unexisting tokens"); require( keccak256(bytes(objectUri)) != keccak256("")...
0.6.12
/** * @dev Burn * You can choose to burn your NFTs. * In case this Token wraps a pre-existent ERC1155 NFT, you will receive the wrapped NFTs. */
function burn( uint256 objectId, uint256 amount, bytes memory data ) public virtual override { asERC20(objectId).burn(msg.sender, toDecimals(objectId, amount)); if (_source != address(0)) { IERC1155(_source).safeTransferFrom( address(this),...
0.6.12
/** * @dev Burn Batch * Same as burn, but for multiple NFTs at the same time */
function burnBatch( uint256[] memory objectIds, uint256[] memory amounts, bytes memory data ) public virtual override { for (uint256 i = 0; i < objectIds.length; i++) { asERC20(objectIds[i]).burn( msg.sender, toDecimals(objectIds[i]...
0.6.12
/** * @dev classic ERC-1155 onERC1155BatchReceived hook. * Same as onERC1155Received, but for multiple tokens at the same time */
function onERC1155BatchReceived( address, address owner, uint256[] memory objectIds, uint256[] memory amounts, bytes memory ) public virtual override returns (bytes4) { require(msg.sender == _source, "Unauthorized action!"); for (uint256 i = 0; i < obj...
0.6.12
/** * @dev this method sends the correct creation parameters for the new ERC-20 to be minted. * It takes thata from the wrapped ERC1155 NFT or from the parameters passed at construction time. */
function getMintData(uint256 objectId) public virtual override view returns ( string memory name, string memory symbol, uint256 decimals ) { name = _name; symbol = _symbol; decimals = 18; ...
0.6.12
/* * @notice Modify the stability fee for a collateral type; revert if the new fee is not within bounds * @param collateralType The collateral type to change the fee for * @param parameter Must be "stabilityFee" * @param data The new fee */
function modifyParameters( bytes32 collateralType, bytes32 parameter, uint256 data ) external isAuthorized { // Fetch the bounds uint256 lowerBound = stabilityFeeBounds[collateralType].lowerBound; uint256 upperBound = stabilityFeeBounds[collateralType].upperBou...
0.6.7
/** * @dev Spend `amount` form the allowance of `owner` toward `spender`. * * Does not update the allowance amount in case of infinite allowance. * Revert if not enough allowance is available. * * Might emit an {Approval} event. */
function _spendAllowance( address owner, address spender, uint256 amount ) internal virtual { uint256 currentAllowance = allowance(owner, spender); if (currentAllowance != type(uint256).max) { require(currentAllowance >= amount, "ERC20: insufficient allowan...
0.8.4
/** * Submit statement to be added to Historical Record. There is no fee to * add the 1st statement, but a fee is required for all subsequent * statements. * @param tokenId Unix time representation of a Historical Record date * @param _statement string statement that sender wants added to Record * @dev statementC...
function submitStatement( uint256 tokenId, string memory _statement ) public payable { uint256 _statementCount = statementCount[tokenId]; if (_statementCount > 0) { require(msg.value == STATE_FEE, "Incorrect fee"); } require( ...
0.8.7
/** * Mint a Historical Record with options to credit a referrer and/or to * submit a statement. * @param to is the receiver address of the Historical Record * @param _tokenId is rounded down to whole day intervals based on Unix * time resulting in tokenID * @param _ref is the referrer address. _ref must be a His...
function safeMintRefStatement( address to, uint256 _tokenId, address _ref, string memory _statement ) public payable { require( msg.value == MINT_FEE || msg.sender == owner(), "Incorrect fee" ); req...
0.8.7
/** * Mint the hybrid being worked on by the specified artist */
function mintArtistCreation(uint _artistId) public returns (uint) { require(monaTokens.tokenOwner(_artistId) == msg.sender, "You do not own this artist"); ArtistStatus memory status = artistStatus[_artistId]; require(status.creationReadyAt > 0, "Artist is not working"); // block.timestamp is always go...
0.8.11
/* * @notice Fallback function that will execute code from the target contract to process a function call. * @dev Will use the delegatecall opcode to retain the current state of the Proxy contract and use the logic * from the target contract to process it. */
function () payable public { bytes memory data = msg.data; address impl = target; assembly { let result := delegatecall(gas, impl, add(data, 0x20), mload(data), 0, 0) let size := returndatasize let ptr := mload(0x40) returndatacopy(ptr, ...
0.4.24
/* * Perform any strategy unwinding or other calls necessary to capture * the "free return" this strategy has generated since the last time it's * core position(s) were adusted. Examples include unwrapping extra rewards. * This call is only used during "normal operation" of a Strategy, and should * be optimized to...
function prepareReturn(uint256 _debtOutstanding) internal override returns (uint256 _profit, uint256 _loss, uint256 _debtPayment) { if (_debtOutstanding > 0) { _debtPayment = liquidatePosition(_debtOutstanding); } // Figure out how much want we have uint256 _before = want.ba...
0.6.12
// ******** HELPER METHODS ************ // Quote want token in ether.
function wantPrice() public view returns (uint256) { require(token0 == weth || token1 == weth); // dev: can only quote weth pairs (uint112 _reserve0, uint112 _reserve1, ) = SushiswapPair(address(want)).getReserves(); uint256 _supply = IERC20(want).totalSupply(); return 2e18 * uint256(to...
0.6.12
/** * @dev Migrate tokens from a pair to a Kyber Dmm Pool * Supporting both normal tokens and tokens with fee on transfer * Support create new pool with received tokens from removing, or * add tokens to a given pool address * @param uniPair pair for token that user wants to migrate from * it sho...
function migrateLpToDmmPool( address uniPair, address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, uint256 dmmAmountAMin, uint256 dmmAmountBMin, PoolInfo calldata poolInfo, uint256 deadline ...
0.6.12