comment
stringlengths
11
2.99k
function_code
stringlengths
165
3.15k
version
stringclasses
80 values
/// @notice Creates clone of main DAO and migrates an existing DAO to it. /// @param token_ Governing token that needs to migrate to new dao.
function migrate(address token_) public onlyOwner { ITorroDao currentDao = ITorroDao(_pools[token_]); // Create a new clone of main DAO. address daoProxy = createClone(_torroDao); // Initialize it with parameters from existing dao. ITorroDao(daoProxy).initializeCustom( _torroToken, token...
0.6.6
/** * @dev Stakes the specified `amount` of tokens, this will attempt to transfer the given amount from the caller. * It will count the actual number of tokens trasferred as being staked * MUST trigger Staked event. * Returns the number of tokens actually staked **/
function stake(uint256 amount) external override nonReentrant returns (uint256){ require(amount > 0, "Cannot Stake 0"); uint256 previousAmount = IERC20(_token).balanceOf(address(this)); _token.safeTransferFrom( msg.sender, address(this), amount); uint256 transferred = IERC20(_token).bala...
0.8.10
/** * @dev Stakes the specified `amount` of tokens from `staker` on behalf of address `voter`, * this will attempt to transfer the given amount from the caller. * Must be called from an ISTAKINGPROXY contract that has been approved by `staker`. * Tokens will be staked towards the voting power of address `voter` all...
function stakeFor(address voter, address staker, uint256 amount) external override nonReentrant returns (uint256){ require(amount > 0, "Cannot Stake 0"); uint256 previousAmount = IERC20(_token).balanceOf(address(this)); //_token.safeTransferFrom( msg.sender, address(this), amount); ISTAK...
0.8.10
/** * @dev Unstakes the specified `amount` of tokens, this SHOULD return the given amount of tokens to the caller, * MUST trigger Unstaked event. */
function unstake(uint256 amount) external override nonReentrant{ require(amount > 0, "Cannot UnStake 0"); require(amount <= stakes[msg.sender].stakedAmount[msg.sender], "INSUFFICENT TOKENS TO UNSTAKE"); _token.safeTransfer( msg.sender, amount); stakes[msg.sender].totalStake = stakes[msg....
0.8.10
/** * @dev Unstakes the specified `amount` of tokens currently staked by `staker` on behalf of `voter`, * this SHOULD return the given amount of tokens to the calling contract * calling contract is responsible for returning tokens to `staker` if applicable. * MUST trigger Unstaked event. */
function unstakeFor(address voter, address staker, uint256 amount) external override nonReentrant{ require(amount > 0, "Cannot UnStake 0"); require(amount <= stakes[voter].stakedAmount[msg.sender], "INSUFFICENT TOKENS TO UNSTAKE"); //_token.safeTransfer( msg.sender, amount); _token.safeT...
0.8.10
/** * @param _startFundingTime The UNIX time that the BaseTokenSale will be able to start receiving funds * @param _endFundingTime The UNIX time that the BaseTokenSale will stop being able to receive funds * @param _vaultAddress The address that will store the donated funds * @param _tokenAddress Addr...
function BaseTokenSale( uint _startFundingTime, uint _endFundingTime, address _vaultAddress, address _tokenAddress ) public { require(_endFundingTime > now); require(_endFundingTime >= _startFundingTime); require(_vaultAddress != 0); require...
0.4.19
/// @dev `doPayment()` is an internal function that sends the ether that this /// contract receives to the `vault` and creates tokens in the address of the /// `_owner` assuming the BaseTokenSale is still accepting funds /// @param _owner The address that will hold the newly created tokens
function doPayment(address _owner) internal returns(bool success) { //info("step", "enter doPayment"); require(msg.value >= minFunding); require(endFundingTime > now); // Track how much the BaseTokenSale has collected require(totalCollected < maximumFunding); tota...
0.4.19
/// @notice `finalizeSale()` ends the BaseTokenSale. It will generate the platform and team tokens /// and set the controller to the referral fee contract. /// @dev `finalizeSale()` can only be called after the end of the funding period or if the maximum amount is raised.
function finalizeSale() onlyController public { require(now > endFundingTime || totalCollected >= maximumFunding); require(!finalized); //20000 TNB/ETH and 90 percent discount uint256 totalTokens = totalCollected * tokensPerEther * 10**18; if (!tokenContract.generateTokens...
0.4.19
// internal function only ever called from constructor
function _addBeneficiary(address beneficiary, uint256 amount, uint8 divide, uint256 claimFrequency) internal { _vestingAllowances[beneficiary] = amount; _claimFrequency[beneficiary] = claimFrequency; _claimAmounts[beneficiary] = amount.div(divide); _lastClaime...
0.5.0
/// @dev Function that is called when a user or another contract wants to transfer funds . /// @param _to Recipient address /// @param _value Transfer amount in unit /// @param _data the data pass to contract reveiver
function transfer( address _to, uint _value, bytes _data) public isTradable returns (bool success) { require(_to != 0x0); balances[msg.sender] = balanceOf(msg.sender).sub(_value); balances[_to] = balanceOf(_to).add(_value); Transfer(msg.s...
0.4.20
/* solhint-disable code-complexity */
function exp(uint p, uint q, uint precision) public pure returns (uint) { uint n = 0; uint nFact = 1; uint currentP = 1; uint currentQ = 1; uint sum = 0; uint prevSum = 0; while (true) { if (checkMultOverflow(currentP, precision)) return su...
0.4.18
/* solhint-enable code-complexity */
function countLeadingZeros(uint p, uint q) public pure returns (uint) { uint denomator = (uint(1)<<255); for (int i = 255; i >= 0; i--) { if ((q*denomator)/denomator != q) { // overflow denomator = denomator/2; continue; } ...
0.4.18
// log2 for a number that it in [1,2)
function log2ForSmallNumber(uint x, uint numPrecisionBits) public pure returns (uint) { uint res = 0; uint one = (uint(1)<<numPrecisionBits); uint two = 2 * one; uint addition = one; require((x >= one) && (x <= two)); require(numPrecisionBits < 125); fo...
0.4.18
/** * @dev purchase asset token with el. * * This can be used to purchase asset token with Elysia Token (EL). * * Requirements: * - `amount` this contract should have more asset tokens than the amount. * - `amount` msg.sender should have more el than elAmount converted from the amount. */
function purchase(uint256 amount) external override whenNotPaused { _checkBalance(msg.sender, address(this), amount); ExchangeLocalVars memory vars = ExchangeLocalVars({ currencyPrice: eController.getPrice(payment), assetTokenPrice...
0.7.4
/** * @dev refund asset token. * * This can be used to refund asset token with Elysia Token (EL). * * Requirements: * - `amount` msg.sender should have more asset token than the amount. * - `amount` this contract should have more el than elAmount converted from the amount. */
function refund(uint256 amount) external override whenNotPaused { _checkBalance(address(this), msg.sender, amount); ExchangeLocalVars memory vars = ExchangeLocalVars({ currencyPrice: eController.getPrice(payment), assetTokenPrice: ...
0.7.4
/** * @dev check if buyer and seller have sufficient balance. * * This can be used to check balance of buyer and seller before swap. * * Requirements: * - `amount` buyer should have more asset token than the amount. * - `amount` seller should have more el than elAmount converted from the amount. */
function _checkBalance( address buyer, address seller, uint256 amount ) internal view { ExchangeLocalVars memory vars = ExchangeLocalVars({ currencyPrice: eController.getPrice(payment), assetTokenPrice: price }); requi...
0.7.4
/** * @dev Allows the user to deposit some amount of Hydro tokens. Records user/swap data and emits a SwapDeposit event. * @param amount Amount of input tokens to be swapped. */
function swap( uint256 amount) external { require (isActive==true); require(amount > 0, "Input amount must be positive."); uint256 outputAmount = amount; require(outputAmount > 0, "Amount too small."); require(IERC20(Hydro_ADDRESS).transferFrom(msg.sender, Main_ADDRESS, amo...
0.6.12
/** * Mint your signature tokens! * @param name: Minter's name. Whatever the minter wants it to be. Can never be changed. */
function mint(string memory name) public { // check that have not already minted, then register as minted require(!hasMinted[msg.sender], DUPLICATE_MINT_ERROR); hasMinted[msg.sender] = true; uint256 tmpId = nextTokenId; // mint the tokens _mint(msg.sender, tmpId...
0.6.12
/** * Call sign to sign any ERC-721 owned by msg.sender with a signature token, * while also burning your signature token. * * @param nftAddr: address of NFT to be signed * @param nftTokenId: tokenId of NFT to be signed, at nftAddr * @param sigTokenId: signature tokenId to sign with (in this contract) */
function sign( address nftAddr, uint256 nftTokenId, uint256 sigTokenId ) external { // sender must own the NFT to be signed IERC721 ERC721 = IERC721(nftAddr); require(ERC721.ownerOf(nftTokenId) == msg.sender, OWNERSHIP_ERROR); // burn the signature tok...
0.6.12
/** * @notice Mint multiple NFTs * @param to address that new NFTs will belong to * @param tokenIds ids of new NFTs to create * @param preApprove optional account that is pre-approved to move tokens * after token creation. */
function massMint( address to, uint256[] calldata tokenIds, address preApprove ) external onlyOwner { for (uint256 i = 0; i < tokenIds.length; i++) { _mint(to, tokenIds[i]); if (preApprove != address(0)) { _approve(preApprove, tokenIds[i]); ...
0.8.4
/** * @dev Assign `amount_` of privately distributed tokens * to someone identified with `to_` address. * @param to_ Tokens owner * @param group_ Group identifier of privately distributed tokens * @param amount_ Number of tokens distributed with decimals part */
function assignReserved(address to_, uint8 group_, uint amount_) onlyOwner public { require(to_ != address(0) && (group_ & 0x3) != 0); if (group_ == RESERVED_UTILITY_GROUP) { require(block.timestamp >= utilityLockedDate); } // SafeMath will check reserved[group_] >= am...
0.4.18
/** * Constructor * @param _owner The owner of the contract * @param _payee The payee - the account that can collect payments from this contract * @param _paymentInterval Interval for payments, unit: seconds * @param _paymentAmount The amount payee can claim per period, unit: wei * @param _startTime Date an...
function StandingOrder( address _owner, address _payee, uint _paymentInterval, uint _paymentAmount, uint _startTime, string _label ) payable { // Sanity check parameters require(_paymentInterval > 0); require(_paymentAmo...
0.4.15
/** * Determine how much funds payee is entitled to collect * Note that this might be more than actual funds available! * @return Number of wei that payee is entitled to collect */
function getEntitledFunds() constant returns (uint) { // First check if the contract startTime has been reached at all if (now < startTime) { // startTime not yet reached return 0; } // startTime has been reached, so add first payment uint entitle...
0.4.15
/** * Determine how much funds are still owned by owner (not yet reserved for payee) * Note that this can be negative in case contract is not funded enough to cover entitled amount for payee! * @return number of wei belonging owner, negative if contract is missing funds to cover payments */
function getOwnerFunds() constant returns (int) { // Conversion from unsigned int to int will produce unexpected results only for very large // numbers (2^255 and greater). This is about 5.7e+58 ether. // -> There will be no situation when the contract balance (this.balance) will hit this lim...
0.4.15
/** * Collect payment * Can only be called by payee. This will transfer all available funds (see getUnclaimedFunds) to payee * @return amount that has been transferred! */
function collectFunds() onlyPayee returns(uint) { uint amount = getUnclaimedFunds(); if (amount <= 0) { // nothing to collect :-( revert(); } // keep track of collected funds claimedFunds = claimedFunds.add(amount); // create log entry ...
0.4.15
/** * Withdraw requested amount back to owner. * Only funds not (yet) reserved for payee can be withdrawn. So it is not possible for the owner * to withdraw unclaimed funds - They can only be claimed by payee! * Withdrawing funds does not terminate the order, at any time owner can fund it again! * @param amou...
function WithdrawOwnerFunds(uint amount) onlyOwner { int intOwnerFunds = getOwnerFunds(); // this might be negative in case of underfunded contract! if (intOwnerFunds <= 0) { // nothing available to withdraw :-( revert(); } // conversion int -> uint is safe ...
0.4.15
/** * Create a new standing order * The owner of the new order will be the address that called this function (msg.sender) * @param _payee The payee - the account that can collect payments from this contract * @param _paymentInterval Interval for payments, unit: seconds * @param _paymentAmount The amount payee...
function createStandingOrder(address _payee, uint _paymentAmount, uint _paymentInterval, uint _startTime, string _label) returns (StandingOrder) { StandingOrder so = new StandingOrder(msg.sender, _payee, _paymentInterval, _paymentAmount, _startTime, _label); standingOrdersByOwner[msg.sender].push(so);...
0.4.15
// ------------------------------------------------------------------------ // 1,000 LEIA per 1 ETH // ------------------------------------------------------------------------
function () public payable { require(now >= startDate && now <= endDate); uint tokens; if (now <= bonusEnds) { tokens = msg.value * 1200; } else { tokens = msg.value * 1000; } balances[msg.sender] = balances[msg.sender].add(tokens); ...
0.4.18
/** * @param _rate Number of token units a buyer gets per wei * @param _wallet Address where collected funds will be forwarded to * @param _token Address of the token being sold */
function Crowdsale(uint256 _rate, address _wallet, SancojTokenContract _token, address _tokenWallet, address _owner) public { require(_rate > 0); require(_wallet != address(0)); require(_token != address(0)); require(_tokenWallet != address(0)); rate = _rate; wallet = _wallet; token...
0.4.21
/** * @notice Calculates available amount for a claim * @dev A pure function which doesn't reads anything from state * @param _now A timestamp to calculate the available amount * @param _start The vesting period start timestamp * @param _amountPerMember The amount of ERC20 tokens to be distributed to each mem...
function getAvailable( uint256 _now, uint256 _start, uint256 _amountPerMember, uint256 _duration, uint256 _alreadyClaimed ) public pure returns (uint256) { if (_now <= _start) { return 0; } // uint256 vestingEndsAt = _start + _duration; uint256 vestingEndsAt = _s...
0.6.12
/*** Owner Methods ***/
function increaseDurationT(uint256 _newDurationT) external onlyOwner { require(_newDurationT > durationT, "Vesting::increaseDurationT: Too small duration"); require((_newDurationT - durationT) < 180 days, "Vesting::increaseDurationT: Too big duration"); uint256 prevDurationT = durationT; uint256 p...
0.6.12
/** * @notice An active member claims a distributed amount of votes * @dev Caches unclaimed balance per block number which could be used by voting contract * @param _to address to claim votes to */
function claimVotes(address _to) external { Member memory member = members[_to]; require(member.active == true, "Vesting::claimVotes: User not active"); uint256 votes = getAvailableVotes(member.alreadyClaimedVotes); require(block.timestamp <= endT, "Vesting::claimVotes: Vote vesting has ended");...
0.6.12
/** * @notice An active member claims a distributed amount of ERC20 tokens * @param _to address to claim ERC20 tokens to */
function claimTokens(address _to) external { Member memory member = members[msg.sender]; require(member.active == true, "Vesting::claimTokens: User not active"); uint256 bigAmount = getAvailableTokens(member.alreadyClaimedTokens); require(bigAmount > 0, "Vesting::claimTokens: Nothing to claim"); ...
0.6.12
/** * @notice Delegates an already claimed votes amount to the given address * @param _to address to delegate votes */
function delegateVotes(address _to) external { Member memory member = members[msg.sender]; require(_to != address(0), "Vesting::delegateVotes: Can't delegate to 0 address"); require(member.active == true, "Vesting::delegateVotes: msg.sender not active"); address currentDelegate = getVoteUser(msg.s...
0.6.12
/** * @notice Transfers a vested rights for a member funds to another address * @dev A new member won't have any votes for a period between a start timestamp and a current timestamp * @param _to address to transfer a vested right to */
function transfer(address _to) external { Member memory from = members[msg.sender]; Member memory to = members[_to]; uint96 alreadyClaimedTokens = from.alreadyClaimedTokens; uint96 alreadyClaimedVotes = from.alreadyClaimedVotes; require(from.active == true, "Vesting::transfer: From member i...
0.6.12
/// @dev A copy from CVP token, only the event name changed
function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes ) internal { uint32 blockNumber = safe32(block.number, "Vesting::_writeCheckpoint: Block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromB...
0.6.12
/// @notice Gets the amount that Totle needs to give for this order /// @param genericPayload the data for this order in a generic format /// @return amountToGive amount taker needs to give in order to fill the order
function getAmountToGive( bytes genericPayload ) public view onlyTotle whenNotPaused returns (uint256 amountToGive) { bool success; bytes4 functionSelector = selectorProvider.getSelector(this.getAmountToGive.selector); assembly...
0.4.25
/// @notice Perform exchange-specific checks on the given order /// @dev this should be called to check for payload errors /// @param genericPayload the data for this order in a generic format /// @return checksPassed value representing pass or fail
function staticExchangeChecks( bytes genericPayload ) public view onlyTotle whenNotPaused returns (bool checksPassed) { bool success; bytes4 functionSelector = selectorProvider.getSelector(this.staticExchangeChecks.selector); ass...
0.4.25
/// @dev Calculates EIP712 encoding for a hash struct in this EIP712 Domain. /// @param hashStruct The EIP712 hash struct. /// @return EIP712 hash applied to this EIP712 Domain.
function hashEIP712Message(bytes32 hashStruct) internal view returns (bytes32 result) { bytes32 eip712DomainHash = EIP712_DOMAIN_HASH; // Assembly for more efficient computing: // keccak256(abi.encodePacked( // EIP191_HEADER, // EIP7...
0.4.25
/// @dev Calculates EIP712 hash of the order. /// @param order The order structure. /// @return EIP712 hash of the order.
function hashOrder(Order memory order) internal pure returns (bytes32 result) { bytes32 schemaHash = EIP712_ORDER_SCHEMA_HASH; bytes32 makerAssetDataHash = keccak256(order.makerAssetData); bytes32 takerAssetDataHash = keccak256(order.takerAssetData); ...
0.4.25
/// @notice Gets the amount that Totle needs to give for this order /// @param data LibOrder.Order struct containing order values /// @return amountToGive amount taker needs to give in order to fill the order
function getAmountToGive_( OrderData data ) public view onlySelf returns (uint256 amountToGive) { LibOrder.OrderInfo memory orderInfo = exchange.getOrderInfo( getZeroExOrder(data) ); uint makerAssetAvailable = getAssetDataAvailable(d...
0.4.25
/// @notice Perform exchange-specific checks on the given order /// @dev This should be called to check for payload errors /// @param data LibOrder.Order struct containing order values /// @return checksPassed value representing pass or fail
function staticExchangeChecks_( OrderData data ) public view onlySelf returns (bool checksPassed) { // Make sure that: // The order is not expired // Both the maker and taker assets are ERC20 tokens // The taker does not hav...
0.4.25
/// @notice Perform a buy order at the exchange /// @param data LibOrder.Order struct containing order values /// @return amountSpentOnOrder the amount that would be spent on the order /// @return amountReceivedFromOrder the amount that was received from this order
function performBuyOrder_( OrderData data ) public payable onlySelf returns (uint256 amountSpentOnOrder, uint256 amountReceivedFromOrder) { uint256 amountToGiveForOrder = toUint(msg.data, msg.data.length - 32); approveAddress(ERC20_ASSET_PROXY, ...
0.4.25
// utility functions
function uint2str(uint256 _i) internal pure returns (string memory _uintAsString) { if (_i == 0) { return "0"; } uint256 j = _i; uint256 len; while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint256 k = len; while (_i != 0) { k = k - 1; uint8 temp = (48 + uint8(_i ...
0.8.4
/* Restricted functions (owner only) */
function reject(address applicant) public onlyOwner onlyPendingApplication(applicant) { applications[applicant].state = ApplicationState.Rejected; // protection against function reentry on an overriden transfer() function uint contribution = applications[applicant].contr...
0.4.19
/// @notice Add/replace/remove any number of functions and optionally execute /// a function with delegatecall /// @param _diamondCut Contains the facet addresses and function selectors /// @param _init The address of the contract or facet to execute _calldata /// @param _calldata A function call, including fun...
function diamondCut( FacetCut[] calldata _diamondCut, address _init, bytes calldata _calldata ) external override { LibDiamond.enforceIsContractOwner(); LibDiamond.DiamondStorage storage ds = LibDiamond.diamondStorage(); uint256 originalSelectorCount = ds.selec...
0.7.1
/** * @param tokenAmount Amount of tokens to swap with bep2 * @param BNB_Address address of Binance Chain to which to receive the bep2 tokens */
function swap(uint tokenAmount, string memory BNB_Address) public returns(bool) { bool success = token.transferFrom(msg.sender, owner, tokenAmount); if(!success) { revert("Transfer of tokens to Swap contract failed."); } emit Swaped(tokenAmo...
0.5.8
/** * @dev Moves specified amount of tokens from main balance to mining balance * @param _amount An uint256 representing the amount of tokens to transfer to main balance */
function depositToMiningBalance(uint _amount) public { require(balances[msg.sender] >= _amount, "not enough tokens"); require(getCurrentDayDeposited().add(_amount) <= DAY_MINING_DEPOSIT_LIMIT, "Day mining deposit exceeded"); require(miningTotalDeposited.add(_amount) <= TOTAL_MINING_DEPOSIT_LIMIT, "Tota...
0.4.24
/** * @dev Get number of days for reward on mining. Maximum 100 days. * @return An uint256 representing number of days user will get reward for. */
function getDaysForReward() public view returns (uint rewardDaysNum){ if(lastMiningBalanceUpdateTime[msg.sender] == 0) { return 0; } else { uint value = (now - lastMiningBalanceUpdateTime[msg.sender]) / (1 days); if(value > 100) { return 100; } else { return value; } } }
0.4.24
/** * @dev Calculate current mining reward based on total supply of tokens * @return An uint256 representing reward in percents multiplied by 1000000000 */
function getReward(uint _totalSupply) public pure returns (uint rewardPercent){ uint rewardFactor = 1000000 * (10 ** uint256(decimals)); uint decreaseFactor = 41666666; if(_totalSupply < 23 * rewardFactor) { return 2000000000 - (decreaseFactor.mul(_totalSupply.div(rewardFactor))); } if(_totalSupp...
0.4.24
/** * @dev Receive payment in ether and return tokens. */
function buyTokens() payable public { require(msg.value>=getPrice(),'Tx value cannot be lower than price of 1 token'); uint256 amount = msg.value.div(getPrice()); ERC20 erc20 = ERC20(token); require(erc20.balanceOf(address(this))>=amount,"Sorry, token vendor does not possess enough t...
0.5.11
/** * @dev Receive payment in tokens and return ether. * Only usable by accounts which allowed the smart contract to transfer tokens from their account. */
function sellTokens(uint256 _amount) public { require(_amount>0,'You cannot sell 0 tokens'); uint256 ethToSend = _amount.mul(getPrice()); require(address(this).balance>=ethToSend,'Sorry, vendor does not possess enough Ether to trade for your tokens'); ERC20 erc20 = ERC20(token); ...
0.5.11
/** * @notice Update royalty info for collection * @param collection address of the NFT contract * @param setter address that sets the receiver * @param receiver receiver for the royalty fee * @param fee fee (500 = 5%, 1,000 = 10%) */
function updateRoyaltyInfoForCollection( address collection, address setter, address receiver, uint256 fee ) external override onlyOwner { require(fee <= royaltyFeeLimit, "Registry: Royalty fee too high"); _royaltyFeeInfoCollection[collection] = FeeInfo({ ...
0.8.7
/** * @dev Get random number. * @dev Random number calculation depends on block timestamp, * @dev difficulty, number and hash. * * @param min Minimal number. * @param max Maximum number. * @param time Timestamp. * @param difficulty Block difficulty. * @param number Block number. * @param bHash Block...
function randomNumber( uint min, uint max, uint time, uint difficulty, uint number, bytes32 bHash ) public pure returns (uint) { min ++; max ++; uint random = uint(keccak256( time * ...
0.4.24
/** * @dev Start the new game. * @dev Checks ticket price changes, if exists new ticket price the price will be changed. * @dev Checks game status changes, if exists request for changing game status game status * @dev will be changed. */
function startGame() internal { require(isActive); game = block.number; if (newPrice != 0) { ticketPrice = newPrice; newPrice = 0; } if (toogleStatus) { isActive = !isActive; toogleStatus = false; } emit...
0.4.24
/** * @dev Pick the winner. * @dev Check game players, depends on player count provides next logic: * @dev - if in the game is only one player, by game rules the whole jackpot * @dev without commission returns to him. * @dev - if more than one player smart contract randomly selects one player, * @dev calc...
function pickTheWinner() internal { uint winner; uint toPlayer; if (players[game].length == 1) { toPlayer = jackpot[game]; players[game][0].transfer(jackpot[game]); winner = 0; } else { winner = randomNumber( 0, ...
0.4.24
/** * @dev Checks if the player is in referral system. * @dev Sending earned ether to partners. * * @param partner Partner address. * @param referral Player address. */
function processReferralSystem(address partner, address referral) internal { address partnerRef = referralInstance.getPartnerByReferral(referral); if (partner != address(0) || partnerRef != address(0)) { if (partnerRef == address(0)) { referralInstance.add...
0.4.24
/** * @dev Sending earned ether to partners. * * @param referral Player address. */
function transferToPartner(address referral) internal { address partner = referralInstance.getPartnerByReferral(referral); if (partner != address(0)) { uint sum = getPartnerAmount(partner); if (sum != 0) { partner.transfer(sum); paidToPartner...
0.4.24
/** * @dev Sending earned ether to sales partners. * * @param partner Partner address. */
function transferToSalesPartner(address partner) internal { address salesPartner = referralInstance.getSalesPartner(partner); if (salesPartner != address(0)) { uint sum = getSalesPartnerAmount(partner); if (sum != 0) { salesPartner.transfer(sum); ...
0.4.24
/** * Uses the Curve protocol to convert the wbtc asset into to mixed renwbtc token. */
function mixFromWBTC() internal { uint256 wbtcBalance = IERC20(wbtc).balanceOf(address(this)); if (wbtcBalance > 0) { IERC20(wbtc).safeApprove(curve, 0); IERC20(wbtc).safeApprove(curve, wbtcBalance); // we can accept 0 as minimum because this is called only by a trusted role uint25...
0.5.16
/** * Uses the Curve protocol to convert the mixed token back into the wbtc asset. If it cannot * acquire the limit amount, it will acquire the maximum it can. */
function mixToWBTC(uint256 wbtcLimit) internal { uint256 mixTokenBalance = IERC20(mixToken).balanceOf(address(this)); // this is the maximum number of wbtc we can get for our mixed token uint256 wbtcMaximumAmount = wbtcValueFromMixToken(mixTokenBalance); if (wbtcMaximumAmount == 0) { return...
0.5.16
/** * Withdraws an wbtc asset from the strategy to the vault in the specified amount by asking * by removing imbalanced liquidity from the Curve protocol. The rest is deposited back to the * Curve protocol pool. If the amount requested cannot be obtained, the method will get as much * as we have. */
function withdrawToVault(uint256 amountWbtc) external restricted { // withdraw all from gauge Gauge(gauge).withdraw(Gauge(gauge).balanceOf(address(this))); // convert the mix to WBTC, but get at most amountWbtc mixToWBTC(amountWbtc); // we can transfer the asset to the vault uint256 actual...
0.5.16
/** * Withdraws all assets from the vault. */
function withdrawAllToVault() external restricted { // withdraw all from gauge Gauge(gauge).withdraw(Gauge(gauge).balanceOf(address(this))); // convert the mix to WBTC, we want the entire balance mixToWBTC(uint256(~0)); // we can transfer the asset to the vault uint256 actualBalance = IERC...
0.5.16
/** * Invests all wbtc assets into our mixToken vault. */
function investAllUnderlying() internal { // convert the entire balance not yet invested into mixToken first mixFromWBTC(); // then deposit into the mixToken vault uint256 mixTokenBalance = IERC20(mixToken).balanceOf(address(this)); if (mixTokenBalance > 0) { IERC20(mixToken).safeAppro...
0.5.16
/** * Salvages a token. We cannot salvage mixToken tokens, CRV, or wbtc assets. */
function salvage(address recipient, address token, uint256 amount) public onlyGovernance { // To make sure that governance cannot come in and take away the coins require(!unsalvagableTokens[token], "token is defined as not salvageable"); IERC20(token).safeTransfer(recipient, amount); }
0.5.16
/** * Returns the wbtc invested balance. The is the wbtc amount in this stragey, plus the gauge * amount of the mixed token converted back to wbtc. */
function investedUnderlyingBalance() public view returns (uint256) { uint256 gaugeBalance = Gauge(gauge).balanceOf(address(this)); uint256 wbtcBalance = IERC20(wbtc).balanceOf(address(this)); if (gaugeBalance == 0) { // !!! if we have 0 balance in gauge, the conversion to wbtc reverts in Curve ...
0.5.16
/** * Claims the CRV crop, converts it to WBTC/renWBTC on Uniswap */
function claimAndLiquidateCrv() internal { if (!sell) { // Profits can be disabled for possible simplified and rapid exit emit ProfitsNotCollected(); return; } Mintr(mintr).mint(gauge); // claiming rewards and liquidating them uint256 crvBalance = IERC20(crv).balanceOf(addr...
0.5.16
/** * Allows user to destroy a specified token * This would allow a user to claim his prize for the destroyed token * @param _tokenId uint256 ID of the token */
function claimReward(uint256 _tokenId) public { require(winningTokenId > 0, "The is not winner yet!"); require(_tokenId == winningTokenId, "This token is not the winner!"); ensureAddressIsTokenOwner(msg.sender, _tokenId); winnerAddress = msg.sender; ...
0.5.7
/** * Allows the buyer of at least the number of WLC tokens, specified in WLCRewardAmount * to receive a DCC as a bonus. * This can only be called by the deployed WLC contract, by the address specified in WLCAdress * @param _boughtWLCAmount uint256 the number of bought WLC tokens * @param _owner address the a...
function getWLCReward(uint256 _boughtWLCAmount, address _owner) public returns (uint256 _remaining) { if (WLCAdress != address(0) && WLCRewardAmount > 0 && _boughtWLCAmount >= WLCRewardAmount) { require(WLCAdress == msg.sender, "You cannot invoke this function directly!"); ...
0.5.7
/** * Allows an onwer of WLC token to excange it for DCC token * This can only be called by the deployed WLC contract, by the address specified in WLCAdress * @param _owner address the address of the exchanger */
function getForWLC(address _owner) public { require(WLCAdress == msg.sender, "You cannot invoke this function directly!"); require(nextTokenId <= totalTokenSupply, "Not enough tokens are available for purchase!"); _addTokensToAddress(_owner, 1); emit Buy...
0.5.7
/** * @dev apply BDR exchange Abc * @param _value uint256 amount of BDR to exchange * @return uint256 the sequence of exchange request */
function applyExchangeToken(uint256 _value) public whenNotPaused returns (uint256) { uint256 trxSeq = applyCounts; require(exchangeTrx[trxSeq].from == address(0),"trxSeq already exist"); require(balances[msg.sender] >= _value); exchangeTrx[trxSeq].executed = false; exchangeT...
0.5.4
/** * @dev signer confirms one exchange request * @param _trxSeq uint256 the Sequence of exchange request */
function confirmExchangeTrx(uint256 _trxSeq) public onlySigner { require(exchangeTrx[_trxSeq].from != address(0),"_trxSeq not exist"); require(exchangeTrx[_trxSeq].signers.length < requestSigners,"trx already has enough signers"); require(exchangeTrx[_trxSeq].executed == false,"trx already ex...
0.5.4
/** * @dev signer cancel confirmed exchange request * @param _trxSeq uint256 the Sequence of exchange request */
function cancelConfirm(uint256 _trxSeq) public onlySigner { require(exchangeTrx[_trxSeq].from != address(0),"_trxSeq not exist"); require(isConfirmer(_trxSeq, msg.sender),"Signer didn't confirm"); require(exchangeTrx[_trxSeq].executed == false,"trx already executed"); uint256 len = e...
0.5.4
/** * @dev execute exchange request which confirmed by enough signers * @param _trxSeq uint256 the Sequence of exchange request */
function executeExchangeTrx(uint256 _trxSeq) public whenNotPaused{ address from = exchangeTrx[_trxSeq].from; uint256 value = exchangeTrx[_trxSeq].value; require(from != address(0),"trxSeq not exist"); require(exchangeTrx[_trxSeq].executed == false,"trxSeq has executed"); req...
0.5.4
/** * @dev Contract initialization * @param _ownerAddress address Token owner address * @param _startTime uint256 Crowdsale end time * */
function SmartCityToken(address _ownerAddress, uint256 _startTime) public { owner = _ownerAddress; // token Owner startTime = _startTime; // token Start Time unlockOwnerDate = startTime + 2 years; balances[owner] = totalSupply; // all tokens are initially allocated to token owner ...
0.4.18
/** * @dev Workaround for vulnerability described here: https://docs.google.com/document/d/1YLPtQxZu1UAvO9cZ1O2RPXBbT0mooh4DYKjA_jp-RLM */
function _approve(address _spender, uint256 _value) internal returns(bool success) { require((_value == 0) || (allowances[msg.sender][_spender] == 0)); allowances[msg.sender][_spender] = _value; // Set spender allowance Approval(msg.sender, _spender, _value); // Trigger Approval event ...
0.4.18
/** * @dev Burns all the tokens which has not been sold during ICO */
function burn() public { if (!burned && now > startTime) { uint256 diff = balances[owner].sub(amountReserved); // Get the amount of unsold tokens balances[owner] = amountReserved; totalSupply = totalSupply.sub(diff); // Reduce total provision number burne...
0.4.18
/** * @notice Deploys token * @param _symbol Token symbol * @param _name Token name * @param _decimals Token decimals * @param _totalSupply Token total supply * @param _tokenOwner Owner of the deployed token * @param _tokenRegistry Token Registry */
function deployToken( string calldata _symbol, string calldata _name, uint8 _decimals, uint256 _totalSupply, address _tokenOwner, address _tokenRegistry, bool _saveHoldersHistory, address _allowable, address _getter ) onlyOwn...
0.5.12
// Stake SYRUP tokens to StakingPool
function deposit(uint256 _amount) public { PoolInfo storage pool = poolInfo[0]; UserInfo storage user = userInfo[msg.sender]; // require (_amount.add(user.amount) <= maxStaking, 'exceed max stake'); updatePool(0); if (user.amount > 0) { uint256 pending = use...
0.6.12
/// @notice Reserved for owner to mint
function ownerMint(address to, uint amount) public onlyOwner { uint mintsRemaining = ownerMintsRemaining; /// @notice Owner mints cannot be minted after the maximum has been reached require(mintsRemaining > 0, "Groupies: Max owner mint limit reached"); if (amount > mintsRemaining){ amount = min...
0.8.6
/** * @notice Adds given role to the user * @param _user Address of user wallet * @param _role Role name * param _withApproval Flag whether we need an approval */
function addRole( address _user, bytes32 _role, bool _withApproval, bool _withSameRole, bytes32[] storage roleNames, mapping(bytes32 => mapping(address => AddressList.Data)) storage roleUserData, mapping(bytes32 => address[]) storage roleUsers, map...
0.5.12
/** * @notice Requests to add given role to the user * @param _user Address of user wallet * @param _role Role name */
function addRoleRequest( address _user, bytes32 _role, bool _withSameRole, mapping(bytes32 => mapping(address => AddressList.Data)) storage roleUserData, mapping(address => mapping(bytes32 => address)) storage addRoleInitiators ) public { _checkRo...
0.5.12
/** * @notice Removes given role from the user * @param _user Address of user wallet * @param _role Role name */
function removeRole( address _user, bytes32 _role, bool _withApproval, bool _withSameRole, bytes32[] storage roleNames, mapping(bytes32 => mapping(address => AddressList.Data)) storage roleUserData, mapping(bytes32 => address[]) storage roleUsers, ...
0.5.12
/** * @notice Requests to remove given role to the user * @param _user Address of user wallet * @param _role Role name */
function removeRoleRequest( address _user, bytes32 _role, bool _withSameRole, mapping(bytes32 => mapping(address => AddressList.Data)) storage roleUserData, mapping(address => mapping(bytes32 => address)) storage removeRoleInitiators ) public { _c...
0.5.12
/** * @notice Checks whether the role has been already added * @param _role Role name */
function isExists( bytes32 _role, bytes32[] storage roleNames ) private view returns (bool) { for (uint i = 0; i < roleNames.length; i++) { if (_role == roleNames[i]) { return true; } } return fa...
0.5.12
/** * @dev Override the base isApprovedForAll(address owner, address operator) to allow us to * specifically allow the opense operator to transfer tokens * * @param owner_ owner address * @param operator_ operator address * @return bool if the operator is approved for all */
function isApprovedForAll( address owner_, address operator_ ) public view override returns (bool) { // Whitelist OpenSea proxy contract for easy trading. ProxyRegistry proxyRegistry = ProxyRegistry(_proxyAddress); if (address(proxyRegistry.proxies(owner_)) == operator_...
0.8.0
// View function to see pending JINs on frontend.
function pendingJin(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accJinPerShare = pool.accJinPerShare; uint256 lpSupply = pool.lpToken.bala...
0.6.12
/// @notice Withdraws the tokens that have been deposited /// Only `withdrawer` can call this. /// @param _to The address where the withdrawn tokens should go
function withdraw(address payable _to) external { uint256 balance = token.balanceOf(address(this)); require(msg.sender == withdrawer, "the caller is not the withdrawer"); require(block.timestamp >= release_at || service_registry.deprecated(), "deposit not released yet"); require(balance ...
0.8.7
/** * Set fee parameters. * * @param _fixedFee fixed fee in token units * @param _minVariableFee minimum variable fee in token units * @param _maxVariableFee maximum variable fee in token units * @param _variableFeeNumerator variable fee numerator */
function setFeeParameters ( uint256 _fixedFee, uint256 _minVariableFee, uint256 _maxVariableFee, uint256 _variableFeeNumerator) public delegatable payable { require (msg.sender == owner); require (_minVariableFee <= _maxVariableFee); require (_variableFeeNumerator <= MAX_FEE_NUMERAT...
0.4.26
/** * Calculate fee for transfer of given number of tokens. * * @param _amount transfer amount to calculate fee for * @return fee for transfer of given amount */
function calculateFee (uint256 _amount) public delegatable view returns (uint256 _fee) { require (_amount <= MAX_TOKENS_COUNT); _fee = safeMul (_amount, variableFeeNumerator) / FEE_DENOMINATOR; if (_fee < minVariableFee) _fee = minVariableFee; if (_fee > maxVariableFee) _fee = maxVariableFee;...
0.4.26
/** * @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. * @param beneficiary Address performing the token purchase * @param weiAmount Value in wei involved in the purchase */
function _preValidatePurchase(address beneficiary, uint256 weiAmount) internal { require(beneficiary != address(0), "beneficiary is the zero address"); require(weiAmount != 0, "weiAmount is 0"); require(weiAmount >= minDeposit && weiAmount <= maxDeposit, "Amount should be within 0.05 eth and ...
0.8.7
/** * * @dev Kickstart the ICO by setting the opning time and manually seting the closing time to a week after the opening time. */
function startIco( uint256 _openingTime) external onlyAdmin { require(_openingTime >= block.timestamp, "JPEGVaultICO: opening time is before current block timestamp"); require(openingTime == 0 || hasClosed(), "You can't restart ICO in the middle of sales period"); openingTime = _openingTime; ...
0.8.7
// This is used to prevent stack too deep errors
function calculateFee( int128 _gLiq, int128[] memory _bals, Storage.Curve storage curve, int128[] memory _weights ) internal view returns (int128 psi_) { int128 _beta = curve.beta; int128 _delta = curve.delta; psi_ = calculateFee(_gLiq, _bals, _beta, _delta, ...
0.7.3
// Admin calls this function.
function setPoolInfo( uint256 _poolId, address _vault, IERC20 _token, uint256 _allocPoint, bool _withUpdate ) external onlyOwner { if (_withUpdate) { massUpdatePools(); } if (_poolId >= poolLength) { poolLength = _p...
0.6.12
// ===== Admin functions ===== //
function setFeeSchedule( uint _flatFee, uint _contractFee, uint _exerciseFee, uint _settlementFee ) public auth { flatFee = _flatFee; contractFee = _contractFee; exerciseFee = _exerciseFee; settlementFee = _settlementFee; require(co...
0.4.22
// ========== PUT OPTIONS EXCHANGE ========== //
function putBtoWithSto( uint amount, uint expiration, bytes32 nonce, uint price, uint size, uint strike, uint validUntil, bytes32 r, bytes32 s, uint8 v ) public hasFee(amount) { bytes32 h = keccak...
0.4.22
// Deposit tokens to Pool for Token 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.accTokenPerShare).div(1e12).sub(user.rew...
0.6.12
// DepositFor tokens to Pool for Token allocation.
function depositFor(address _beneficiary, uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_beneficiary]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accTokenPerShar...
0.6.12
/** * @dev Store the PublicKey info for a Name * @param _id The ID of the Name * @param _defaultKey The default public key for this Name * @param _writerKey The writer public key for this Name * @return true on success */
function initialize(address _id, address _defaultKey, address _writerKey) external isName(_id) keyNotTaken(_defaultKey) keyNotTaken(_writerKey) onlyFactory returns (bool) { require (!isExist(_id)); keyToNameId[_defaultKey] = _id; if (_defaultKey != _writerKey) { keyToNameId[_writerKey] = _...
0.5.4
/** * @dev Add publicKey to list for a Name * @param _id The ID of the Name * @param _key The publicKey to be added * @param _nonce The signed uint256 nonce (should be Name's current nonce + 1) * @param _signatureV The V part of the signature * @param _signatureR The R part of the signature ...
function addKey(address _id, address _key, uint256 _nonce, uint8 _signatureV, bytes32 _signatureR, bytes32 _signatureS ) public isName(_id) onlyAdvocate(_id) keyNotTaken(_key) senderNameNotCompromised { require (_nonce == _nameFactory.nonces(_id).add(1)); bytes32 _hash = keccak256(abi.encodePacke...
0.5.4