comment
stringlengths
11
2.99k
function_code
stringlengths
165
3.15k
version
stringclasses
80 values
// Deposit tokens to liquidity mining for reward token allocation.
function deposit(uint256 _pid, uint256 _amount) external { require(block.number <= endBlock, "LP mining has ended."); updatePool(_pid); accrueReward(_pid); UserPoolInfo storage userPool = userPoolInfo[_pid][msg.sender]; if (_amount > 0) { poolInfo[_pid].token.safeTransferFrom( address(msg.sender), address(this), _amount ); userPool.amount = userPool.amount.add(_amount); } userPool.accruedReward = calcReward(poolInfo[_pid], userPoolInfo[_pid][msg.sender]); emit Deposited(msg.sender, _pid, _amount); }
0.7.6
// Set unlocks infos - block number and quota.
function setUnlocks(uint256[] calldata _blocks, uint256[] calldata _quotas) external onlyOwner { require(_blocks.length == _quotas.length, "Should be same length"); for (uint256 i = 0; i < _blocks.length; ++i) { unlocks.push(UnlockInfo(_blocks[i], _quotas[i])); unlocksTotalQuotation = unlocksTotalQuotation.add(_quotas[i]); } }
0.7.6
// Withdraw tokens from rewardToken liquidity mining.
function withdraw(uint256 _pid, uint256 _amount) external { require(userPoolInfo[_pid][msg.sender].amount >= _amount, "withdraw: not enough amount"); updatePool(_pid); accrueReward(_pid); UserPoolInfo storage userPool = userPoolInfo[_pid][msg.sender]; if (_amount > 0) { userPool.amount = userPool.amount.sub(_amount); poolInfo[_pid].token.safeTransfer(address(msg.sender), _amount); } userPool.accruedReward = calcReward(poolInfo[_pid], userPoolInfo[_pid][msg.sender]); emit Withdrawn(msg.sender, _pid, _amount); }
0.7.6
// Withdraws amount specified (ETH) from balance of contract to owner account (owner-only)
function withdrawPartial(uint256 _amount) public onlyOwner { require(twoStage); // Check that amount is not more than total contract balance require( _amount > 0 && _amount <= address(this).balance, "Withdraw amount must be positive and not exceed total contract balance" ); payable(msg.sender).transfer(_amount); twoStage = false; }
0.8.7
// Migrate token to another lp contract. Can be called by anyone.
function migrate(uint256 _pid) external { require(address(migrator) != address(0), "migrate: no migrator"); PoolInfo storage pool = poolInfo[_pid]; IERC20 token = pool.token; uint256 bal = token.balanceOf(address(this)); token.safeApprove(address(migrator), bal); IERC20 newToken = migrator.migrate(token); require(bal == newToken.balanceOf(address(this)), "migrate: bad"); pool.token = newToken; delete poolPidByAddress[address(token)]; poolPidByAddress[address(newToken)] = _pid; emit TokenMigrated(address(token), address(newToken), _pid); }
0.7.6
/** * @dev Triggers a transfer to `account` of the amount of Ether they are owed, according to their percentage of the * total shares and their previous withdrawals. */
function release(address payable account) public virtual { require(_shares[account] > 0, "PaymentSplitter: account has no shares"); uint256 totalReceived = address(this).balance + totalReleased(); uint256 payment = _pendingPayment(account, totalReceived, released(account)); require(payment != 0, "PaymentSplitter: account is not due payment"); _released[account] += payment; _totalReleased += payment; AddressUpgradeable.sendValue(account, payment); emit PaymentReleased(account, payment); }
0.8.4
// function to get claimable amount for any user
function getClaimableAmount(address _user) external view returns(uint256) { LockInfo[] memory lockInfoArrayForUser = lockInfoByUser[_user]; uint256 totalTransferableAmount = 0; uint i; for (i=latestCounterByUser[_user]; i<lockInfoArrayForUser.length; i++){ uint256 lockingPeriodHere = lockingPeriod; if(lockInfoArrayForUser[i]._isDev){ lockingPeriodHere = devLockingPeriod; } if(now >= (lockInfoArrayForUser[i]._timestamp.add(lockingPeriodHere))){ totalTransferableAmount = totalTransferableAmount.add(lockInfoArrayForUser[i]._amount); } else { break; } } return totalTransferableAmount; }
0.6.12
/** * @dev Add a new payee to the contract. * @param account The address of the payee to add. * @param shares_ The number of shares owned by the payee. */
function _addPayee(address account, uint256 shares_) private { require(account != address(0), "PaymentSplitter: account is the zero address"); require(shares_ > 0, "PaymentSplitter: shares are 0"); require(_shares[account] == 0, "PaymentSplitter: account already has shares"); _payees.push(account); _shares[account] = shares_; _totalShares = _totalShares + shares_; emit PayeeAdded(account, shares_); }
0.8.4
/** * Add new star */
function addStar(address owner, uint8 gid, uint8 zIndex, uint16 box, uint8 inbox, uint8 stype, uint8 color, uint256 price) internal returns(uint256) { Star memory _star = Star({ owner: owner, gid: gid, zIndex: zIndex, box: box, inbox: inbox, stype: stype, color: color, price: price, sell: 0, deleted: false, name: "", message: "" }); uint256 starId = stars.push(_star) - 1; placeStar(gid, zIndex, box, starId); return starId; }
0.4.21
/** * Get star by id */
function getStar(uint256 starId) external view returns(address owner, uint8 gid, uint8 zIndex, uint16 box, uint8 inbox, uint8 stype, uint8 color, uint256 price, uint256 sell, bool deleted, string name, string message) { Star storage _star = stars[starId]; owner = _star.owner; gid = _star.gid; zIndex = _star.zIndex; box = _star.box; inbox = _star.inbox; stype = _star.stype; color = _star.color; price = _star.price; sell = _star.sell; deleted = _star.deleted; name = _star.name; message = _star.message; }
0.4.21
/** * Set validation data */
function setValidationData(uint16 _zMin, uint16 _zMax, uint8 _lName, uint8 _lMessage, uint8 _maxCT, uint8 _maxIR, uint16 _boxSize) external onlyOwner { zMin = _zMin; zMax = _zMax; lName = _lName; lMessage = _lMessage; maxCT = _maxCT; maxIRandom = _maxIR; boxSize = _boxSize; inboxXY = uint8((boxSize * boxSize) / 4); }
0.4.21
/** * Get random star position */
function getRandomPosition(uint8 gid, uint8 zIndex) internal returns(uint16 box, uint8 inbox) { uint16 boxCount = getBoxCountZIndex(zIndex); uint16 randBox = 0; if (boxCount == 0) revert(); uint8 ii = maxIRandom; bool valid = false; while (!valid && ii > 0) { randBox = getRandom16(0, boxCount); valid = isValidBox(gid, zIndex, randBox); ii--; } if (!valid) revert(); return(randBox, getRandom8(0, inboxXY)); }
0.4.21
/** * Create star */
function createStar(uint8 gid, uint16 z, string name, string message) external payable { // Check basic requires require(isValidGid(gid)); require(isValidZ(z)); require(isValidNameLength(name)); require(isValidMessageLength(message)); // Get zIndex uint8 zIndex = getZIndex(z); uint256 starPrice = getCreatePrice(z, getZCount(gid, zIndex)); require(isValidMsgValue(starPrice)); // Create star (need to split method into two because solidity got error - to deep stack) uint256 starId = newStar(gid, zIndex, starPrice); setStarNameMessage(starId, name, message); // Event and returns data emit StarCreated(starId); }
0.4.21
/** * Update start method */
function updateStar(uint256 starId, string name, string message) external payable { // Exists and owned star require(starExists(starId)); require(isStarOwner(starId, msg.sender)); // Check basic requires require(isValidNameLength(name)); require(isValidMessageLength(message)); // Get star update price uint256 commission = getCommission(stars[starId].price); require(isValidMsgValue(commission)); // Update star setStarNameMessage(starId, name, message); emit StarUpdated(starId, 1); }
0.4.21
/** * Delete star */
function deleteStar(uint256 starId) external payable { // Exists and owned star require(starExists(starId)); require(isStarOwner(starId, msg.sender)); // Get star update price uint256 commission = getCommission(stars[starId].price); require(isValidMsgValue(commission)); // Update star data setStarDeleted(starId); emit StarDeleted(starId, msg.sender); }
0.4.21
/** * Gift star */
function giftStar(uint256 starId, address recipient) external payable { // Check star exists owned require(starExists(starId)); require(recipient != address(0)); require(isStarOwner(starId, msg.sender)); require(!isStarOwner(starId, recipient)); // Get gift commission uint256 commission = getCommission(stars[starId].price); require(isValidMsgValue(commission)); // Update star setStarNewOwner(starId, recipient); setStarSellPrice(starId, 0); emit StarGifted(starId, msg.sender, recipient); emit StarUpdated(starId, 3); }
0.4.21
/** * Buy star */
function buyStar(uint256 starId, string name, string message) external payable { // Exists and NOT owner require(starExists(starId)); require(!isStarOwner(starId, msg.sender)); require(stars[starId].sell > 0); // Get sell commission and check value uint256 commission = getCommission(stars[starId].price); uint256 starPrice = stars[starId].sell; uint256 totalPrice = starPrice + commission; require(isValidMsgValue(totalPrice)); // Transfer money to seller address seller = stars[starId].owner; seller.transfer(starPrice); // Update star data setStarNewOwner(starId, msg.sender); setStarSellPrice(starId, 0); setStarNameMessage(starId, name, message); emit StarSold(starId, seller, msg.sender, starPrice); emit StarUpdated(starId, 4); }
0.4.21
// Forward ERC20 methods to upgraded contract after the upgrade timestamp has been reached
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { if (now > upgradeTimestamp) { return UpgradedStandardToken(upgradeAddress).transferFromByLegacy(msg.sender, _from, _to, _value); } else { return super.transferFrom(_from, _to, _value); } }
0.4.24
// Deposit LP tokens to TopDog for BONE allocation.
function deposit(uint256 _pid, uint256 _amount) public nonReentrant { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accBonePerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { // safeBoneTransfer(msg.sender, pending); uint256 sendAmount = pending.mul(rewardMintPercent).div(100); safeBoneTransfer(msg.sender, sendAmount); if(rewardMintPercent != 100) { safeBoneTransfer(address(boneLocker), pending.sub(sendAmount)); // Rest amount sent to Bone token contract boneLocker.lock(msg.sender, pending.sub(sendAmount), false); //function called for token time-lock } } } if(_amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); } user.rewardDebt = user.amount.mul(pool.accBonePerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); }
0.6.12
/** * @notice Initiates a new rebase operation, provided the minimum time period has elapsed. * * @dev The supply adjustment equals (_totalSupply * DeviationFromTargetRate) / rebaseLag * Where DeviationFromTargetRate is (MarketOracleRate - targetRate) / targetRate * and targetRate is 1 */
function rebase() external onlyOrchestrator { require(inRebaseWindow()); // This comparison also ensures there is no reentrancy. require(lastRebaseTimestampSec.add(minRebaseTimeIntervalSec) < now); // Snap the rebase time to the start of this window. lastRebaseTimestampSec = now.sub( now.mod(minRebaseTimeIntervalSec)).add(rebaseWindowOffsetSec); epoch = epoch.add(1); uint256 targetRate = TARGET_RATE; uint256 exchangeRate; bool rateValid; (exchangeRate, rateValid) = marketOracle.getData(); require(rateValid); if (exchangeRate > MAX_RATE) { exchangeRate = MAX_RATE; } int256 supplyDelta = computeSupplyDelta(exchangeRate, targetRate); // Apply the Dampening factor. supplyDelta = supplyDelta.div(rebaseLag.toInt256Safe()); if (supplyDelta > 0 && uFrags.totalSupply().add(uint256(supplyDelta)) > MAX_SUPPLY) { supplyDelta = (MAX_SUPPLY.sub(uFrags.totalSupply())).toInt256Safe(); } uint256 supplyAfterRebase = uFrags.rebase(epoch, supplyDelta); assert(supplyAfterRebase <= MAX_SUPPLY); emit LogRebase(epoch, exchangeRate, supplyDelta, now); }
0.4.24
// Method which is used to mint during the standard minting window
function mint(uint256 _amountMinted, address _recipient) public payable nonReentrant { if (owner() != _msgSender()) { require( saleTime != 0 && saleTime <= block.timestamp, "ERC721: Sale is paused..." ); } require(totalSupply() < supplyCap, "ERC721: Sale is finished."); require( _amountMinted > 0 && _amountMinted <= perTxLimit, "ERC721: You may only mint up to 20 Empty Buns." ); require( totalSupply() + _amountMinted < supplyCap, "ERC721: Transaction would exceed supply cap." ); require( msg.value >= getTokenPrice(true) * _amountMinted, "ERC721: Incorrect value sent." ); // Prevent nefarious contracts from bypassing limits require( tx.origin == _msgSender(), "ERC721: The caller is another contract." ); for (uint256 i = 0; i < _amountMinted; i++) { _safeMint(_recipient, tokenCounter); tokenCounter++; } }
0.8.7
// Public method which retrieves holders inventory of tokens
function getHoldersTokens(address _holder) public view returns (uint256[] memory) { uint256 tokenCount = balanceOf(_holder); uint256[] memory tokensId = new uint256[](tokenCount); for (uint256 i; i < tokenCount; i++) { tokensId[i] = tokenOfOwnerByIndex(_holder, i); } return tokensId; }
0.8.7
// BID // Lets player pick number // Locks his potential winnings
function Bid(uint256 _number) payable public { require(now < timerEnd, "game is over!"); require(msg.value > bid, "not enough to beat current leader"); require(_number >= numberMin, "number too low"); require(_number <= numberMax, "number too high"); bid = msg.value; pot = pot.add(msg.value); shareToWinner = ComputeShare(); uint256 _share = 100; shareToThrone = _share.sub(shareToWinner); leader = msg.sender; number = _number; emit GameBid(msg.sender, msg.value, number, pot, shareToWinner); }
0.5.7
// END // Can be called manually after the game ends // Sends pot to winner and snailthrone
function End() public { require(now > timerEnd, "game is still running!"); uint256 _throneReward = pot.mul(shareToThrone).div(100); pot = pot.sub(_throneReward); (bool success, bytes memory data) = SNAILTHRONE.call.value(_throneReward)(""); require(success); uint256 _winnerReward = pot; pot = 0; leader.transfer(_winnerReward); emit GameEnd(leader, _winnerReward, _throneReward, number); }
0.5.7
// ref: https://blogs.sas.com/content/iml/2016/05/16/babylonian-square-roots.html
function sqrt(uint256 x) internal pure returns (uint256 y) { uint256 z = (x + 1) / 2; y = x; while (z < y) { y = z; z = (x / z + z) / 2; } }
0.8.7
/** * @notice Hash an order into bytes32 * @dev EIP-191 header and domain separator included * @param order Order The order to be hashed * @param domainSeparator bytes32 * @return bytes32 A keccak256 abi.encodePacked value */
function hashOrder( Order calldata order, bytes32 domainSeparator ) external pure returns (bytes32) { return keccak256(abi.encodePacked( EIP191_HEADER, domainSeparator, keccak256(abi.encode( ORDER_TYPEHASH, order.nonce, order.expiry, keccak256(abi.encode( PARTY_TYPEHASH, order.signer.kind, order.signer.wallet, order.signer.token, order.signer.amount, order.signer.id )), keccak256(abi.encode( PARTY_TYPEHASH, order.sender.kind, order.sender.wallet, order.sender.token, order.sender.amount, order.sender.id )), keccak256(abi.encode( PARTY_TYPEHASH, order.affiliate.kind, order.affiliate.wallet, order.affiliate.token, order.affiliate.amount, order.affiliate.id )) )) )); }
0.5.12
/** * @notice Send an Order to be forwarded to Swap * @dev Sender must authorize this contract on the swapContract * @dev Sender must approve this contract on the wethContract * @param order Types.Order The Order */
function swap( Types.Order calldata order ) external payable { // Ensure msg.sender is sender wallet. require(order.sender.wallet == msg.sender, "MSG_SENDER_MUST_BE_ORDER_SENDER"); // Ensure that the signature is present. // The signature will be explicitly checked in Swap. require(order.signature.v != 0, "SIGNATURE_MUST_BE_SENT"); // Wraps ETH to WETH when the sender provides ETH and the order is WETH _wrapEther(order.sender); // Perform the swap. swapContract.swap(order); // Unwraps WETH to ETH when the sender receives WETH _unwrapEther(order.sender.wallet, order.signer.token, order.signer.amount); }
0.5.12
// Withdraw without caring about rewards. EMERGENCY ONLY.
function emergencyWithdraw(uint amount) public shouldStarted { require(amount <= _stakerTokenBalance[msg.sender] && _stakerTokenBalance[msg.sender] > 0, "Bad withdraw."); if(_stakerStakingPlan[msg.sender] == 4 || _stakerStakingPlan[msg.sender] == 5){ require(block.timestamp >= _stakerStakingTime[msg.sender] + 30 days, "Early withdrawal available after 30 days"); } updateRewards(msg.sender); _stakerTokenBalance[msg.sender] = _stakerTokenBalance[msg.sender].sub(amount); _stakerTokenRewardsClaimed[msg.sender] = 0; _stakerStakingPlan[msg.sender] = 0; if(_stakerWithdrawFeeRate[msg.sender] > 0){ uint256 _burnedAmount = amount.mul(_stakerWithdrawFeeRate[msg.sender]).div(100); amount = amount.sub(_burnedAmount); token.burn(_burnedAmount); } token.safeTransfer(msg.sender, amount); emit Withdraw(msg.sender, amount); }
0.6.12
/** * @notice Send an Order to be forwarded to a Delegate * @dev Sender must authorize the Delegate contract on the swapContract * @dev Sender must approve this contract on the wethContract * @dev Delegate's tradeWallet must be order.sender - checked in Delegate * @param order Types.Order The Order * @param delegate IDelegate The Delegate to provide the order to */
function provideDelegateOrder( Types.Order calldata order, IDelegate delegate ) external payable { // Ensure that the signature is present. // The signature will be explicitly checked in Swap. require(order.signature.v != 0, "SIGNATURE_MUST_BE_SENT"); // Wraps ETH to WETH when the signer provides ETH and the order is WETH _wrapEther(order.signer); // Provide the order to the Delegate. delegate.provideOrder(order); // Unwraps WETH to ETH when the signer receives WETH _unwrapEther(order.signer.wallet, order.sender.token, order.sender.amount); }
0.5.12
// Return accumulate rewards over the given _fromTime to _toTime.
function getGeneratedReward(uint256 _fromTime, uint256 _toTime) public view returns (uint256) { for (uint8 epochId = 2; epochId >= 1; --epochId) { if (_toTime >= epochEndTimes[epochId - 1]) { if (_fromTime >= epochEndTimes[epochId - 1]) { return _toTime.sub(_fromTime).mul(epochApePerSecond[epochId]); } uint256 _generatedReward = _toTime.sub(epochEndTimes[epochId - 1]).mul(epochApePerSecond[epochId]); if (epochId == 1) { return _generatedReward.add(epochEndTimes[0].sub(_fromTime).mul(epochApePerSecond[0])); } for (epochId = epochId - 1; epochId >= 1; --epochId) { if (_fromTime >= epochEndTimes[epochId - 1]) { return _generatedReward.add(epochEndTimes[epochId].sub(_fromTime).mul(epochApePerSecond[epochId])); } _generatedReward = _generatedReward.add(epochEndTimes[epochId].sub(epochEndTimes[epochId - 1]).mul(epochApePerSecond[epochId])); } return _generatedReward.add(epochEndTimes[0].sub(_fromTime).mul(epochApePerSecond[0])); } } return _toTime.sub(_fromTime).mul(epochApePerSecond[0]); }
0.8.1
/** * @notice Wraps ETH to WETH when a trade requires it * @param party Types.Party The side of the trade that may need wrapping */
function _wrapEther(Types.Party memory party) internal { // Check whether ether needs wrapping if (party.token == address(wethContract)) { // Ensure message value is param. require(party.amount == msg.value, "VALUE_MUST_BE_SENT"); // Wrap (deposit) the ether. wethContract.deposit.value(msg.value)(); // Transfer the WETH from the wrapper to party. // Return value not checked - WETH throws on error and does not return false wethContract.transfer(party.wallet, party.amount); } else { // Ensure no unexpected ether is sent. require(msg.value == 0, "VALUE_MUST_BE_ZERO"); } }
0.5.12
/** * @notice Unwraps WETH to ETH when a trade requires it * @dev The unwrapping only succeeds if recipientWallet has approved transferFrom * @param recipientWallet address The trade recipient, who may have received WETH * @param receivingToken address The token address the recipient received * @param amount uint256 The amount of token the recipient received */
function _unwrapEther(address recipientWallet, address receivingToken, uint256 amount) internal { // Check whether ether needs unwrapping if (receivingToken == address(wethContract)) { // Transfer weth from the recipient to the wrapper. wethContract.transferFrom(recipientWallet, address(this), amount); // Unwrap (withdraw) the ether. wethContract.withdraw(amount); // Transfer ether to the recipient. // solium-disable-next-line security/no-call-value (bool success, ) = recipientWallet.call.value(amount)(""); require(success, "ETH_RETURN_FAILED"); } }
0.5.12
// Deposit LP tokens.
function deposit(uint256 _pid, uint256 _amount) public { address _sender = msg.sender; PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_sender]; updatePool(_pid); if (user.amount > 0) { uint256 _pending = user.amount.mul(pool.accApePerShare).div(1e18).sub(user.rewardDebt); if (_pending > 0) { safeApeTransfer(_sender, _pending); emit RewardPaid(_sender, _pending); } } if (_amount > 0) { pool.token.safeTransferFrom(_sender, address(this), _amount); user.amount = user.amount.add(_amount); } user.rewardDebt = user.amount.mul(pool.accApePerShare).div(1e18); emit Deposit(_sender, _pid, _amount); }
0.8.1
// Withdraw LP tokens.
function withdraw(uint256 _pid, uint256 _amount) public { address _sender = msg.sender; PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 _pending = user.amount.mul(pool.accApePerShare).div(1e18).sub(user.rewardDebt); if (_pending > 0) { safeApeTransfer(_sender, _pending); emit RewardPaid(_sender, _pending); } if (_amount > 0) { user.amount = user.amount.sub(_amount); pool.token.safeTransfer(_sender, _amount); } user.rewardDebt = user.amount.mul(pool.accApePerShare).div(1e18); emit Withdraw(_sender, _pid, _amount); }
0.8.1
// Safe ape transfer function, just in case if rounding error causes pool to not have enough Apes.
function safeApeTransfer(address _to, uint256 _amount) internal { uint256 _apeBal = ape.balanceOf(address(this)); if (_apeBal > 0) { if (_amount > _apeBal) { ape.safeTransfer(_to, _apeBal); } else { ape.safeTransfer(_to, _amount); } } }
0.8.1
// Transfer amount of tokens from sender account to recipient. // Only callable after the crowd fund is completed
function transfer(address _to, uint _value) { if (_to == msg.sender) return; // no-op, allow even during crowdsale, in order to work around using grantVestedTokens() while in crowdsale // if (!isCrowdfundCompleted()) throw; super.transfer(_to, _value); }
0.4.19
//constant function returns the current XFM price.
function getPriceRate() constant returns (uint o_rate) { uint delta = now; if (delta < PRESALE_START_WEEK1) return PRICE_PRESALE_START; if (delta < PRESALE_START_WEEK2) return PRICE_PRESALE_WEEK1; if (delta < PRESALE_START_WEEK3) return PRICE_PRESALE_WEEK2; if (delta < CROWDSALE_START) return PRICE_PRESALE_WEEK3; return (PRICE_CROWDSALE); }
0.4.19
// Returns `amount` in scope as the number of XFM tokens that it will purchase.
function processPurchase(uint _rate, uint _remaining) internal returns (uint o_amount) { o_amount = calcAmount(msg.value, _rate); if (o_amount > _remaining) throw; if (!multisigAddress.send(msg.value)) throw; balances[ownerAddress] = balances[ownerAddress].sub(o_amount); balances[msg.sender] = balances[msg.sender].add(o_amount); XFMSold += o_amount; etherRaised += msg.value; }
0.4.19
// To be called at the end of crowdfund period // WARNING: transfer(), which is called by grantVestedTokens(), wants a minimum message length
function grantVested(address _XferMoneyTeamAddress, address _XferMoneyFundAddress) is_crowdfund_completed only_owner is_not_halted { // Grant tokens pre-allocated for the team grantVestedTokens( _XferMoneyTeamAddress, ALLOC_TEAM, uint64(now), uint64(now) + 91 days , uint64(now) + 365 days, false, false ); // Grant tokens that remain after crowdsale to the XferMoney fund, vested for 2 years grantVestedTokens( _XferMoneyFundAddress, balances[ownerAddress], uint64(now), uint64(now) + 182 days , uint64(now) + 730 days, false, false ); }
0.4.19
// List every tokens an owner owns
function tokensOfOwner(address _owner) public view returns (uint256[] memory) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { return new uint256[](0); } else { uint256[] memory result = new uint256[](tokenCount); uint256 index; for (index = 0; index < tokenCount; index++) { result[index] = tokenOfOwnerByIndex(_owner, index); } return result; } }
0.8.4
// Before any transfer, add the new owner to the holders list of this token
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); // Save the holder only once per token if (!_alreadyHoldToken[tokenId][to]) { cardInfo[tokenId].holders.push(to); _alreadyHoldToken[tokenId][to] = true; } }
0.8.4
//Safe Maths
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.7.1
/* Buy Token 1 token for x ether */
function buyTokens() public whenCrowdsaleNotPaused payable { require(!accounts[msg.sender].blacklisted); require(msg.value > 0); require(msg.value >= _tokenPrice); require(msg.value % _tokenPrice == 0); var numTokens = msg.value / _tokenPrice; require(numTokens >= _minimumTokens); balanceOf[msg.sender] += numTokens; Transfer(0, msg.sender, numTokens); wallet.transfer(msg.value); accounts[msg.sender].balance = accounts[msg.sender].balance.add(numTokens); insertShareholder(msg.sender); if (msg.sender != owner) { totalSupply += numTokens; } }
0.4.19
/** * @dev Function to mint tokens: uri must be is unique and msg.value sufficient * @param to The address that will receive the minted tokens. * @param tokenURI The token URI of the minted token. * @return A boolean that indicates if the operation was successful. */
function mintWithTokenURI(address to, string memory tokenURI) public payable returns (bool) { require(_enabled == true, "Minting has been disabled"); // Confirm payment require(msg.value == mintPrice, ""); uint256 tokenId = ++_totalMinted; require(bytes(tokenURI).length > 0, "Invalid tokenURI"); // Set and validate tokenURI unique _mapTokenURIToId(tokenURI, tokenId); _mint(to, tokenId); _setTokenURI(tokenId, tokenURI); return true; }
0.6.12
//An identifier: eg SBX
function scearu( uint256 _initialAmount, string _tokenName, uint8 _decimalUnits, string _tokenSymbol ) public { balances[msg.sender] = _initialAmount; // Give the creator all initial tokens totalSupply = _initialAmount; // Update total supply name = _tokenName; // Set the name for display purposes decimals = _decimalUnits; // Amount of decimals for display purposes symbol = _tokenSymbol; // Set the symbol for display purposes }
0.4.21
/// @notice Harvest profits while preventing a sandwich attack exploit. /// @param maxBalance The maximum balance of the underlying token that is allowed to be in BentoBox. /// @param rebalance Whether BentoBox should rebalance the strategy assets to acheive it's target allocation. /// @param maxChangeAmount When rebalancing - the maximum amount that will be deposited to or withdrawn from a strategy to BentoBox. /// @param harvestRewards If we want to claim any accrued reward tokens /// @dev maxBalance can be set to 0 to keep the previous value. /// @dev maxChangeAmount can be set to 0 to allow for full rebalancing.
function safeHarvest( uint256 maxBalance, bool rebalance, uint256 maxChangeAmount, bool harvestRewards ) external onlyExecutor { if (harvestRewards) { _harvestRewards(); } if (maxBalance > 0) { maxBentoBoxBalance = maxBalance; } IBentoBoxMinimal(bentoBox).harvest(strategyToken, rebalance, maxChangeAmount); }
0.8.7
// Deposit LP tokens to TravelAgency for CITY allocation.
function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accCityPerShare).div(1e12).sub(user.rewardDebt); safeCityTransfer(msg.sender, pending); } pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accCityPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); }
0.6.12
/// @inheritdoc IStrategy
function withdraw(uint256 amount) external override isActive onlyBentoBox returns (uint256 actualAmount) { _withdraw(amount); /// @dev Make sure we send and report the exact same amount of tokens by using balanceOf. actualAmount = IERC20(strategyToken).balanceOf(address(this)); IERC20(strategyToken).safeTransfer(bentoBox, actualAmount); }
0.8.7
/// @inheritdoc IStrategy /// @dev do not use isActive modifier here; allow bentobox to call strategy.exit() multiple times
function exit(uint256 balance) external override onlyBentoBox returns (int256 amountAdded) { _exit(); /// @dev Check balance of token on the contract. uint256 actualBalance = IERC20(strategyToken).balanceOf(address(this)); /// @dev Calculate tokens added (or lost). amountAdded = int256(actualBalance) - int256(balance); /// @dev Transfer all tokens to bentoBox. IERC20(strategyToken).safeTransfer(bentoBox, actualBalance); /// @dev Flag as exited, allowing the owner to manually deal with any amounts available later. exited = true; }
0.8.7
//***************************** TRANSFER TOKENS FROM YOUR ACCOUNT **************
function transfer(address _to, uint256 _val) public returns (bool) { require(holders[msg.sender] >= _val); require(msg.sender != _to); assert(_val <= holders[msg.sender]); holders[msg.sender] = holders[msg.sender] - _val; holders[_to] = holders[_to] + _val; assert(holders[_to] >= _val); emit Transfer(msg.sender, _to, _val); return true; }
0.4.26
//**************************** TRANSFER TOKENS FROM ANOTHER ACCOUNT ************
function transferFrom(address _from, address _to, uint256 _val) public returns (bool) { require(holders[_from] >= _val); require(approach[_from][msg.sender] >= _val); assert(_val <= holders[_from]); holders[_from] = holders[_from] - _val; assert(_val <= approach[_from][msg.sender]); approach[_from][msg.sender] = approach[_from][msg.sender] - _val; holders[_to] = holders[_to] + _val; assert(holders[_to] >= _val); emit Transfer(_from, _to, _val); return true; }
0.4.26
/** * @notice Buy function. Used to buy tokens using ETH, USDT or USDC * @param _paymentAmount --> Result of multiply number of tokens to buy per price per token. Must be always multiplied per 1000 to avoid decimals * @param _tokenPayment --> Address of the payment token (or 0x0 if payment is ETH) */
function buy(uint256 _paymentAmount, address _tokenPayment) external payable { require(_isICOActive() == true, "ICONotActive"); uint256 paidTokens = 0; if (msg.value == 0) { // Stable coin payment require(_paymentAmount > 0, "BadPayment"); require(_tokenPayment == usdtToken || _tokenPayment == usdcToken, "TokenNotSupported"); require(IERC20(_tokenPayment).transferFrom(msg.sender, address(this), _paymentAmount)); paidTokens = _paymentAmount * 2666666666666666667 / 1000000000000000000; // 0.375$ per token in the ICO } else { // ETH Payment uint256 usdETH = _getUSDETHPrice(); uint256 paidUSD = msg.value * usdETH / 10**18; paidTokens = paidUSD * 2666666666666666666 / 1000000000000000000; // 0.375$ per token in the ICO } require((paidTokens + 1*10**18) >= minTokensBuyAllowed, "BadTokensQuantity"); // One extra token as threshold rounding decimals require(maxICOTokens - icoTokensBought >= paidTokens, "NoEnoughTokensInICO"); userBoughtTokens[msg.sender] += paidTokens; icoTokensBought += paidTokens; if (maxICOTokens - icoTokensBought < minTokensBuyAllowed) { // We finish the ICO icoFinished = true; emit onICOFinished(block.timestamp); } emit onTokensBought(msg.sender, paidTokens, _paymentAmount, _tokenPayment); }
0.8.7
/** * @notice Get the vesting unlock dates * @param _period --> There are 4 periods (0,1,2,3) * @return _date Returns the date in UnixDateTime UTC format */
function getVestingDate(uint256 _period) external view returns(uint256 _date) { if (_period == 0) { _date = tokenListingDate; } else if (_period == 1) { _date = tokenListingDate + _3_MONTHS_IN_SECONDS; } else if (_period == 2) { _date = tokenListingDate + _6_MONTHS_IN_SECONDS; } else if (_period == 3) { _date = tokenListingDate + _9_MONTHS_IN_SECONDS; } }
0.8.7
/** * @notice Uses Chainlink to query the USDETH price * @return Returns the ETH amount in weis (Fixed value of 3932.4 USDs in localhost development environments) */
function _getUSDETHPrice() internal view returns(uint256) { int price = 0; if (address(priceFeed) != address(0)) { (, price, , , ) = priceFeed.latestRoundData(); } else { // For local testing price = 393240000000; } return uint256(price * 10**10); }
0.8.7
//create new escrow
function createNewEscrow(address escrowpayee, uint escrowamount) external { require(factorycontractactive, "Factory Contract should be Active"); require(escrowid < maxuint, "Maximum escrowid reached"); require(msg.sender != escrowpayee,"The Payer, payee should be different"); require(escrowpayee != address(0),"The Escrow Payee can not be address(0)"); require(escrowamount > 0,"Escrow amount has to be greater than 0"); require(daiToken.allowance(msg.sender,address(this)) >= mathlib.add(escrowamount, escrowfee), "daiToken allowance exceeded"); bytes32 esid = keccak256(abi.encodePacked(escrowid)); Escrows[esid] = Escrow({escrowpayer:msg.sender, escrowpayee:escrowpayee, escrowamount:escrowamount, escrowsettlementamount:escrowamount, estatus:escrowstatus.ACTIVATED,escrowmoderator:address(0),escrowmoderatorfee:0}); escrowid = mathlib.add(escrowid,1); //The Esrow Amount gets transferred to factory contract daiToken.transferFrom(msg.sender, address(this), escrowamount); //Transfer the escrow fee to factory manager daiToken.transferFrom(msg.sender, manager, escrowfee); emit NewEscrowEvent(esid, msg.sender, escrowpayee, escrowamount, now); emit NewEscrowEventById(esid, msg.sender, escrowpayee, escrowamount, now); }
0.6.12
//create new escrow overload
function createNewEscrow(address escrowpayee, uint escrowamount, address escrowmoderator, uint escrowmoderatorfee) external { require(factorycontractactive, "Factory Contract should be Active"); require(escrowid < maxuint, "Maximum escrowid reached"); require(msg.sender != escrowpayee && msg.sender != escrowmoderator && escrowpayee != escrowmoderator,"The Payer, payee & moderator should be different"); require(escrowpayee != address(0) && escrowmoderator!=address(0),"Escrow Payee or moderator can not be address(0)"); require(escrowamount > 0,"Escrow amount has to be greater than 0"); uint dailockedinnewescrow = mathlib.add(escrowamount,escrowmoderatorfee); require(daiToken.allowance(msg.sender,address(this)) >= mathlib.add(dailockedinnewescrow, escrowfee), "daiToken allowance exceeded"); bytes32 esid = keccak256(abi.encodePacked(escrowid)); Escrows[esid] = Escrows[esid] = Escrow({escrowpayer:msg.sender, escrowpayee:escrowpayee, escrowamount:escrowamount, escrowsettlementamount:escrowamount, estatus:escrowstatus.ACTIVATED,escrowmoderator:escrowmoderator,escrowmoderatorfee:escrowmoderatorfee}); escrowid = mathlib.add(escrowid,1); //The Esrow Amount and Moderator fee gets transferred to factory contract daiToken.transferFrom(msg.sender, address(this), dailockedinnewescrow); //Transfer the escrow fee to factory manager daiToken.transferFrom(msg.sender, manager, escrowfee); emit NewEscrowEvent(esid, msg.sender, escrowpayee, escrowamount, escrowmoderator, escrowmoderatorfee ,now); emit NewEscrowEventById(esid, msg.sender, escrowpayee, escrowamount, escrowmoderator, escrowmoderatorfee, now); }
0.6.12
/** * @dev Claim your share of the balance. */
function claim() public { address payee = msg.sender; require(shares[payee] > 0); uint256 totalReceived = this.balance.add(totalReleased); uint256 payment = totalReceived.mul(shares[payee]).div(totalShares).sub(released[payee]); require(payment != 0); require(this.balance >= payment); released[payee] = released[payee].add(payment); totalReleased = totalReleased.add(payment); payee.transfer(payment); }
0.4.21
/*function _transfer(address _from, address _to, uint256 _tokenId) internal { ownershipTokenCount[_to]++; // transfer ownership cardIndexToOwner[_tokenId] = _to; // Emit the transfer event. Transfer(_from, _to, _tokenId); }*/
function _createCard(uint256 _prototypeId, address _owner) internal returns (uint) { // This will assign ownership, and also emit the Transfer event as // per ERC721 draft require(uint256(1000000) > lastPrintedCard); lastPrintedCard++; tokenToCardIndex[lastPrintedCard] = _prototypeId; _setTokenOwner(lastPrintedCard, _owner); //_addTokenToOwnersList(_owner, lastPrintedCard); Transfer(0, _owner, lastPrintedCard); //tokenCountIndex[_prototypeId]++; //_transfer(0, _owner, lastPrintedCard); //<-- asd return lastPrintedCard; }
0.4.21
/// @notice Transfers the ownership of an NFT from one address to another address /// @dev This works identically to the other function with an extra data parameter, /// except this function just sets data to "" /// @param _from The current owner of the NFT /// @param _to The new owner /// @param _tokenId The NFT to transfer
function safeTransferFrom(address _from, address _to, uint256 _tokenId) external payable { require(_getApproved(_tokenId) == msg.sender); require(_ownerOf(_tokenId) == _from); require(_to != address(0)); _clearApprovalAndTransfer(_from, _to, _tokenId); Approval(_from, 0, _tokenId); Transfer(_from, _to, _tokenId); if (isContract(_to)) { bytes4 value = ERC721TokenReceiver(_to).onERC721Received(_from, _tokenId, ""); if (value != bytes4(keccak256("onERC721Received(address,uint256,bytes)"))) { revert(); } } }
0.4.21
/// @inheritdoc IPeripheryPayments
function sweepToken( address token, uint256 amountMinimum, address recipient ) external payable override { uint256 balanceToken = IERC20(token).balanceOf(address(this)); require(balanceToken >= amountMinimum, 'Insufficient token'); if (balanceToken > 0) { TransferHelper.safeTransfer(token, recipient, balanceToken); } }
0.8.6
/// @param token The token to pay /// @param payer The entity that must pay /// @param recipient The entity that will receive payment /// @param value The amount to pay
function pay( address token, address payer, address recipient, uint256 value ) internal { if (token == WETH9 && address(this).balance >= value) { // pay with WETH9 IWETH9(WETH9).deposit{value: value}(); // wrap only what is needed to pay IWETH9(WETH9).transfer(recipient, value); } else if (payer == address(this)) { // pay with tokens already in the contract (for the exact input multihop case) TransferHelper.safeTransfer(token, recipient, value); } else { // pull payment TransferHelper.safeTransferFrom(token, payer, recipient, value); } }
0.8.6
/** * Returns whether the target address is a contract * @dev This function will return false if invoked during the constructor of a contract, * as the code is not actually created until after the constructor finishes. * @param _addr address to check * @return whether the target address is a contract */
function isContract(address _addr) internal view returns (bool) { uint256 size; // XXX Currently there is no better way to check if there is a contract in an address // than to check the size of the code at that address. // See https://ethereum.stackexchange.com/a/14016/36603 // for more details about how this works. // TODO Check this again before the Serenity release, because all addresses will be // contracts then. // solium-disable-next-line security/no-inline-assembly assembly { size := extcodesize(_addr) } return size > 0; }
0.6.12
/** * @dev Transfers the ownership of a given token ID to another address * Usage of this method is discouraged, use `safeTransferFrom` whenever possible * Requires the msg sender to be the owner, approved, or operator * @param _from current owner of the token * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred */
function transferFrom( address _from, address _to, uint256 _tokenId ) public override { require(isApprovedOrOwner(msg.sender, _tokenId)); require(_from != address(0)); require(_to != address(0)); clearApproval(_from, _tokenId); removeTokenFrom(_from, _tokenId); addTokenTo(_to, _tokenId); emit Transfer(_from, _to, _tokenId); }
0.6.12
/** * @dev Returns whether the given spender can transfer a given token ID * @param _spender address of the spender to query * @param _tokenId uint256 ID of the token to be transferred * @return bool whether the msg.sender is approved for the given token ID, * is an operator of the owner, or is the owner of the token */
function isApprovedOrOwner( address _spender, uint256 _tokenId ) internal view returns (bool) { address owner = ownerOf(_tokenId); // Disable solium check because of // https://github.com/duaraghav8/Solium/issues/175 // solium-disable-next-line operator-whitespace return ( _spender == owner || getApproved(_tokenId) == _spender || isApprovedForAll(owner, _spender) ); }
0.6.12
// set room message
function setRoomMessage(uint256 tokenId, string memory newRoomMessage) external payable { require(_tokenIdCounter.current() >= tokenId && tokenId > 0, tokenIdInvalid); require( msg.sender == ownerOf(tokenId), "token owner only"); require( msg.value >= _price, "incorrect ETH sent" ); _roomMessage[tokenId] = newRoomMessage; }
0.8.7
/** * @dev Returns an URI for a given token ID. * Throws if the token ID does not exist. May return an empty string. * @param tokenId uint256 ID of the token to query */
function tokenURI(uint256 tokenId) external view returns (string memory) { require(exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory url = _tokenURIs[tokenId]; bytes memory urlAsBytes = bytes(url); if (urlAsBytes.length == 0) { bytes memory baseURIAsBytes = bytes(baseURI); bytes memory tokenIdAsBytes = uintToBytes(tokenId); bytes memory b = new bytes(baseURIAsBytes.length + tokenIdAsBytes.length); uint256 i; uint256 j; for (i = 0; i < baseURIAsBytes.length; i++) { b[j++] = baseURIAsBytes[i]; } for (i = 0; i < tokenIdAsBytes.length; i++) { b[j++] = tokenIdAsBytes[i]; } return string(b); } else { return _tokenURIs[tokenId]; } }
0.6.12
/** * @dev Mint token * * @param _to address of token owner */
function mint(address _to,uint256 amount) public returns (uint256) { require(_tokenIds.current() + amount < _max_supply, "CulturalArtTreasure: maximum quantity reached"); require(amount > 0, "You must buy at least one ."); uint256 newTokenId = 1; for (uint256 i = 0; i < amount; i++) { _tokenIds.increment(); newTokenId = _tokenIds.current(); _mint(_to, newTokenId); Attributes.Data storage attributes = attributesByTokenIds[newTokenId]; attributes.init(); } return newTokenId; }
0.6.12
// get room message
function getRoomMessage(uint256 tokenId) public view returns (string memory) { require(_tokenIdCounter.current() >= tokenId && tokenId > 0, tokenIdInvalid); bytes memory tempEmptyStringTest = bytes(_roomMessage[tokenId]); if (tempEmptyStringTest.length == 0) { uint256 randMsg = random("nft", tokenId); if (randMsg % 17 == 3) return "LFG!"; else if (randMsg % 7 == 3) return "WAGMI!"; else return "gm!"; } else { return _roomMessage[tokenId]; } }
0.8.7
// mint num of keycards
function mint(uint256 num) external payable nonReentrant { require( _publicSale, "public sale paused" ); require( num <= 10, "max 10 per TX" ); require( _tokenIdCounter.current() + num <= _maxSupply, "max supply reached" ); require( msg.value >= _price * num, "incorrect ETH sent" ); for( uint i = 0; i < num; i++ ) { _safeMint(_msgSender(), _tokenIdCounter.current() + 1); _tokenIdCounter.increment(); } }
0.8.7
/** * @dev Creates a vesting contract that vests its balance of any ERC20 token to the * _beneficiary, gradually in a linear fashion until _start + _duration. By then all * of the balance will have vested. * @param _beneficiary address of the beneficiary to whom vested tokens are transferred * @param _cliff duration in seconds of the cliff in which tokens will begin to vest * @param _duration duration in seconds of the period in which the tokens will vest * @param _revocable whether the vesting is revocable or not */
function TokenVesting(address _beneficiary, uint256 _start, uint256 _cliff, uint256 _duration, bool _revocable) public { require(_beneficiary != address(0)); require(_cliff <= _duration); beneficiary = _beneficiary; revocable = _revocable; duration = _duration; cliff = _start.add(_cliff); start = _start; }
0.4.18
/** * @dev Calculates the amount that has already vested. * @param token ERC20 token which is being vested */
function vestedAmount(ERC20Basic token) public view returns (uint256) { uint256 currentBalance = token.balanceOf(this); uint256 totalBalance = currentBalance.add(released[token]); if (now < cliff) { return 0; } else if (now >= start.add(duration) || revoked[token]) { return totalBalance; } else { return totalBalance.mul(now.sub(start)).div(duration); } }
0.4.18
/** * @dev Issues FTT to entitled accounts. * @param _user address to issue FTT to. * @param _fttAmount amount of FTT to issue. */
function issueFTT(address _user, uint256 _fttAmount) public onlyTdeIssuer tdeRunning returns(bool) { uint256 newAmountIssued = fttIssued.add(_fttAmount); require(_user != address(0)); require(_fttAmount > 0); require(newAmountIssued <= FT_TOKEN_SALE_CAP); balances[_user] = balances[_user].add(_fttAmount); fttIssued = newAmountIssued; FTTIssued(tdeIssuer, _user, _fttAmount, block.timestamp); if (fttIssued == FT_TOKEN_SALE_CAP) { capReached = true; } return true; }
0.4.18
/** * @dev Allows the contract owner to finalize the TDE. */
function finalize() external tdeEnded onlyOwner { require(!isFinalized); // Deposit team fund amount into team vesting contract. uint256 teamVestingCliff = 15778476; // 6 months uint256 teamVestingDuration = 1 years; TokenVesting teamVesting = new TokenVesting(owner, now, teamVestingCliff, teamVestingDuration, true); teamVesting.transferOwnership(owner); teamVestingAddress = address(teamVesting); balances[teamVestingAddress] = FT_TEAM_FUND; if (!capReached) { // Deposit unsold FTT into unsold vesting contract. uint256 unsoldVestingCliff = 3 years; uint256 unsoldVestingDuration = 10 years; TokenVesting unsoldVesting = new TokenVesting(owner, now, unsoldVestingCliff, unsoldVestingDuration, true); unsoldVesting.transferOwnership(owner); unsoldVestingAddress = address(unsoldVesting); balances[unsoldVestingAddress] = FT_TOKEN_SALE_CAP - fttIssued; } // Allocate operational reserve of FTT. balances[operationalReserveAddress] = FT_OPERATIONAL_FUND - FT_TEAM_FUND; isFinalized = true; TdeFinalized(block.timestamp); }
0.4.18
/** * @dev Transfer tokens from one address to another. Trading limited - requires the TDE to have ended. * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { if (!isFinalized) return false; require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; }
0.4.18
/** * @dev Transfer token for a specified address. Trading limited - requires the TDE to have ended. * @param _to The address to transfer to. * @param _value The amount to be transferred. */
function transfer(address _to, uint256 _value) public returns (bool) { if (!isFinalized) return false; require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; }
0.4.18
/** * @notice The Synthetix contract informs us when fees are paid. */
function feePaid(bytes4 currencyKey, uint amount) external onlySynthetix { uint xdrAmount; if (currencyKey != "XDR") { xdrAmount = synthetix.effectiveValue(currencyKey, amount, "XDR"); } else { xdrAmount = amount; } // Keep track of in XDRs in our fee pool. recentFeePeriods[0].feesToDistribute = recentFeePeriods[0].feesToDistribute.add(xdrAmount); }
0.4.25
// generate metadata for stars
function haveStar(uint256 tokenId) private pure returns (string memory) { uint256 starSeed = random("star", tokenId); string memory traitTypeJson = ', {"trait_type": "Star", "value": "'; if (starSeed % 47 == 1) return string(abi.encodePacked(traitTypeJson, 'Sirius"}')); if (starSeed % 11 == 1) return string(abi.encodePacked(traitTypeJson, 'Vega"}')); return ''; }
0.8.7
// render stars in SVG
function renderStar(uint256 tokenId) private pure returns (string memory) { string memory starFirstPart = '<defs><linearGradient id="star" x1="100%" y1="100%"><stop offset="0%" stop-color="black" stop-opacity=".5"><animate attributeName="stop-color" values="black;black;black;black;gray;'; string memory starLastPart = ';gray;black;black;black;black" dur="3s" repeatCount="indefinite" /></stop></linearGradient></defs><g style="transform:translate(130px,244px)"><g style="transform:scale(0.1,0.1)"><path fill="url(#star)" d="M189.413,84c-36.913,0-37.328,38.157-37.328,38.157c0-33.181-36.498-38.157-36.498-38.157 c37.328,0,36.498-38.157,36.498-38.157C152.085,84,189.413,84,189.413,84z" /></g></g>'; uint256 starSeed = random("star", tokenId); if (starSeed % 47 == 1) return string(abi.encodePacked(starFirstPart, 'aqua', starLastPart)); if (starSeed % 11 == 1) return string(abi.encodePacked(starFirstPart, 'white', starLastPart)); return ''; }
0.8.7
// generate metadata for keys
function haveKey(uint256 tokenId) private pure returns (string memory) { uint256 keySeed = random("key", tokenId); string memory traitTypeJson = ', {"trait_type": "Key", "value": "'; if (keySeed % 301 == 1) return string(abi.encodePacked(traitTypeJson, 'Rainbow Key"}')); if (keySeed % 161 == 1) return string(abi.encodePacked(traitTypeJson, 'Crystal Key"}')); //afcfff if (keySeed % 59 == 1) return string(abi.encodePacked(traitTypeJson, 'Gold Key"}')); //ffff33 if (keySeed % 31 == 1) return string(abi.encodePacked(traitTypeJson, 'Silver Key"}')); //dddddd if (keySeed % 11 == 1) return string(abi.encodePacked(traitTypeJson, 'Jade Key"}')); // 66ff66 return string(abi.encodePacked(traitTypeJson, 'Copper Key"}')); // 995500 }
0.8.7
// generate metadata for description
function getDescription(uint256 tokenId) private view returns (string memory) { string memory description0 = string(abi.encodePacked('This is a keycard to launch [#', toString(tokenId), ' ', getRoomTheme(tokenId), ' ', getRoomType(tokenId),'](', string(abi.encodePacked(_roomBaseUrl, toString(tokenId))), ') with one click.')); string memory description1 = ' And check the linked '; uint256 link1Id = getAssetLink1(tokenId); if (link1Id > 0) { string memory link1description = string(abi.encodePacked('[#', toString(link1Id), ' ', getRoomTheme(link1Id), ' ', getRoomType(link1Id), '](', string(abi.encodePacked(_roomBaseUrl, toString(link1Id))) ,')')); uint256 link2Id = getAssetLink2(tokenId); if (link2Id > 0) { string memory link2description = string(abi.encodePacked('[#', toString(link2Id), ' ', getRoomTheme(link2Id), ' ', getRoomType(link2Id), '](', string(abi.encodePacked(_roomBaseUrl, toString(link2Id))) ,')')); if (link2Id > link1Id) return string(abi.encodePacked(description0, description1, link1description,' and ',link2description, '.')); else return string(abi.encodePacked(description0, description1, link2description,' and ',link1description, '.')); } else { return string(abi.encodePacked(description0, description1, link1description,'.')); } } else { return description0; } }
0.8.7
/// @notice Returns PoolKey: the ordered tokens with the matched fee levels /// @param tokenA The first token of a pool, unsorted /// @param tokenB The second token of a pool, unsorted /// @param fee The fee level of the pool /// @return Poolkey The pool details with ordered token0 and token1 assignments
function getPoolKey( address tokenA, address tokenB, uint24 fee ) internal pure returns (PoolKey memory) { if (tokenA > tokenB) (tokenA, tokenB) = (tokenB, tokenA); return PoolKey({token0: tokenA, token1: tokenB, fee: fee}); }
0.8.6
/// @notice Deterministically computes the pool address given the factory and PoolKey /// @param factory The Uniswap V3 factory contract address /// @param key The PoolKey /// @return pool The contract address of the V3 pool
function computeAddress(address factory, PoolKey memory key) internal pure returns (address pool) { require(key.token0 < key.token1); pool = address( uint160(uint256( keccak256( abi.encodePacked( hex'ff', factory, keccak256(abi.encode(key.token0, key.token1, key.fee)), POOL_INIT_CODE_HASH ) ) )) ); }
0.8.6
/** * @notice Calculate the Fee charged on top of a value being sent * @return Return the fee charged */
function transferFeeIncurred(uint value) public view returns (uint) { return value.multiplyDecimal(transferFeeRate); // Transfers less than the reciprocal of transferFeeRate should be completely eaten up by fees. // This is on the basis that transfers less than this value will result in a nil fee. // Probably too insignificant to worry about, but the following code will achieve it. // if (fee == 0 && transferFeeRate != 0) { // return _value; // } // return fee; }
0.4.25
/** @notice queue address to change boolean in mapping @param _managing MANAGING @param _address address @return bool */
function queue(MANAGING _managing, address _address) external onlyManager() returns (bool) { require(_address != address(0)); if (_managing == MANAGING.RESERVEDEPOSITOR) {// 0 reserveDepositorQueue[_address] = block.number.add(blocksNeededForQueue); } else if (_managing == MANAGING.RESERVESPENDER) {// 1 reserveSpenderQueue[_address] = block.number.add(blocksNeededForQueue); } else if (_managing == MANAGING.RESERVETOKEN) {// 2 reserveTokenQueue[_address] = block.number.add(blocksNeededForQueue); } else if (_managing == MANAGING.RESERVEMANAGER) {// 3 ReserveManagerQueue[_address] = block.number.add(blocksNeededForQueue.mul(2)); } else if (_managing == MANAGING.LIQUIDITYDEPOSITOR) {// 4 LiquidityDepositorQueue[_address] = block.number.add(blocksNeededForQueue); } else if (_managing == MANAGING.LIQUIDITYTOKEN) {// 5 LiquidityTokenQueue[_address] = block.number.add(blocksNeededForQueue); } else if (_managing == MANAGING.LIQUIDITYMANAGER) {// 6 LiquidityManagerQueue[_address] = block.number.add(blocksNeededForQueue.mul(2)); } else if (_managing == MANAGING.DEBTOR) {// 7 debtorQueue[_address] = block.number.add(blocksNeededForQueue); } else if (_managing == MANAGING.REWARDMANAGER) {// 8 rewardManagerQueue[_address] = block.number.add(blocksNeededForQueue); } else if (_managing == MANAGING.SGWS) {// 9 sGWSQueue = block.number.add(blocksNeededForQueue); } else return false; emit ChangeQueued(_managing, _address); return true; }
0.7.5
/* A contract attempts to get the coins */
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { if (_to == 0x0) revert(); // Prevent transfer to 0x0 address. Use burn() instead if (balanceOf[_from] < _value) revert(); // Check if the sender has enough if (balanceOf[_to] + _value < balanceOf[_to]) revert(); // Check for overflows if (_value > allowance[_from][msg.sender]) revert(); // Check allowance balanceOf[_from] -= _value; // Subtract from the sender balanceOf[_to] += _value; // Add the same to the recipient allowance[_from][msg.sender] -= _value; Transfer(_from, _to, _value); return true; }
0.4.13
/** * @dev transfers tokens to a given address on behalf of another address * throws on any error rather then return a false flag to minimize user errors * * @param _from source address * @param _to target address * @param _value transfer amount * * @return true if the transfer was successful, false if it wasn't */
function transferFrom(address _from, address _to, uint256 _value) public virtual override validAddress(_from) validAddress(_to) returns (bool) { allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_value); balanceOf[_from] = balanceOf[_from].sub(_value); balanceOf[_to] = balanceOf[_to].add(_value); emit Transfer(_from, _to, _value); return true; }
0.6.12
/// @inheritdoc IPrizeFlush
function flush() external override onlyManagerOrOwner returns (bool) { // Captures interest from PrizePool and distributes funds using a PrizeSplitStrategy. strategy.distribute(); // After funds are distributed using PrizeSplitStrategy we EXPECT funds to be located in the Reserve. IReserve _reserve = reserve; IERC20 _token = _reserve.getToken(); uint256 _amount = _token.balanceOf(address(_reserve)); // IF the tokens were succesfully moved to the Reserve, now move them to the destination (PrizeDistributor) address. if (_amount > 0) { address _destination = destination; // Create checkpoint and transfers new total balance to PrizeDistributor _reserve.withdrawTo(_destination, _amount); emit Flushed(_destination, _amount); return true; } return false; }
0.8.6
/// @notice Deploy a proxy that fetches its implementation from this /// ProxyBeacon.
function deployProxy(bytes32 create2Salt, bytes calldata encodedParameters) external onlyProxyDeployer returns (address) { // Deploy without initialization code so that the create2 address isn't // based on the initialization parameters. address proxy = address(new BeaconProxy{salt: create2Salt}(address(this), "")); Address.functionCall(address(proxy), encodedParameters); return proxy; }
0.8.7
// join the club! // make a deposit to another account if it exists // or initialize a deposit for a new account
function deposit(address _to) payable public { require(msg.value > 0); if (_to == 0) _to = msg.sender; // if a new member, init a hodl time if (hodlers[_to].time == 0) { hodlers[_to].time = now + hodl_interval; m_hodlers++; } hodlers[_to].value += msg.value; }
0.4.18
/// @param vaultId The vault to liquidate /// @notice Liquidates a vault with help from a Uniswap v3 flash loan
function liquidate(bytes12 vaultId) external { uint24 poolFee = 3000; // 0.3% DataTypes.Vault memory vault = cauldron.vaults(vaultId); DataTypes.Balances memory balances = cauldron.balances(vaultId); DataTypes.Series memory series = cauldron.series(vault.seriesId); address base = cauldron.assets(series.baseId); address collateral = cauldron.assets(vault.ilkId); uint128 baseLoan = cauldron.debtToBase(vault.seriesId, balances.art); // tokens in PoolKey must be ordered bool ordered = (collateral < base); PoolAddress.PoolKey memory poolKey = PoolAddress.PoolKey({ token0: ordered ? collateral : base, token1: ordered ? base : collateral, fee: poolFee }); IUniswapV3Pool pool = IUniswapV3Pool(PoolAddress.computeAddress(factory, poolKey)); // data for the callback to know what to do FlashCallbackData memory args = FlashCallbackData({ vaultId: vaultId, base: base, collateral: collateral, baseLoan: baseLoan, baseJoin: address(witch.ladle().joins(series.baseId)), poolKey: poolKey }); // initiate flash loan, with the liquidation logic embedded in the flash loan callback pool.flash( address(this), ordered ? 0 : baseLoan, ordered ? baseLoan : 0, abi.encode( args ) ); }
0.8.6
//allows the owner to abort the contract and retrieve all funds
function kill() public { if (msg.sender == owner) // only allow this action if the account sending the signal is the creator selfdestruct(owner); // kills this contract and sends remaining funds back to creator }
0.4.19
// Make sure draft tokens are already set up in Manifold Studio and get their metadata URIs prior to bulk minting
function airdropURIs(address[] calldata receivers, string[] calldata uris) external adminRequired { require(receivers.length == uris.length, "Length mismatch"); for (uint i = 0; i < receivers.length; i++) { IERC721CreatorCore(_creator).mintExtension(receivers[i], uris[i]); } _minted += receivers.length; }
0.8.7
/** * @notice changes a string to upper case * @param _base string to change */
function upper(string _base) internal pure returns (string) { bytes memory _baseBytes = bytes(_base); for (uint i = 0; i < _baseBytes.length; i++) { bytes1 b1 = _baseBytes[i]; if (b1 >= 0x61 && b1 <= 0x7A) { b1 = bytes1(uint8(b1)-32); } _baseBytes[i] = b1; } return string(_baseBytes); }
0.4.24
/** * @notice Register the token symbol for its particular owner * @notice Once the token symbol is registered to its owner then no other issuer can claim * @notice its ownership. If the symbol expires and its issuer hasn't used it, then someone else can take it. * @param _symbol token symbol * @param _tokenName Name of the token * @param _owner Address of the owner of the token * @param _swarmHash Off-chain details of the issuer and token */
function registerTicker(address _owner, string _symbol, string _tokenName, bytes32 _swarmHash) public whenNotPaused { require(_owner != address(0), "Owner should not be 0x"); require(bytes(_symbol).length > 0 && bytes(_symbol).length <= 10, "Ticker length should always between 0 & 10"); if(registrationFee > 0) require(ERC20(polyToken).transferFrom(msg.sender, this, registrationFee), "Failed transferFrom because of sufficent Allowance is not provided"); string memory symbol = upper(_symbol); require(expiryCheck(symbol), "Ticker is already reserved"); registeredSymbols[symbol] = SymbolDetails(_owner, now, _tokenName, _swarmHash, false); emit LogRegisterTicker (_owner, symbol, _tokenName, _swarmHash, now); }
0.4.24
/** * @notice Check the validity of the symbol * @param _symbol token symbol * @param _owner address of the owner * @param _tokenName Name of the token * @return bool */
function checkValidity(string _symbol, address _owner, string _tokenName) public returns(bool) { string memory symbol = upper(_symbol); require(msg.sender == securityTokenRegistry, "msg.sender should be SecurityTokenRegistry contract"); require(registeredSymbols[symbol].status != true, "Symbol status should not equal to true"); require(registeredSymbols[symbol].owner == _owner, "Owner of the symbol should matched with the requested issuer address"); require(registeredSymbols[symbol].timestamp.add(expiryLimit) >= now, "Ticker should not be expired"); registeredSymbols[symbol].tokenName = _tokenName; registeredSymbols[symbol].status = true; return true; }
0.4.24
/** * @notice Check the symbol is reserved or not * @param _symbol Symbol of the token * @param _owner Owner of the token * @param _tokenName Name of the token * @param _swarmHash off-chain hash * @return bool */
function isReserved(string _symbol, address _owner, string _tokenName, bytes32 _swarmHash) public returns(bool) { string memory symbol = upper(_symbol); require(msg.sender == securityTokenRegistry, "msg.sender should be SecurityTokenRegistry contract"); if (registeredSymbols[symbol].owner == _owner && !expiryCheck(_symbol)) { registeredSymbols[symbol].status = true; return false; } else if (registeredSymbols[symbol].owner == address(0) || expiryCheck(symbol)) { registeredSymbols[symbol] = SymbolDetails(_owner, now, _tokenName, _swarmHash, true); emit LogRegisterTicker (_owner, symbol, _tokenName, _swarmHash, now); return false; } else return true; }
0.4.24
/** * @notice Returns the owner and timestamp for a given symbol * @param _symbol symbol * @return address * @return uint256 * @return string * @return bytes32 * @return bool */
function getDetails(string _symbol) public view returns (address, uint256, string, bytes32, bool) { string memory symbol = upper(_symbol); if (registeredSymbols[symbol].status == true||registeredSymbols[symbol].timestamp.add(expiryLimit) > now) { return ( registeredSymbols[symbol].owner, registeredSymbols[symbol].timestamp, registeredSymbols[symbol].tokenName, registeredSymbols[symbol].swarmHash, registeredSymbols[symbol].status ); }else return (address(0), uint256(0), "", bytes32(0), false); }
0.4.24
/** * @notice To re-initialize the token symbol details if symbol validity expires * @param _symbol token symbol * @return bool */
function expiryCheck(string _symbol) internal returns(bool) { if (registeredSymbols[_symbol].owner != address(0)) { if (now > registeredSymbols[_symbol].timestamp.add(expiryLimit) && registeredSymbols[_symbol].status != true) { registeredSymbols[_symbol] = SymbolDetails(address(0), uint256(0), "", bytes32(0), false); return true; }else return false; } return true; }
0.4.24
// Function 02 - Contribute (Hodl Platform)
function HodlTokens(address tokenAddress, uint256 amount) public contractActive { require(tokenAddress != 0x0); require(amount > 0); if(contractaddress[tokenAddress] = false) { revert(); } ERC20Interface token = ERC20Interface(tokenAddress); require(token.transferFrom(msg.sender, address(this), amount)); uint256 affiliatecomission = mul(amount, affiliate) / 100; // * uint256 nocashback = mul(amount, 28) / 100; // * if (cashbackcode[msg.sender] == 0 ) { uint256 data_amountbalance = mul(amount, 72) / 100; uint256 data_cashbackbalance = 0; address data_referrer = superOwner; cashbackcode[msg.sender] = superOwner; emit onCashbackCode(msg.sender, superOwner); _systemReserves[tokenAddress] = add(_systemReserves[tokenAddress], nocashback); } else { data_amountbalance = sub(amount, affiliatecomission); data_cashbackbalance = mul(amount, cashback) / 100; data_referrer = cashbackcode[msg.sender]; _systemReserves[tokenAddress] = add(_systemReserves[tokenAddress], affiliatecomission); } //--->>> Dont forget to change code // Insert to Database _userSafes[msg.sender].push(_currentIndex); _safes[_currentIndex] = Safe( _currentIndex, amount, now + hodlingTime, msg.sender, tokenAddress, token.symbol(), data_amountbalance, data_cashbackbalance, now, percent, 0, 0, 0, data_referrer); // Update Token Balance, Current Index, CountSafes _totalSaved[tokenAddress] = add(_totalSaved[tokenAddress], amount); _currentIndex++; _countSafes++; emit onHodlTokens(msg.sender, tokenAddress, token.symbol(), amount, now + hodlingTime); }
0.4.25
// Function 05 - Get Data Values
function GetSafe(uint256 _id) public view returns (uint256 id, address user, address tokenAddress, uint256 amount, uint256 endtime, string tokenSymbol, uint256 amountbalance, uint256 lasttime, uint256 percentage, uint256 percentagereceive, uint256 tokenreceive, address referrer) { Safe storage s = _safes[_id]; return(s.id, s.user, s.tokenAddress, s.amount, s.endtime, s.tokenSymbol, s.amountbalance, s.lasttime, s.percentage, s.percentagereceive, s.tokenreceive, s.referrer); }
0.4.25