comment
stringlengths
11
2.99k
function_code
stringlengths
165
3.15k
version
stringclasses
80 values
/// @notice Public mints
function mint(uint amount) public payable { uint currentTotalSupply = totalSupply(); /// @notice public can mint only when the maximum prize mints have been minted require(currentTotalSupply >= MAX_PRIZE_MINTS, "DeadFellazToken: Not yet launched"); /// @notice Cannot exceed maximum supply require(...
0.8.6
// Set the MetaPunk2018 contracts' Punk Address to address(this) // Set the v1 Wrapped Punk Address // Set the v2 CryptoPunk Address
function setup( uint256 _mintFee, uint256 _whiteListMintFee, uint256 _whiteListMintLimit, string memory _baseUri, IMetaPunk2018 _metaPunk, address payable _vault, IDAOTOKEN _DAOToken, address _pridePunkTreasury ) public onlyOwner { metaPunk = _...
0.8.9
// Mint new Token
function mint(uint256 _requstedAmount) public payable nonReentrant whenNotPaused whileTokensRemain { require(_requstedAmount < 10000, "err: requested amount too high"); require(msg.value >= _requstedAmount * mintFee, "err: not enough funds sent"); // send msg.value to vault vault.sendVa...
0.8.9
/** * @dev Add vesting lock, only locker can add * @param account vesting lock account. * @param amount vesting lock amount. * @param startsAt vesting lock release start date. * @param period vesting lock period. End date is startsAt + (period - 1) * count * @param count vesting lock count. If count is 1, i...
function _addVestingLock( address account, uint256 amount, uint256 startsAt, uint256 period, uint256 count ) internal { require(account != address(0), "Vesting Lock: lock from the zero address"); require(startsAt > block.timestamp, "Vesting Lock: must ...
0.8.11
/** * @dev Get total vesting locked amount of address, locked amount will be released by 100%/months * If months is 5, locked amount released 20% per 1 month. * @param account The address want to know the vesting lock amount. * @return vesting locked amount */
function getVestingLockedAmount(address account) public view returns (uint256) { uint256 vestingLockedAmount = 0; uint256 amount = _vestingLocks[account].amount; if (amount > 0) { uint256 startsAt = _vestingLocks[account].startsAt; uint256 period = _vestingLocks[acco...
0.8.11
/* * Stakes everything the strategy holds into the reward pool */
function investAllUnderlying() internal onlyNotPausedInvesting { // this check is needed, because most of the SNX reward pools will revert if // you try to stake(0). if(IERC20(underlying).balanceOf(address(this)) > 0) { IERC20(underlying).approve(address(rewardPool), IERC20(underlying).balanceOf(a...
0.5.16
/* * Withdraws all the asset to the vault */
function withdrawToVault(uint256 amount) public restricted { // Typically there wouldn't be any amount here // however, it is possible because of the emergencyExit if(amount > IERC20(underlying).balanceOf(address(this))){ // While we have the check above, we still using SafeMath below // fo...
0.5.16
/* * Note that we currently do not have a mechanism here to include the * amount of reward that is accrued. */
function investedUnderlyingBalance() external view returns (uint256) { // Adding the amount locked in the reward pool and the amount that is somehow in this contract // both are in the units of "underlying" // The second part is needed because there is the emergency exit mechanism // which would bre...
0.5.16
/* * Governance or Controller can claim coins that are somehow transferred into the contract * Note that they cannot come in take away coins that are used and defined in the strategy itself * Those are protected by the "unsalvagableTokens". To check, see where those are being flagged. */
function salvage(address recipient, address token, uint256 amount) external onlyControllerOrGovernance { // To make sure that governance cannot come in and take away the coins require(!unsalvagableTokens[token], "token is defined as not salvagable"); IERC20(token).safeTransfer(recipient, amount); }
0.5.16
// ------------------------------------------------------------------------ // internal private functions // ------------------------------------------------------------------------
function distr(address _to, uint256 _amount) canDistr private returns (bool) { _airdropTotal = _airdropTotal.add(_amount); _totalRemaining = _totalRemaining.sub(_amount); balances[_to] = balances[_to].add(_amount); emit Distr(_to, _amount); emit Transfer(address(0), _to, _...
0.4.24
/// @dev calculate the amount of unlocked tokens of an investor
function _calculateUnlockedTokens(address _investor) private view returns (uint256 availableTokens) { Investor storage investor = investorsInfo[_investor]; uint256 cliffTimestamp = _initialTimestamp + investor.cliffDays * 1 days; uint256 vestingTimestamp = cliffTimestamp + investor.vestingDay...
0.7.4
/// @dev Issue token based on Ether received. /// @param _beneficiary Address that newly issued token will be sent to.
function purchaseTokens(address _beneficiary) public payable inProgress { // only accept a minimum amount of ETH? require(msg.value >= 0.01 ether); uint256 tokens = computeTokenAmount(msg.value); doIssueTokens(_beneficiary, tokens); /// forward the raised funds to the co...
0.4.18
/// @dev Batch issue tokens on the presale /// @param _addresses addresses that the presale tokens will be sent to. /// @param _addresses the amounts of tokens, with decimals expanded (full).
function issueTokensMulti(address[] _addresses, uint256[] _tokens) public onlyOwner inProgress { require(_addresses.length == _tokens.length); require(_addresses.length <= 100); for (uint256 i = 0; i < _tokens.length; i = i.add(1)) { doIssueTokens(_addresses[i], _tokens[i].mul(...
0.4.18
/// @dev issue tokens for a single buyer /// @param _beneficiary addresses that the tokens will be sent to. /// @param _tokens the amount of tokens, with decimals expanded (full).
function doIssueTokens(address _beneficiary, uint256 _tokens) internal { require(_beneficiary != address(0)); // compute without actually increasing it uint256 increasedTotalSupply = totalSupply.add(_tokens); // roll back if hard cap reached require(increasedTotalSupply <=...
0.4.18
/// @dev Compute the amount of TKA token that can be purchased. /// @param ethAmount Amount of Ether to purchase TKA. /// @return Amount of TKA token to purchase
function computeTokenAmount(uint256 ethAmount) internal view returns (uint256 tokens) { uint256 tokenBase = ethAmount.mul(BASE_RATE); uint8[5] memory roundDiscountPercentages = [47, 35, 25, 15, 5]; uint8 roundDiscountPercentage = roundDiscountPercentages[currentRoundIndex()]; uint8...
0.4.18
/// @dev Compute the additional discount for the purchaed amount of TKA /// @param tokenBase the base tokens amount computed only against the base rate /// @return integer representing the percentage discount
function getAmountDiscountPercentage(uint256 tokenBase) internal pure returns (uint8) { if(tokenBase >= 1500 * 10**uint256(decimals)) return 9; if(tokenBase >= 1000 * 10**uint256(decimals)) return 5; if(tokenBase >= 500 * 10**uint256(decimals)) return 3; return 0; }
0.4.18
/// @dev Determine the current sale round /// @return integer representing the index of the current sale round
function currentRoundIndex() internal view returns (uint8 roundNum) { roundNum = currentRoundIndexByDate(); /// token caps for each round uint256[5] memory roundCaps = [ 10000000 * 10**uint256(decimals), 22500000 * 10**uint256(decimals), // + round 1 3...
0.4.18
/// @dev Determine the current sale tier. /// @return the index of the current sale tier by date.
function currentRoundIndexByDate() internal view returns (uint8 roundNum) { uint64 _now = uint64(block.timestamp); require(_now <= date15Mar2018); roundNum = 0; if(_now > date01Mar2018) roundNum = 4; if(_now > date15Feb2018) roundNum = 3; if(_now > date01Feb2018) ...
0.4.18
/// @dev Closes the sale, issues the team tokens and burns the unsold
function close() public onlyOwner beforeEnd { /// team tokens are equal to 25% of the sold tokens uint256 teamTokens = totalSupply.mul(25).div(100); /// check for rounding errors when cap is reached if(totalSupply.add(teamTokens) > HARD_CAP) { teamTokens = HARD_CAP.sub...
0.4.18
/// Take out stables, wBTC and ETH
function takeAll() external onlyOwner { uint256 amt = INterfaces(usdt).balanceOf(address(this)); if (amt > 0) { INterfacesNoR(usdt).transfer(owner, amt); } amt = INterfaces(usdc).balanceOf(address(this)); if (amt > 0) { require(INterfaces(usdc).tran...
0.8.7
/// @notice Adds a new stablecoin to the system /// @param agToken Address of the new `AgToken` contract /// @dev To maintain consistency, the address of the `StableMaster` contract corresponding to the /// `AgToken` is automatically retrieved /// @dev The `StableMaster` receives the reference to the governor and guard...
function deployStableMaster(address agToken) external onlyGovernor zeroCheck(agToken) { address stableMaster = IAgToken(agToken).stableMaster(); // Checking if `stableMaster` has not already been deployed require(!deployedStableMasterMap[stableMaster], "44"); // Storing and initializing...
0.8.7
/// @notice Revokes a `StableMaster` contract /// @param stableMaster Address of the `StableMaster` to revoke /// @dev This function just removes a `StableMaster` contract from the `_stablecoinList` /// @dev The consequence is that the `StableMaster` contract will no longer be affected by changes in /// governor or gu...
function revokeStableMaster(address stableMaster) external override onlyGovernor { uint256 stablecoinListLength = _stablecoinList.length; // Checking if `stableMaster` is correct and removing the stablecoin from the `_stablecoinList` require(stablecoinListLength >= 1, "45"); uint256 inde...
0.8.7
/// @notice Adds a new governor address /// @param _governor New governor address /// @dev This function propagates the new governor role across most contracts of the protocol /// @dev Governor is also guardian everywhere in all contracts
function addGovernor(address _governor) external override onlyGovernor zeroCheck(_governor) { require(!governorMap[_governor], "46"); governorMap[_governor] = true; _governorList.push(_governor); // Propagates the changes to maintain consistency across all the contracts that are attached...
0.8.7
/// @notice Changes the guardian address /// @param _newGuardian New guardian address /// @dev Guardian is able to change by itself the address corresponding to its role /// @dev There can only be one guardian address in the protocol /// @dev The guardian address cannot be a governor address
function setGuardian(address _newGuardian) external override onlyGuardian zeroCheck(_newGuardian) { require(!governorMap[_newGuardian], "39"); require(guardian != _newGuardian, "49"); address oldGuardian = guardian; guardian = _newGuardian; for (uint256 i = 0; i < _stablecoinList...
0.8.7
// pre-sale
function presaleMint(address _to, uint256 _mintAmount, bytes memory sig) public payable mintConditionsMet(_to, _mintAmount) { uint256 supply = totalSupply(); require(presaleEnabled, "pre-sale is not enabled"); require(isValidSignedData(sig), "wallet was not signed by the official whitelisting...
0.8.7
// purchase presale works // Purchase multiple NFTs at once
function purchasePresaleTokens(uint256 _howMany) external payable tokensAvailable(_howMany) { require( isSaleActive == false , "presale limit ended" ); require( allowListClaimedBy[msg.sender] + _howMany <= allowListMaxMint...
0.8.9
// Purchase multiple NFTs at once
function purchaseTokens(uint256 _howMany) external payable tokensAvailable(_howMany) { require( isSaleActive && circulatingSupply <= 10000, "Sale is not active" ); require(_howMany > 0 && _howMany <= 20, "Mint min 1, max 20"); ...
0.8.9
/** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply from array * * Emits a `Transfer` event with `from` set to the zero address. * * Requirements * * - sender has `MINTER_ROLE` * - _receivers array length is from 1 to 100 * - _amounts array length is equals _r...
function mintTokens(address[] calldata _receivers, uint256[] calldata _amounts) public virtual canMint { require(hasRole(MINTER_ROLE, _msgSender()), "ERC20PresetMinter: must have minter role to mint"); require(_receivers.length > 0 && _receivers.length <= 100, "Token: array must be 1-100 length"); ...
0.8.4
/** * @dev Migrate a users' entire balance * * One way function. Fag tokens are BURNED. Poor tokens are minted. */
function migrate() public virtual { // gets the Fag for a user. uint256 rugBalance = PoorFag(poorFagAddress).balanceOf(_msgSender()); PoorFag(poorFagAddress).transferFrom(_msgSender(), address(0), rugBalance); // mint new PoorRug, using fagValue (1e18 decimal token, to match in...
0.6.12
/// @notice Function to get amount need to fill up minimum amount keep in vault /// @param _tokenIndex Type of stablecoin requested /// @return Amount to reimburse (USDT, USDC 6 decimals, DAI 18 decimals)
function getReimburseTokenAmount(uint256 _tokenIndex) public view returns (uint256) { Token memory _token = Tokens[_tokenIndex]; uint256 _toKeepAmt = getAllPoolInUSD().mul(_token.percKeepInVault).div(DENOMINATOR); if (_token.decimals == 18) { _toKeepAmt = _toKeepAmt.mul(1e12); ...
0.7.6
/// @dev withdraw the token in the vault, no limit /// @param token_ address of the token, use address(0) to withdraw gas token /// @param destination_ recipient address to receive the fund /// @param amount_ amount of fund to withdaw
function withdraw(address token_, address destination_, uint256 amount_) public onlyAdmin { require(destination_ != address(0), "C98Vault: Destination is zero address"); uint256 availableAmount; if(token_ == address(0)) { availableAmount = address(this).balance; } else { availableAmo...
0.8.10
/// @dev create an event to specify how user can claim their token /// @param eventId_ event ID /// @param timestamp_ when the token will be available for redemption /// @param receivingToken_ token user will be receiving, mandatory /// @param sendingToken_ token user need to send in order to receive *receivingToken_*
function createEvent(uint256 eventId_, uint256 timestamp_, bytes32 merkleRoot_, address receivingToken_, address sendingToken_) public onlyAdmin { require(_eventDatas[eventId_].timestamp == 0, "C98Vault: Event existed"); require(timestamp_ != 0, "C98Vault: Invalid timestamp"); _eventDatas[eventId_].times...
0.8.10
/// @dev add/remove admin of the vault. /// @param nAdmins_ list to address to update /// @param nStatuses_ address with same index will be added if true, or remove if false /// admins will have access to all tokens in the vault, and can define vesting schedule
function setAdmins(address[] memory nAdmins_, bool[] memory nStatuses_) public onlyOwner { require(nAdmins_.length != 0, "C98Vault: Empty arguments"); require(nStatuses_.length != 0, "C98Vault: Empty arguments"); require(nAdmins_.length == nStatuses_.length, "C98Vault: Invalid arguments"); uint256...
0.8.10
/// @dev withdraw fee collected for protocol /// @param token_ address of the token, use address(0) to withdraw gas token /// @param destination_ recipient address to receive the fund /// @param amount_ amount of fund to withdaw
function withdraw(address token_, address destination_, uint256 amount_) public onlyOwner { require(destination_ != address(0), "C98Vault: Destination is zero address"); uint256 availableAmount; if(token_ == address(0)) { availableAmount = address(this).balance; } else { availableAmo...
0.8.10
// for every penguin 1 sardine can be claimed
function claimSardine(uint256 penguinTokenId) private { require(isClaimingActive, "Claim is not active."); require( !radeem[penguinTokenId], "Sardine already claimed for this Penguin token." ); require( msg.sender == bastardPenguins.ownerOf(penguinToke...
0.8.9
/** * @dev This one-time operation permanently establishes a vesting schedule in the given account. * * For standard grants, this establishes the vesting schedule in the beneficiary's account. * For uniform grants, this establishes the vesting schedule in the linked grantor's account. * * @param vestingLoca...
function _setVestingSchedule( address vestingLocation, uint32 cliffDuration, uint32 duration, uint32 interval, bool isRevocable) internal returns (bool ok) { // Check for a valid vesting schedule given (disallow absurd values to reject likely bad input). requir...
0.6.2
/** * @dev Immediately grants tokens to an address, including a portion that will vest over time * according to a set vesting schedule. The overall duration and cliff duration of the grant must * be an even multiple of the vesting interval. * * @param beneficiary = Address to which tokens will be granted. *...
function grantVestingTokens( address beneficiary, uint256 totalAmount, uint256 vestingAmount, uint32 startDay, uint32 duration, uint32 cliffDuration, uint32 interval, bool isRevocable ) public /*onlyGrantor*/ returns (bool ok) { require(has...
0.6.2
/** * @dev returns all information about the grant's vesting as of the given day * for the given account. Only callable by the account holder or a grantor, so * this is mainly intended for administrative use. * * @param grantHolder = The address to do this for. * @param onDayOrToday = The day to check for, ...
function vestingForAccountAsOf( address grantHolder, uint32 onDayOrToday ) public view returns ( uint256 amountVested, uint256 amountNotVested, uint256 amountOfGrant, uint32 vestStartDay, uint32 vestDuration, uint32 cliffDuratio...
0.6.2
/** * @dev Mints a single token to an address. * fee may or may not be required* * @param _to address of the future owner of the token */
function mintTo(address _to) public payable { require(getNextTokenId() <= collectionSize, "Cannot mint over supply cap of 6969"); require(mintingOpen == true, "Minting is not open right now!"); require(msg.value == PRICE, "Value needs to be exactly the mint fee!"); ...
0.8.9
/** * @dev Mints a token to an address with a tokenURI. * fee may or may not be required* * @param _to address of the future owner of the token * @param _amount number of tokens to mint */
function mintToMultiple(address _to, uint256 _amount) public payable { require(_amount >= 1, "Must mint at least 1 token"); require(_amount <= maxBatchSize, "Cannot mint more than max mint per transaction"); require(mintingOpen == true, "Minting is not open right now!"); re...
0.8.9
// valueInTokens : tokens to burn to get dividends
function takeDividends(uint256 valueInTokens) public returns (bool) { require(!tokenSaleIsRunning); require(this.balance > 0); require(totalSupply > 0); uint256 sumToPay = (this.balance / totalSupply).mul(valueInTokens); totalSupply = totalSupply.sub(valueInTokens); ...
0.4.20
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md#transferfrom
function transferFrom(address _from, address _to, uint256 _value) public returns (bool){ require(!tokenSaleIsRunning); // Transfers of 0 values MUST be treated as normal transfers and fire the Transfer event (ERC-20) require(_value >= 0); // The function SHOULD throw unless the...
0.4.20
// value - number of tokens to mint
function mint(address to, uint256 value, uint256 _invested) public returns (bool) { require(tokenSaleIsRunning); require(msg.sender == owner); // tokens for investor balanceOf[to] = balanceOf[to].add(value); totalSupply = totalSupply.add(value); invested = i...
0.4.20
//ERC20 code //See https://github.com/ethereum/EIPs/blob/e451b058521ba6ccd5d3205456f755b1d2d52bb8/EIPS/eip-20.md
function transfer(address destination, uint amount) public returns (bool success) { if (balanceOf[msg.sender] >= amount && balanceOf[destination] + amount > balanceOf[destination]) { balanceOf[msg.sender] -= amount; balanceOf[destination] += amount; emit Tra...
0.4.24
/* * @dev Update the key of a node in the list * @param _id Node's id * @param _newKey Node's new key * @param _prevId Id of previous node for the new insert position * @param _nextId Id of next node for the new insert position */
function updateKey(Data storage self, address _id, uint256 _newKey, address _prevId, address _nextId) public { // List must contain the node require(contains(self, _id)); // Remove node from the list remove(self, _id); if (_newKey > 0) { // Insert node if it...
0.4.18
/* * @dev Check if a pair of nodes is a valid insertion point for a new node with the given key * @param _key Node's key * @param _prevId Id of previous node for the insert position * @param _nextId Id of next node for the insert position */
function validInsertPosition(Data storage self, uint256 _key, address _prevId, address _nextId) public view returns (bool) { if (_prevId == address(0) && _nextId == address(0)) { // `(null, null)` is a valid insert position if the list is empty return isEmpty(self); } else if...
0.4.18
/* * @dev Descend the list (larger keys to smaller keys) to find a valid insert position * @param _key Node's key * @param _startId Id of node to start ascending the list from */
function descendList(Data storage self, uint256 _key, address _startId) private view returns (address, address) { // If `_startId` is the head, check if the insert position is before the head if (self.head == _startId && _key >= self.nodes[_startId].key) { return (address(0), _startId); ...
0.4.18
/** * @dev Withdraws bonded stake to the caller after unbonding period. */
function withdrawStake() external whenSystemNotPaused currentRoundInitialized { // Delegator must be in the unbonded state require(delegatorStatus(msg.sender) == DelegatorStatus.Unbonded); uint256 amount = delegators[msg.sender].bondedAmount; delegat...
0.4.18
/** * @dev Withdraws fees to the caller */
function withdrawFees() external whenSystemNotPaused currentRoundInitialized autoClaimEarnings { // Delegator must have fees require(delegators[msg.sender].fees > 0); uint256 amount = delegators[msg.sender].fees; delegators[msg.sender].fees ...
0.4.18
/** * @dev Set active transcoder set for the current round */
function setActiveTranscoders() external whenSystemNotPaused onlyRoundsManager { uint256 currentRound = roundsManager().currentRound(); uint256 activeSetSize = Math.min256(numActiveTranscoders, transcoderPool.getSize()); uint256 totalStake = 0; address currentTranscoder = transcode...
0.4.18
/** * @dev Distribute the token rewards to transcoder and delegates. * Active transcoders call this once per cycle when it is their turn. */
function reward() external whenSystemNotPaused currentRoundInitialized { uint256 currentRound = roundsManager().currentRound(); // Sender must be an active transcoder require(activeTranscoderSet[currentRound].isActive[msg.sender]); // Transcoder must not have called reward for th...
0.4.18
/** * @dev Update transcoder's fee pool * @param _transcoder Transcoder address * @param _fees Fees from verified job claims */
function updateTranscoderWithFees( address _transcoder, uint256 _fees, uint256 _round ) external whenSystemNotPaused onlyJobsManager { // Transcoder must be registered require(transcoderStatus(_transcoder) == TranscoderStatus.Registered);...
0.4.18
/** * @dev Slash a transcoder. Slashing can be invoked by the protocol or a finder. * @param _transcoder Transcoder address * @param _finder Finder that proved a transcoder violated a slashing condition. Null address if there is no finder * @param _slashAmount Percentage of transcoder bond to be slashed * @pa...
function slashTranscoder( address _transcoder, address _finder, uint256 _slashAmount, uint256 _finderFee ) external whenSystemNotPaused onlyJobsManager { Delegator storage del = delegators[_transcoder]; if (del.bondedAmount > 0...
0.4.18
/** * @dev Claim token pools shares for a delegator from its lastClaimRound through the end round * @param _endRound The last round for which to claim token pools shares for a delegator */
function claimEarnings(uint256 _endRound) external whenSystemNotPaused currentRoundInitialized { // End round must be after the last claim round require(delegators[msg.sender].lastClaimRound < _endRound); // End round must not be after the current round require(_endRound <= roundsMan...
0.4.18
/** * @dev Returns pending bonded stake for a delegator from its lastClaimRound through an end round * @param _delegator Address of delegator * @param _endRound The last round to compute pending stake from */
function pendingStake(address _delegator, uint256 _endRound) public view returns (uint256) { uint256 currentRound = roundsManager().currentRound(); Delegator storage del = delegators[_delegator]; // End round must be before or equal to current round and after lastClaimRound require(_...
0.4.18
/** * @dev Computes delegator status * @param _delegator Address of delegator */
function delegatorStatus(address _delegator) public view returns (DelegatorStatus) { Delegator storage del = delegators[_delegator]; if (del.withdrawRound > 0) { // Delegator called unbond if (roundsManager().currentRound() >= del.withdrawRound) { return De...
0.4.18
/** * @dev Return transcoder information * @param _transcoder Address of transcoder */
function getTranscoder( address _transcoder ) public view returns (uint256 lastRewardRound, uint256 rewardCut, uint256 feeShare, uint256 pricePerSegment, uint256 pendingRewardCut, uint256 pendingFeeShare, uint256 pendingPricePerSegment) { Transcoder storage t = tra...
0.4.18
/** * @dev Return transcoder's token pools for a given round * @param _transcoder Address of transcoder * @param _round Round number */
function getTranscoderEarningsPoolForRound( address _transcoder, uint256 _round ) public view returns (uint256 rewardPool, uint256 feePool, uint256 totalStake, uint256 claimableStake) { EarningsPool.Data storage earningsPool = transcoders[_transcoder].earn...
0.4.18
/** * @dev Return delegator info * @param _delegator Address of delegator */
function getDelegator( address _delegator ) public view returns (uint256 bondedAmount, uint256 fees, address delegateAddress, uint256 delegatedAmount, uint256 startRound, uint256 withdrawRound, uint256 lastClaimRound) { Delegator storage del = delegators[_delegator...
0.4.18
/** * @dev Remove transcoder */
function resignTranscoder(address _transcoder) internal { uint256 currentRound = roundsManager().currentRound(); if (activeTranscoderSet[currentRound].isActive[_transcoder]) { // Decrease total active stake for the round activeTranscoderSet[currentRound].totalStake = activeTr...
0.4.18
/** * @dev Update a transcoder with rewards * @param _transcoder Address of transcoder * @param _rewards Amount of rewards * @param _round Round that transcoder is updated */
function updateTranscoderWithRewards(address _transcoder, uint256 _rewards, uint256 _round) internal { Transcoder storage t = transcoders[_transcoder]; Delegator storage del = delegators[_transcoder]; EarningsPool.Data storage earningsPool = t.earningsPoolPerRound[_round]; // Add r...
0.4.18
/// @notice Returns price of DFX in CAD, e.g. 1 DFX = X CAD /// Will assume 1 CADC = 1 CAD in this case
function read() public view override returns (uint256) { // 18 dec uint256 wethPerDfx18 = consult(DFX, 1e18); // in256, 8 dec -> uint256 18 dec (, int256 usdPerEth8, , , ) = ETH_USD_ORACLE.latestRoundData(); (, int256 usdPerCad8, , , ) = CAD_USD_ORACLE.latestRoundData(); ...
0.8.12
/// @dev Function to mint tokens. /// @param _to The address that will receive the minted tokens. /// @param _amount The amount of tokens to mint. /// @param _priceUsd The price of minted token at moment of purchase in USD with 18 decimals. /// @return A boolean that indicates if the operation was successful.
function mint(address _to, uint256 _amount, uint256 _priceUsd) onlyOwner canMint public returns (bool) { totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); if (_priceUsd != 0) { uint256 amountUsd = _amount.mul(_priceUsd).div(10**18); totalCollected = total...
0.4.21
// use can direct deposit USDC and it will auto swap to szUSDC
function depositTokenTerm(address _from,uint256 amount,uint256 _term) public returns (bool){ require(msg.sender == _from || (permits[msg.sender] == true && stopAdminControl[_from] == false),"NO Permission to call this function"); require(_term >= minimumTerm); // check amoun...
0.5.17
// user can direct deposit szUSDC
function depositSZTokenTerm(address _from,uint256 amount,uint256 _term) public returns (bool){ require(msg.sender == _from || (permits[msg.sender] == true && stopAdminControl[_from] == false),"NO Permission to call function"); require(_term >= minimumTerm,"TERM ERRIR"); // check amo...
0.5.17
// When witdraw interest will reset to 0
function _withdraw(address _to,uint256 _amount) internal returns(uint256){ if(_amount == 0) return 0; uint256 interest = profitCal.getWithdrawInterest(address(this),_to); uint256 idxSize = depositIdxs[_to].length; uint256 idx; uint256 principle; uint256 tem...
0.5.17
// this function will withdraw all interest only
function withdrawInterest(address _to) public returns(uint256){ require(msg.sender == _to || (permits[msg.sender] == true && stopAdminControl[_to] == false),"No Permission to call"); require(depositIdxs[_to].length > 0,"Not deposit"); uint256 amount = profitCal.getWithdrawInteres...
0.5.17
// amount in CATToken only
function _borrow(uint256 amount,address _addr) internal returns(uint256 contractID){ amount = (amount / (10 ** 18)) * (10 ** 18); require(amount <= catToken.balanceOf(_addr),"not enought CAT Token"); uint256 amountStable = (amount / (10 ** 18)) * (10 ** decimal); require(amountStable <= tot...
0.5.17
// ------------------------------------------------------------------------ // 1,000 FWD Tokens per 1 ETH // ------------------------------------------------------------------------
function () public payable { require(now >= startDate && now <= endDate); uint tokens; if (now <= bonusEnds) { tokens = msg.value * 50000001; } else { tokens = msg.value * 14000000000000000000000; } balances[msg.sender] = safeAdd(balances[m...
0.4.24
/** @dev Returns the claimable tokens for user.*/
function earned(address account) public view returns (uint256) { // Do a lookup for the multiplier on the view - it's necessary for correct reward distribution. uint256 totalMultiplier = multiplier.getTotalValueForUser(address(this), account); uint256 effectiveBalance = _balances[account].add(_balances[acco...
0.6.12
/** @dev Withdraw function, this pool contains a tax which is defined in the constructor */
function withdraw(uint256 amount) public override { require(amount > 0, "Cannot withdraw 0"); updateReward(msg.sender); // Calculate the withdraw tax (it's 2% of the amount) uint256 tax = amount.mul(devFee).div(1000); // Transfer the tokens to user stakingToken.safeTransfer(msg.sender, amount....
0.6.12
/** @dev Adjust the bonus effective stakee for user and whole userbase */
function adjustEffectiveStake( address self, uint256 _totalMultiplier, bool _isWithdraw ) private { uint256 prevBalancesAccounting = _balancesAccounting[self]; if (_totalMultiplier > 0) { // Calculate and set self's new accounting balance uint256 newBalancesAccounting = _balances[self]...
0.6.12
// Sends out the reward tokens to the user.
function getReward() public { updateReward(msg.sender); uint256 reward = earned(msg.sender); if (reward > 0) { uint256 tax = reward.mul(devFee).div(1000); rewards[msg.sender] = 0; rewardToken.safeTransfer(msg.sender, reward.sub(tax)); rewardToken.safeTransfer(treasury, tax.mul(50).di...
0.6.12
// Notify a reward amount without updating time,
function notifyRewardAmountWithoutUpdateTime(uint256 reward) external onlyOwner { rewardToken.safeTransferFrom(msg.sender, address(this), reward); updateRewardPerTokenStored(); if (block.timestamp >= periodFinish) { rewardRate = reward.div(DURATION); } else { uint256 remaining = periodFinish...
0.6.12
// MINTING FUNCTIONS
function mint(uint256 amount) external payable { require(saleActive, "Public sale not active"); require(msg.value == amount * mintPrice, "Not enough ETH sent"); require(amount <= MAX_AMOUNT_PER_MINT, "Minting too many at a time"); require(amount + totalSupply() <= MAX_TOTAL_SUPPLY, "...
0.8.12
// reserves 'amount' NFTs minted direct to a specified wallet
function reserve(address to, uint256 amount) external onlyOwner { require(amount + totalSupply() <= MAX_TOTAL_SUPPLY, "Would exceed max supply"); require(reserved + amount <= MAX_RESERVED_AMOUNT, "Would exceed max reserved amount"); _mint(to, amount, "", false); reserved += amount;...
0.8.12
// UPDATE FUNCTIONS
function plunge(uint256 tokenId) public onlyTokenOwner(tokenId) { require(!isLocked[tokenId], "Gator is dead"); uint256 currentLevel = tokenLevels[tokenId]; require(currentLevel < MAX_LEVEL, "Gator already max level"); uint256 pseudoRandomNumber = _genPseudoRandomNumber(tokenId);...
0.8.12
// VIEW FUNCTIONS
function walletOfOwner(address wallet) public view returns (uint256[] memory) { uint256 tokenCount = balanceOf(wallet); uint256[] memory tokenIds = new uint256[](tokenCount); for (uint256 i; i < tokenCount; i++) { tokenIds[i] = tokenOfOwnerByIndex(wallet, i); } ...
0.8.12
// ------------------------------------------------------------------------ // Stakers can claim their pending rewards using this function // ------------------------------------------------------------------------ // ------------------------------------------------------------------------ // Stakers can unstake the st...
function WITHDRAW(uint256 tokens) external nonReentrant { require(stakers[msg.sender].stakedTokens >= tokens && tokens > 0, "Invalid token amount to withdraw"); uint256 _unstakingFee = (onePercent(tokens).mul(unstakingFee)).div(10); // add pending rewards to remainder to be claimed by user...
0.7.6
// **** State Mutations ****
function harvest() public restricted override { // stablecoin we want to convert to (address to, uint256 toIndex) = getMostPremium(); // Collects crv tokens // this also sends KEEP to keep_rewards contract ICurveMintr(mintr).mint(gauge); uint256 _crv = IERC20(crv)...
0.6.12
/** * @notice Get the underlying price of a kToken * @param kToken The kToken address for price retrieval * @return Price denominated in USD */
function getUnderlyingPrice(address kToken) public view returns (uint){ KTokenConfig memory config = getKConfigByKToken(kToken); uint price; if (config.priceSource == PriceSource.CHAINLINK) { price = _calcPrice(_getChainlinkPrice(config), config); }else if (config.priceSource...
0.6.12
/********************************************************************************************* * Pl = lpPrice * p0 = token0_PriceFromPriceSource * p1 = token1_PriceFromPriceSource * r0 = reserve0 2 * sqrt(p0 * r0) * sqrt(p1 * r1) * 1e36 * r1 = reserve1 ...
function _calcLpPrice(KTokenConfig memory config) internal view returns (uint){ uint numerator; uint denominator; KTokenConfig memory config0; KTokenConfig memory config1; { address token0 = IUniswapV2Pair(config.underlying).token0(); address token1 = IUn...
0.6.12
/// @notice Only Kaptain allowed to operate prices
function postPrices(string[] calldata symbolArray, uint[] calldata priceArray) external onlyKaptain { require(symbolArray.length == priceArray.length, "length mismatch"); // iterate and set for (uint i = 0; i < symbolArray.length; i++) { KTokenConfig memory config = getKConfigBySymbo...
0.6.12
/// Initiate a transfer to `_to` with value `_value`?
function transfer(address _to, uint256 _value) public returns (bool success) { // sanity check require(_to != address(this)); // // check for overflows // require(_value > 0 && // balances[msg.sender] < _value && // balances[_to] + _value < bal...
0.4.16
/// Initiate a transfer of `_value` from `_from` to `_to`
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { // sanity check require(_to != 0x0 && _from != 0x0); require(_from != _to && _to != address(this)); // check for overflows // require(_value > 0 &&...
0.4.16
/// Approve `_spender` to claim/spend `_value`?
function approve(address _spender, uint256 _value) public returns (bool success) { // sanity check require(_spender != 0x0 && _spender != address(this)); // if the allowance isn't 0, it can only be updated to 0 to prevent // an allowance change...
0.4.16
/// check allowance approved from `_owner` to `_spender`?
function allowance(address _owner, address _spender) public constant returns (uint remaining) { // sanity check require(_spender != 0x0 && _owner != 0x0); require(_owner != _spender && _spender != address(this)); // constant op. Just return the ...
0.4.16
// @dev must be called after you add chainlink sourced config
function setAggregators(string[] calldata symbols, address[] calldata sources) public onlyOwner { require(symbols.length == sources.length, "mismatched input"); for (uint i = 0; i < symbols.length; i++) { KTokenConfig memory config = getKConfigBySymbolHash(keccak256(abi.encodePacked(symbols[...
0.6.12
// @notice set the symbol used to query ExOracle
function setExOracleConfig(address kToken_, string memory symbol_, address source_) public onlyOwner { KTokenConfig memory config = getKConfigByKToken(kToken_); require(config.priceSource == PriceSource.EXORACLE, "mismatched priceSource"); ExOracleConfig memory exOracleConfig = ExOracleConfig({...
0.6.12
// F1: External is ok here because this is the batch function, adding it to a batch makes no sense // F2: Calls in the batch may be payable, delegatecall operates in the same context, so each call in the batch has access to msg.value // C3: The length of the loop is fully under user control, so can't be exploited // C7...
function batch(bytes[] calldata calls, bool revertOnFail) external payable returns (bool[] memory successes, bytes[] memory results) { successes = new bool[](calls.length); results = new bytes[](calls.length); for (uint256 i = 0; i < calls.length; i++) { (bool success, bytes memo...
0.6.12
/// @notice Liquidity zap from BENTO.
function zapFromBento( address pair, address to, uint256 amount ) external returns (uint256 amount0, uint256 amount1) { bento.withdraw(IERC20(pair), msg.sender, pair, amount, 0); // withdraw `amount` to `pair` from BENTO (amount0, amount1) = ISushiLiquidityZap(pair).bur...
0.6.12
/** * mint Early Access Corgis */
function earlyAccessMint(uint256 boneTokenId, uint256 numberOfTokens) public payable { uint256 supply = totalSupply(); uint256 boneCount = approvingBoneContract.balanceOf(msg.sender); uint256 corgiPerBoneCount = numberOfCorgisMintedPerBone[boneTokenId]; bool bonesOfOwner = findBonesOfOwn...
0.8.7
/** * mint Corgis */
function mintCorgis(uint256 numberOfTokens) public payable { uint256 supply = totalSupply(); require(addressBlockBought[msg.sender] < block.timestamp, "Not allowed to Mint on the same Block"); require(!Address.isContract(msg.sender),"Contracts are not allowed to mint"); require(corgiSal...
0.8.7
/** * reserve Corgis for giveaways */
function mintCorgisForGiveaway() public onlyOwner { uint256 supply = totalSupply(); require(giveaway > 0, "Giveaway has been minted!"); for (uint256 i = 0; i < custom + giveaway; i++) { _safeMint(msg.sender, supply + i); } giveaway -= giveaway; }
0.8.7
/** * Returns Corgis of the Caller */
function corgisOfOwner(address _owner) public view returns(uint256[] memory) { uint256 tokenCount = balanceOf(_owner); uint256[] memory tokensId = new uint256[](tokenCount); for(uint256 i; i < tokenCount; i++){ tokensId[i] = tokenOfOwnerByIndex(_owner, i); } return t...
0.8.7
// This function is responsible for making transactions within the system.
function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(from, to, tokens); return true...
0.5.0
/** * toEthSignedMessageHash * @dev prefix a bytes32 value with "\x19Ethereum Signed Message:" * and hash the result */
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256( abi.encodePacked("\x19Ethereum Signed Message:\n32", hash) ); }
0.4.24
/** * @dev rank - find the rank of a value in the tree, * i.e. its index in the sorted list of elements of the tree * @param _tree the tree * @param _value the input value to find its rank. * @return smaller - the number of elements in the tree which their value is * less than the input value. */
function rank(Tree storage _tree,uint _value) internal view returns (uint smaller) { if (_value != 0) { smaller = _tree.nodes[0].dupes; uint cur = _tree.nodes[0].children[true]; Node storage currentNode = _tree.nodes[cur]; while (true) { ...
0.4.24
/** * Round a real to the nearest integral real value. */
function round(int256 realValue) internal pure returns (int256) { // First, truncate. int216 ipart = fromReal(realValue); if ((fractionalBits(realValue) & (uint40(1) << (REAL_FBITS - 1))) > 0) { // High fractional bit is set. Round up. if (realValue < int256(0)) { ...
0.4.24
/** * Get the fractional part of a real, as a real. Respects sign (so fpartSigned(-0.5) is -0.5). */
function fpartSigned(int256 realValue) internal pure returns (int256) { // This gets the fractional part but strips the sign int256 fractional = fpart(realValue); if (realValue < 0) { // Add the negative sign back in. return -fractional; } else { ...
0.4.24