comment
stringlengths
11
2.99k
function_code
stringlengths
165
3.15k
version
stringclasses
80 values
/* function withdraw() external { require (approvedRecipients) sendAmount = whatever was calculated (bool success, ) = msg.sender.call{value: sendAmount}(""); require(success, "Transaction Unsuccessful"); } */
function ownerMint(address _to, uint256 qty) external onlyOwner { require((numberMinted + qty) > numberMinted, "Math overflow error"); require((numberMinted + qty) < totalTokens, "Cannot fill order"); uint256 mintSeedValue = numberMinted; //Store the starting value of the mint batch...
0.8.7
// Emergency drain in case of a bug // Adds all funds to owner to refund people // Designed to be as simple as possible // function emergencyDrain24hAfterLiquidityGenerationEventIsDone() public onlyOwner { // require(contractStartTimestamp.add(4 days) < block.timestamp, "Liquidity generation grace period still ongo...
function emergencyDrain24hAfterLiquidityGenerationEventIsDone() public onlyOwner { require(contractStartTimestamp.add(6 days) < block.timestamp, "Liquidity generation grace period still ongoing"); // About 24h after liquidity generation happens // (bool success, ) = msg.sender.call.value(addre...
0.6.12
//@dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
function tokenURI(uint256 tokenId) external view returns (string memory){ require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory tokenuri; if (_hideTokens) { //redirect to mystery box tokenuri = string(abi.enco...
0.8.7
/// @notice Computes the amount of liquidity received for a given amount of token0 and price range /// @dev Calculates amount0 * (sqrt(upper) * sqrt(lower)) / (sqrt(upper) - sqrt(lower)) /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the sec...
function getLiquidityForAmount0( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint256 amount0 ) internal pure returns (uint128 liquidity) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); uint256 intermediate = FullMa...
0.7.6
/// @notice Computes the maximum amount of liquidity received for a given amount of token0, token1, the current /// pool prices and the prices at the tick boundaries /// @param sqrtRatioX96 A sqrt price representing the current pool prices /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @...
function getLiquidityForAmounts( uint160 sqrtRatioX96, uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint256 amount0, uint256 amount1 ) internal pure returns (uint128 liquidity) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX9...
0.7.6
/// @notice Computes the amount of token1 for a given amount of liquidity and a price range /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param liquidity The liquidity being valued /// @return amount1 The amoun...
function getAmount1ForLiquidity( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity ) internal pure returns (uint256 amount1) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); return FullMath.mulDiv(liqu...
0.7.6
/** * @notice Setup mint * @param _mintStart Unix timestamp when minting should be opened * @param _mintEnd Unix timestamp when minting should be closed * @param _mintFee Minting fee * @param _mintLimit Limits how many tokens can be minted */
function setupMint( uint256 _mintStart, uint256 _mintEnd, uint256 _mintFee, uint256 _mintLimit ) external onlyOwner { require(_mintStart < _mintEnd, "wrong mint end"); require(mintLimit == 0 || _mintLimit == mintLimit, "change mint limit not allowed"); mintSta...
0.8.10
/// @dev Wrapper around `LiquidityAmounts.getAmountsForLiquidity()`. /// @param pool Uniswap V3 pool /// @param liquidity The liquidity being valued /// @param _tickLower The lower tick of the range /// @param _tickUpper The upper tick of the range /// @return amounts of token0 and token1 that corresponds to liquidity
function amountsForLiquidity( IUniswapV3Pool pool, uint128 liquidity, int24 _tickLower, int24 _tickUpper ) internal view returns (uint256, uint256) { //Get current price from the pool (uint160 sqrtRatioX96, , , , , , ) = pool.slot0(); return ...
0.7.6
/// @dev Wrapper around `LiquidityAmounts.getLiquidityForAmounts()`. /// @param pool Uniswap V3 pool /// @param amount0 The amount of token0 /// @param amount1 The amount of token1 /// @param _tickLower The lower tick of the range /// @param _tickUpper The upper tick of the range /// @return The maximum amount of liqui...
function liquidityForAmounts( IUniswapV3Pool pool, uint256 amount0, uint256 amount1, int24 _tickLower, int24 _tickUpper ) internal view returns (uint128) { //Get current price from the pool (uint160 sqrtRatioX96, , , , , , ) = pool.slot0(); ...
0.7.6
/// @dev Amounts of token0 and token1 held in contract position. /// @param pool Uniswap V3 pool /// @param _tickLower The lower tick of the range /// @param _tickUpper The upper tick of the range /// @return amount0 The amount of token0 held in position /// @return amount1 The amount of token1 held in position
function positionAmounts(IUniswapV3Pool pool, int24 _tickLower, int24 _tickUpper) internal view returns (uint256 amount0, uint256 amount1) { //Compute position key bytes32 positionKey = PositionKey.compute(address(this), _tickLower, _tickUpper); //Get Positi...
0.7.6
/// @dev Amount of liquidity in contract position. /// @param pool Uniswap V3 pool /// @param _tickLower The lower tick of the range /// @param _tickUpper The upper tick of the range /// @return liquidity stored in position
function positionLiquidity(IUniswapV3Pool pool, int24 _tickLower, int24 _tickUpper) internal view returns (uint128 liquidity) { //Compute position key bytes32 positionKey = PositionKey.compute(address(this), _tickLower, _tickUpper); //Get liquidity stored in po...
0.7.6
/// @dev Rounds tick down towards negative infinity so that it's a multiple /// of `tickSpacing`.
function floor(int24 tick, int24 tickSpacing) internal pure returns (int24) { int24 compressed = tick / tickSpacing; if (tick < 0 && tick % tickSpacing != 0) compressed--; return compressed * tickSpacing; }
0.7.6
/// @dev Gets amounts of token0 and token1 that can be stored in range of upper and lower ticks /// @param pool Uniswap V3 pool /// @param amount0Desired The desired amount of token0 /// @param amount1Desired The desired amount of token1 /// @param _tickLower The lower tick of the range /// @param _tickUpper The upper ...
function amountsForTicks(IUniswapV3Pool pool, uint256 amount0Desired, uint256 amount1Desired, int24 _tickLower, int24 _tickUpper) internal view returns(uint256 amount0, uint256 amount1) { uint128 liquidity = liquidityForAmounts(pool, amount0Desired, amount1Desired, _tickLower, _tickUpper); (amount0,...
0.7.6
// Check price has not moved a lot recently. This mitigates price // manipulation during rebalance and also prevents placing orders // when it's too volatile.
function checkDeviation(IUniswapV3Pool pool, int24 maxTwapDeviation, uint32 twapDuration) internal view { (, int24 currentTick, , , , , ) = pool.slot0(); int24 twap = getTwap(pool, twapDuration); int24 deviation = currentTick > twap ? currentTick - twap : twap - currentTick; require(...
0.7.6
/// @dev Fetches time-weighted average price in ticks from Uniswap pool for specified duration
function getTwap(IUniswapV3Pool pool, uint32 twapDuration) internal view returns (int24) { uint32 _twapDuration = twapDuration; uint32[] memory secondsAgo = new uint32[](2); secondsAgo[0] = _twapDuration; secondsAgo[1] = 0; (int56[] memory tickCumulatives, ) = pool.observe...
0.7.6
/** * @notice Withdraws liquidity in share proportion to the Sorbetto's totalSupply. * @param pool Uniswap V3 pool * @param tickLower The lower tick of the range * @param tickUpper The upper tick of the range * @param totalSupply The amount of total shares in existence * @param share to burn * @param to R...
function burnLiquidityShare( IUniswapV3Pool pool, int24 tickLower, int24 tickUpper, uint256 totalSupply, uint256 share, address to ) internal returns (uint256 amount0, uint256 amount1) { require(totalSupply > 0, "TS"); uint128 liquidityInPool ...
0.7.6
/** * @notice Withdraws exact amount of liquidity * @param pool Uniswap V3 pool * @param tickLower The lower tick of the range * @param tickUpper The upper tick of the range * @param liquidity to burn * @param to Recipient of amounts * @return amount0 Amount of token0 withdrawed * @return amount1 Amount...
function burnExactLiquidity( IUniswapV3Pool pool, int24 tickLower, int24 tickUpper, uint128 liquidity, address to ) internal returns (uint256 amount0, uint256 amount1) { uint128 liquidityInPool = pool.positionLiquidity(tickLower, tickUpper); require(li...
0.7.6
/** * @notice Withdraws all liquidity in a range from Uniswap pool * @param pool Uniswap V3 pool * @param tickLower The lower tick of the range * @param tickUpper The upper tick of the range */
function burnAllLiquidity( IUniswapV3Pool pool, int24 tickLower, int24 tickUpper ) internal { // Burn all liquidity in this range uint128 liquidity = pool.positionLiquidity(tickLower, tickUpper); if (liquidity > 0) { pool.burn(tickLower, ...
0.7.6
/** * @notice Returns imageIds for a range of token ids * @param startTokenId first token id in the range * @param rangeLength length of the range * @return imgIds array of image ids */
function imageIdsForRange(uint256 startTokenId, uint256 rangeLength) public view returns (bytes32[] memory imgIds) { imgIds = new bytes32[](rangeLength); uint256 i = startTokenId; for (uint256 c = 0; c < rangeLength; c++) { imgIds[c] = imageId(i); i++; } }
0.8.10
/// @notice Gets the next sqrt price given a delta of token0 /// @dev Always rounds up, because in the exact output case (increasing price) we need to move the price at least /// far enough to get the desired output amount, and in the exact input case (decreasing price) we need to move the /// price less in order to no...
function getNextSqrtPriceFromAmount0RoundingUp( uint160 sqrtPX96, uint128 liquidity, uint256 amount, bool add ) internal pure returns (uint160) { // we short circuit amount == 0 because the result is otherwise not guaranteed to equal the input price if (amount ...
0.7.6
/// @notice Gets the next sqrt price given a delta of token1 /// @dev Always rounds down, because in the exact output case (decreasing price) we need to move the price at least /// far enough to get the desired output amount, and in the exact input case (increasing price) we need to move the /// price less in order to ...
function getNextSqrtPriceFromAmount1RoundingDown( uint160 sqrtPX96, uint128 liquidity, uint256 amount, bool add ) internal pure returns (uint160) { // if we're adding (subtracting), rounding down requires rounding the quotient down (up) // in both cases, avoid ...
0.7.6
//initialize strategy
function init() external onlyGovernance { require(!finalized, "F"); finalized = true; int24 baseThreshold = tickSpacing * ISorbettoStrategy(strategy).tickRangeMultiplier(); ( , int24 currentTick, , , , , ) = pool.slot0(); int24 tickFloor = PoolVariables.floor(currentTick, ti...
0.7.6
/// @inheritdoc ISorbettoFragola
function deposit( uint256 amount0Desired, uint256 amount1Desired ) external payable override nonReentrant checkDeviation updateVault(msg.sender) returns ( uint256 shares, uint256 amount0, uint256...
0.7.6
/// @dev collects fees from the pool
function _earnFees() internal returns (uint256 userCollect0, uint256 userCollect1) { // Do zero-burns to poke the Uniswap pools so earned fees are updated pool.burn(tickLower, tickUpper, 0); (uint256 collect0, uint256 collect1) = pool.collect( address(...
0.7.6
/// @notice Pull in tokens from sender. Called to `msg.sender` after minting liquidity to a position from IUniswapV3Pool#mint. /// @dev In the implementation you must pay to the pool for the minted liquidity. /// @param amount0 The amount of token0 due to the pool for the minted liquidity /// @param amount1 The amount ...
function uniswapV3MintCallback( uint256 amount0, uint256 amount1, bytes calldata data ) external { require(msg.sender == address(pool), "FP"); MintCallbackData memory decoded = abi.decode(data, (MintCallbackData)); if (amount0 > 0) pay(token0, decoded.payer, ms...
0.7.6
/// @notice Called to `msg.sender` after minting swaping from IUniswapV3Pool#swap. /// @dev In the implementation you must pay to the pool for swap. /// @param amount0 The amount of token0 due to the pool for the swap /// @param amount1 The amount of token1 due to the pool for the swap /// @param _data Any data passed ...
function uniswapV3SwapCallback( int256 amount0, int256 amount1, bytes calldata _data ) external { require(msg.sender == address(pool), "FP"); require(amount0 > 0 || amount1 > 0); // swaps entirely within 0-liquidity regions are not supported SwapCallbackData me...
0.7.6
/** * @notice Used to withdraw accumulated protocol fees. */
function collectProtocolFees( uint256 amount0, uint256 amount1 ) external nonReentrant onlyGovernance updateVault(address(0)) { require(accruedProtocolFees0 >= amount0, "A0F"); require(accruedProtocolFees1 >= amount1, "A1F"); uint256 balance0 = _balance0(); ...
0.7.6
/** * @notice Used to withdraw accumulated user's fees. */
function collectFees(uint256 amount0, uint256 amount1) external nonReentrant updateVault(msg.sender) { UserInfo storage user = userInfo[msg.sender]; require(user.token0Rewards >= amount0, "A0R"); require(user.token1Rewards >= amount1, "A1R"); uint256 balance0 = _balance0(); ...
0.7.6
// Updates user's fees reward
function _updateFeesReward(address account) internal { uint liquidity = pool.positionLiquidity(tickLower, tickUpper); if (liquidity == 0) return; // we can't poke when liquidity is zero (uint256 collect0, uint256 collect1) = _earnFees(); token0PerShareStored = _to...
0.7.6
/** * Convienience function for the Curator to calculate the required amount of Wei * that needs to be transferred to this contract. */
function requiredEndowment() constant returns (uint endowment) { uint sum = 0; for(uint i=0; i<trustedProposals.length; i++) { uint proposalId = trustedProposals[i]; DAO childDAO = whiteList[proposalId]; sum += childDAO.totalSupply(); } return sum; }
0.3.6
/** * Function call to withdraw ETH by burning childDao tokens. * @param proposalId The split proposal ID which created the childDao * @dev This requires that the token-holder authorizes this contract's address using the approve() function. */
function withdraw(uint proposalId) external { //Check the token balance uint balance = whiteList[proposalId].balanceOf(msg.sender); // Transfer childDao tokens first, then send Ether back in return if (!whiteList[proposalId].transferFrom(msg.sender, this, balance) || !msg.sender.send(balance)) ...
0.3.6
/// @notice Notify the new reward to the LGV4 /// @param _tokenReward token to notify /// @param _amount amount to notify
function _notifyReward(address _tokenReward, uint256 _amount) internal { require(gauge != address(0), "gauge not set"); require(_amount > 0, "set an amount > 0"); uint256 balanceBefore = IERC20(_tokenReward).balanceOf(address(this)); require(balanceBefore >= _amount, "amount not enough")...
0.8.7
/// @notice A function that rescue any ERC20 token /// @param _token token address /// @param _amount amount to rescue /// @param _recipient address to send token rescued
function rescueERC20( address _token, uint256 _amount, address _recipient ) external { require(msg.sender == governance, "!gov"); require(_amount > 0, "set an amount > 0"); require(_recipient != address(0), "can't be zero address"); IERC20(_token).safeTransfer(_recipient, _amount); emit ERC...
0.8.7
/** * Get the possibleResultsCount of an Event.Output as uint. * Should be changed in a future version to use an Oracle function that directly returns possibleResultsCount instead of receive the whole eventOutputs structure */
function getEventOutputMaxUint(address oracleAddress, uint eventId, uint outputId) private view returns (uint) { (bool isSet, string memory title, uint possibleResultsCount, uint eventOutputType, string memory announcement, uint decimals) = OracleContract(oracleAddress).eventOutputs(eventId,outputId); ...
0.5.2
/** * Settle fees of Oracle and House for a bet */
function settleBetFees(uint betId) onlyOwner public { require(bets[betId].isCancelled || bets[betId].isOutcomeSet,"Bet should be cancelled or has an outcome"); require(bets[betId].freezeDateTime <= now,"Bet payments are freezed"); if (!housePaid[betId] && houseEdgeAmountForBet[betId] > 0) { ...
0.5.2
/** * @dev Use this function to withdraw released tokens * */
function withdrawTrb() external { uint256 _availableBalance = ITellor(tellorAddress).balanceOf(address(this)); if(_availableBalance > maxAmount){ maxAmount = _availableBalance; } uint256 _releasedAmount = maxAmount * (block.timestamp - lastReleaseTime)/(86400* 365 * 2); //2 y...
0.8.3
// We use parameter '_tokenId' as the divisibility
function transfer(address _to, uint256 _tokenId) external { // Requiring this contract be tradable require(tradable == true); require(_to != address(0)); require(msg.sender != _to); // Take _tokenId as divisibility uint256 _divisibility = _tokenId; ...
0.4.18
// Transfer gift to a new owner.
function assignSharedOwnership(address _to, uint256 _divisibility) onlyOwner external returns (bool success) { require(_to != address(0)); require(msg.sender != _to); require(_to != address(this)); // Requir...
0.4.18
/** * @dev mints a given amount of tokens for a given recipient * * requirements: * * - the caller must have the ROLE_ADMIN privileges, and the contract must not be paused */
function mint(address recipient, uint256 amount) external onlyRole(ROLE_ADMIN) whenNotPaused { if (recipient == address(0)) { revert InvalidRecipient(); } if (amount == 0) { revert InvalidAmount(); } _token.safeTransfer(recipient, amount); _totalSu...
0.8.9
/** * @notice Allow user's OpenSea proxy accounts to enable gas-less listings * @notice Eenable extendibility for the project * @param _owner The active owner of the token * @param _operator The origin of the action being called */
function isApprovedForAll(address _owner, address _operator) public view override returns (bool) { ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddr); if ( (address(proxyRegistry.proxies(_owner)) == _operator && !addressToRegis...
0.8.9
/// @notice only l1Target can update greeting
function cudlToL2(address _cudler, uint256 _amount) public { // To check that message came from L1, we check that the sender is the L1 contract's L2 alias. require( msg.sender == AddressAliasHelper.applyL1ToL2Alias(l1Target), "Greeting only updateable by L1" ); /...
0.8.2
// burn supply, not negative rebase
function verysmashed() external { require(!state.paused, "still paused"); require(state.lastAttack + state.attackCooldown < block.timestamp, "Dogira coolingdown"); uint256 rLp = state.accounts[state.addresses.pool].rTotal; uint256 amountToDeflate = (rLp / (state.divisors.tokenLPBurn...
0.8.1
// positive rebase
function dogebreath() external { require(!state.paused, "still paused"); require(state.lastAttack + state.attackCooldown < block.timestamp, "Dogira coolingdown"); uint256 rate = ratio(); uint256 target = state.balances.burned == 0 ? state.balances.tokenSupply : state.balances.burned;...
0.8.1
// disperse amount to all holders
function wow(uint256 amount) external { address sender = msg.sender; uint256 rate = ratio(); require(!getExcluded(sender), "Excluded addresses can't call this function"); require(amount * rate < state.accounts[sender].rTotal, "too much"); state.accounts[sender].rTotal -= (am...
0.8.1
// award community members from the treasury
function muchSupport(address awardee, uint256 multiplier) external onlyAdminOrOwner { uint256 n = block.timestamp; require(!state.paused, "still paused"); require(state.accounts[awardee].lastShill + 1 days < n, "nice shill but need to wait"); require(!getExcluded(awardee), "excluded ...
0.8.1
// burn amount, for cex integration?
function suchburn(uint256 amount) external { address sender = msg.sender; uint256 rate = ratio(); require(!getExcluded(sender), "Excluded addresses can't call this function"); require(amount * rate < state.accounts[sender].rTotal, "too much"); state.accounts[sender].rTotal -...
0.8.1
/** * @dev See {IERC721Enumerable-totalSupply}. * @dev Burned tokens are calculated here, use _totalMinted() if you want to count just minted tokens. */
function totalSupply() public view returns (uint256) { // Counter underflow is impossible as _burnCounter cannot be incremented // more than _currentIndex - _startTokenId() times unchecked { return _currentIndex - _burnCounter - _startTokenId(); } }
0.8.4
/** * Returns the total amount of tokens minted in the contract. */
function _totalMinted() internal view returns (uint256) { // Counter underflow is impossible as _currentIndex does not decrement, // and it is initialized to _startTokenId() unchecked { return _currentIndex - _startTokenId(); } }
0.8.4
/** * @dev CraftyCrowdsale constructor sets the token, period and exchange rate * @param _token The address of Crafty Token. * @param _preSaleStart The start time of pre-sale. * @param _preSaleEnd The end time of pre-sale. * @param _saleStart The start time of sale. * @param _saleEnd The end time of sale. ...
function CraftyCrowdsale(address _token, uint256 _preSaleStart, uint256 _preSaleEnd, uint256 _saleStart, uint256 _saleEnd, uint256 _rate) public { require(_token != address(0)); require(_preSaleStart < _preSaleEnd && _preSaleEnd < _saleStart && _saleStart < _saleEnd); require(_rate > 0); ...
0.4.18
/** * @dev Function used to buy tokens */
function buyTokens() public saleIsOn whenNotPaused payable { require(msg.sender != address(0)); require(msg.value >= 20 finney); uint256 weiAmount = msg.value; uint256 currentRate = getRate(weiAmount); // calculate token amount to be created uint256 newTokens = ...
0.4.18
/** * @dev Function used to set wallets and enable the sale. * @param _etherWallet Address of ether wallet. * @param _teamWallet Address of team wallet. * @param _advisorWallet Address of advisors wallet. * @param _bountyWallet Address of bounty wallet. * @param _fundWallet Address of fund wallet. */
function setWallets(address _etherWallet, address _teamWallet, address _advisorWallet, address _bountyWallet, address _fundWallet) public onlyOwner inState(State.BEFORE_START) { require(_etherWallet != address(0)); require(_teamWallet != address(0)); require(_advisorWallet != address(0)); ...
0.4.18
/** * @dev Get exchange rate based on time and amount. * @param amount Amount received. * @return An uint256 representing the exchange rate. */
function getRate(uint256 amount) internal view returns (uint256) { if(now < preSaleEnd) { require(amount >= 6797 finney); if(amount <= 8156 finney) return rate.mul(105).div(100); if(amount <= 9515 finney) return rate.mul(1055).div(1000)...
0.4.18
/// @notice Transfer `_value` tokens from sender's account /// `msg.sender` to provided account address `_to`. /// @notice This function is disabled during the funding. /// @dev Required state: Operational /// @param _to The address of the tokens recipient /// @param _value The amount of token to be transferred /// @re...
function transfer(address _to, uint256 _value) public returns (bool) { // Abort if not in Operational state. var senderBalance = balances[msg.sender]; if (senderBalance >= _value && _value > 0) { senderBalance -= _value; balances[msg.sender] = senderBalance...
0.4.19
//this method is responsible for taking all fee where fee is require to be deducted.
function _tokenTransfer(address sender, address recipient, uint256 amount) private { if(recipient==uniswapV2Pair) { setAllFees(_saleTaxFee, _saleLiquidityFee, _saleTreasuryFee, _saleMarketingFee); } if(_isExcludedFromFee[sender] || _isExcludedFr...
0.8.9
/** * @dev SavingsandLoans Constructor * Mints the initial supply of tokens, this is the hard cap, no more tokens will be minted. * Allocate the tokens to the foundation wallet, issuing wallet etc. */
function SavingsandLoans() public { // Mint initial supply of tokens. All further minting of tokens is disabled totalSupply_ = INITIAL_SUPPLY; // Transfer all initial tokens to msg.sender balances[msg.sender] = INITIAL_SUPPLY; Transfer(0x0, msg.sender, INITIAL_SUPPLY); }
0.4.19
// we use this to clone our original strategy to other vaults
function cloneConvex3CrvRewards( address _vault, address _strategist, address _rewardsToken, address _keeper, uint256 _pid, address _curvePool, string memory _name ) external returns (address newStrategy) { require(isOriginal); // Cop...
0.6.12
/* ========== KEEP3RS ========== */
function harvestTrigger(uint256 callCostinEth) public view override returns (bool) { // trigger if we want to manually harvest if (forceHarvestTriggerOnce) { return true; } // harvest if we have a profit to claim if (cl...
0.6.12
// convert our keeper's eth cost into want
function ethToWant(uint256 _ethAmount) public view override returns (uint256) { uint256 callCostInWant; if (_ethAmount > 0) { address[] memory ethPath = new address[](2); ethPath[0] = address(weth); ethPath[1] = address(da...
0.6.12
// These functions are useful for setting parameters of the strategy that may need to be adjusted. // Set optimal token to sell harvested funds for depositing to Curve. // Default is DAI, but can be set to USDC or USDT as needed by strategist or governance.
function setOptimal(uint256 _optimal) external onlyAuthorized { if (_optimal == 0) { crvPath[2] = address(dai); convexTokenPath[2] = address(dai); if (hasRewards) { rewardsPath[2] = address(dai); } optimal = 0; } else if...
0.6.12
// Use to add or update rewards
function updateRewards(address _rewardsToken) external onlyGovernance { // reset allowance to zero for our previous token if we had one if (address(rewardsToken) != address(0)) { rewardsToken.approve(sushiswap, uint256(0)); } // update with our new token, use dai as defa...
0.6.12
/** * @dev Public function for purchasing {num} amount of tokens. Checks for current price. * Calls mint() for minting processs * @param _to recipient of the NFT minted * @param _num number of NFTs minted (Max is 20) */
function buy(address _to, uint256 _num) public payable { require(!salePaused, "Sale hasn't started"); require(_num < (maxMint+1),"You can mint a maximum of 20 NFTPs at a time"); require(msg.value >= price * _num,"Ether amount sent is not correct"); mint(_to, _num);...
0.8.4
/** * @dev Public function for purchasing presale {num} amount of tokens. Requires whitelistEligible() * Calls mint() for minting processs * @param _to recipient of the NFT minted * @param _num number of NFTs minted (Max is 20) */
function presale(address _to, uint256 _num) public payable { require(!presalePaused, "Presale hasn't started"); require(whitelistEligible(_to), "You're not eligible for the presale"); require(_num < (maxMint+1),"You can mint a maximum of 20 NFTPs at a time"); require(...
0.8.4
/** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an in...
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold ...
0.5.1
/** Increases the number of drag-along tokens. Requires minter to deposit an equal amount of share tokens */
function wrap(address shareholder, uint256 amount) public noOfferPending() { require(active, "Contract not active any more."); require(wrapped.balanceOf(msg.sender) >= amount, "Share balance not sufficient"); require(wrapped.allowance(msg.sender, address(this)) >= amount, "Share allowance not...
0.5.10
/** @dev Function to start drag-along procedure * This can be called by anyone, but there is an upfront payment. */
function initiateAcquisition(uint256 pricePerShare) public { require(active, "An accepted offer exists"); uint256 totalEquity = IShares(getWrappedContract()).totalShares(); address buyer = msg.sender; require(totalSupply() >= totalEquity.mul(MIN_DRAG_ALONG_QUOTA).div(10000), "This ...
0.5.10
// Get your money back before the raffle occurs
function getRefund() public { uint refund = 0; for (uint i = 0; i < totalTickets; i++) { if (msg.sender == contestants[i].addr && raffleId == contestants[i].raffleId) { refund += pricePerTicket; contestants[i] = Contestant(address(0), 0); ...
0.4.16
// Refund everyone's money, start a new raffle, then pause it
function endRaffle() public { if (msg.sender == feeAddress) { paused = true; for (uint i = 0; i < totalTickets; i++) { if (raffleId == contestants[i].raffleId) { TicketRefund(raffleId, contestants[i].addr, i); contestants[i]...
0.4.16
/** * Pay from sender to receiver a certain amount over a certain amount of time. **/
function paymentCreate(address payable _receiver, uint256 _time) public payable { // Verify that value has been sent require(msg.value > 0); // Verify the time is non-zero require(_time > 0); payments.push(Payment({ sender: msg.sender, receiver: _receiver, timestamp: block....
0.5.0
/** * Return the wei owed on a payment at the current block timestamp. **/
function paymentWeiOwed(uint256 index) public view returns (uint256) { requirePaymentIndexInRange(index); Payment memory payment = payments[index]; // Calculate owed wei based on current time and total wei owed/paid return max(payment.weiPaid, payment.weiValue * min(block.timestamp - payment.timesta...
0.5.0
/** * Public functions for minting. */
function mint(uint256 amount) public payable { uint256 totalIssued = _tokenIds.current(); require(msg.value == amount*price && saleStart && totalIssued.add(amount) <= maxSupply && amount <= maxMint); if(accesslistSale) { require(Accesslist[msg.sender]); require(Wallets[ms...
0.8.4
/* * Money management. */
function withdraw() public payable onlyOwner { // Splits uint256 saraPay = (address(this).balance / 100) * 15; uint256 teamPay = (address(this).balance / 1000) * 415; uint256 communityPay = (address(this).balance / 100) * 2; // Payouts require(payable(sara).send(saraPay...
0.8.4
/** *@dev Token Creator - This function is called by the factory contract and creates new tokens *for the user *@param _supply amount of DRCT tokens created by the factory contract for this swap *@param _owner address *@param _swap address */
function createToken(TokenStorage storage self,uint _supply, address _owner, address _swap) public{ require(msg.sender == self.factory_contract); //Update total supply of DRCT Tokens self.total_supply = self.total_supply.add(_supply); //Update the total balance of the owner ...
0.4.24
/** *@dev Called by the factory contract, and pays out to a _party *@param _party being paid *@param _swap address */
function pay(TokenStorage storage self,address _party, address _swap) public{ require(msg.sender == self.factory_contract); uint party_balance_index = self.swap_balances_index[_swap][_party]; require(party_balance_index > 0); uint party_swap_balance = self.swap_balances[_swap][party_...
0.4.24
/** *@dev Removes the address from the swap balances for a swap, and moves the last address in the *swap into their place *@param _remove address of prevous owner *@param _swap address used to get last addrss of the swap to replace the removed address */
function removeFromSwapBalances(TokenStorage storage self,address _remove, address _swap) internal { uint last_address_index = self.swap_balances[_swap].length.sub(1); address last_address = self.swap_balances[_swap][last_address_index].owner; //If the address we want to remove is the final a...
0.4.24
/** *@dev ERC20 compliant transfer function *@param _to Address to send funds to *@param _amount Amount of token to send *@return true for successful */
function transfer(TokenStorage storage self, address _to, uint _amount) public returns (bool) { require(isWhitelisted(self,_to)); uint balance_owner = self.user_total_balances[msg.sender]; if ( _to == msg.sender || _to == address(0) || _amount == 0 || ...
0.4.24
/** *@dev ERC20 compliant transferFrom function *@param _from address to send funds from (must be allowed, see approve function) *@param _to address to send funds to *@param _amount amount of token to send *@return true for successful */
function transferFrom(TokenStorage storage self, address _from, address _to, uint _amount) public returns (bool) { require(isWhitelisted(self,_to)); uint balance_owner = self.user_total_balances[_from]; uint sender_allowed = self.allowed[_from][msg.sender]; if ( _to == _...
0.4.24
/** *@dev Allows a user to deploy a new swap contract, if they pay the fee *@param _start_date the contract start date *@return new_contract address for he newly created swap address and calls *event 'ContractCreation' */
function deployContract(uint _start_date) public payable returns (address) { require(msg.value >= fee && isWhitelisted(msg.sender)); require(_start_date % 86400 == 0); address new_contract = deployer.newContract(msg.sender, user_contract, _start_date); contracts.push(new_contract); ...
0.4.24
/** *@dev Deploys DRCT tokens for given start date *@param _start_date of contract */
function deployTokenContract(uint _start_date) public{ address _token; require(_start_date % 86400 == 0); require(long_tokens[_start_date] == address(0) && short_tokens[_start_date] == address(0)); _token = new DRCT_Token(); token_dates[_token] = _start_date; long_t...
0.4.24
/** *@dev Deploys new tokens on a DRCT_Token contract -- called from within a swap *@param _supply The number of tokens to create *@param _party the address to send the tokens to *@param _start_date the start date of the contract *@returns ltoken the address of the created DRCT long tokens *@returns s...
function createToken(uint _supply, address _party, uint _start_date) public returns (address, address, uint) { require(created_contracts[msg.sender] == _start_date); address ltoken = long_tokens[_start_date]; address stoken = short_tokens[_start_date]; require(ltoken != address(0) &&...
0.4.24
/** *@dev Allows for a transfer of tokens to _to *@param _to The address to send tokens to *@param _amount The amount of tokens to send */
function transfer(address _to, uint _amount) public returns (bool) { if (balances[msg.sender] >= _amount && _amount > 0 && balances[_to] + _amount > balances[_to]) { balances[msg.sender] = balances[msg.sender] - _amount; balances[_to] = balances[_to] + _amount; ...
0.4.24
/** *@dev Allows an address with sufficient spending allowance to send tokens on the behalf of _from *@param _from The address to send tokens from *@param _to The address to send tokens to *@param _amount The amount of tokens to send */
function transferFrom(address _from, address _to, uint _amount) public returns (bool) { if (balances[_from] >= _amount && allowed[_from][msg.sender] >= _amount && _amount > 0 && balances[_to] + _amount > balances[_to]) { balances[_from] = balances[_from] - _amount; ...
0.4.24
/// @inheritdoc IRaribleSecondarySales
function getFeeRecipients(uint256 tokenId) public view override returns (address payable[] memory recipients) { // using ERC2981 implementation to get the recipient & amount (address recipient, uint256 amount) = royaltyInfo(tokenId, 10000); if (amount != 0) { ...
0.8.4
/** * @notice batch received */
function onERC1155BatchReceived(address _operator, address _from, uint256[] calldata _ids, uint256[] calldata _amounts, bytes calldata _data) external nonReentrant returns(bytes4) { require(msg.sender == address(nft), "DrawCard: only accept self nft"); require(_ids.length == _amounts.length,"DrawCard: i...
0.6.12
/** * @notice when card is ready for init */
function init() public onlyOperator{ require(!isInit,"DrawCard: already init!"); for (uint256 i = 2; i <= 6; i++) { /* token 2 - 5 is 1000 piece */ require(nft.balanceOf(address(this),i) == INIT_BALANCE_B,"DrawCard: cards value not right!"); } /* token 1 ...
0.6.12
/** * @notice draw card functions * @param time draw card time * @param seed seed for produce a random number */
function drawCard(uint256 time, uint256 seed) public whenNotPaused nonReentrant { require(isInit,"DrawCard: not init yet!"); require(time > 0 && time <= MAX_DRAW_COUNT,"DrawCard: draw card time not good!"); require(time <= countCard(),"DrawCard: not enough card!"); uint256 costMee = DRA...
0.6.12
/** * @notice transfer cards to deal address for exchange id 1 card */
function exchangeCard1(uint256 number) public whenNotPaused nonReentrant{ require(number > 0, "DrawCard: can not exchange 1 card 0 piece!"); require(nft.balanceOf(address(this),1) >= number,"DrawCard: not enought card 1 for exchange!"); uint256[] memory ids = new uint256[](5); uint25...
0.6.12
/** * Transfers `amount` tokens from `from` address to `to` * the sender needs to have allowance for this operation * @param from - address to take tokens from * @param to - address to send tokens to * @param amount - amount of tokens to send * @return success - `true` if the transfer was succesful, `fal...
function transferFrom (address from, address to, uint256 amount) returns (bool success) { if (balances[from] < amount) return false; if(allowed[from][msg.sender] < amount) return false; if(amount == 0) return false; if(balances[to] + am...
0.4.15
/// @inheritdoc Variety
function plant(address, bytes32[] memory) external view override onlySower returns (uint256) { // this ensure that noone, even Sower, can directly mint tokens on this contract // they can only be created through the wrapping method revert('No direct pl...
0.8.4
/// @notice Slugify a name (tolower and replace all non 0-9az by -) /// @param str the string to keyIfy /// @return the key
function slugify(string memory str) public pure returns (string memory) { bytes memory strBytes = bytes(str); bytes memory lowerCase = new bytes(strBytes.length); uint8 charCode; bytes1 char; for (uint256 i; i < strBytes.length; i++) { char = strBytes[i]; ...
0.8.4
/// @dev allows to set a name internally. /// checks that the name is valid and not used, else throws /// @param tokenId the token to name /// @param seedlingName the name
function _setName(uint256 tokenId, string memory seedlingName) internal { bytes32 slugBytes; // if the name is not empty, require that it's valid and not used if (bytes(seedlingName).length > 0) { require(isNameValid(seedlingName) == true, 'Invalid name.'); // also requ...
0.8.4
//Starts a new calculation epoch // Because averge since start will not be accurate
function startNewEpoch() public { for (uint256 _pid = 0; _pid < poolInfo.length; _pid++) { require( poolInfo[_pid].epochCalculationStartBlock + 50000 < block.number, "New epoch not ready yet" ); // About a week poolIn...
0.6.12
// Add a new token pool. Can only be called by the owner. // Note contract owner is meant to be a governance contract allowing NERD governance consensus
function add( uint256 _allocPoint, IERC20 _token, bool _withUpdate ) public onlyOwner { require( isTokenPairValid(address(_token)), "One of the paired tokens must be NERD" ); if (_withUpdate) { massUpdatePools(); ...
0.6.12
//return value is /1000
function getPenaltyFactorForEarlyUnlockers(uint256 _pid, address _addr) public view returns (uint256) { uint256 lpReleaseStart = getLpReleaseStart(_pid, _addr); if (lpReleaseStart == 0 || block.timestamp < lpReleaseStart) return 1000; uint256 weeks...
0.6.12
// Update reward vairables for all pools. Be careful of gas spending!
function massUpdatePools() public { console.log("Mass Updating Pools"); uint256 length = poolInfo.length; uint256 allRewards; for (uint256 pid = 0; pid < length; ++pid) { allRewards = allRewards.add(updatePool(pid)); } pendingRewards = pendingRewards....
0.6.12
// ---- // Function that adds pending rewards, called by the NERD token. // ----
function updatePendingRewards() public { uint256 newRewards = nerd.balanceOf(address(this)).sub(nerdBalance); if (newRewards > 0) { nerdBalance = nerd.balanceOf(address(this)); // If there is no change the balance didn't change pendingRewards = pendingRewards.add(newRewards...
0.6.12
// Deposit tokens to NerdVault for NERD allocation.
function deposit(uint256 _pid, uint256 _originAmount) public { claimLPTokensToFarmingPool(msg.sender); PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; massUpdatePools(); // Transfer pending tokens // to user u...
0.6.12
// Test coverage // [x] Does user get the deposited amounts? // [x] Does user that its deposited for update correcty? // [x] Does the depositor get their tokens decreased
function depositFor( address _depositFor, uint256 _pid, uint256 _originAmount ) public { claimLPTokensToFarmingPool(_depositFor); // requires no allowances PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_depositFor]; ...
0.6.12
// Test coverage // [x] Does allowance decrease? // [x] Do oyu need allowance // [x] Withdraws to correct address
function withdrawFrom( address owner, uint256 _pid, uint256 _amount ) public { claimLPTokensToFarmingPool(owner); PoolInfo storage pool = poolInfo[_pid]; require( pool.allowance[owner][msg.sender] >= _amount, "withdraw: insufficient al...
0.6.12
// Low level withdraw function
function _withdraw( uint256 _pid, uint256 _amount, address from, address to ) internal { PoolInfo storage pool = poolInfo[_pid]; //require(pool.withdrawable, "Withdrawing from this pool is disabled"); UserInfo storage user = userInfo[_pid][from]; ...
0.6.12
// function that lets owner/governance contract // approve allowance for any token inside this contract // This means all future UNI like airdrops are covered // And at the same time allows us to give allowance to strategy contracts. // Upcoming cYFI etc vaults strategy contracts will se this function to manage and fa...
function setStrategyContractOrDistributionContractAllowance( address tokenAddress, uint256 _amount, address contractAddress ) public onlySuperAdmin { require( isContract(contractAddress), "Recipent is not a smart contract, BAD" ); requ...
0.6.12