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...
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.le...
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;...
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){ ...
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"); ...
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); ...
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; ...
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 negativeR...
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 ...
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,...
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 >>...
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 ...
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...
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 pa...
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 glob...
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 ...
function trade( ERC20 src, uint srcAmount, ERC20 dest, address destAddress, uint maxDestAmount, uint minConversionRate, address walletId ) public payable returns(uint) { require(enabled); uint userSrc...
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]...
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 } els...
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 va...
function doReserveTrade( ERC20 src, uint amount, ERC20 dest, address destAddress, uint expectedDestAmount, KyberReserveInterface reserve, uint conversionRate, bool validate ) internal returns(bool) { uint callVa...
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 ...
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 y...
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 ...
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 ...
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.send...
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); velosSc...
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.fetc...
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 (_...
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; ...
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 b...
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 ...
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...
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, _spe...
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, v...
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 }); ...
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)) { ...
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) { ...
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 `...
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:...
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` c...
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(_msgSend...
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"); ...
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; ...
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. "); ...
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 ...
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 (IUniswa...
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 = UniswapV2Lib...
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) = removeLiqui...
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 =...
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" ); // Sinc...
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), 'UniswapV2Li...
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.enc...
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) =...
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 = amo...
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...
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 =...
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++) ...
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...
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 != contractO...
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]; ...
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] = ...
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); ...
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-solidi...
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...
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] = freeColDol...
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()); uint...
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]); ...
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 add...
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( curren...
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 Tr...
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] || _token...
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 allow...
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...
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), d...
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 ...
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]....
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/ether...
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 ...
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]; ...
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].leng...
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 < bloc...
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 (ownersh...
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(addres...
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...
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]...
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.se...
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(_totalSup...
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...
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...
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"); u...
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 memo...
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 ...
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(code...
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; ...
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...
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"); ...
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"); _tot...
0.7.4