comment stringlengths 11 2.99k | function_code stringlengths 165 3.15k | version stringclasses 80
values |
|---|---|---|
/**
* @dev internal transfer function
*/ | function _transfer(address _from, address _to, uint _value) internal returns (bool){
require(_to != address(0));
require(_value > 0);
require(balances[_from] >= _value);
// SafeMath.sub will throw if there is not enough balance.
balances[_from] = balances[_from].sub(_value... | 0.4.21 |
// Mint new tokens to the specified address and token amount | function mintToken(address _account, uint256 _count) external onlyLogic {
require(_account != address(0), "Invalid Address");
require(_maxSupply >= totalSupply() + _count, "All Tokens Have Been Minted");
for (uint8 i = 0; i < _count; i++) {
uint256 tokenId = _getNextTokenId();
_mint(_account, t... | 0.8.7 |
// TransferFrom Token with timelocks | function transferLockedFrom(address _from, address _to, uint256[] _time, uint256[] _value) public
validAddress(_from) validAddress(_to) returns (bool success) {
require(_value.length == _time.length);
if (lockNum[_from] > 0) calcUnlock(_from);
uint256 i = 0;
uint256 totalValu... | 0.4.24 |
// owner may burn own token | function burn(uint256 _value) public onlyOwner returns (bool _success) {
if (lockNum[msg.sender] > 0) calcUnlock(msg.sender);
require(balanceP[msg.sender] >= _value && _value >= 0);
balanceP[msg.sender] = sub(balanceP[msg.sender], _value);
_totalSupply = sub(_totalSupply, _value);
... | 0.4.24 |
/// We don't need to use respectTimeFrame modifier here as we do for ETH contributions,
/// because foreign transaction can came with a delay thus it's a problem of outer server to manage time.
/// @param _buyer - ETH address of buyer where we will send tokens to. | function externalSale(address _buyer, uint256 _amountInUsd, uint256 _tokensSoldNoDecimals, uint256 _unixTs)
ifNotPaused canNotify {
if (_buyer == 0 || _amountInUsd == 0 || _tokensSoldNoDecimals == 0) throw;
if (_unixTs == 0 || _unixTs > getNow()) throw; // Cannot accept timestamp of a s... | 0.4.16 |
/*
* @dev Deposits desiredAmount into YF contract and creates NFTs for principal and reward
* @param desiredAmount Desired stake amount
* @param interval Lock time interval (in seconds)
*/ | function stake(uint256 desiredAmount, uint256 interval) external override nonReentrant {
require(desiredAmount > 0, 'INVALID_DESIRED_AMOUNT');
require(interval >= minLockTime, 'INVALID_MIN_INTERVAL');
require(interval <= maxLockTime, 'INVALID_MAX_INTERVAL');
// compute reward
(u... | 0.8.4 |
/*
* @dev Burns the nft with the given _tokenId and sets `claimed` true
*/ | function claim(uint256 _tokenId) external override nonReentrant {
require(nftMetadata[_tokenId].token != address(0), 'INVALID_TOKEN_ID');
require(nftMetadata[_tokenId].claimed == false, 'ALREADY_CLAIMED');
require(block.timestamp >= nftMetadata[_tokenId].endTime, 'NFT_LOCKED');
address ... | 0.8.4 |
/*
* @dev Returns stakedAmount and reward
* maxStaked = rewardPool / [multiplier * (interval / maxLockTime)^2]
* reward = multiplier * stakeAmount * (interval / maxLockInterval)^2
*/ | function _computeReward(uint256 desiredAmount, uint256 interval)
internal
view
returns (uint256 stakeAmount, uint256 rewardAmount)
{
uint256 maxStaked = _getMaxStake(interval);
stakeAmount = desiredAmount;
if (stakeAmount > maxStaked) {
stakeAmount = maxSt... | 0.8.4 |
/*
* @dev Mint eqzYieldNft to sender, creates and adds nft metadata
*/ | function _mintNft(
address tokenAddress,
uint256 amount,
uint256 interval,
NftTypes nftType
) internal returns (uint256) {
tokenId++;
uint256 currentTokenId = tokenId;
eqzYieldNft.mint(msg.sender, currentTokenId);
nftMetadata[currentTokenId] = NFTMetad... | 0.8.4 |
// SIP-75 Public keeper function to freeze a pynth that is out of bounds | function freezeRate(bytes32 currencyKey) external {
InversePricing storage inverse = inversePricing[currencyKey];
require(inverse.entryPoint > 0, "Cannot freeze non-inverse rate");
require(!inverse.frozenAtUpperLimit && !inverse.frozenAtLowerLimit, "The rate is already frozen");
uint ra... | 0.5.16 |
// SIP-75 View to determine if freezeRate can be called safely | function canFreezeRate(bytes32 currencyKey) external view returns (bool) {
InversePricing memory inverse = inversePricing[currencyKey];
if (inverse.entryPoint == 0 || inverse.frozenAtUpperLimit || inverse.frozenAtLowerLimit) {
return false;
} else {
uint rate = _getRate(c... | 0.5.16 |
/**
* @notice overrides ERC20 transferFrom function to introduce tax functionality
* @param from address amount is coming from
* @param to address amount is going to
* @param amount amount being sent
*/ | function transferFrom(address from, address to, uint256 amount) public virtual override returns (bool) {
address spender = _msgSender();
_spendAllowance(from, spender, amount);
require(balanceOf(from) >= amount, "ERC20: transfer amount exceeds balance");
if(_taxActive && !_whiteliste... | 0.8.0 |
/**
* @notice : overrides ERC20 transfer function to introduce tax functionality
* @param to address amount is going to
* @param amount amount being sent
*/ | function transfer(address to, uint256 amount) public virtual override returns (bool) {
address owner = _msgSender();
require(balanceOf(owner) >= amount, "ERC20: transfer amount exceeds balance");
if(_taxActive && !_whitelisted[owner] && !_whitelisted[to]) {
uint256 tax = amount*_taxTotal/_... | 0.8.0 |
/**
* @notice : adds address with tax amount to taxable addresses list
* @param wallet address to add
* @param _tax tax amount this address receives
*/ | function addTaxRecipient(address wallet, uint16 _tax) external onlyOwner {
require(_taxRecipients.length < 100, "Reached maximum number of tax addresses");
require(wallet != address(0), "Cannot add 0 address");
require(!_isTaxRecipient[wallet], "Recipient already added");
require(_tax > 0 &&... | 0.8.0 |
/**
* @notice : updates address tax amount
* @param wallet address to update
* @param newTax new tax amount
*/ | function updateTaxPercentage(address wallet, uint16 newTax) external onlyOwner {
require(wallet != address(0), "Cannot add 0 address");
require(_isTaxRecipient[wallet], "Not a tax address");
uint16 currentTax = _taxRecipientAmounts[wallet];
require(currentTax != newTax, "Tax already this a... | 0.8.0 |
/**
* @notice : remove address from taxed list
* @param wallet address to remove
*/ | function removeTaxRecipient(address wallet) external onlyOwner {
require(wallet != address(0), "Cannot add 0 address");
require(_isTaxRecipient[wallet], "Recipient has not been added");
uint16 _tax = _taxRecipientAmounts[wallet];
for(uint8 i = 0; i < _taxRecipients.length; i++) {
... | 0.8.0 |
/**
* @notice : withdraws taxable amount to tax recipients
*/ | function distributeTaxes() external onlyOwner {
require(balanceOf(address(this)) > 0, "Nothing to withdraw");
uint256 taxableAmount = balanceOf(address(this));
for(uint8 i = 0; i < _taxRecipients.length; i++) {
address taxAddress = _taxRecipients[i];
if(i == _taxRecipients.length ... | 0.8.0 |
/**
* Deposit ETH to get in line to be credited back the multiplier as a percent,
* add that ETH to the pool, get the dividends and put them in the pool,
* then pay out who we owe and buy more tokens.
*/ | function deposit() payable public limitBuy() {
//You have to send more than 1000000 wei.
require(msg.value > 1000000);
//Compute how much to pay them
uint256 amountCredited = (msg.value * multiplier) / 100;
//Get in line to be paid back.
participants.push(Participan... | 0.4.24 |
/// @dev check that vault has sufficient funds is done by the call to vault | function earn(address strategy, uint256 amount) public updateEpoch {
require(msg.sender == strategy, "!strategy");
address token = IStrategy(strategy).want();
require(approvedStrategies[token][strategy], "strat !approved");
TokenStratInfo storage info = tokenStratsInfo[token];
... | 0.5.17 |
// handle vault withdrawal | function withdraw(address token, uint256 withdrawAmount) external updateEpoch {
TokenStratInfo storage info = tokenStratsInfo[token];
require(msg.sender == (address(info.vault)), "!vault");
uint256 remainingWithdrawAmount = withdrawAmount;
for (uint256 i = 0; i < info.strategies.le... | 0.5.17 |
//process the fees, hdx20 appreciation, calcul results at the end of the race | function process_Taxes( GameRoundData_s storage _GameRoundData ) private
{
uint32 turnround = _GameRoundData.extraData[0];
if (turnround>0 && turnround<(1<<30))
{
_GameRoundData.extraData[0] = turnround | (1<<30);
uint256 _sharePrice =... | 0.4.25 |
// Withdraw partial funds | function withdraw(address _token, address _gauge, uint256 _amount) public returns(bool){
require(msg.sender == operator, "!auth");
uint256 _balance = IERC20(_token).balanceOf(address(this));
if (_balance < _amount) {
_amount = _withdrawSome(_gauge, _amount.sub(_balance));
... | 0.6.12 |
// Function for token sell contract to call on transfers | function transferFromTokenSell(address _to, address _from, uint256 _amount) external onlyTokenSale returns (bool success) {
require(_amount > 0);
require(_to != 0x0);
require(balanceOf(_from) >= _amount);
decrementBalance(_from, _amount);
addToBalance(_to, _amount);
Transfer(_from, _to, _amount);
r... | 0.4.23 |
// Finalize private. If there are leftover TTT, overflow to presale | function finalizePrivatesale() external onlyTokenSale returns (bool success) {
require(privatesaleFinalized == false);
uint256 amount = balanceOf(privatesaleAddress);
if (amount != 0) {
addToBalance(presaleAddress, amount);
decrementBalance(privatesaleAddress, amount);
}
privatesaleFinalized = tr... | 0.4.23 |
// Finalize presale. If there are leftover TTT, overflow to crowdsale | function finalizePresale() external onlyTokenSale returns (bool success) {
require(presaleFinalized == false && privatesaleFinalized == true);
uint256 amount = balanceOf(presaleAddress);
if (amount != 0) {
addToBalance(crowdsaleAddress, amount);
decrementBalance(presaleAddress, amount);
}
presale... | 0.4.23 |
// Finalize crowdsale. If there are leftover TTT, add 10% to airdrop, 20% to ecosupply, burn 70% at a later date | function finalizeCrowdsale(uint256 _burnAmount, uint256 _ecoAmount, uint256 _airdropAmount) external onlyTokenSale returns(bool success) {
require(presaleFinalized == true && crowdsaleFinalized == false);
uint256 amount = balanceOf(crowdsaleAddress);
assert((_burnAmount.add(_ecoAmount).add(_airdropAmount)) == ... | 0.4.23 |
/**
* @dev Burns a specific amount of tokens. * added onlyOwner, as this will only happen from owner, if there are crowdsale leftovers
* @param _value The amount of token to be burned.
* @dev imported from https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/token/ERC20/BurnableToken.sol
... | function burn(uint256 _value) public onlyOwner {
require(_value <= balances[msg.sender]);
require(crowdsaleFinalized == true);
// no need to require value <= totalSupply, since that would imply the
// sender's balance is greater than the totalSupply, which *should* be an assertion failure
address burne... | 0.4.23 |
// Transfer tokens from the vested address. 50% available 12/01/2018, the rest available 06/01/2019 | function transferFromVest(uint256 _amount) public onlyOwner {
require(block.timestamp > firstVestStartsAt);
require(crowdsaleFinalized == true);
require(_amount > 0);
if(block.timestamp > secondVestStartsAt) {
// all tokens available for vest withdrawl
require(_amount <= teamSupply);
require(_am... | 0.4.23 |
/**
* @dev Returns the address where a contract will be stored if deployed via {deploy} from a contract located at
* `deployer`. If `deployer` is this contract's address, returns the same value as {computeAddress}.
*/ | function computeAddress(bytes32 salt, bytes memory bytecodeHash, address deployer) internal pure returns (address) {
bytes32 bytecodeHashHash = keccak256(bytecodeHash);
bytes32 _data = keccak256(
abi.encodePacked(bytes1(0xff), deployer, salt, bytecodeHashHash)
);
return addre... | 0.7.6 |
/** @notice Allow us to transfer tokens that someone might've accidentally sent to this contract
@param _tokenAddress this is the address of the token contract
@param _recipient This is the address of the person receiving the tokens
@param _amount This is the amount of tokens to send
*/ | function transferForeignToken(
address _tokenAddress,
address _recipient,
uint256 _amount)
public
onlyAdmin
returns (bool)
{
require(_recipient != address(0), "recipient address can't be empty");
// don't allow us to transfer RTC tokens stored... | 0.4.24 |
/// @inheritdoc IAloePredictionsDerivedState | function current()
external
view
override
returns (
bool,
uint176,
uint128,
uint128
)
{
require(epoch != 0, "Aloe: No data yet");
uint176 mean = computeMean();
(uint256 lower, uint256 upper) = computeSem... | 0.8.4 |
/// @inheritdoc IAloePredictionsActions | function advance() external override lock {
require(summaries[epoch].accumulators.stakeTotal != 0, "Aloe: No proposals with stake");
require(uint32(block.timestamp) > epochExpectedEndTime(), "Aloe: Too early");
epochStartTime = uint32(block.timestamp);
if (epoch != 0) {
(Bou... | 0.8.4 |
/**
* @dev See {IERC1155-balanceOf}.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/ | function balanceOf(address account, uint256 id) public view virtual override returns (uint256) {
require(account != address(0), "ERC1155: balance query for the zero address");
(address owner,,) = getData(id);
if(owner == account) {
return 1;
}
return 0;
} | 0.8.2 |
/**
* @dev Returns the score of an amulet.
* 0-3: Not an amulet
* 4: common
* 5: uncommon
* 6: rare
* 7: epic
* 8: legendary
* 9: mythic
* 10+: beyond mythic
*/ | function getScore(string memory amulet) public override pure returns(uint32) {
uint256 hash = uint256(sha256(bytes(amulet)));
uint maxlen = 0;
uint len = 0;
for(;hash > 0; hash >>= 4) {
if(hash & 0xF == 8) {
len += 1;
if(len > maxlen) {
... | 0.8.2 |
/**
* @dev Mint a new amulet.
* @param data The ID and owner for the new token.
*/ | function mint(MintData memory data) public override {
require(data.owner != address(0), "ERC1155: mint to the zero address");
require(_tokens[data.tokenId] == 0, "ERC1155: mint of existing token");
_tokens[data.tokenId] = uint256(uint160(data.owner));
emit TransferSingle(msg.sender, add... | 0.8.2 |
/**
* @dev Reveals an amulet.
* @param data The title, text, and offset URL for the amulet.
*/ | function reveal(RevealData calldata data) public override {
require(bytes(data.amulet).length <= 64, "Amulet: Too long");
uint256 tokenId = uint256(keccak256(bytes(data.amulet)));
(address owner, uint64 blockRevealed, uint32 score) = getData(tokenId);
require(
owner == msg.se... | 0.8.2 |
/**
* @dev Returns the Amulet's owner address, the block it was revealed in, and its score.
*/ | function getData(uint256 tokenId) public override view returns(address owner, uint64 blockRevealed, uint32 score) {
uint256 t = _tokens[tokenId];
owner = address(uint160(t));
blockRevealed = uint64(t >> 160);
score = uint32(t >> 224);
} | 0.8.2 |
/**************************************************************************
* Internal/private methods
*************************************************************************/ | function _doSafeTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
)
private
{
if (to.isContract()) {
try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount,... | 0.8.2 |
/**
* @dev function to claim the Frens NFT
*/ | function claimNFF()
external
onlyWhitelisted
{
//validation before minting
require(
maxTokensPerWallet[msg.sender] == 0,
"NFF: You are not allowed to mint anymore tokens"
);
require(
_pauseContract == false,
"NFF: Contr... | 0.8.6 |
/**
* @dev override the tokenURI and generate the metadata on-chain
*/ | function tokenURI(uint256 tokenId)
public
view
override
returns (string memory)
{
require(
_exists(tokenId),
"ERC721Metadata: URI query for nonexistent token"
);
return
string(
abi.encodePacked(
"data:application/json;base64,",
... | 0.8.6 |
/**
* @dev set the initial lvl value for the trait
*/ | function setTraitValue(uint _tokenId)
internal
{
SEED++;
uint tempValue = uint256(
keccak256(
abi.encodePacked(
block.timestamp,
block.difficulty,
_tokenId,
msg.sender,
... | 0.8.6 |
// BURNER INTERFACE | function initiateTokenBurn(uint256 _tokenId) external {
require(msg.sender == burner, "Only burner allowed");
require(burnTimeoutAt[_tokenId] == 0, "Burn already initiated");
require(tokenContract.ownerOf(_tokenId) != address(0), "Token doesn't exists");
uint256 duration = burnTimeoutDuration[_tok... | 0.5.16 |
// CONTROLLER INTERFACE | function setInitialDetails(
uint256 _privatePropertyId,
IPPToken.TokenType _tokenType,
IPPToken.AreaSource _areaSource,
uint256 _area,
bytes32 _ledgerIdentifier,
string calldata _humanAddress,
string calldata _dataLink,
bool _claimUniqueness
)
external
onlyMinter
... | 0.5.16 |
// COMMON INTERFACE | function propose(
bytes calldata _data,
string calldata _dataLink
)
external
payable
{
address msgSender = msg.sender;
uint256 tokenId = fetchTokenId(_data);
uint256 proposalId = _nextId();
Proposal storage p = proposals[proposalId];
if (msgSender == geoDataManager... | 0.5.16 |
// PERMISSIONLESS INTERFACE | function execute(uint256 _proposalId) public {
Proposal storage p = proposals[_proposalId];
require(p.tokenOwnerApproved == true, "Token owner approval required");
require(p.geoDataManagerApproved == true, "GeoDataManager approval required");
require(p.status == ProposalStatus.APPROVED, "Expect AP... | 0.5.16 |
// USER INTERFACE | function build(
string calldata _tokenName,
string calldata _tokenSymbol,
string calldata _dataLink,
uint256 _defaultBurnDuration,
bytes32[] calldata _feeKeys,
uint256[] calldata _feeValues,
bytes32 _legalAgreementIpfsHash
)
external
payable
returns (address)
{
... | 0.5.16 |
/// @notice converts number to string
/// @dev source: https://github.com/provable-things/ethereum-api/blob/master/oraclizeAPI_0.5.sol#L1045
/// @param _i integer to convert
/// @return _uintAsString | function uintToStr(uint _i) internal pure returns (string memory _uintAsString) {
uint number = _i;
if (number == 0) {
return "0";
}
uint j = number;
uint len;
while (j != 0) {
len++;
j /= 10;
}
bytes memory b... | 0.6.12 |
/**
* @dev function withdraw ETH to account owner
* @param _amount is amount withdraw
*/ | function withdrawETH(uint256 _amount) external onlyOwner {
require(_amount > 0, "_amount must be greater than 0");
require(
address(this).balance >= _amount,
"_amount must be less than the ETH balance of the contract"
);
msg.sender.transfer(_amount);
} | 0.6.12 |
//@dev returns the tokenURI of tokenID | function tokenURI(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
require(
_exists(tokenId),
"Huey: URI query for nonexistent token"
);
string memory currentBaseURI = _baseURI();
r... | 0.8.11 |
// Withdraw to notifinance + board | function withdraw() public payable onlyOwner {
// 1% of all profits are split between members of the board
uint256 boardCut = address(this).balance * 1 / 100;
for (uint i = 0; i < board.length - 1; i++) {
(bool hs, ) = payable(board[i]).call{value: boardCut / board.length}("");... | 0.8.7 |
// Whitelist mint - whitelisted users can mint up to the max mint amount | function whitelistMint(uint256 amount) public payable mintable(amount) {
require(status == Status.WHITELIST, "Whitelist sale currently unavailable");
require(whitelisted[msg.sender] == true, "You are not whitelisted");
require(numMinted[msg.sender] + amount <= maxMintPerWallet, "You reached t... | 0.8.7 |
// Action functions | function changeContractOwner(address _newOwner) public {
require (msg.sender == owner); // Only the current owner can change the ownership of the contract
owner = _newOwner; // Update the owner
// Trigger ownership change event.
emit ChangedOwnership(_newOwner);
} | 0.4.26 |
// fiatTrader adds collateral to the open swap | function addFiatTraderCollateral(bytes32 _tradeID, uint256 _erc20Value) public onlyInitializedSwaps(_tradeID) {
Swap storage swap = swaps[_tradeID]; // Get information about the swap position
require (_erc20Value >= swap.daiTraderCollateral); // Cannot send less than what the daiTrader has in collateral
... | 0.4.26 |
// daiTrader is refunding as fiatTrader never sent the collateral | function refundSwap(bytes32 _tradeID) public onlyInitializedSwaps(_tradeID) {
// Refund the swap.
Swap storage swap = swaps[_tradeID];
require (msg.sender == swap.daiTrader); // Only the daiTrader can call this function to refund
swap.swapState = States.REFUNDED; // Swap is now refunded, sending all... | 0.4.26 |
// daiTrader is aborting as fiatTrader failed to hold up its part of the swap
// Aborting refunds the sendAmount to daiTrader but returns part of the collateral based on the penalty
// Penalty must be between 75-100% | function diaTraderAbort(bytes32 _tradeID, uint256 penaltyPercent) public onlyActiveSwaps(_tradeID) {
// diaTrader aborted the swap.
require (penaltyPercent >= 75000 && penaltyPercent <= 100000); // Penalty must be between 75-100%
Swap storage swap = swaps[_tradeID];
require (msg.sender == swap.dai... | 0.4.26 |
// fiatTrader is aborting due to unexpected difficulties sending fiat
// Aborting refunds the sendAmount to daiTrader but returns part of the collateral based on the penalty
// Penalty must be between 2.5-100% | function fiatTraderAbort(bytes32 _tradeID, uint256 penaltyPercent) public onlyActiveSwaps(_tradeID) {
// fiatTrader aborted the swap.
require (penaltyPercent >= 2500 && penaltyPercent <= 100000); // Penalty must be between 2.5-100%
Swap storage swap = swaps[_tradeID];
require (msg.sender == swap.f... | 0.4.26 |
/* Trying out function parameters for a functional map */ | function mapToken(IERC20[] storage self, function (IERC20) view returns (uint256) f) internal view returns (uint256[] memory r) {
uint256 len = self.length;
r = new uint[](len);
for (uint i = 0; i < len; i++) {
r[i] = f(self[i]);
}
} | 0.6.12 |
// function rewardExtras() onlyHarvester external view returns(uint256[] memory totals) {
// totals = new uint256[](_rewards.length);
// for (uint256 i = 0; i < _rewards.length; i++) {
// totals[i] = _rewardExtra[_rewards[i]];
// }
// } | function owedRewards() external view returns(uint256[] memory rewards) {
rewards = new uint256[](_rewards.length);
mapping (IERC20 => uint256) storage owed = _owedRewards[msg.sender];
for (uint256 i = 0; i < _rewards.length; i++) {
IERC20 token = _rewards[i];
rewards[i] = owed[token];
}
} | 0.6.12 |
/**
* @dev Withdraw tokens only after the deliveryTime.
*/ | function withdrawTokens() public {
require(goalReached());
// solium-disable-next-line security/no-block-members
require(block.timestamp > deliveryTime);
super.withdrawTokens();
uint256 _bonusTokens = bonuses[msg.sender];
if (_bonusTokens > 0) {
bonuses[msg.sender] = 0;
requi... | 0.4.24 |
/**
* @dev Executed when a purchase has been validated and is ready to be executed. Not necessarily emits/sends tokens.
* It computes the bonus and store it using the timelockController.
* @param _beneficiary Address receiving the tokens
* @param _tokenAmount Number of tokens to be purchased
*/ | function _processPurchase( address _beneficiary, uint256 _tokenAmount ) internal {
uint256 _totalTokens = _tokenAmount;
// solium-disable-next-line security/no-block-members
uint256 _bonus = getBonus(block.timestamp, _beneficiary, msg.value);
if (_bonus>0) {
uint256 _bonusTokens = _tokenAmoun... | 0.4.24 |
/**
* @dev Computes the bonus. The bonus is
* - 0 by default
* - 30% before reaching the softCap for those whitelisted.
* - 15% the first week
* - 10% the second week
* - 8% the third week
* - 6% the remaining time.
* @param _time when the purchased happened.
* @param _beneficiary Address performing t... | function getBonus(uint256 _time, address _beneficiary, uint256 _value) view internal returns (uint256 _bonus) {
//default bonus is 0.
_bonus = 0;
// at this level the amount was added to weiRaised
if ( (weiRaised.sub(_value) < goal) && earlyInvestors.whitelist(_beneficiary) ) {
_bonus =... | 0.4.24 |
/**
* @dev Performs the finalization tasks:
* - if goal reached, activate the controller and burn the remaining tokens
* - transfer the ownership of the token contract back to the owner.
*/ | function finalization() internal {
// only when the goal is reached we burn the tokens and activate the controller.
if (goalReached()) {
// activate the controller to enable the investors and team members
// to claim their tokens when the time comes.
timelockController.activate();
... | 0.4.24 |
/**
* @notice Create new vesting schedules in a batch
* @notice A transfer is used to bring tokens into the VestingDepositAccount so pre-approval is required
* @param _beneficiaries array of beneficiaries of the vested tokens
* @param _amounts array of amount of tokens (in wei)
* @dev array index of address s... | function createVestingSchedules(
address[] calldata _beneficiaries,
uint256[] calldata _amounts
) external onlyOwner {
require(
_beneficiaries.length > 0,
"VestingContract::createVestingSchedules: Empty Data"
);
require(
_beneficia... | 0.8.9 |
/// @notice Fetches Compound prices for tokens
/// @param _cTokens Arr. of cTokens for which to get the prices
/// @return prices Array of prices | function getPrices(address[] memory _cTokens) public view returns (uint[] memory prices) {
prices = new uint[](_cTokens.length);
address oracleAddr = comp.oracle();
for (uint i = 0; i < _cTokens.length; ++i) {
prices[i] = CompoundOracleInterface(oracleAddr).getUnderlyingPrice(_cToke... | 0.6.6 |
/// @notice Fetches all the collateral/debt address and amounts, denominated in usd
/// @param _user Address of the user
/// @return data LoanData information | function getLoanData(address _user) public view returns (LoanData memory data) {
address[] memory assets = comp.getAssetsIn(_user);
address oracleAddr = comp.oracle();
data = LoanData({
user: _user,
ratio: 0,
collAddr: new address[](assets.length),
... | 0.6.6 |
/// @notice Information about cTokens
/// @param _cTokenAddresses Array of cTokens addresses
/// @return tokens Array of cTokens infomartion | function getTokensInfo(address[] memory _cTokenAddresses) public returns(TokenInfo[] memory tokens) {
tokens = new TokenInfo[](_cTokenAddresses.length);
address oracleAddr = comp.oracle();
for (uint i = 0; i < _cTokenAddresses.length; ++i) {
(, uint collFactor) = comp.markets(_cToke... | 0.6.6 |
// Notes:
// - This function does not track if real IERC20 balance has changed. Needs to blindly "trust" DaiProxy. | function onFundingReceived(address lender, uint256 amount)
external
onlyCreated
onlyProxy
returns (bool)
{
if (isAuctionExpired()) {
if (auctionBalance < minAmount) {
setState(LoanState.FAILED_TO_FUND);
emit FailedToFund(ad... | 0.5.10 |
/// @notice Calculates the gas cost for transaction
/// @param _amount Amount that is converted
/// @param _user Actuall user addr not DSProxy
/// @param _gasCost Ether amount of gas we are spending for tx
/// @param _tokenAddr token addr. of token we are getting for the fee
/// @return gasCost The amount we took for t... | function getGasCost(uint _amount, address _user, uint _gasCost, address _tokenAddr) internal returns (uint gasCost) {
address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle();
if (_gasCost != 0) {
uint256 price = IPriceOracleGetterAave(priceOr... | 0.6.6 |
// bytes b must be hp encoded | function _getNibbleArray(bytes memory b)
internal
pure
returns (bytes memory)
{
bytes memory nibbles = "";
if (b.length > 0) {
uint8 offset;
uint8 hpNibble = uint8(_getNthNibbleOfBytes(0, b));
if (hpNibble == 1 || hpNibble == 3) {
... | 0.7.3 |
// withdrawBalance
// - Withdraws balance to contract owner
// - Automatic withdrawal of donation | function withdrawBalance() public onlyOwner {
// Get the total balance
uint256 balance = address(this).balance;
// Get share to send to donation wallet (10 % charity donation)
uint256 donationShare = balance.mul(donationPercentage).div(100);
uint256 ownerShare = balance.su... | 0.8.4 |
// Mint boy
// - Mints lostboys by quantities | function mintBoy(uint numberOfBoys) public payable {
require(mintingActive, "Minting is not activated yet.");
require(numberOfBoys > 0, "Why are you minting less than zero boys.");
require(
totalSupply().add(numberOfBoys) <= MAX_LOSTBOYS,
'Only 10,000 boys are avail... | 0.8.4 |
// mintBoyAsMember
// - Mints lostboy as whitelisted member | function mintBoyAsMember(uint numberOfBoys) public payable {
require(isPresaleActive, "Presale is not active yet.");
require(numberOfBoys > 0, "Why are you minting less than zero boys.");
require(_whiteListedMembers[msg.sender] == MemberClaimStatus.Listed, "You are not a whitelisted member !"... | 0.8.4 |
/// @notice Disable internal _transfer function | function transferFrom(address from, address to, uint256 tokenId) public override(ERC721, IERC721) onlyManager {
// Disable internal _transfer function for ERC721 - do nth, must use safeTransferFrom to transfer token
_transfer(from, to, tokenId);
} | 0.7.6 |
/// @notice Mint a new token of `productId` and `serialNumber` and assigned to `to`
/// @dev Only `_manager` can mint | function mintItem(uint256 productId, uint256 serialNumber, address to) external override onlyManager returns (uint256) {
/// increase counter by one
_tokenCounter.increment();
uint256 newTokenId;
// retry if token clash. given it 10 retries, but shouldn't happen.
for (ui... | 0.7.6 |
/**
* @dev Safely transfers the ownership of a given token ID to another address
* If the target address is a contract, it must implement {IERC721Receiver-onERC721Received},
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))... | function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public {
require(
_isApprovedOrOwner(_msgSender(), tokenId),
"ERC721: transfer caller is not owner nor approved"
);
_safeTransferFrom(f... | 0.5.17 |
// member function to mint time based vesting tokens to a beneficiary | function mintTokensWithTimeBasedVesting(address beneficiary, uint256 tokens, uint256 start, uint256 cliff, uint256 duration) public onlyOwner {
require(beneficiary != 0x0);
require(tokens > 0);
vesting[beneficiary] = new TokenVesting(beneficiary, start, cliff, duration, false);
require(token.mint(... | 0.4.18 |
// Function to withdraw or send Ether from Contract owner's account to a specified account. | function TransferToGsContractFromOwnerAccount(address payable receiver, uint amount) public {
require(msg.sender == owner, "You're not owner of the account"); // Only the Owner of this contract can run this function.
require(amount < address(this).balance, "Insufficient balance.");
receiver.t... | 0.5.17 |
//
// Token Creation/Destruction Functions
//
// For a holder to buy an offer of tokens | function purchase()
payable
canEnter
returns (bool)
{
Holder holder = holders[msg.sender];
// offer must exist
require(holder.offerAmount > 0);
// offer not expired
require(holder.offerExpiry > now);
// correct payment has been sent
... | 0.4.10 |
// For holders to destroy tokens in return for ether during a redeeming
// round | function redeem(uint _amount)
public
canEnter
isHolder(msg.sender)
returns (bool)
{
uint redeemPrice;
uint eth;
Holder holder = holders[msg.sender];
require(_amount <= holder.tokenBalance);
updateDividendsFor(holde... | 0.4.10 |
// ========== MODIFIERS ========== //
// ========== MUTATIVE FUNCTIONS ========== //
// ========== PRIVATE / INTERNAL ========== //
// ========== RESTRICTED FUNCTIONS ========== // | function setRewardTokens(address[] calldata _tokens, bool[] calldata _statuses)
external
onlyOwner {
require(_tokens.length > 0, "please pass a positive number of reward tokens");
require(_tokens.length == _statuses.length, "please pass same number of tokens and statuses");
for (u... | 0.7.5 |
//
// Ballot functions
//
// To vote for a preferred Trustee. | function vote(address _candidate)
public
isHolder(msg.sender)
isHolder(_candidate)
returns (bool)
{
// Only prevent reentry not entry during panic
require(!__reMutex);
Holder holder = holders[msg.sender];
revoke(holder);
hol... | 0.4.10 |
/**
Get asset 1 twap price for the period of [now - secondsAgo, now]
*/ | function getTWAP(int56[] memory prices, uint32 secondsAgo)
internal
pure
returns (int128)
{
// Formula is
// 1.0001 ^ (currentPrice - pastPrice) / secondsAgo
if (secondsAgo == 0) {
return ABDKMath64x64.fromInt(1);
}
int256 currentPrice = in... | 0.7.6 |
/**
* Helper function to calculate how much to swap to deposit / withdraw
* In Uni Pool to satisfy the required buffer balance in xU3LP of 5%
*/ | function calculateSwapAmount(
uint256 amount0ToMint,
uint256 amount1ToMint,
uint256 amount0Minted,
uint256 amount1Minted,
int128 liquidityRatio
) internal pure returns (uint256 swapAmount) {
// formula: swapAmount =
// (amount0ToMint * amount1Minted -
... | 0.7.6 |
// comparator for 32-bit timestamps
// @return bool Whether a <= b | function lte(
uint32 time,
uint32 a,
uint32 b
) internal pure returns (bool) {
if (a <= time && b <= time) return a <= b;
uint256 aAdjusted = a > time ? a : a + 2**32;
uint256 bAdjusted = b > time ? b : b + 2**32;
return aAdjusted <= bAdjusted;
} | 0.7.6 |
// Loops through holders to find the holder with most votes and declares
// them to be the Executive; | function election()
internal
{
uint max;
uint winner;
uint votes;
uint8 i;
address addr;
if (0 == totalSupply) return;
while(++i != 0)
{
addr = holderIndex[i];
if (addr != 0x0) {
... | 0.4.10 |
/// @notice This mints a teddy.
/// @param recipient This is the address of the user who is minting the teddy.
/// @param voucher This is the unique NFTVoucher that is to be minted. | function mintNFT(address recipient, NFTVoucher calldata voucher) external payable returns (uint256) {
address signer = _verify(voucher);
require(voucher.tokenId > 0, "Invalid Token ID.");
require(voucher.edition >= 1 && voucher.edition <= 5, "Invalid token data. (Edition must be between 1 and 5)... | 0.8.0 |
/// @notice When a user orders a custom NFT, the user works with our designer to build the perfect NFT.
/// Once happy with the product, the metadata is updated using this function and locked.
/// @param tokenId The Token ID to be updated
/// @param uri The new URI to be set on the token. | function updateMetadata(uint256 tokenId, string calldata uri) external onlyOwner {
require(tokenId <= 100, "Customizations are only available for the first 100 tokens.");
require(_locks[tokenId] != true, "The metadata for this token is locked.");
_setTokenLock(tokenId, true);
_setTokenUR... | 0.8.0 |
/// @notice Gets all the tokens that the address owns.
/// @param _owner The address of an owner you want to view tokens of. | function getTokenIds(address _owner) external view returns (uint[] memory) {
uint[] memory _tokensOfOwner = new uint[](balanceOf(_owner));
uint i;
for (i = 0; i < balanceOf(_owner); i++) {
_tokensOfOwner[i] = tokenOfOwnerByIndex(_owner, i);
}
return (_tokensOfOwner)... | 0.8.0 |
/// @notice This safely converts a string into an uint.
/// @param _a This is the string to be converted into a uint. | function _safeParseInt(string memory _a) private pure returns (uint _parsedInt) {
bytes memory bresult = bytes(_a);
uint mint = 0;
bool decimals = false;
for (uint i = 0; i < bresult.length; i++) {
if ((uint(uint8(bresult[i])) >= 48) && (uint(uint8(bresult[i])) <= 57)) {
... | 0.8.0 |
/**
* @notice Make New 0xBatz
* @param amount Amount of 0xBatz to mint
* @dev Utilize unchecked {} and calldata for gas savings.
*/ | function mint(uint256 amount) public payable {
require(mintEnabled, "Minting is disabled.");
require(psupply + amount <= maxSupply - reserved, "Amount exceeds maximum supply of 0xBatz.");
require(amount <= perMint, "Amount exceeds current maximum 0xBatz per mint.");
require(price * amount <=... | 0.8.10 |
/**
* @notice Send reserved 0xBatz
* @param _to address to send reserved nfts to.
* @param _amount number of nfts to send
*/ | function fetchTeamReserved(address _to, uint16 _amount)
public
onlyOwner
{
require( _to != address(0), "Zero address error");
require( _amount <= reserved, "Exceeds reserved babies supply");
uint16 supply = psupply;
unchecked {
for (uint8 i = 0; i < _amount; i++) {... | 0.8.10 |
//////////////////////////////////////////////////
/// Begin Ulink token functionality
//////////////////////////////////////////////////
/// @dev Ulink token constructor | function Ulink() public
{
// Define owner
owner = msg.sender;
// Define initial owner supply. (ether here is used only to get the decimals right)
uint _initOwnerSupply = 50000 ether;
// One-time bulk mint given to owner
bool _success = mint(msg.sender, _initOwn... | 0.4.18 |
/**
* @dev Sets or upgrades the RariGovernanceTokenDistributor of the RariFundToken. Caller must have the {MinterRole}.
* @param newContract The address of the new RariGovernanceTokenDistributor contract.
* @param force Boolean indicating if we should not revert on validation error.
*/ | function setGovernanceTokenDistributor(address payable newContract, bool force) external onlyMinter {
if (!force && address(rariGovernanceTokenDistributor) != address(0)) {
require(rariGovernanceTokenDistributor.disabled(), "The old governance token distributor contract has not been disabl... | 0.5.17 |
/*
* @notice Moves `amount` tokens from the caller's account to `recipient`.
* @dev Claims RGT earned by the sender and `recipient` beforehand (so RariGovernanceTokenDistributor can continue distributing RGT considering the new RYPT balances).
* @return A boolean value indicating whether the operation succeeded.
... | function transfer(address recipient, uint256 amount) public returns (bool) {
// Claim RGT/set timestamp for initial transfer of RYPT to `recipient`
if (address(rariGovernanceTokenDistributor) != address(0) && block.number > rariGovernanceTokenDistributor.distributionStartBlock()) {
rariGo... | 0.5.17 |
/**
* @dev Creates `amount` tokens and assigns them to `account`, increasing the total supply. Caller must have the {MinterRole}.
* @dev Claims RGT earned by `account` beforehand (so RariGovernanceTokenDistributor can continue distributing RGT considering the new RYPT balance of the caller).
*/ | function mint(address account, uint256 amount) public onlyMinter returns (bool) {
if (address(rariGovernanceTokenDistributor) != address(0) && block.number > rariGovernanceTokenDistributor.distributionStartBlock()) {
// Claim RGT/set timestamp for initial transfer of RYPT to `account`
... | 0.5.17 |
/**
* @dev Retrives the latest mUSD/USD price given the prices of the underlying bAssets.
*/ | function getMUsdUsdPrice(uint256[] memory bAssetUsdPrices) internal view returns (uint256) {
(MassetStructs.Basset[] memory bAssets, ) = _basketManager.getBassets();
uint256 usdSupplyScaled = 0;
for (uint256 i = 0; i < bAssets.length; i++) usdSupplyScaled = usdSupplyScaled.add(bAssets[i].vaul... | 0.5.17 |
/**
* @notice Returns the price of each supported currency in USD.
*/ | function getCurrencyPricesInUsd() external view returns (uint256[] memory) {
// Get bAsset prices and mUSD price
uint256 ethUsdPrice = getEthUsdPrice();
uint256[] memory prices = new uint256[](7);
prices[0] = getDaiUsdPrice();
prices[1] = getPriceInEth("USDC").mul(ethUsdPric... | 0.5.17 |
/**
* @dev Returns a token's cToken contract address given its ERC20 contract address.
* @param erc20Contract The ERC20 contract address of the token.
*/ | function getCErc20Contract(address erc20Contract) private pure returns (address) {
if (erc20Contract == 0x6B175474E89094C44Da98b954EedeAC495271d0F) return 0x5d3a536E4D6DbD6114cc1Ead35777bAB948E3643; // DAI => cDAI
if (erc20Contract == 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48) return 0x39AA39c021dfba... | 0.5.17 |
/**
* @dev Approves tokens to Compound without spending gas on every deposit.
* @param erc20Contract The ERC20 contract address of the token.
* @param amount Amount of the specified token to approve to Compound.
*/ | function approve(address erc20Contract, uint256 amount) external {
address cErc20Contract = getCErc20Contract(erc20Contract);
IERC20 token = IERC20(erc20Contract);
uint256 allowance = token.allowance(address(this), cErc20Contract);
if (allowance == amount) return;
if (amount... | 0.5.17 |
/**
* @dev Deposits funds to the Compound pool. Assumes that you have already approved >= the amount to Compound.
* @param erc20Contract The ERC20 contract address of the token to be deposited.
* @param amount The amount of tokens to be deposited.
*/ | function deposit(address erc20Contract, uint256 amount) external {
require(amount > 0, "Amount must be greater than 0.");
CErc20 cErc20 = CErc20(getCErc20Contract(erc20Contract));
uint256 mintResult = cErc20.mint(amount);
require(mintResult == 0, "Error calling mint on Compound cToke... | 0.5.17 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.