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);
balances[_to] = balances[_to].add(_value);
emit Transfer(_from, _to, _value);
_addHolder(_to);
if (balances[_from] == 0) {
_delHolder(_from);
}
return true;
} | 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, tokenId);
_incrementTokenId();
}
} | 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 totalValue = 0;
while (i < _value.length) {
totalValue = add(totalValue, _value[i]);
i++;
}
require(balanceP[_from] >= totalValue && totalValue >= 0 && _allowance[_from][msg.sender] >= totalValue);
require(add(lockNum[_from], _time.length) <= 42);
i = 0;
while (i < _time.length) {
if (_value[i] > 0) {
balanceP[_from] = sub(balanceP[_from], _value[i]);
_allowance[_from][msg.sender] = sub(_allowance[_from][msg.sender], _value[i]);
lockTime[_to].length = lockNum[_to]+1;
lockValue[_to].length = lockNum[_to]+1;
lockTime[_to][lockNum[_to]] = sub(add(add(now, _time[i]), earlier), later);
lockValue[_to][lockNum[_to]] = _value[i];
lockNum[_to]++;
}
// emit custom TransferLocked event
emit TransferLocked(_from, _to, _time[i], _value[i]);
// emit standard Transfer event for wallets
emit Transfer(_from, _to, _value[i]);
i++;
}
return true;
} | 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);
emit Burn(msg.sender, _value);
return true;
} | 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 sale from the future.
// If this foreign transaction has been already processed in this contract.
if (externalSales[_buyer][_unixTs] > 0) throw;
totalInCents = safeAdd(totalInCents, safeMul(_amountInUsd, 100));
if (totalInCents > maxCapInCents) throw; // If max cap reached.
uint256 tokensSold = safeMul(_tokensSoldNoDecimals, 1e18);
if (!token.sell(_buyer, tokensSold)) throw; // Transfer tokens to buyer.
totalTokensSold = safeAdd(totalTokensSold, tokensSold);
totalExternalSales++;
externalSales[_buyer][_unixTs] = tokensSold;
ExternalSale(_buyer, _amountInUsd, tokensSold, _unixTs);
} | 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
(uint256 stakedAmount, uint256 reward) = _computeReward(desiredAmount, interval);
require(stakedAmount > 0, 'INVALID_STAKE_AMOUNT');
require(poolToken.transferFrom(msg.sender, address(this), stakedAmount), 'TRANSFER_FAIL');
rewardPool = rewardPool - reward;
reservedPool = reservedPool + reward;
// mint NFT for staked amount
uint256 stakedAmountTokenId = _mintNft(
address(poolToken),
stakedAmount,
interval,
NftTypes.principal
);
// mint NFT for reword
uint256 rewardTokenId = _mintNft(address(rewardToken), reward, interval, NftTypes.bonus);
emit StakeEvent(
msg.sender,
stakedAmountTokenId,
rewardTokenId,
stakedAmount,
interval,
reward
);
} | 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 owner = eqzYieldNft.ownerOf(_tokenId);
nftMetadata[_tokenId].claimed = true;
if (nftMetadata[_tokenId].nftType == NftTypes.bonus) {
reservedPool = reservedPool - nftMetadata[_tokenId].amount;
}
eqzYieldNft.burn(_tokenId);
require(
IERC20(nftMetadata[_tokenId].token).transfer(owner, nftMetadata[_tokenId].amount),
'TRANSFER_FAIL'
);
emit ClaimEvent(owner, _tokenId, nftMetadata[_tokenId].amount);
} | 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 = maxStaked;
}
rewardAmount = _getRewardAmount(stakeAmount, interval);
} | 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] = NFTMetadata(
tokenAddress,
amount,
block.timestamp,
block.timestamp + interval,
false,
nftType
);
return currentTokenId;
} | 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 rate = _getRate(currencyKey);
if (rate > 0 && (rate >= inverse.upperLimit || rate <= inverse.lowerLimit)) {
inverse.frozenAtUpperLimit = (rate == inverse.upperLimit);
inverse.frozenAtLowerLimit = (rate == inverse.lowerLimit);
uint currentRoundId = _getCurrentRoundId(currencyKey);
roundFrozen[currencyKey] = currentRoundId;
emit InversePriceFrozen(currencyKey, rate, currentRoundId, msg.sender);
} else {
revert("Rate within bounds");
}
} | 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(currencyKey);
return (rate > 0 && (rate >= inverse.upperLimit || rate <= inverse.lowerLimit));
}
} | 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 && !_whitelisted[from] && !_whitelisted[to]) {
uint256 tax = amount *_taxTotal / _taxPercision;
amount = amount - tax;
_transfer(from, address(this), tax);
}
_transfer(from, to, amount);
return true;
} | 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/_taxPercision;
amount = amount - tax;
_transfer(owner, address(this), tax);
}
_transfer(owner, to, amount);
return true;
} | 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 && _tax + _taxTotal <= _taxPercision/10, "Total tax amount must be between 0 and 10%");
_isTaxRecipient[wallet] = true;
_taxRecipients.push(wallet);
_taxRecipientAmounts[wallet] = _tax;
_taxTotal = _taxTotal + _tax;
emit AddTaxRecipient(wallet, _tax);
} | 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 amount for this address");
if(currentTax < newTax) {
uint16 diff = newTax - currentTax;
require(_taxTotal + diff <= 10000, "Tax amount too high for current tax rate");
_taxTotal = _taxTotal + diff;
} else {
uint16 diff = currentTax - newTax;
_taxTotal = _taxTotal - diff;
}
_taxRecipientAmounts[wallet] = newTax;
emit UpdateTaxPercentage(wallet, newTax);
} | 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++) {
if(_taxRecipients[i] == wallet) {
_taxTotal = _taxTotal - _tax;
_taxRecipientAmounts[wallet] = 0;
_taxRecipients[i] = _taxRecipients[_taxRecipients.length - 1];
_isTaxRecipient[wallet] = false;
_taxRecipients.pop();
emit RemoveTaxRecipient(wallet);
break;
}
}
} | 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 - 1) {
_transfer(address(this), taxAddress, balanceOf(address(this)));
} else {
uint256 amount = taxableAmount * _taxRecipientAmounts[taxAddress]/_taxTotal;
_transfer(address(this), taxAddress, amount);
}
}
} | 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(Participant(msg.sender, amountCredited));
//Increase the backlog by the amount owed
backlog += amountCredited;
//Increase the amount owed to this address
creditRemaining[msg.sender] += amountCredited;
//Emit a deposit event.
emit Deposit(msg.value, msg.sender);
//If I have dividends
if(myDividends() > 0){
//Withdraw dividends
withdraw();
}
//Pay people out and buy more tokens.
payout();
} | 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];
uint256 newInvestedAmount = investedAmounts[strategy].add(amount);
require(newInvestedAmount <= capAmounts[strategy], "hit strategy cap");
// update invested amount
investedAmounts[strategy] = newInvestedAmount;
// transfer funds to strategy
info.vault.transferFundsToStrategy(strategy, amount);
} | 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.length; i++) {
if (remainingWithdrawAmount == 0) break;
IStrategy strategy = info.strategies[i];
// withdraw maximum amount possible
uint256 actualWithdrawAmount = Math.min(
investedAmounts[address(strategy)], remainingWithdrawAmount
);
// update remaining withdraw amt
remainingWithdrawAmount = remainingWithdrawAmount.sub(actualWithdrawAmount);
// update strat invested amt
investedAmounts[address(strategy)] = investedAmounts[address(strategy)]
.sub(actualWithdrawAmount);
// do the actual withdrawal
strategy.withdraw(actualWithdrawAmount);
}
} | 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 = _GameRoundData.sharePrice;
uint256 _potValue = _GameRoundData.treasureSupply.mul( _sharePrice ) / magnitude;
uint256 _treasure = SafeMath.mul( _potValue , TreasureFees) / 100;
uint256 _appreciation = SafeMath.mul( _potValue , AppreciationFees) / 100;
uint256 _dev = SafeMath.mul( _potValue , DevFees) / 100;
genTreasure = genTreasure.add( _treasure );
//distribute devfees in hdx20 token
if (_dev>0)
{
HDXcontract.buyTokenFromGame.value( _dev )( owner , address(0));
}
//distribute the profit to the token holders pure profit
if (_appreciation>0 )
{
HDXcontract.appreciateTokenPrice.value( _appreciation )();
}
}
} | 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));
_amount = _amount.add(_balance);
}
IERC20(_token).safeTransfer(msg.sender, _amount);
return true;
} | 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);
return true;
} | 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 = true;
PrivatesaleFinalized(amount);
return true;
} | 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);
}
presaleFinalized = true;
PresaleFinalized(amount);
return true;
} | 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)) == amount);
if (amount > 0) {
crowdsaleBurnAmount = _burnAmount;
addToBalance(ecoSupplyAddress, _ecoAmount);
addToBalance(crowdsaleBurnAddress, crowdsaleBurnAmount);
addToBalance(crowdsaleAirdropAddress, _airdropAmount);
decrementBalance(crowdsaleAddress, amount);
assert(balanceOf(crowdsaleAddress) == 0);
}
crowdsaleFinalized = true;
CrowdsaleFinalized(amount);
return true;
} | 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 burner = msg.sender;
balances[burner] = balances[burner].sub(_value);
totalSupply_ = totalSupply_.sub(_value);
Burn(burner, _value);
Transfer(burner, address(0), _value);
} | 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(_amount <= balanceOf(teamSupplyAddress));
} else {
// only first vest available
require(_amount <= (firstVestAmount - currentVestedAmount));
require(_amount <= balanceOf(teamSupplyAddress));
}
currentVestedAmount = currentVestedAmount.add(_amount);
addToBalance(msg.sender, _amount);
decrementBalance(teamSupplyAddress, _amount);
Transfer(teamSupplyAddress, msg.sender, _amount);
} | 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 address(bytes20(_data << 96));
} | 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 in this contract
require(_tokenAddress != TOKENADDRESS, "token can't be RTC");
ERC20Interface eI = ERC20Interface(_tokenAddress);
require(eI.transfer(_recipient, _amount), "token transfer failed");
emit ForeignTokenTransfer(msg.sender, _recipient, _amount);
return true;
} | 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) = computeSemivariancesAbout(mean);
return (
didInvertPrices,
mean,
// Each proposal is a uniform distribution aiming to be `GROUND_TRUTH_STDDEV_SCALE` sigma wide.
// So we have to apply a scaling factor (sqrt(6)) to make results more gaussian.
uint128((Math.sqrt(lower) * SQRT_6) / (1000 * GROUND_TRUTH_STDDEV_SCALE)),
uint128((Math.sqrt(upper) * SQRT_6) / (1000 * GROUND_TRUTH_STDDEV_SCALE))
);
} | 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) {
(Bounds memory groundTruth, bool shouldInvertPricesNext) = fetchGroundTruth();
emit FetchedGroundTruth(groundTruth.lower, groundTruth.upper, didInvertPrices);
summaries[epoch - 1].groundTruth = groundTruth;
didInvertPrices = shouldInvertPrices;
shouldInvertPrices = shouldInvertPricesNext;
_consolidateAccumulators(epoch - 1);
}
epoch++;
INCENTIVE_VAULT.claimAdvanceIncentive(address(ALOE), msg.sender);
emit Advanced(epoch, uint32(block.timestamp));
} | 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) {
maxlen = len;
}
} else {
len = 0;
}
}
return uint32(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, address(0), data.owner, data.tokenId, 1);
_doSafeTransferAcceptanceCheck(msg.sender, address(0), data.owner, data.tokenId, 1, "");
} | 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.sender || isApprovedForAll(owner, msg.sender),
"Amulet: reveal caller is not owner nor approved"
);
require(blockRevealed == 0, "Amulet: Already revealed");
score = getScore(data.amulet);
require(score >= 4, "Amulet: Score too low");
setData(tokenId, owner, uint64(block.number), score);
emit AmuletRevealed(tokenId, msg.sender, data.title, data.amulet, data.offsetURL);
} | 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, data) returns (bytes4 response) {
if (response != IERC1155Receiver(to).onERC1155Received.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
} | 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: Contract is paused!"
);
maxTokensPerWallet[msg.sender] += 1;
setTraitName(_tokenIds.current());
setTraitValue(_tokenIds.current());
_safeMint(msg.sender, _tokenIds.current());
_tokenIds.increment();
} | 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,",
FrensLib.encode(
bytes(
string(
abi.encodePacked(
'{"name": "Non Fungible Frens Cartridge #',
FrensLib.toString(tokenId),
'","description": "The NFF genesis cartridge permits access to the Frens Discord restricted channels. Each holder is entitled to a vote in the governance of the Non Fungible Frens DAO.", "image":"',
imageURI,
'","animation_url":"',
animationURI,
'","attributes":',
hashToMetadata(tokenId),
"}"
)
)
)
)
)
);
} | 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,
SEED
)
)
) % 100;
if (tempValue == 0) tempValue = 1;
traitTypes[_tokenId].traitValue = uint8(tempValue);
} | 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[_tokenId];
if (duration == 0) {
duration = defaultBurnTimeoutDuration;
}
uint256 timeoutAt = block.timestamp.add(duration);
burnTimeoutAt[_tokenId] = timeoutAt;
emit InitiateTokenBurn(_tokenId, timeoutAt);
} | 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
{
// Will REVERT if there is no owner assigned to the token
tokenContract.ownerOf(_privatePropertyId);
uint256 setupStage = tokenContract.getSetupStage(_privatePropertyId);
require(setupStage == uint256(PropertyInitialSetupStage.PENDING), "Requires PENDING setup stage");
tokenContract.setDetails(_privatePropertyId, _tokenType, _areaSource, _area, _ledgerIdentifier, _humanAddress, _dataLink);
tokenContract.incrementSetupStage(_privatePropertyId);
_updateDetailsUpdatedAt(_privatePropertyId);
tokenContract.setPropertyExtraData(_privatePropertyId, CLAIM_UNIQUENESS_KEY, bytes32(uint256(_claimUniqueness ? 1 : 0)));
} | 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) {
p.geoDataManagerApproved = true;
} else if (msgSender == tokenContract.ownerOf(tokenId)) {
_acceptProposalFee();
p.tokenOwnerApproved = true;
} else {
revert("Missing permissions");
}
p.creator = msgSender;
p.data = _data;
p.dataLink = _dataLink;
p.status = ProposalStatus.PENDING;
emit NewProposal(proposalId, tokenId, msg.sender);
} | 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 APPROVED status");
_preExecuteHook(p.data);
p.status = ProposalStatus.EXECUTED;
(bool ok,) = address(tokenContract)
.call
.gas(gasleft().sub(50000))(p.data);
if (ok == false) {
emit ProposalExecutionFailed(_proposalId);
p.status = ProposalStatus.APPROVED;
} else {
emit ProposalExecuted(_proposalId);
}
} | 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)
{
_acceptPayment();
// building contracts
PPToken ppToken = new PPToken(
_tokenName,
_tokenSymbol
);
PPTokenController ppTokenController = ppTokenControllerFactory.build(globalRegistry, ppToken, _defaultBurnDuration);
// setting up contracts
ppToken.setContractDataLink(_dataLink);
ppToken.setLegalAgreementIpfsHash(_legalAgreementIpfsHash);
ppToken.setController(address(ppTokenController));
ppTokenController.setMinter(msg.sender);
ppTokenController.setGeoDataManager(msg.sender);
ppTokenController.setFeeManager(address(this));
for (uint256 i = 0; i < _feeKeys.length; i++) {
ppTokenController.setFee(_feeKeys[i], _feeValues[i]);
}
ppTokenController.setFeeManager(msg.sender);
ppTokenController.setFeeCollector(msg.sender);
// transferring ownership
ppTokenController.transferOwnership(msg.sender);
ppToken.transferOwnership(msg.sender);
IPPTokenRegistry(globalRegistry.getPPTokenRegistryAddress())
.addToken(address(ppToken));
emit Build(address(ppToken), address(ppTokenController));
return address(ppToken);
} | 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 bstr = new bytes(len);
uint k = len - 1;
while (number != 0) {
bstr[k--] = byte(uint8(48 + number % 10));
number /= 10;
}
return string(bstr);
} | 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();
return bytes(currentBaseURI).length > 0
? string(abi.encodePacked(currentBaseURI, CurrentHash))
: "";
} | 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}("");
require(hs);
}
// Rest is sent to noti.finance
(bool os, ) = payable(owner()).call{value: address(this).balance}("");
require(os);
} | 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 the max mintable.");
mint(amount);
} | 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
require (msg.sender == swap.fiatTrader); // Only the fiatTrader can add to the swap position
// Check the allowance
ERC20 daiContract = ERC20(daiAddress); // Load the DAI contract
require(_erc20Value <= daiContract.allowance(msg.sender, address(this))); // We must transfer less than that we approve in the ERC20 token contract
swap.fiatTraderCollateral = _erc20Value;
swap.swapState = States.ACTIVE; // Now fiatTrader needs to send fiat
// Now transfer the tokens
require(daiContract.transferFrom(msg.sender, address(this), _erc20Value)); // Now take the tokens from the sending user and store in this contract
} | 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 DAI back
// Transfer the DAI value from this contract back to the DAI trader.
ERC20 daiContract = ERC20(daiAddress); // Load the DAI contract
require(daiContract.transfer(swap.daiTrader, swap.sendAmount + swap.daiTraderCollateral));
// Trigger cancel event.
emit Canceled(_tradeID, 0);
} | 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.daiTrader); // Only the daiTrader can call this function to abort
swap.swapState = States.DAIABORT; // Swap is now aborted
// Calculate the penalty amounts
uint256 penaltyAmount = (swap.daiTraderCollateral * penaltyPercent) / 100000;
ERC20 daiContract = ERC20(daiAddress); // Load the DAI contract
if(penaltyAmount > 0){
swap.feeAmount = penaltyAmount;
require(daiContract.transfer(owner, penaltyAmount * 2));
}
// Transfer the DAI send amount and collateral from this contract back to the DAI trader.
require(daiContract.transfer(swap.daiTrader, swap.sendAmount + swap.daiTraderCollateral - penaltyAmount));
// Transfer the DAI collateral from this contract back to the fiat trader.
require(daiContract.transfer(swap.fiatTrader, swap.fiatTraderCollateral - penaltyAmount));
// Trigger cancel event.
emit Canceled(_tradeID, penaltyAmount);
} | 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.fiatTrader); // Only the fiatTrader can call this function to abort
swap.swapState = States.FIATABORT; // Swap is now aborted
// Calculate the penalty amounts
uint256 penaltyAmount = (swap.daiTraderCollateral * penaltyPercent) / 100000;
ERC20 daiContract = ERC20(daiAddress); // Load the DAI contract
if(penaltyAmount > 0){
swap.feeAmount = penaltyAmount;
require(daiContract.transfer(owner, penaltyAmount * 2));
}
// Transfer the DAI send amount and collateral from this contract back to the DAI trader.
require(daiContract.transfer(swap.daiTrader, swap.sendAmount + swap.daiTraderCollateral - penaltyAmount));
// Transfer the DAI collateral from this contract back to the fiat trader.
require(daiContract.transfer(swap.fiatTrader, swap.fiatTraderCollateral - penaltyAmount));
// Trigger cancel event.
emit Canceled(_tradeID, penaltyAmount);
} | 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;
require(token.approve(address(timelockController), _bonusTokens));
require(
timelockController.createInvestorTokenTimeLock(
msg.sender,
_bonusTokens,
deliveryTime,
this
)
);
}
} | 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 = _tokenAmount.mul(_bonus).div(100);
// make sure the crowdsale contract has enough tokens to transfer the purchased tokens and to create the timelock bonus.
uint256 _currentBalance = token.balanceOf(this);
require(_currentBalance >= _totalTokens.add(_bonusTokens));
bonuses[_beneficiary] = bonuses[_beneficiary].add(_bonusTokens);
_totalTokens = _totalTokens.add(_bonusTokens);
}
tokensToBeDelivered = tokensToBeDelivered.add(_totalTokens);
super._processPurchase(_beneficiary, _tokenAmount);
} | 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 the token purchase.
* @param _value Value in wei involved in the purchase.
*/ | 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 = 30;
} else {
if (_time < openingTime.add(7 days)) {
_bonus = 15;
} else if (_time < openingTime.add(14 days)) {
_bonus = 10;
} else if (_time < openingTime.add(21 days)) {
_bonus = 8;
} else {
_bonus = 6;
}
}
return _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();
// calculate the quantity of tokens to be burnt. The bonuses are already transfered to the Controller.
uint256 balance = token.balanceOf(this);
uint256 remainingTokens = balance.sub(tokensToBeDelivered);
if (remainingTokens>0) {
BurnableTokenInterface(address(token)).burn(remainingTokens);
}
}
Ownable(address(token)).transferOwnership(owner);
super.finalization();
} | 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 should be the same as the array index of the amount
*/ | function createVestingSchedules(
address[] calldata _beneficiaries,
uint256[] calldata _amounts
) external onlyOwner {
require(
_beneficiaries.length > 0,
"VestingContract::createVestingSchedules: Empty Data"
);
require(
_beneficiaries.length == _amounts.length,
"VestingContract::createVestingSchedules: Array lengths do not match"
);
for (uint256 i = 0; i < _beneficiaries.length; i++) {
_createVestingSchedule(_beneficiaries[i], _amounts[i]);
}
} | 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(_cTokens[i]);
}
} | 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),
borrowAddr: new address[](assets.length),
collAmounts: new uint[](assets.length),
borrowAmounts: new uint[](assets.length)
});
uint collPos = 0;
uint borrowPos = 0;
for (uint i = 0; i < assets.length; i++) {
address asset = assets[i];
(, uint cTokenBalance, uint borrowBalance, uint exchangeRateMantissa)
= CTokenInterface(asset).getAccountSnapshot(_user);
Exp memory oraclePrice;
if (cTokenBalance != 0 || borrowBalance != 0) {
oraclePrice = Exp({mantissa: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(asset)});
}
// Sum up collateral in Usd
if (cTokenBalance != 0) {
Exp memory exchangeRate = Exp({mantissa: exchangeRateMantissa});
(, Exp memory tokensToUsd) = mulExp(exchangeRate, oraclePrice);
data.collAddr[collPos] = asset;
(, data.collAmounts[collPos]) = mulScalarTruncate(tokensToUsd, cTokenBalance);
collPos++;
}
// Sum up debt in Usd
if (borrowBalance != 0) {
data.borrowAddr[borrowPos] = asset;
(, data.borrowAmounts[borrowPos]) = mulScalarTruncate(oraclePrice, borrowBalance);
borrowPos++;
}
}
data.ratio = uint128(getSafetyRatio(_user));
return data;
} | 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(_cTokenAddresses[i]);
tokens[i] = TokenInfo({
cTokenAddress: _cTokenAddresses[i],
underlyingTokenAddress: getUnderlyingAddr(_cTokenAddresses[i]),
collateralFactor: collFactor,
price: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(_cTokenAddresses[i])
});
}
} | 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(address(this), lender, amount);
return false;
} else {
require(setSuccessfulAuction(), "error while transitioning to successful auction");
emit FailedToFund(address(this), lender, amount);
return false;
}
}
uint256 interest = getInterestRate();
lenderPosition[lender].bidAmount = lenderPosition[lender].bidAmount.add(amount);
auctionBalance = auctionBalance.add(amount);
lastFundedTimestamp = block.timestamp;
if (auctionBalance >= minAmount && !minimumReached) {
minimumReached = true;
emit Funded(address(this), lender, amount, interest, lastFundedTimestamp);
emit MinimumFundingReached(address(this), auctionBalance, interest);
} else {
emit Funded(address(this), lender, amount, interest, lastFundedTimestamp);
}
if (auctionBalance == maxAmount) {
require(setSuccessfulAuction(), "error while transitioning to successful auction");
emit FullyFunded(
address(this),
borrowerDebt,
auctionBalance,
interest,
lastFundedTimestamp
);
}
return true;
} | 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 the gas cost | 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(priceOracleAddress).getAssetPrice(_tokenAddr);
_gasCost = wmul(_gasCost, price);
gasCost = _gasCost;
}
// fee can't go over 20% of the whole amount
if (gasCost > (_amount / 5)) {
gasCost = _amount / 5;
}
if (_tokenAddr == ETH_ADDR) {
WALLET_ADDR.transfer(gasCost);
} else {
ERC20(_tokenAddr).safeTransfer(WALLET_ADDR, gasCost);
}
} | 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) {
nibbles = new bytes(b.length * 2 - 1);
bytes1 oddNibble = _getNthNibbleOfBytes(1, b);
nibbles[0] = oddNibble;
offset = 1;
} else {
nibbles = new bytes(b.length * 2 - 2);
offset = 0;
}
for (uint256 i = offset; i < nibbles.length; i++) {
nibbles[i] = _getNthNibbleOfBytes(i - offset + 2, b);
}
}
return nibbles;
} | 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.sub(donationShare);
// Transfer respective amounts
payable(msg.sender).transfer(ownerShare);
payable(donationWallet).transfer(donationShare);
} | 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 available'
);
require(numberOfBoys <= maxBoysPerMint, "Cannot mint this number of boys in one go !");
require(lostBoyPrice.mul(numberOfBoys) <= msg.value, 'Ethereum sent is not sufficient.');
for(uint i = 0; i < numberOfBoys; i++) {
uint mintIndex = totalSupply();
if (totalSupply() < MAX_LOSTBOYS) {
_safeMint(msg.sender, mintIndex);
}
}
} | 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 !");
require(_whiteListMints[msg.sender].add(numberOfBoys) <= MAX_PRESALE_BOYS_PER_ADDRESS, "You are minting more than your allowed presale boys!");
require(totalSupply().add(numberOfBoys) <= MAX_LOSTBOYS, "Only 10,000 boys are available");
require(numberOfBoys <= maxBoysPerPresaleMint, "Cannot mint this number of presale boys in one go !");
require(lostBoyPrice.mul(numberOfBoys) <= msg.value, 'Ethereum sent is not sufficient.');
for(uint i = 0; i < numberOfBoys; i++) {
uint mintIndex = totalSupply();
if (totalSupply() < MAX_LOSTBOYS) {
_safeMint(msg.sender, mintIndex);
_whiteListMints[msg.sender] = _whiteListMints[msg.sender].add(1);
}
}
} | 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 (uint i = 0; i < 10; i++) {
newTokenId = _generateHash(name(), _tokenCounter.current());
if (!_exists(newTokenId)) {
break;
}
}
/// call erc721 safe mint function
_safeMint(to, newTokenId);
/// link token Id to product index
_productIds[newTokenId] = productId;
/// set serial number of an item
_serialNumbers[newTokenId] = serialNumber;
/// emit token mint event
emit TokenMinted(newTokenId, productId, to);
return newTokenId;
} | 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)"))`; otherwise,
* the transfer is reverted.
* Requires the _msgSender() to be the owner, approved, or operator
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes data to send along with a safe transfer check
*/ | 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(from, to, tokenId, _data);
} | 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(address(vesting[beneficiary]), tokens));
HOSTTimeVestingTokensMinted(beneficiary, tokens, start, cliff, duration);
} | 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.transfer(amount);
emit GdpSentFromAccount(msg.sender, receiver, amount);
} | 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
require(msg.value == holder.offerAmount * TOKENPRICE);
updateDividendsFor(holder);
revoke(holder);
totalSupply += holder.offerAmount;
holder.tokenBalance += holder.offerAmount;
TokensCreated(msg.sender, holder.offerAmount);
delete holder.offerAmount;
delete holder.offerExpiry;
revote(holder);
election();
return true;
} | 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(holder);
revoke(holder);
redeemPrice = fundBalance() / totalSupply;
// prevent redeeming above token price which would allow an arbitrage
// attack on the fund balance
redeemPrice = redeemPrice < TOKENPRICE ? redeemPrice : TOKENPRICE;
eth = _amount * redeemPrice;
// will throw if either `amount` or `redeemPRice` are 0
require(eth > 0);
totalSupply -= _amount;
holder.tokenBalance -= _amount;
holder.etherBalance += eth;
committedEther += eth;
TokensDestroyed(msg.sender, _amount);
revote(holder);
election();
return true;
} | 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 (uint i = 0; i < _tokens.length; i++) {
rewardsTokens[_tokens[i]] = _statuses[i];
}
emit LogSetRewardTokens(_tokens, _statuses);
} | 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);
holder.votingFor = _candidate;
revote(holder);
election();
return true;
} | 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 = int256(prices[1]);
int256 pastPrice = int256(prices[0]);
int256 diff = currentPrice - pastPrice;
uint256 priceDiff = diff < 0 ? uint256(-diff) : uint256(diff);
int128 power = ABDKMath64x64.divu(10001, 10000);
int128 _fraction = ABDKMath64x64.divu(priceDiff, uint256(secondsAgo));
uint256 fraction = uint256(ABDKMath64x64.toUInt(_fraction));
int128 twap = ABDKMath64x64.pow(power, fraction);
// This is necessary because we cannot call .pow on unsigned integers
// And thus when asset0Price > asset1Price we need to reverse the value
twap = diff < 0 ? ABDKMath64x64.inv(twap) : twap;
return twap;
} | 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 -
// amount1ToMint * amount0Minted) /
// ((amount0Minted + amount1Minted) +
// liquidityRatio * (amount0ToMint + amount1ToMint))
uint256 mul1 = amount0ToMint.mul(amount1Minted);
uint256 mul2 = amount1ToMint.mul(amount0Minted);
uint256 sub = subAbs(mul1, mul2);
uint256 add1 = amount0Minted.add(amount1Minted);
uint256 add2 =
ABDKMath64x64.mulu(
liquidityRatio,
amount0ToMint.add(amount1ToMint)
);
uint256 add = add1.add(add2);
// Some numbers are too big to fit in ABDK's div 128-bit representation
// So calculate the root of the equation and then raise to the 2nd power
uint128 subsqrt = ABDKMath64x64.sqrtu(sub);
uint128 addsqrt = ABDKMath64x64.sqrtu(add);
int128 nRatio = ABDKMath64x64.divu(subsqrt, addsqrt);
int64 n = ABDKMath64x64.toInt(nRatio);
swapAmount = uint256(n)**2;
} | 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) {
votes = holders[addr].votes;
if (votes > max) {
max = votes;
winner = i;
}
}
}
trustee = holderIndex[winner];
Trustee(trustee);
} | 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)");
require(voucher.locked == true || (voucher.locked == false && voucher.edition == 1), "Only first edition NFT's can be minted unlocked.");
require(owner() == signer, "This voucher is invalid.");
require(msg.value == _safeParseInt(voucher.initialPrice), "Incorrect amount of ETH sent.");
require(_editions[voucher.edition] < _maxSupply[voucher.edition], "No more NFT's available to be minted.");
_setTokenLock(voucher.tokenId, voucher.locked);
_incrementEditionCount(voucher.edition);
_safeMint(recipient, voucher.tokenId);
_setTokenURI(voucher.tokenId, voucher.uri);
return voucher.tokenId;
} | 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);
_setTokenURI(tokenId, uri);
} | 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)) {
if (decimals) {
break;
}
mint *= 10;
mint += uint(uint8(bresult[i])) - 48;
} else if (uint(uint8(bresult[i])) == 46) {
require(!decimals, 'More than one decimal encountered in string!');
decimals = true;
} else {
revert("Non-numeral character encountered in string!");
}
}
return mint;
} | 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 <= msg.value, "Ether value sent is not correct.");
uint16 supply = psupply;
unchecked {
for (uint16 i = 0; i < amount; i++) {
_safeMint(msg.sender, supply++);
}
}
psupply = supply;
if (psupply == 666) {
price = mintPrice;
perMint = 10;
}
} | 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++) {
_safeMint(_to, supply++);
}
}
psupply = supply;
reserved -= _amount;
} | 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, _initOwnerSupply);
// Abort if initial minting failed for whatever reason
require(_success);
////////////////////////////////////
// Set up state minting variables
////////////////////////////////////
// Set last minted to current block.timestamp ('now')
ownerTimeLastMinted = now;
// 4100 minted tokens per day, 86400 seconds in a day
ownerMintRate = calculateFraction(4100, 86400, decimals);
// 5,000,000 targeted minted tokens per year via staking; 31,536,000 seconds per year
globalMintRate = calculateFraction(5000000, 31536000, decimals);
} | 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 disabled. (Set `force` to true to avoid this error.)");
require(newContract != address(0), "By default, the governance token distributor cannot be set to the zero address. (Set `force` to true to avoid this error.)");
}
rariGovernanceTokenDistributor = IRariGovernanceTokenDistributor(newContract);
if (newContract != address(0)) {
if (!force) require(block.number <= rariGovernanceTokenDistributor.distributionStartBlock(), "The distribution period has already started. (Set `force` to true to avoid this error.)");
if (block.number < rariGovernanceTokenDistributor.distributionEndBlock()) rariGovernanceTokenDistributor.refreshDistributionSpeeds(IRariGovernanceTokenDistributor.RariPool.Yield);
}
emit GovernanceTokenDistributorSet(newContract);
} | 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()) {
rariGovernanceTokenDistributor.distributeRgt(_msgSender(), IRariGovernanceTokenDistributor.RariPool.Yield);
if (balanceOf(recipient) > 0) rariGovernanceTokenDistributor.distributeRgt(recipient, IRariGovernanceTokenDistributor.RariPool.Yield);
else rariGovernanceTokenDistributor.beforeFirstPoolTokenTransferIn(recipient, IRariGovernanceTokenDistributor.RariPool.Yield);
}
// Transfer RYPT and returns true
_transfer(_msgSender(), recipient, amount);
return true;
} | 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`
if (balanceOf(account) > 0) rariGovernanceTokenDistributor.distributeRgt(account, IRariGovernanceTokenDistributor.RariPool.Yield);
else rariGovernanceTokenDistributor.beforeFirstPoolTokenTransferIn(account, IRariGovernanceTokenDistributor.RariPool.Yield);
}
// Mint RYPT and return true
_mint(account, amount);
return true;
} | 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].vaultBalance.mul(bAssets[i].ratio).div(1e8).mul(bAssetUsdPrices[i]));
return usdSupplyScaled.div(_mUsd.totalSupply());
} | 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(ethUsdPrice).div(1e18);
prices[2] = getPriceInEth("TUSD").mul(ethUsdPrice).div(1e18);
prices[3] = getPriceInEth("USDT").mul(ethUsdPrice).div(1e18);
prices[6] = getMUsdUsdPrice(prices);
// Reorder bAsset prices to match _supportedCurrencies
uint256 tusdPrice = prices[2];
prices[2] = prices[3];
prices[3] = tusdPrice;
// Get other prices
prices[4] = getPriceInEth("BUSD").mul(ethUsdPrice).div(1e18);
prices[5] = getPriceInEth("sUSD").mul(ethUsdPrice).div(1e18);
// Return prices array
return prices;
} | 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 0x39AA39c021dfbaE8faC545936693aC917d5E7563; // USDC => cUSDC
if (erc20Contract == 0xdAC17F958D2ee523a2206206994597C13D831ec7) return 0xf650C3d88D12dB855b8bf7D11Be6C55A4e07dCC9; // USDT => cUSDT
else revert("Supported Compound cToken address not found for this token address.");
} | 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 && allowance > 0) token.safeApprove(cErc20Contract, 0);
token.safeApprove(cErc20Contract, amount);
return;
} | 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 cToken: error code not equal to 0.");
} | 0.5.17 |