comment
stringlengths 11
2.99k
| function_code
stringlengths 165
3.15k
| version
stringclasses 80
values |
---|---|---|
/**
*
* @dev mint tokens with the owner
* @param init // the init batch
* @param qty // qty for the batch
**/ | function mintTokens(uint256 init, uint256 qty) external onlyOwner {
require(isActive, 'Contract is not active');
require(totalSupply() < TOKEN_MAX, 'All tokens have been minted');
require(init >= totalSupply() + 1, 'Must start from the last mint batch');
uint256 i = init;
do{
_safeMint(msg.sender, i);
unchecked { ++i; }
}while(i <= qty);
} | 0.8.7 |
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/ | function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
} | 0.8.7 |
/*
* @dev End the staking pool
*/ | function end() public onlyOwner returns (bool){
require(!ended, "Staking already ended");
address _aux;
for(uint i = 0; i < holders.length(); i = i.add(1)){
_aux = holders.at(i);
rewardEnded[_aux] = getPendingRewards(_aux);
unclaimed[_aux] = 0;
stakingTime[_aux] = block.timestamp;
progressiveTime[_aux] = block.timestamp;
alreadyProgUnstaked[_aux] = 0;
amountPerInterval[_aux] = depositedTokens[_aux].div(number_intervals);
}
ended = true;
endTime = block.timestamp;
return true;
} | 0.8.7 |
/*
* @dev Max amount withdrawable on basis on time
*/ | function getMaxAmountWithdrawable(address _staker) public view returns(uint){
uint _res = 0;
if(block.timestamp.sub(stakingTime[msg.sender]) < unstakeTime && !ended && alreadyProgUnstaked[_staker] == 0){
_res = 0;
}else if(alreadyProgUnstaked[_staker] == 0 && !ended){
if(block.timestamp.sub(stakingTime[msg.sender]) > unstakeTime){
_res = depositedTokens[_staker].div(number_intervals);
}
}else{
uint _time = progressiveTime[_staker];
if(block.timestamp < _time.add(duration_interval)){
_res = 0;
}else{
uint _numIntervals = (block.timestamp.sub(_time)).div(duration_interval);
if(_numIntervals == 0){
return 0;
}
if(!ended){
_numIntervals = _numIntervals.add(1);
}
if(_numIntervals > number_intervals){
_numIntervals = number_intervals;
}
if(_numIntervals.mul(amountPerInterval[_staker]) > alreadyProgUnstaked[_staker]){
_res = _numIntervals.mul(amountPerInterval[_staker]).sub(alreadyProgUnstaked[_staker]);
}else{
_res = 0;
}
}
}
return _res;
} | 0.8.7 |
/*
* @dev Progressive Unstaking (Second, third, fourth... Progressive withdraws)
*/ | function withdraw2(uint amountToWithdraw) public returns (bool){
require(holders.contains(msg.sender), "Not a staker");
require(amountToWithdraw <= getMaxAmountWithdrawable(msg.sender), "Maximum reached");
require(alreadyProgUnstaked[msg.sender] > 0 || ended, "Use withdraw first");
alreadyProgUnstaked[msg.sender] = alreadyProgUnstaked[msg.sender].add(amountToWithdraw);
uint fee = amountToWithdraw.mul(unstakingFeeRate).div(1e4);
uint amountAfterFee = amountToWithdraw.sub(fee);
updateAccount(msg.sender, false, true);
require(Token(tokenDepositAddress).transfer(owner, fee), "Could not transfer withdraw fee.");
require(Token(tokenDepositAddress).transfer(msg.sender, amountAfterFee), "Could not transfer tokens.");
depositedTokens[msg.sender] = depositedTokens[msg.sender].sub(amountToWithdraw);
availablePoolSize = availablePoolSize.add(amountToWithdraw);
totalDeposited = totalDeposited.sub(amountToWithdraw);
if (holders.contains(msg.sender) && depositedTokens[msg.sender] == 0 && getPendingRewards(msg.sender) == 0) {
holders.remove(msg.sender);
firstTime[msg.sender] = 0;
}
return true;
} | 0.8.7 |
/*
* @dev Progressive Unstaking (First withdraw)
*/ | function withdraw(uint amountToWithdraw) public returns (bool){
require(holders.contains(msg.sender), "Not a staker");
require(alreadyProgUnstaked[msg.sender] == 0 && !ended , "Use withdraw2 function");
amountPerInterval[msg.sender] = depositedTokens[msg.sender].div(number_intervals);
require(depositedTokens[msg.sender].div(number_intervals) >= amountToWithdraw, "Invalid amount to withdraw");
alreadyProgUnstaked[msg.sender] = amountToWithdraw;
require(block.timestamp.sub(stakingTime[msg.sender]) > unstakeTime || ended, "You recently staked, please wait before withdrawing.");
updateAccount(msg.sender, false, true);
uint fee = amountToWithdraw.mul(unstakingFeeRate).div(1e4);
uint amountAfterFee = amountToWithdraw.sub(fee);
require(Token(tokenDepositAddress).transfer(owner, fee), "Could not transfer withdraw fee.");
require(Token(tokenDepositAddress).transfer(msg.sender, amountAfterFee), "Could not transfer tokens.");
depositedTokens[msg.sender] = depositedTokens[msg.sender].sub(amountToWithdraw);
availablePoolSize = availablePoolSize.add(amountToWithdraw);
totalDeposited = totalDeposited.sub(amountToWithdraw);
progressiveTime[msg.sender] = block.timestamp;
return true;
} | 0.8.7 |
/**
* Calculate x * y rounding down. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/ | function mul (int128 x, int128 y) internal pure returns (int128) {
int256 result = int256(x) * y >> 64;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
} | 0.6.12 |
/**
* Calculate x * y rounding towards zero, where x is signed 64.64 fixed point
* number and y is signed 256-bit integer number. Revert on overflow.
*
* @param x signed 64.64 fixed point number
* @param y signed 256-bit integer number
* @return signed 256-bit integer number
*/ | function muli (int128 x, int256 y) internal pure returns (int256) {
if (x == MIN_64x64) {
require (y >= -0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF &&
y <= 0x1000000000000000000000000000000000000000000000000);
return -y << 63;
} else {
bool negativeResult = false;
if (x < 0) {
x = -x;
negativeResult = true;
}
if (y < 0) {
y = -y; // We rely on overflow behavior here
negativeResult = !negativeResult;
}
uint256 absoluteResult = mulu (x, uint256 (y));
if (negativeResult) {
require (absoluteResult <=
0x8000000000000000000000000000000000000000000000000000000000000000);
return -int256 (absoluteResult); // We rely on overflow behavior here
} else {
require (absoluteResult <=
0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
return int256 (absoluteResult);
}
}
} | 0.6.12 |
/**
* Calculate x / y rounding towards zero. Revert on overflow or when y is
* zero.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/ | function div (int128 x, int128 y) internal pure returns (int128) {
require (y != 0);
int256 result = (int256 (x) << 64) / y;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
} | 0.6.12 |
/**
* Calculate x / y rounding towards zero, where x and y are signed 256-bit
* integer numbers. Revert on overflow or when y is zero.
*
* @param x signed 256-bit integer number
* @param y signed 256-bit integer number
* @return signed 64.64-bit fixed point number
*/ | function divi (int256 x, int256 y) internal pure returns (int128) {
require (y != 0);
bool negativeResult = false;
if (x < 0) {
x = -x; // We rely on overflow behavior here
negativeResult = true;
}
if (y < 0) {
y = -y; // We rely on overflow behavior here
negativeResult = !negativeResult;
}
uint128 absoluteResult = divuu (uint256 (x), uint256 (y));
if (negativeResult) {
require (absoluteResult <= 0x80000000000000000000000000000000);
return -int128 (absoluteResult); // We rely on overflow behavior here
} else {
require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
return int128 (absoluteResult); // We rely on overflow behavior here
}
} | 0.6.12 |
// NOTE: we return and unscaled integer between roughly
// 8 and 135 to approximate the gas fee for the
// velocity transaction | function calc_fee_gas(
uint256 max_gas_block,
uint256 min_gas_tx,
uint256 ema_long,
uint256 tx_size,
uint256 total_supply,
uint256 _gov_fee_factor
) public pure returns (uint256) {
uint256 max_gas_chi_per_block = max_gas_block;
uint256 min_gas_chi_fee_per_tx = min_gas_tx;
uint256 tx_fee_ratio_disc =
calc_fee_ratio_discrete(0, ema_long, tx_size, total_supply, _gov_fee_factor);
uint256 tx_fee_chi_disc =
max_gas_chi_per_block * tx_fee_ratio_disc / 100 / 10**18;
if ( tx_fee_chi_disc < min_gas_chi_fee_per_tx ) {
tx_fee_chi_disc = min_gas_chi_fee_per_tx;
}
return tx_fee_chi_disc;
} | 0.5.17 |
/**
* Calculate geometric average of x and y, i.e. sqrt (x * y) rounding down.
* Revert on overflow or in case x * y is negative.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/ | function gavg (int128 x, int128 y) internal pure returns (int128) {
int256 m = int256 (x) * int256 (y);
require (m >= 0);
require (m <
0x4000000000000000000000000000000000000000000000000000000000000000);
return int128 (sqrtu (uint256 (m), uint256 (x) + uint256 (y) >> 1));
} | 0.6.12 |
/**
* Calculate x^y assuming 0^0 is 1, where x is signed 64.64 fixed point number
* and y is unsigned 256-bit integer number. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @param y uint256 value
* @return signed 64.64-bit fixed point number
*/ | function pow (int128 x, uint256 y) internal pure returns (int128) {
uint256 absoluteResult;
bool negativeResult = false;
if (x >= 0) {
absoluteResult = powu (uint256 (x) << 63, y);
} else {
// We rely on overflow behavior here
absoluteResult = powu (uint256 (uint128 (-x)) << 63, y);
negativeResult = y & 1 > 0;
}
absoluteResult >>= 63;
if (negativeResult) {
require (absoluteResult <= 0x80000000000000000000000000000000);
return -int128 (absoluteResult); // We rely on overflow behavior here
} else {
require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
return int128 (absoluteResult); // We rely on overflow behavior here
}
} | 0.6.12 |
/**
* Calculate natural exponent of x. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/ | function exp (int128 x) internal pure returns (int128) {
require (x < 0x400000000000000000); // Overflow
if (x < -0x400000000000000000) return 0; // Underflow
return exp_2 (
int128 (int256 (x) * 0x171547652B82FE1777D0FFDA0D23A7D12 >> 128));
} | 0.6.12 |
/**
* Calculate sqrt (x) rounding down, where x is unsigned 256-bit integer
* number.
*
* @param x unsigned 256-bit integer number
* @return unsigned 128-bit integer number
*/ | function sqrtu (uint256 x, uint256 r) private pure returns (uint128) {
if (x == 0) return 0;
else {
require (r > 0);
while (true) {
uint256 rr = x / r;
if (r == rr || r + 1 == rr) return uint128 (r);
else if (r == rr + 1) return uint128 (rr);
r = r + rr + 1 >> 1;
}
}
} | 0.6.12 |
// Must be internal because of the struct | function calcMintFractionalFRAX(MintFF_Params memory params) internal pure returns (uint256, uint256) {
// Since solidity truncates division, every division operation must be the last operation in the equation to ensure minimum error
// The contract must check the proper ratio was sent to mint FRAX. We do this by seeing the minimum mintable FRAX based on each amount
uint256 fxs_dollar_value_d18;
uint256 c_dollar_value_d18;
// Scoping for stack concerns
{
// USD amounts of the collateral and the FXS
fxs_dollar_value_d18 = params.fxs_amount.mul(params.fxs_price_usd).div(1e6);
c_dollar_value_d18 = params.collateral_amount.mul(params.col_price_usd).div(1e6);
}
uint calculated_fxs_dollar_value_d18 =
(c_dollar_value_d18.mul(1e6).div(params.col_ratio))
.sub(c_dollar_value_d18);
uint calculated_fxs_needed = calculated_fxs_dollar_value_d18.mul(1e6).div(params.fxs_price_usd);
return (
c_dollar_value_d18.add(calculated_fxs_dollar_value_d18),
calculated_fxs_needed
);
} | 0.8.6 |
/**
* @notice Called when LINK is sent to the contract via `transferAndCall`
* @dev The data payload's first 2 words will be overwritten by the `_sender` and `_amount`
* values to ensure correctness. Calls oracleRequest.
* @param _sender Address of the sender
* @param _amount Amount of LINK sent (specified in wei)
* @param _data Payload of the transaction
*/ | function onTokenTransfer(
address _sender,
uint256 _amount,
bytes _data
)
public
onlyLINK
validRequestLength(_data)
permittedFunctionsForLINK(_data)
{
assembly { // solhint-disable-line no-inline-assembly
mstore(add(_data, 36), _sender) // ensure correct sender is passed
mstore(add(_data, 68), _amount) // ensure correct amount is passed
}
// solhint-disable-next-line avoid-low-level-calls
require(address(this).delegatecall(_data), "Unable to create request"); // calls oracleRequest
} | 0.4.24 |
// Returns value of collateral that must increase to reach recollateralization target (if 0 means no recollateralization) | function recollateralizeAmount(uint256 total_supply, uint256 global_collateral_ratio, uint256 global_collat_value) public pure returns (uint256) {
uint256 target_collat_value = total_supply.mul(global_collateral_ratio).div(1e6); // We want 18 decimals of precision so divide by 1e6; total_supply is 1e18 and global_collateral_ratio is 1e6
// Subtract the current value of collateral from the target value needed, if higher than 0 then system needs to recollateralize
return target_collat_value.sub(global_collat_value); // If recollateralization is not needed, throws a subtraction underflow
// return(recollateralization_left);
} | 0.8.6 |
/// @notice use token address ETH_TOKEN_ADDRESS for ether
/// @dev makes a trade between src and dest token and send dest token to destAddress
/// @param src Src token
/// @param srcAmount amount of src tokens
/// @param dest Destination token
/// @param destAddress Address to send tokens to
/// @param maxDestAmount A limit on the amount of dest tokens
/// @param minConversionRate The minimal conversion rate. If actual rate is lower, trade is canceled.
/// @param walletId is the wallet ID to send part of the fees
/// @return amount of actual dest tokens | function trade(
ERC20 src,
uint srcAmount,
ERC20 dest,
address destAddress,
uint maxDestAmount,
uint minConversionRate,
address walletId
)
public
payable
returns(uint)
{
require(enabled);
uint userSrcBalanceBefore;
uint userSrcBalanceAfter;
uint userDestBalanceBefore;
uint userDestBalanceAfter;
userSrcBalanceBefore = getBalance(src, msg.sender);
if (src == ETH_TOKEN_ADDRESS)
userSrcBalanceBefore += msg.value;
userDestBalanceBefore = getBalance(dest, destAddress);
uint actualDestAmount = doTrade(src,
srcAmount,
dest,
destAddress,
maxDestAmount,
minConversionRate,
walletId
);
require(actualDestAmount > 0);
userSrcBalanceAfter = getBalance(src, msg.sender);
userDestBalanceAfter = getBalance(dest, destAddress);
require(userSrcBalanceAfter <= userSrcBalanceBefore);
require(userDestBalanceAfter >= userDestBalanceBefore);
require((userDestBalanceAfter - userDestBalanceBefore) >=
calcDstQty((userSrcBalanceBefore - userSrcBalanceAfter), getDecimals(src), getDecimals(dest),
minConversionRate));
return actualDestAmount;
} | 0.4.18 |
/// @notice can be called only by admin
/// @dev add or deletes a reserve to/from the network.
/// @param reserve The reserve address.
/// @param add If true, the add reserve. Otherwise delete reserve. | function addReserve(KyberReserveInterface reserve, bool add) public onlyAdmin {
if (add) {
require(!isReserve[reserve]);
reserves.push(reserve);
isReserve[reserve] = true;
AddReserveToNetwork(reserve, true);
} else {
isReserve[reserve] = false;
// will have trouble if more than 50k reserves...
for (uint i = 0; i < reserves.length; i++) {
if (reserves[i] == reserve) {
reserves[i] = reserves[reserves.length - 1];
reserves.length--;
AddReserveToNetwork(reserve, false);
break;
}
}
}
} | 0.4.18 |
/// @notice can be called only by admin
/// @dev allow or prevent a specific reserve to trade a pair of tokens
/// @param reserve The reserve address.
/// @param src Src token
/// @param dest Destination token
/// @param add If true then enable trade, otherwise delist pair. | function listPairForReserve(address reserve, ERC20 src, ERC20 dest, bool add) public onlyAdmin {
(perReserveListedPairs[reserve])[keccak256(src, dest)] = add;
if (src != ETH_TOKEN_ADDRESS) {
if (add) {
src.approve(reserve, 2**255); // approve infinity
} else {
src.approve(reserve, 0);
}
}
setDecimals(src);
setDecimals(dest);
ListReservePairs(reserve, src, dest, add);
} | 0.4.18 |
/// @notice use token address ETH_TOKEN_ADDRESS for ether
/// @dev do one trade with a reserve
/// @param src Src token
/// @param amount amount of src tokens
/// @param dest Destination token
/// @param destAddress Address to send tokens to
/// @param reserve Reserve to use
/// @param validate If true, additional validations are applicable
/// @return true if trade is successful | function doReserveTrade(
ERC20 src,
uint amount,
ERC20 dest,
address destAddress,
uint expectedDestAmount,
KyberReserveInterface reserve,
uint conversionRate,
bool validate
)
internal
returns(bool)
{
uint callValue = 0;
if (src == ETH_TOKEN_ADDRESS) {
callValue = amount;
} else {
// take src tokens to this contract
src.transferFrom(msg.sender, this, amount);
}
// reserve sends tokens/eth to network. network sends it to destination
require(reserve.trade.value(callValue)(src, amount, dest, this, conversionRate, validate));
if (dest == ETH_TOKEN_ADDRESS) {
destAddress.transfer(expectedDestAmount);
} else {
require(dest.transfer(destAddress, expectedDestAmount));
}
return true;
} | 0.4.18 |
/// @notice use token address ETH_TOKEN_ADDRESS for ether
/// @dev checks that user sent ether/tokens to contract before trade
/// @param src Src token
/// @param srcAmount amount of src tokens
/// @return true if input is valid | function validateTradeInput(ERC20 src, uint srcAmount, address destAddress) internal view returns(bool) {
if ((srcAmount >= MAX_QTY) || (srcAmount == 0) || (destAddress == 0))
return false;
if (src == ETH_TOKEN_ADDRESS) {
if (msg.value != srcAmount)
return false;
} else {
if ((msg.value != 0) || (src.allowance(msg.sender, this) < srcAmount))
return false;
}
return true;
} | 0.4.18 |
/**
* @dev When accumulated CAPs have last been claimed for a CosmoMask index
*/ | function lastClaim(uint256 tokenIndex) public view returns (uint256) {
require(ICosmoArtShort(nftAddress).ownerOf(tokenIndex) != address(0), "CosmoArtPower: owner cannot be 0 address");
require(tokenIndex < ICosmoArtShort(nftAddress).totalSupply(), "CosmoArtPower: CosmoArt at index has not been minted yet");
uint256 lastClaimed = uint256(_lastClaim[tokenIndex]) != 0
? uint256(_lastClaim[tokenIndex])
: emissionStart;
return lastClaimed;
} | 0.7.6 |
/**
* @dev Accumulated CAP tokens for a CosmoMask token index.
*/ | function accumulated(uint256 tokenIndex) public view returns (uint256) {
require(block.timestamp > emissionStart, "CosmoArtPower: emission has not started yet");
require(ICosmoArtShort(nftAddress).ownerOf(tokenIndex) != address(0), "CosmoArtPower: owner cannot be 0 address");
require(tokenIndex < ICosmoArtShort(nftAddress).totalSupply(), "CosmoArtPower: CosmoArt at index has not been minted yet");
uint256 lastClaimed = lastClaim(tokenIndex);
// Sanity check if last claim was on or after emission end
if (lastClaimed >= emissionEnd)
return 0;
// Getting the min value of both
uint256 accumulationPeriod = block.timestamp < emissionEnd ? block.timestamp : emissionEnd;
uint256 totalAccumulated = accumulationPeriod.sub(lastClaimed).mul(emissionPerDay).div(SECONDS_IN_A_DAY);
// If claim hasn't been done before for the index, add initial allotment (plus prereveal multiplier if applicable)
if (lastClaimed == emissionStart) {
uint256 initialAllotment = ICosmoArtShort(nftAddress).isMintedBeforeReveal(tokenIndex) == true
? INITIAL_ALLOTMENT.mul(PRE_REVEAL_MULTIPLIER)
: INITIAL_ALLOTMENT;
totalAccumulated = totalAccumulated.add(initialAllotment);
}
return totalAccumulated;
} | 0.7.6 |
/**
* @dev Claim mints CAPs and supports multiple CosmoMask token indices at once.
*/ | function claim(uint256[] memory tokenIndices) public returns (uint256) {
require(block.timestamp > emissionStart, "CosmoArtPower: Emission has not started yet");
uint256 totalClaimQty = 0;
for (uint256 i = 0; i < tokenIndices.length; i++) {
// Sanity check for non-minted index
require(tokenIndices[i] < ICosmoArtShort(nftAddress).totalSupply(), "CosmoArtPower: CosmoArt at index has not been minted yet");
// Duplicate token index check
for (uint256 j = i + 1; j < tokenIndices.length; j++)
require(tokenIndices[i] != tokenIndices[j], "CosmoArtPower: duplicate token index" );
uint256 tokenIndex = tokenIndices[i];
require(ICosmoArtShort(nftAddress).ownerOf(tokenIndex) == msg.sender, "CosmoArtPower: sender is not the owner");
uint256 claimQty = accumulated(tokenIndex);
if (claimQty != 0) {
totalClaimQty = totalClaimQty.add(claimQty);
_lastClaim[tokenIndex] = block.timestamp;
}
}
require(totalClaimQty != 0, "CosmoArtPower: no accumulated tokens");
_mint(msg.sender, totalClaimQty);
return totalClaimQty;
} | 0.7.6 |
// minting functions (normal) | function normalMint() payable external onlySender publicMinting {
require(msg.value == mintingCost, "Wrong Cost!");
require(normalTokensMinted + 1 <= availableTokens, "No available tokens remaining!");
uint _mintId = getNormalMintId();
addNormalTokensMinted();
_mint(msg.sender, _mintId);
emit Mint(msg.sender, _mintId);
} | 0.8.6 |
/* - Rebase function - */ | function rebase(uint256 scaling_modifier)
external
onlyRebaser
{
uint256 prevVelosScalingFactor = velosScalingFactor;
// velosScalingFactor is in precision 24
velosScalingFactor = velosScalingFactor
.mul(scaling_modifier)
.div(internalDecimals);
velosScalingFactor = Math.min(velosScalingFactor, 1 * internalDecimals);
totalSupply = initSupply.mul(velosScalingFactor).div(internalDecimals);
emit Rebase(prevVelosScalingFactor, velosScalingFactor);
} | 0.5.17 |
/**
* Add market information (price and total borrowed par if the market is closing) to the cache.
* Return true if the market information did not previously exist in the cache.
*/ | function addMarket(
MarketCache memory cache,
Storage.State storage state,
uint256 marketId
)
internal
view
returns (bool)
{
if (cache.hasMarket(marketId)) {
return false;
}
cache.markets[marketId].price = state.fetchPrice(marketId);
if (state.markets[marketId].isClosing) {
cache.markets[marketId].isClosing = true;
cache.markets[marketId].borrowPar = state.getTotalPar(marketId).borrow;
}
return true;
} | 0.5.7 |
/* ============ Util Functions ============ */ | function uint2str(uint _i) internal pure returns (string memory) {
if (_i == 0) {
return "0";
}
uint j = _i;
uint len;
while (j != 0) {
len++;
j /= 10;
}
bytes memory bStr = new bytes(len);
uint k = len;
while (_i != 0) {
k = k - 1;
uint8 temp = (48 + uint8(_i - _i / 10 * 10));
bytes1 b1 = bytes1(temp);
bStr[k] = b1;
_i /= 10;
}
return string(bStr);
} | 0.7.6 |
/**
* Destroy tokens from other account
*
* Remove `_value` tokens from the system irreversibly on behalf of `_from`.
*
* @param _from the address of the sender
* @param _value the amount of money to burn
*/ | function burnFrom(address _from, uint256 _value) public returns (bool success) {
require(balanceOf[_from] >= _value); // Check if the targeted balance is enough
require(_value <= allowance[_from][msg.sender]); // Check allowance
balanceOf[_from] -= _value; // Subtract from the targeted balance
allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance
totalSupply -= _value; // Update totalSupply
Burn(_from, _value);
return true;
} | 0.4.19 |
/**
* @dev Multiplies two numbers, throws on overflow.
*/ | function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
} | 0.4.24 |
/**
* @dev Integer division of two numbers, truncating the quotient.
*/ | function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
} | 0.4.24 |
/**
* Get a new market Index based on the old index and market interest rate.
* Calculate interest for borrowers by using the formula rate * time. Approximates
* continuously-compounded interest when called frequently, but is much more
* gas-efficient to calculate. For suppliers, the interest rate is adjusted by the earningsRate,
* then prorated the across all suppliers.
*
* @param index The old index for a market
* @param rate The current interest rate of the market
* @param totalPar The total supply and borrow par values of the market
* @param earningsRate The portion of the interest that is forwarded to the suppliers
* @return The updated index for a market
*/ | function calculateNewIndex(
Index memory index,
Rate memory rate,
Types.TotalPar memory totalPar,
Decimal.D256 memory earningsRate
)
internal
view
returns (Index memory)
{
(
Types.Wei memory supplyWei,
Types.Wei memory borrowWei
) = totalParToWei(totalPar, index);
// get interest increase for borrowers
uint32 currentTime = Time.currentTime();
uint256 borrowInterest = rate.value.mul(uint256(currentTime).sub(index.lastUpdate));
// get interest increase for suppliers
uint256 supplyInterest;
if (Types.isZero(supplyWei)) {
supplyInterest = 0;
} else {
supplyInterest = Decimal.mul(borrowInterest, earningsRate);
if (borrowWei.value < supplyWei.value) {
supplyInterest = Math.getPartial(supplyInterest, borrowWei.value, supplyWei.value);
}
}
assert(supplyInterest <= borrowInterest);
return Index({
borrow: Math.getPartial(index.borrow, borrowInterest, BASE).add(index.borrow).to96(),
supply: Math.getPartial(index.supply, supplyInterest, BASE).add(index.supply).to96(),
lastUpdate: currentTime
});
} | 0.5.7 |
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/ | function approve(address _spender, uint256 _value) public returns (bool) {
// avoid race condition
require((_value == 0) || (allowed[msg.sender][_spender] == 0), "reset allowance to 0 before change it's value.");
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
} | 0.4.24 |
/*
* Convert a principal amount to a token amount given an index.
*/ | function parToWei(
Types.Par memory input,
Index memory index
)
internal
pure
returns (Types.Wei memory)
{
uint256 inputValue = uint256(input.value);
if (input.sign) {
return Types.Wei({
sign: true,
value: inputValue.getPartial(index.supply, BASE)
});
} else {
return Types.Wei({
sign: false,
value: inputValue.getPartialRoundUp(index.borrow, BASE)
});
}
} | 0.5.7 |
/*
* Convert the total supply and borrow principal amounts of a market to total supply and borrow
* token amounts.
*/ | function totalParToWei(
Types.TotalPar memory totalPar,
Index memory index
)
internal
pure
returns (Types.Wei memory, Types.Wei memory)
{
Types.Par memory supplyPar = Types.Par({
sign: true,
value: totalPar.supply
});
Types.Par memory borrowPar = Types.Par({
sign: false,
value: totalPar.borrow
});
Types.Wei memory supplyWei = parToWei(supplyPar, index);
Types.Wei memory borrowWei = parToWei(borrowPar, index);
return (supplyWei, borrowWei);
} | 0.5.7 |
/**
* @param _holder address of token holder to check
* @return bool - status of freezing and group
*/ | function isFreezed (address _holder) public view returns(bool, uint) {
bool freezed = false;
uint i = 0;
while (i < groups) {
uint index = indexOf(_holder, lockup[i].holders);
if (index == 0) {
if (checkZeroIndex(_holder, i)) {
freezed = true;
i++;
continue;
}
else {
i++;
continue;
}
}
if (index != 0) {
freezed = true;
i++;
continue;
}
i++;
}
if (!freezed) i = 0;
return (freezed, i);
} | 0.5.2 |
/**
* @dev calculate how much month have gone after end of ICO
*/ | function getFullMonthAfterIco () internal view returns (uint256) {
uint256 currentTime = block.timestamp;
if (currentTime < endOfIco)
return 0;
else {
uint256 delta = currentTime - endOfIco;
uint256 step = 2592000;
if (delta > step) {
uint256 times = delta.div(step);
return times;
}
else {
return 0;
}
}
} | 0.5.2 |
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/ | function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
unchecked {
_approve(sender, _msgSender(), currentAllowance - amount);
}
return true;
} | 0.8.10 |
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/ | function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
}
return true;
} | 0.8.10 |
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/ | function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
} | 0.8.10 |
//Unlocks the contract for owner when _lockTime is exceeds | function unlock() public virtual {
require(_previousOwner == msg.sender, "You don't have permission to unlock");
require(now > _lockTime , "Contract is locked until 7 days");
emit OwnershipTransferred(_owner, _previousOwner);
_owner = _previousOwner;
} | 0.6.12 |
/// @notice each address on the presale list may mint up to 3 tokens at the presale price | function presaleMint(bytes32[] calldata _merkleProof, uint quantity) external payable {
require(isPresaleActive(), "PRESALE_INACTIVE");
require(verifyPresale(_merkleProof, msg.sender), "PRESALE_NOT_VERIFIED");
require(totalSupply() + quantity <= COLLECTION_SIZE, "EXCEEDS_COLLECTION_SIZE");
require(_presaleClaimed[msg.sender] + quantity <= PRESALE_LIMIT, "3_TOKEN_LIMIT");
uint cost;
cost = quantity * PRESALE_PRICE;
require(msg.value >= cost, "VALUE_TOO_LOW");
_presaleClaimed[msg.sender] += quantity;
_safeMint(msg.sender, quantity);
} | 0.8.9 |
/// @notice may mint up to 5 tokens per transaction at the public sale price. | function mint(uint quantity) external payable {
require(isPublicSaleActive(), "PUBLIC_SALE_INACTIVE");
require(quantity <= PUBLIC_LIMIT, "5_TOKEN_LIMIT");
require(totalSupply() + quantity <= COLLECTION_SIZE, "EXCEEDS_COLLECTION_SIZE");
uint cost;
cost = quantity * PUBLIC_PRICE;
require(msg.value >= cost, "VALUE_TOO_LOW");
_safeMint(msg.sender, quantity);
} | 0.8.9 |
//Admin pays dev and management team. | function payToken() public onlyOwner {
//check if it's past the next payperiod.
require(block.timestamp >= (time + locktime), "Period not reached yet. ");
//Sends dev payment.
require(token.transfer(dev, devAmount) == true, "You don't have enough in balance. ");
//sends management payments.
require(token.transfer(safe, managementAmount) == true, "You don't have enough in balance. ");
require(token.transfer(mike, managementAmount) == true, "You don't have enough in balance. ");
require(token.transfer(ghost, managementAmount) == true, "You don't have enough in balance. ");
time += locktime;
} | 0.7.1 |
//human 0.1 standard. Just an arbitrary versioning scheme. | function BoxTrade(
) {
balances[msg.sender] = 100000000000000000;
totalSupply = 100000000000000000;
name = "BoxTrade"; // Set the name for display purposes
decimals = 5; // Amount of decimals for display purposes
symbol = "BOXY"; // Set the symbol for display purposes
} | 0.4.23 |
// **** ADD LIQUIDITY **** | function _addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin
) internal virtual returns (uint amountA, uint amountB) {
// create the pair if it doesn't exist yet
if (IUniswapV2Factory(factory).getPair(tokenA, tokenB) == address(0)) {
IUniswapV2Factory(factory).createPair(tokenA, tokenB);
}
(uint reserveA, uint reserveB) = UniswapV2Library.getReserves(factory, tokenA, tokenB);
if (reserveA == 0 && reserveB == 0) {
(amountA, amountB) = (amountADesired, amountBDesired);
} else {
uint amountBOptimal = UniswapV2Library.quote(amountADesired, reserveA, reserveB);
if (amountBOptimal <= amountBDesired) {
require(amountBOptimal >= amountBMin, 'UniswapV2Router: INSUFFICIENT_B_AMOUNT');
(amountA, amountB) = (amountADesired, amountBOptimal);
} else {
uint amountAOptimal = UniswapV2Library.quote(amountBDesired, reserveB, reserveA);
assert(amountAOptimal <= amountADesired);
require(amountAOptimal >= amountAMin, 'UniswapV2Router: INSUFFICIENT_A_AMOUNT');
(amountA, amountB) = (amountAOptimal, amountBDesired);
}
}
} | 0.6.6 |
// **** REMOVE LIQUIDITY **** | function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) public virtual override ensure(deadline) returns (uint amountA, uint amountB) {
address pair = UniswapV2Library.pairFor(factory, tokenA, tokenB);
IUniswapV2Pair(pair).transferFrom(msg.sender, pair, liquidity); // send liquidity to pair
(uint amount0, uint amount1) = IUniswapV2Pair(pair).burn(to);
(address token0,) = UniswapV2Library.sortTokens(tokenA, tokenB);
(amountA, amountB) = tokenA == token0 ? (amount0, amount1) : (amount1, amount0);
require(amountA >= amountAMin, 'UniswapV2Router: INSUFFICIENT_A_AMOUNT');
require(amountB >= amountBMin, 'UniswapV2Router: INSUFFICIENT_B_AMOUNT');
} | 0.6.6 |
// **** REMOVE LIQUIDITY (supporting fee-on-transfer tokens) **** | function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) public virtual override ensure(deadline) returns (uint amountETH) {
(, amountETH) = removeLiquidity(
token,
WETH,
liquidity,
amountTokenMin,
amountETHMin,
address(this),
deadline
);
TransferHelper.safeTransfer(token, to, IERC20(token).balanceOf(address(this)));
IWETH(WETH).withdraw(amountETH);
TransferHelper.safeTransferETH(to, amountETH);
} | 0.6.6 |
// **** SWAP ****
// requires the initial amount to have already been sent to the first pair | function _swap(uint[] memory amounts, address[] memory path, address _to) internal virtual {
for (uint i; i < path.length - 1; i++) {
(address input, address output) = (path[i], path[i + 1]);
(address token0,) = UniswapV2Library.sortTokens(input, output);
uint amountOut = amounts[i + 1];
(uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOut) : (amountOut, uint(0));
address to = i < path.length - 2 ? UniswapV2Library.pairFor(factory, output, path[i + 2]) : _to;
IUniswapV2Pair(UniswapV2Library.pairFor(factory, input, output)).swap(
amount0Out, amount1Out, to, new bytes(0)
);
}
} | 0.6.6 |
// Deleverages until we're supplying <x> amount
// 1. Redeem <x> DAI
// 2. Repay <x> DAI | function deleverageUntil(uint256 _supplyAmount) public onlyKeepers {
uint256 unleveragedSupply = getSuppliedUnleveraged();
uint256 supplied = getSupplied();
require(
_supplyAmount >= unleveragedSupply && _supplyAmount <= supplied,
"!deleverage"
);
// Since we're only leveraging on 1 asset
// redeemable = borrowable
uint256 _redeemAndRepay = getBorrowable();
do {
if (supplied.sub(_redeemAndRepay) < _supplyAmount) {
_redeemAndRepay = supplied.sub(_supplyAmount);
}
require(
ICToken(cdai).redeemUnderlying(_redeemAndRepay) == 0,
"!redeem"
);
IERC20(dai).safeApprove(cdai, 0);
IERC20(dai).safeApprove(cdai, _redeemAndRepay);
require(ICToken(cdai).repayBorrow(_redeemAndRepay) == 0, "!repay");
supplied = supplied.sub(_redeemAndRepay);
} while (supplied > _supplyAmount);
} | 0.6.7 |
// returns sorted token addresses, used to handle return values from pairs sorted in this order | function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) {
require(tokenA != tokenB, 'UniswapV2Library: IDENTICAL_ADDRESSES');
(token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
require(token0 != address(0), 'UniswapV2Library: ZERO_ADDRESS');
} | 0.6.6 |
// calculates the CREATE2 address for a pair without making any external calls | function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = sortTokens(tokenA, tokenB);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
} | 0.6.6 |
// fetches and sorts the reserves for a pair | function getReserves(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) {
(address token0,) = sortTokens(tokenA, tokenB);
(uint reserve0, uint reserve1,) = IUniswapV2Pair(pairFor(factory, tokenA, tokenB)).getReserves();
(reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
} | 0.6.6 |
// given some amount of an asset and pair reserves, returns an equivalent amount of the other asset | function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) {
require(amountA > 0, 'UniswapV2Library: INSUFFICIENT_AMOUNT');
require(reserveA > 0 && reserveB > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
amountB = amountA.mul(reserveB) / reserveA;
} | 0.6.6 |
// given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset | function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) {
require(amountIn > 0, 'UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
uint amountInWithFee = amountIn.mul(997);
uint numerator = amountInWithFee.mul(reserveOut);
uint denominator = reserveIn.mul(1000).add(amountInWithFee);
amountOut = numerator / denominator;
} | 0.6.6 |
/**
* Get an account's summary for each market.
*
* @param account The account to query
* @return The following values:
* - The ERC20 token address for each market
* - The account's principal value for each market
* - The account's (supplied or borrowed) number of tokens for each market
*/ | function getAccountBalances(
Account.Info memory account
)
public
view
returns (
address[] memory,
Types.Par[] memory,
Types.Wei[] memory
)
{
uint256 numMarkets = g_state.numMarkets;
address[] memory tokens = new address[](numMarkets);
Types.Par[] memory pars = new Types.Par[](numMarkets);
Types.Wei[] memory weis = new Types.Wei[](numMarkets);
for (uint256 m = 0; m < numMarkets; m++) {
tokens[m] = getMarketTokenAddress(m);
pars[m] = getAccountPar(account, m);
weis[m] = getAccountWei(account, m);
}
return (
tokens,
pars,
weis
);
} | 0.5.7 |
// performs chained getAmountOut calculations on any number of pairs | function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) {
require(path.length >= 2, 'UniswapV2Library: INVALID_PATH');
amounts = new uint[](path.length);
amounts[0] = amountIn;
for (uint i; i < path.length - 1; i++) {
(uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]);
amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut);
}
} | 0.6.6 |
/**
* Private helper for getting the monetary values of an account.
*/ | function getAccountValuesInternal(
Account.Info memory account,
bool adjustForLiquidity
)
private
view
returns (Monetary.Value memory, Monetary.Value memory)
{
uint256 numMarkets = g_state.numMarkets;
// populate cache
Cache.MarketCache memory cache = Cache.create(numMarkets);
for (uint256 m = 0; m < numMarkets; m++) {
if (!g_state.getPar(account, m).isZero()) {
cache.addMarket(g_state, m);
}
}
return g_state.getAccountValues(account, cache, adjustForLiquidity);
} | 0.5.7 |
// This function to be used if the target is a contract address | function transferToContract(address _to, uint256 _value, bytes _data) internal returns (bool) {
require(balances[msg.sender] >= _value);
require(vestingEnded(msg.sender));
// This will override settings and allow contract owner to send to contract
if(msg.sender != contractOwner){
ERC223ReceivingContract _tokenReceiver = ERC223ReceivingContract(_to);
_tokenReceiver.tokenFallback(msg.sender, _value, _data);
}
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
emit Transfer(msg.sender, _to, _value, _data);
return true;
} | 0.4.24 |
/**
* @dev set available traits and rarities at the same time
* @dev example: [500, 500, 0, 100, 300, 600] sets two sequences separated by '0'
* [500, 500], [100, 300, 600] sequence 0 and 1, index is trait value is rarity
*/ | function setTraits(uint16[] memory rarities) public onlyOwner {
require(rarities.length > 0, "Rarities is empty, Use resetTraits() instead");
resetTraits();
uint16 trait = 0;
sequences.push(trait);
for(uint i; i < rarities.length; i++) {
uint16 rarity = rarities[i];
if (rarity == 0) {
trait++;
sequences.push(trait);
} else {
traits[trait].push(rarity);
sequenceToRarityTotals[trait] += rarity;
}
}
} | 0.8.7 |
// ERC20 standard function | function transferFrom(address _from, address _to, uint256 _value) public returns (bool success){
require(_value <= allowed[_from][msg.sender]);
require(_value <= balances[_from]);
require(vestingEnded(_from));
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
} | 0.4.24 |
// Burn the specified amount of tokens by the owner | function _burn(address _user, uint256 _value) internal ownerOnly {
require(balances[_user] >= _value);
balances[_user] = balances[_user].sub(_value);
_totalSupply = _totalSupply.sub(_value);
emit Burn(_user, _value);
emit Transfer(_user, address(0), _value);
bytes memory _empty;
emit Transfer(_user, address(0), _value, _empty);
} | 0.4.24 |
/**
* @dev Multiplies two numbers, reverts on overflow.
* @param _factor1 Factor number.
* @param _factor2 Factor number.
* @return product The product of the two factors.
*/ | function mul(
uint256 _factor1,
uint256 _factor2
)
internal
pure
returns (uint256 product)
{
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (_factor1 == 0)
{
return 0;
}
product = _factor1 * _factor2;
require(product / _factor1 == _factor2, OVERFLOW);
} | 0.6.2 |
/**
* @dev Integer division of two numbers, truncating the quotient, reverts on division by zero.
* @param _dividend Dividend number.
* @param _divisor Divisor number.
* @return quotient The quotient.
*/ | function div(
uint256 _dividend,
uint256 _divisor
)
internal
pure
returns (uint256 quotient)
{
// Solidity automatically asserts when dividing by 0, using all gas.
require(_divisor > 0, DIVISION_BY_ZERO);
quotient = _dividend / _divisor;
// assert(_dividend == _divisor * quotient + _dividend % _divisor); // There is no case in which this doesn't hold.
} | 0.6.2 |
/* ========== VIEWS ========== */ | function showAllocations() public view returns (uint256[4] memory allocations) {
// All numbers given are in FRAX unless otherwise stated
// Unallocated FRAX
allocations[0] = FRAX.balanceOf(address(this));
// Unallocated Collateral Dollar Value (E18)
allocations[1] = freeColDolVal();
// Sum of Uni v3 Positions liquidity, if it was all in FRAX
allocations[2] = TotalLiquidityFrax();
// Total Value
allocations[3] = allocations[0].add(allocations[1]).add(allocations[2]);
} | 0.8.6 |
// E18 Collateral dollar value | function freeColDolVal() public view returns (uint256) {
uint256 value_tally_e18 = 0;
for (uint i = 0; i < collateral_addresses.length; i++){
ERC20 thisCollateral = ERC20(collateral_addresses[i]);
uint256 missing_decs = uint256(18).sub(thisCollateral.decimals());
uint256 col_bal_e18 = thisCollateral.balanceOf(address(this)).mul(10 ** missing_decs);
uint256 col_usd_value_e18 = collatDolarValue(oracles[collateral_addresses[i]], col_bal_e18);
value_tally_e18 = value_tally_e18.add(col_usd_value_e18);
}
return value_tally_e18;
} | 0.8.6 |
// Needed for the Frax contract to function | function collatDollarBalance() public view returns (uint256) {
// Get the allocations
uint256[4] memory allocations = showAllocations();
// Get the collateral and FRAX portions
uint256 collat_portion = allocations[1];
uint256 frax_portion = (allocations[0]).add(allocations[2]);
// Assumes worst case scenario if FRAX slips out of range.
// Otherwise, it would only be half that is multiplied by the CR
frax_portion = frax_portion.mul(FRAX.global_collateral_ratio()).div(PRICE_PRECISION);
return (collat_portion).add(frax_portion);
} | 0.8.6 |
// Returns this contract's liquidity in a specific [FRAX]-[collateral] uni v3 pool | function liquidityInPool(address _collateral_address, int24 _tickLower, int24 _tickUpper, uint24 _fee) public view returns (uint128) {
IUniswapV3Pool get_pool = IUniswapV3Pool(univ3_factory.getPool(address(FRAX), _collateral_address, _fee));
// goes into the pool's positions mapping, and grabs this address's liquidity
(uint128 liquidity, , , , ) = get_pool.positions(keccak256(abi.encodePacked(address(this), _tickLower, _tickUpper)));
return liquidity;
} | 0.8.6 |
// Iterate through all positions and collect fees accumulated | function collectFees() external onlyByOwnGovCust {
for (uint i = 0; i < positions_array.length; i++){
Position memory current_position = positions_array[i];
INonfungiblePositionManager.CollectParams memory collect_params = INonfungiblePositionManager.CollectParams(
current_position.token_id,
custodian_address,
type(uint128).max,
type(uint128).max
);
// Send to custodian address
univ3_positions.collect(collect_params);
}
} | 0.8.6 |
/* ---------------------------------------------------- */ | function approveTarget(address _target, address _token, uint256 _amount, bool use_safe_approve) public onlyByOwnGov {
if (use_safe_approve) {
// safeApprove needed for USDT and others for the first approval
// You need to approve 0 every time beforehand for USDT: it resets
TransferHelper.safeApprove(_token, _target, _amount);
}
else {
ERC20(_token).approve(_target, _amount);
}
} | 0.8.6 |
// IUniswapV3Pool public current_uni_pool; // only used for mint callback; is set and accessed during execution of addLiquidity() | function addLiquidity(address _tokenA, address _tokenB, int24 _tickLower, int24 _tickUpper, uint24 _fee, uint256 _amount0Desired, uint256 _amount1Desired, uint256 _amount0Min, uint256 _amount1Min) public onlyByOwnGov {
// Make sure the collateral is allowed
require(allowed_collaterals[_tokenA] || _tokenA == address(FRAX), "TokenA not allowed");
require(allowed_collaterals[_tokenB] || _tokenB == address(FRAX), "TokenB not allowed");
ERC20(_tokenA).transferFrom(msg.sender, address(this), _amount0Desired);
ERC20(_tokenB).transferFrom(msg.sender, address(this), _amount1Desired);
ERC20(_tokenA).approve(address(univ3_positions), _amount0Desired);
ERC20(_tokenB).approve(address(univ3_positions), _amount1Desired);
INonfungiblePositionManager.MintParams memory params = INonfungiblePositionManager.MintParams(
_tokenA,
_tokenB,
_fee,
_tickLower,
_tickUpper,
_amount0Desired,
_amount1Desired,
_amount0Min,
_amount1Min,
address(this),
block.timestamp
);
(uint256 tokenId, uint128 amountLiquidity,,) = univ3_positions.mint(params);
Position memory pos = Position(
tokenId,
_tokenA == address(FRAX) ? _tokenB : _tokenA,
amountLiquidity,
_tickLower,
_tickUpper,
_fee
);
positions_array.push(pos);
positions_mapping[tokenId] = pos;
} | 0.8.6 |
// Swap tokenA into tokenB using univ3_router.ExactInputSingle()
// Uni V3 only | function swap(address _tokenA, address _tokenB, uint24 _fee_tier, uint256 _amountAtoB, uint256 _amountOutMinimum, uint160 _sqrtPriceLimitX96) public onlyByOwnGov returns (uint256) {
// Make sure the collateral is allowed
require(allowed_collaterals[_tokenA] || _tokenA == address(FRAX), "TokenA not allowed");
require(allowed_collaterals[_tokenB] || _tokenB == address(FRAX), "TokenB not allowed");
ISwapRouter.ExactInputSingleParams memory swap_params = ISwapRouter.ExactInputSingleParams(
_tokenA,
_tokenB,
_fee_tier,
address(this),
2105300114, // Expiration: a long time from now
_amountAtoB,
_amountOutMinimum,
_sqrtPriceLimitX96
);
// Approval
TransferHelper.safeApprove(_tokenA, address(univ3_router), _amountAtoB);
uint256 amountOut = univ3_router.exactInputSingle(swap_params);
return amountOut;
} | 0.8.6 |
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to to account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------ | function goldTransfer(address to, uint tokens) public whenNotPaused returns (bool success) {
if(goldFreezed[msg.sender] == false){
goldBalances[msg.sender] = safeSub(goldBalances[msg.sender], tokens);
goldBalances[to] = safeAdd(goldBalances[to], tokens);
emit GoldTransfer(msg.sender, to, tokens);
} else {
if(goldBalances[msg.sender] > goldFreezeAmount[msg.sender]) {
require(tokens <= safeSub(goldBalances[msg.sender], goldFreezeAmount[msg.sender]));
goldBalances[msg.sender] = safeSub(goldBalances[msg.sender], tokens);
goldBalances[to] = safeAdd(goldBalances[to], tokens);
emit GoldTransfer(msg.sender, to, tokens);
}
}
return true;
} | 0.4.24 |
// ------------------------------------------------------------------------
// Partner Authorization
// ------------------------------------------------------------------------ | function createPartner(address _partner, uint _amount, uint _singleTrans, uint _durance) public onlyAdmin returns (uint) {
Partner memory _Partner = Partner({
admin: _partner,
tokenPool: _amount,
singleTrans: _singleTrans,
timestamp: uint(now),
durance: _durance
});
uint newPartnerId = partners.push(_Partner) - 1;
emit PartnerCreated(newPartnerId, _partner, _amount, _singleTrans, _durance);
return newPartnerId;
} | 0.4.24 |
// ------------------------------------------------------------------------
// Vip Agreement
// ------------------------------------------------------------------------ | function createVip(address _vip, uint _durance, uint _frequence, uint _salary) public onlyAdmin returns (uint) {
Vip memory _Vip = Vip ({
vip: _vip,
durance: uint(now) + _durance,
frequence: _frequence,
salary: _salary,
timestamp: now + _frequence
});
uint newVipId = vips.push(_Vip) - 1;
emit VipAgreementSign(newVipId, _vip, _durance, _frequence, _salary);
return newVipId;
} | 0.4.24 |
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amout of tokens to be transfered
*/ | function transferFrom(address _from, address _to, uint256 _value) returns (bool) {
var _allowance = allowed[_from][msg.sender];
// Check is not needed because sub(_allowance, _value) will already throw if this condition is not met
// require (_value <= _allowance);
balances[_to] = balances[_to].add(_value);
balances[_from] = balances[_from].sub(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
Transfer(_from, _to, _value);
return true;
} | 0.4.16 |
/**
* @dev Aprove the passed address to spend the specified amount of tokens on behalf of msg.sender.
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/ | function approve(address _spender, uint256 _value) returns (bool) {
// To change the approve amount you first have to reduce the addresses`
// allowance to zero by calling `approve(_spender, 0)` if it is not
// already 0 to mitigate the race condition described here:
// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
require((_value == 0) || (allowed[msg.sender][_spender] == 0));
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
} | 0.4.16 |
/**
* @dev Burns a NFT.
* @notice This is an internal function which should be called from user-implemented external
* burn function. Its purpose is to show and properly initialize data structures when using this
* implementation. Also, note that this burn implementation allows the minter to re-mint a burned
* NFT.
* @param _tokenId ID of the NFT to be burned.
*/ | function _burn(
uint256 _tokenId
)
internal
override
virtual
{
super._burn(_tokenId);
if (bytes(idToUri[_tokenId]).length != 0)
{
delete idToUri[_tokenId];
}
if (bytes(idToPayload[_tokenId]).length != 0)
{
delete idToPayload[_tokenId];
}
uint256 tokenIndex = idToIndex[_tokenId];
uint256 lastTokenIndex = tokens.length - 1;
uint256 lastToken = tokens[lastTokenIndex];
tokens[tokenIndex] = lastToken;
tokens.pop();
// This wastes gas if you are burning the last token but saves a little gas if you are not.
idToIndex[lastToken] = tokenIndex;
idToIndex[_tokenId] = 0;
} | 0.6.2 |
/**
* @dev Removes a NFT from an address.
* @notice Use and override this function with caution. Wrong usage can have serious consequences.
* @param _from Address from wich we want to remove the NFT.
* @param _tokenId Which NFT we want to remove.
*/ | function _removeNFToken(
address _from,
uint256 _tokenId
)
internal
override
virtual
{
require(idToOwner[_tokenId] == _from, NOT_OWNER);
delete idToOwner[_tokenId];
uint256 tokenToRemoveIndex = idToOwnerIndex[_tokenId];
uint256 lastTokenIndex = ownerToIds[_from].length - 1;
if (lastTokenIndex != tokenToRemoveIndex)
{
uint256 lastToken = ownerToIds[_from][lastTokenIndex];
ownerToIds[_from][tokenToRemoveIndex] = lastToken;
idToOwnerIndex[lastToken] = tokenToRemoveIndex;
}
ownerToIds[_from].pop();
} | 0.6.2 |
/**
* @dev Function to unlock timelocked tokens
* If block.timestap passed tokens are sent to owner and lock is removed from database
*/ | function unlock() external
{
require(timeLocks[msg.sender].length > 0, "Unlock: No locks!");
Locker[] storage l = timeLocks[msg.sender];
for (uint i = 0; i < l.length; i++)
{
// solium-disable-next-line security/no-block-members
if (l[i].locktime < block.timestamp) {
uint amount = l[i].amount;
require(amount <= lockedBalance && amount <= _balances[address(this)], "Unlock: Not enough coins on contract!");
lockedBalance = lockedBalance.sub(amount);
_transfer(address(this), msg.sender, amount);
for (uint j = i; j < l.length - 1; j++)
{
l[j] = l[j + 1];
}
l.length--;
i--;
}
}
} | 0.5.10 |
/**
* Gas spent here starts off proportional to the maximum mint batch size.
* It gradually moves to O(1) as tokens get transferred around in the collection over time.
*/ | function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) {
uint256 curr = tokenId;
unchecked {
if (curr < _currentIndex) {
TokenOwnership memory ownership = _ownerships[curr];
if (!ownership.burned) {
if (ownership.addr != address(0)) {
return ownership;
}
// Invariant:
// There will always be an ownership that has an address and is not burned
// before an ownership that does not have an address and is not burned.
// Hence, curr will not underflow.
while (true) {
curr--;
ownership = _ownerships[curr];
if (ownership.addr != address(0)) {
return ownership;
}
}
}
}
}
revert OwnerQueryForNonexistentToken();
} | 0.8.9 |
/**
* @dev Mints `quantity` tokens and transfers them to `to`.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `quantity` must be greater than 0.
*
* Emits a {Transfer} event.
*/ | function _mint(
address to,
uint256 quantity,
bytes memory _data,
bool safe
) internal {
uint256 startTokenId = _currentIndex;
if (to == address(0)) revert MintToZeroAddress();
if (quantity == 0) revert MintZeroQuantity();
_beforeTokenTransfers(address(0), to, startTokenId, quantity);
// Overflows are incredibly unrealistic.
// balance or numberMinted overflow if current value of either + quantity > 1.8e19 (2**64) - 1
// updatedIndex overflows if _currentIndex + quantity > 1.2e77 (2**256) - 1
unchecked {
_addressData[to].balance += uint64(quantity);
_addressData[to].numberMinted += uint64(quantity);
_ownerships[startTokenId].addr = to;
_ownerships[startTokenId].startTimestamp = uint64(block.timestamp);
uint256 updatedIndex = startTokenId;
for (uint256 i; i < quantity; i++) {
emit Transfer(address(0), to, updatedIndex);
if (safe && !_checkOnERC721Received(address(0), to, updatedIndex, _data)) {
revert TransferToNonERC721ReceiverImplementer();
}
updatedIndex++;
}
_currentIndex = updatedIndex;
}
_afterTokenTransfers(address(0), to, startTokenId, quantity);
} | 0.8.9 |
/**
* @dev Fallback function allowing to perform a delegatecall to the given implementation.
* This function will return whatever the implementation call returns
*/ | function () payable public {
bytes32 implementationPosition = implementationPosition_;
address _impl;
assembly {
_impl := sload(implementationPosition)
}
assembly {
let ptr := mload(0x40)
calldatacopy(ptr, 0, calldatasize)
let result := delegatecall(gas, _impl, ptr, calldatasize, 0, 0)
let size := returndatasize
returndatacopy(ptr, 0, size)
switch result
case 0 { revert(ptr, size) }
default { return(ptr, size) }
}
} | 0.4.24 |
/**
* @return Allowed address list.
*/ | function accessList() external view returns (address[] memory) {
address[] memory result = new address[](allowed.length());
for (uint256 i = 0; i < allowed.length(); i++) {
result[i] = allowed.at(i);
}
return result;
} | 0.6.12 |
/**
* @dev transfers IXT
* @param from User address
* @param to Recipient
* @param action Service the user is paying for
*/ | function transferIXT(address from, address to, string action) public allowedOnly isNotPaused returns (bool) {
if (isOldVersion) {
IXTPaymentContract newContract = IXTPaymentContract(nextContract);
return newContract.transferIXT(from, to, action);
} else {
uint price = actionPrices[action];
if(price != 0 && !tokenContract.transferFrom(from, to, price)){
return false;
} else {
emit IXTPayment(from, to, price, action);
return true;
}
}
} | 0.4.21 |
// ------------------------------------------------------------------------
// Token owner can approve for `spender` to transferFrom(...) `tokens`
// from the token owner's account. The `spender` contract function
// `receiveApproval(...)` is then executed
// ------------------------------------------------------------------------ | function approveAndCall(
address spender,
uint256 tokens,
bytes memory data
) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(
msg.sender,
tokens,
address(0),
data
);
return true;
} | 0.7.2 |
// ------------------------------------------------------------------------
// Send tokens to owner for airdrop
// ------------------------------------------------------------------------ | function getAirdropTokens() public onlyOwner {
require(block.timestamp >= startDate && block.timestamp <= endDate);
require(!airdropTokensWithdrawn);
uint256 tokens = 5000000000000000000000;
balances[owner] = safeAdd(balances[owner], tokens);
_totalSupply = safeAdd(_totalSupply, tokens);
emit Transfer(address(0), owner, tokens);
airdropTokensWithdrawn = true;
} | 0.7.2 |
/**
* @dev Actually perform the safeTransferFrom.
* @param _from The current owner of the NFT.
* @param _to The new owner.
* @param _tokenId The NFT to transfer.
* @param _data Additional data with no specified format, sent in call to `_to`.
*/ | function _safeTransferFrom(
address _from,
address _to,
uint256 _tokenId,
bytes memory _data
)
private
canTransfer(_tokenId)
validNFToken(_tokenId)
{
address tokenOwner = idToOwner[_tokenId];
require(tokenOwner == _from, NOT_OWNER);
require(_to != address(0), ZERO_ADDRESS);
_transfer(_to, _tokenId);
if (_to.isContract())
{
bytes4 retval = ERC721TokenReceiver(_to).onERC721Received(msg.sender, _from, _tokenId, _data);
require(retval == MAGIC_ON_ERC721_RECEIVED, NOT_ABLE_TO_RECEIVE_NFT);
}
} | 0.6.2 |
/**
* Notifies all the pools, safe guarding the notification amount.
*/ | function notifyPools(uint256[] memory amounts, address[] memory pools) public onlyGovernance {
require(amounts.length == pools.length, "Amounts and pools lengths mismatch");
for (uint i = 0; i < pools.length; i++) {
require(amounts[i] > 0, "Notify zero");
NoMintRewardPool pool = NoMintRewardPool(pools[i]);
IERC20 token = IERC20(pool.rewardToken());
uint256 limit = token.balanceOf(pools[i]);
require(amounts[i] <= limit, "Notify limit hit");
NoMintRewardPool(pools[i]).notifyRewardAmount(amounts[i]);
}
} | 0.5.16 |
/**
* @return Assets list.
*/ | function assets() external view returns (Asset[] memory) {
Asset[] memory result = new Asset[](size());
for (uint256 i = 0; i < size(); i++) {
result[i] = portfolio[i];
}
return result;
} | 0.6.12 |
/**
* @notice Update information of asset.
* @param id Asset identificator.
* @param amount Amount of asset.
* @param price Cost of one asset in base currency.
* @param updatedAt Timestamp of updated.
* @param proofData Signed data.
* @param proofSignature Data signature.
*/ | function put(
string calldata id,
uint256 amount,
uint256 price,
uint256 updatedAt,
string calldata proofData,
string calldata proofSignature
) external onlyAllowed {
require(size() < maxSize, "RealAssetDepositaryBalanceView::put: too many assets");
uint256 valueIndex = portfolioIndex[id];
if (valueIndex != 0) {
portfolio[valueIndex.sub(1)] = Asset(id, amount, price, block.number);
} else {
portfolio.push(Asset(id, amount, price, block.number));
portfolioIndex[id] = size();
}
emit AssetUpdated(id, updatedAt, Proof(proofData, proofSignature));
} | 0.6.12 |
/**
* @notice Remove information of asset.
* @param id Asset identificator.
*/ | function remove(string calldata id) external onlyAllowed {
uint256 valueIndex = portfolioIndex[id];
require(valueIndex != 0, "RealAssetDepositaryBalanceView::remove: asset already removed");
uint256 toDeleteIndex = valueIndex.sub(1);
uint256 lastIndex = size().sub(1);
Asset memory lastValue = portfolio[lastIndex];
portfolio[toDeleteIndex] = lastValue;
portfolioIndex[lastValue.id] = toDeleteIndex.add(1);
portfolio.pop();
delete portfolioIndex[id];
emit AssetRemoved(id);
} | 0.6.12 |
/**
* @dev Transfer the specified amount of tokens to the specified address.
* Invokes the `tokenFallback` function if the recipient is a contract.
* The token transfer fails if the recipient is a contract
* but does not implement the `tokenFallback` function
* or the fallback function to receive funds.
*
* @param _to Receiver address.
* @param _value Amount of tokens that will be transferred.
* @param _data Transaction metadata.
*/ | function transfer(address _to, uint _value, bytes _data) public returns (bool) {
uint codeLength;
assembly {
codeLength := extcodesize(_to)
}
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
if(codeLength>0) {
ContractReceiver receiver = ContractReceiver(_to);
receiver.tokenFallback(msg.sender, _value, _data);
}
Transfer(msg.sender, _to, _value);
Transfer(msg.sender, _to, _value, _data);
} | 0.4.19 |
//adopts multiple cats at once | function adoptCats(uint256 _howMany) public payable {
require(_howMany <= 10, "max 10 cats at once");
require(itemPrice.mul(_howMany) == msg.value, "insufficient ETH");
for (uint256 i = 0; i < _howMany; i++) {
adopt();
}
} | 0.8.4 |
/// @dev Adds investors. This function doesn't limit max gas consumption,
/// so adding too many investors can cause it to reach the out-of-gas error.
/// @param _investors The addresses of new investors.
/// @param _tokenAllocations The amounts of the tokens that belong to each investor. | function addInvestors(
address[] calldata _investors,
uint256[] calldata _tokenAllocations,
uint256[] calldata _withdrawnTokens
) external onlyOwner {
require(_investors.length == _tokenAllocations.length, "different arrays sizes");
for (uint256 i = 0; i < _investors.length; i++) {
_addInvestor(_investors[i], _tokenAllocations[i], _withdrawnTokens[i]);
}
emit InvestorsAdded(_investors, _tokenAllocations, msg.sender);
} | 0.7.4 |
// 25% at TGE, 75% released daily over 120 Days after 30 Days Cliff | function withdrawTokens() external onlyInvestor() initialized() {
Investor storage investor = investorsInfo[_msgSender()];
uint256 tokensAvailable = withdrawableTokens(_msgSender());
require(tokensAvailable > 0, "no tokens available for withdrawl");
investor.withdrawnTokens = investor.withdrawnTokens.add(tokensAvailable);
_blankToken.safeTransfer(_msgSender(), tokensAvailable);
emit WithdrawnTokens(_msgSender(), tokensAvailable);
} | 0.7.4 |
//adopting a cat | function adopt() private {
//you would be pretty unlucky to pay the miners alot of gas
for (uint256 i = 0; i < 9999; i++) {
uint256 randID = random(1, 3000, uint256(uint160(address(msg.sender))) + i);
if (_totalSupply[randID] == 0) {
_totalSupply[randID] = 1;
_mint(msg.sender, randID, 1, "0x0000");
adoptedCats = adoptedCats + 1;
return;
}
}
revert("you're very unlucky");
} | 0.8.4 |
/// @dev Removes investor. This function doesn't limit max gas consumption,
/// so having too many investors can cause it to reach the out-of-gas error.
/// @param _investor Investor address. | function removeInvestor(address _investor) external onlyOwner() {
require(_investor != address(0), "invalid address");
Investor storage investor = investorsInfo[_investor];
uint256 allocation = investor.tokensAllotment;
require(allocation > 0, "the investor doesn't exist");
_totalAllocatedAmount = _totalAllocatedAmount.sub(allocation);
investor.exists = false;
investor.tokensAllotment = 0;
emit InvestorRemoved(_investor, _msgSender(), allocation);
} | 0.7.4 |