comment stringlengths 11 2.99k | function_code stringlengths 165 3.15k | version stringclasses 80
values |
|---|---|---|
/*
* Liquidate as many assets as possible to `want`, irregardless of slippage,
* up to `_amountNeeded`. Any excess should be re-invested here as well.
*/ | function liquidatePosition(uint256 _amountNeeded) internal override returns (uint256 _amountFreed, uint256 _loss) {
uint256 _balance = want.balanceOf(address(this));
if (_balance >= _amountNeeded) {
//if we don't set reserve here withdrawer will be sent our full balance
ret... | 0.6.12 |
//Locks the contract for owner for the amount of time provided | function lock(uint256 time) public virtual onlyOwner {
require(
time <= (block.timestamp + 31536000),
"Only lockable for up to 1 year"
);
_previousOwner = _owner;
_owner = address(0);
_lockTime = now + time;
emit OwnershipTransferred(_own... | 0.6.12 |
// Removes an address from the circulating supply | function removeAddressFromSupply(address removedAddress) external onlyOwner() {
uint256 id = removedFromCirculation.length;
require(removedAddress != address(uniswapV2Router), "Cannot add router (already accounted for)");
require(removedAddress != 0x000000000000000000000000000000000000dEaD ||... | 0.6.12 |
// Re-Adds an address to the circulating supply | function addAddressToSupply(address addedAddress) external onlyOwner() {
uint256 id = removedAddressIndex[addedAddress];
require(addedAddress != address(uniswapV2Router), "Cannot add router (already accounted for)");
require(addedAddress != 0x000000000000000000000000000000000000dEaD || addedA... | 0.6.12 |
/**
* Mint Waffles
*/ | function mintWaffles(uint256 numberOfTokens) public payable {
require(saleIsActive, "Mint is not available right now");
require(
numberOfTokens <= MAX_PURCHASE,
"Can only mint 20 tokens at a time"
);
require(
totalSupply().add(numberOfTokens) <= MAX_TO... | 0.8.0 |
// once enabled, can never be turned off | function enableTrading() external onlyOwner {
tradingActive = true;
swapEnabled = true;
lastLpBurnTime = block.timestamp;
sellMarketingFee = 9;
sellLiquidityFee = 1;
sellDevFee = 5;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
} | 0.8.10 |
//below function can be used when you want to send every recipeint with different number of tokens | function sendTokens(address[] dests, uint256[] values) whenDropIsActive onlyOwner external {
uint256 i = 0;
while (i < dests.length) {
uint256 toSend = values[i] * 10**8;
sendInternally(dests[i] , toSend, values[i]);
i++;
}
} | 0.4.21 |
// this function can be used when you want to send same number of tokens to all the recipients | function sendTokensSingleValue(address[] dests, uint256 value) whenDropIsActive onlyOwner external {
uint256 i = 0;
uint256 toSend = value * 10**8;
while (i < dests.length) {
sendInternally(dests[i] , toSend, value);
i++;
}
} | 0.4.21 |
/**
* @dev calculates x^n, in ray. The code uses the ModExp precompile
* @param x base
* @param n exponent
* @return z = x^n, in ray
*/ | function rayPow(uint256 x, uint256 n) internal pure returns (uint256 z) {
z = n % 2 != 0 ? x : RAY;
for (n /= 2; n != 0; n /= 2) {
x = rayMul(x, x);
if (n % 2 != 0) {
z = rayMul(z, x);
}
}
} | 0.6.12 |
/**
Public function to release the accumulated fee income to the payees.
@dev anyone can call this.
*/ | function release() public override nonReentrant {
uint256 income = a.core().availableIncome();
require(income > 0, "income is 0");
require(payees.length > 0, "Payees not configured yet");
lastReleasedAt = now;
// Mint USDX to all receivers
for (uint256 i = 0; i < payees.length; i++) {
add... | 0.6.12 |
/**
Internal function to add a new payee.
@dev will update totalShares and therefore reduce the relative share of all other payees.
@param _payee The address of the payee to add.
@param _shares The number of shares owned by the payee.
*/ | function _addPayee(address _payee, uint256 _shares) internal {
require(_payee != address(0), "payee is the zero address");
require(_shares > 0, "shares are 0");
require(shares[_payee] == 0, "payee already has shares");
payees.push(_payee);
shares[_payee] = _shares;
totalShares = totalShares.add... | 0.6.12 |
/**
Updates the payee configuration to a new one.
@dev will release existing fees before the update.
@param _payees Array of payees
@param _shares Array of shares for each payee
*/ | function changePayees(address[] memory _payees, uint256[] memory _shares) public override onlyManager {
require(_payees.length == _shares.length, "Payees and shares mismatched");
require(_payees.length > 0, "No payees");
uint256 income = a.core().availableIncome();
if (income > 0 && payees.length > 0) ... | 0.6.12 |
/// @notice Calculates the sqrt ratio for given price
/// @param token0 The address of token0
/// @param token1 The address of token1
/// @param price The amount with decimals of token1 for 1 token0
/// @return sqrtPriceX96 The greatest tick for which the ratio is less than or equal to the input ratio | function getSqrtRatioAtPrice(
address token0,
address token1,
uint256 price
) internal pure returns (uint160 sqrtPriceX96) {
uint256 base = 1e18;
if (token0 > token1) {
(token0, token1) = (token1, token0);
(base, price) = (price, base);
}
uint256 priceX96 = (price << 192) / bas... | 0.7.6 |
/// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio
/// @dev Throws in case sqrtPriceX96 < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may
/// ever return.
/// @param token0 The address of token0
/// @param token1 The address of token1
/// @param sqrtPriceX96 ... | function getPriceAtSqrtRatio(
address token0,
address token1,
uint160 sqrtPriceX96
) internal pure returns (uint256 price) {
// second inequality must be < because the price can never reach the price at the max tick
require(sqrtPriceX96 >= TickMath.MIN_SQRT_RATIO && sqrtPriceX96 < TickMath.MAX_SQR... | 0.7.6 |
/**
* @dev Claims outstanding rewards from market
*/ | function claimRewards() external {
uint256 len = bAssetsMapped.length;
address[] memory pTokens = new address[](len);
for (uint256 i = 0; i < len; i++) {
pTokens[i] = bAssetToPToken[bAssetsMapped[i]];
}
uint256 rewards = rewardController.claimRewards(pTokens, type(uin... | 0.8.6 |
/**
* @dev Multiplies two unsigned integers, reverts on overflow.
*/ | function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// 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 (a == 0) {
... | 0.5.17 |
/**
* @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero.
*/ | function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
} | 0.5.17 |
/**
* @dev Returns total holdings for all pools (strategy's)
* @return Returns sum holdings (USD) for all pools
*/ | function totalHoldings() public view returns (uint256) {
uint256 length = _poolInfo.length;
uint256 totalHold = 0;
for (uint256 pid = 0; pid < length; pid++) {
totalHold += _poolInfo[pid].strategy.totalHoldings();
}
return totalHold;
} | 0.8.12 |
/**
* @dev in this func user sends funds to the contract and then waits for the completion
* of the transaction for all users
* @param amounts - array of deposit amounts by user
*/ | function delegateDeposit(uint256[3] memory amounts) external whenNotPaused {
for (uint256 i = 0; i < amounts.length; i++) {
if (amounts[i] > 0) {
IERC20Metadata(tokens[i]).safeTransferFrom(_msgSender(), address(this), amounts[i]);
pendingDeposits[_msgSender()][i] += a... | 0.8.12 |
/**
* @dev in this func user sends pending withdraw to the contract and then waits
* for the completion of the transaction for all users
* @param lpAmount - amount of ZLP for withdraw
* @param minAmounts - array of amounts stablecoins that user want minimum receive
*/ | function delegateWithdrawal(uint256 lpAmount, uint256[3] memory minAmounts)
external
whenNotPaused
{
PendingWithdrawal memory withdrawal;
address userAddr = _msgSender();
require(lpAmount > 0, 'Zunami: lpAmount must be higher 0');
withdrawal.lpShares = lpAmount;
... | 0.8.12 |
/**
* @dev Zunami protocol owner complete all active pending withdrawals of users
* @param userList - array of users from pending withdraw to complete
*/ | function completeWithdrawals(address[] memory userList)
external
onlyRole(OPERATOR_ROLE)
startedPool
{
require(userList.length > 0, 'Zunami: there are no pending withdrawals requests');
IStrategy strategy = _poolInfo[defaultWithdrawPid].strategy;
address user;
... | 0.8.12 |
/**
* @dev deposit in one tx, without waiting complete by dev
* @return Returns amount of lpShares minted for user
* @param amounts - user send amounts of stablecoins to deposit
*/ | function deposit(uint256[POOL_ASSETS] memory amounts)
external
whenNotPaused
startedPool
returns (uint256)
{
IStrategy strategy = _poolInfo[defaultDepositPid].strategy;
uint256 holdings = totalHoldings();
for (uint256 i = 0; i < amounts.length; i++) {
... | 0.8.12 |
/**
* @dev withdraw in one tx, without waiting complete by dev
* @param lpShares - amount of ZLP for withdraw
* @param tokenAmounts - array of amounts stablecoins that user want minimum receive
*/ | function withdraw(
uint256 lpShares,
uint256[POOL_ASSETS] memory tokenAmounts,
IStrategy.WithdrawalType withdrawalType,
uint128 tokenIndex
) external whenNotPaused startedPool {
require( checkBit(availableWithdrawalTypes, uint8(withdrawalType)), 'Zunami: withdrawal type not a... | 0.8.12 |
/**
* @dev add a new pool, deposits in the new pool are blocked for one day for safety
* @param _strategyAddr - the new pool strategy address
*/ | function addPool(address _strategyAddr) external onlyRole(DEFAULT_ADMIN_ROLE) {
require(_strategyAddr != address(0), 'Zunami: zero strategy addr');
uint256 startTime = block.timestamp + (launched ? MIN_LOCK_TIME : 0);
_poolInfo.push(
PoolInfo({ strategy: IStrategy(_strategyAddr), sta... | 0.8.12 |
/**
* @dev dev can transfer funds from few strategy's to one strategy for better APY
* @param _strategies - array of strategy's, from which funds are withdrawn
* @param withdrawalsPercents - A percentage of the funds that should be transfered
* @param _receiverStrategyId - number strategy, to which funds are deposi... | function moveFundsBatch(
uint256[] memory _strategies,
uint256[] memory withdrawalsPercents,
uint256 _receiverStrategyId
) external onlyRole(DEFAULT_ADMIN_ROLE) {
require(
_strategies.length == withdrawalsPercents.length,
'Zunami: incorrect arguments for the m... | 0.8.12 |
//Returns a tokenURI of a specific token | function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token.");
string memory baseURI2 = _baseURI();
return bytes(baseURI2).length > 0
? string(abi.encodePacked(baseURI2, to... | 0.8.7 |
//Exclusive Presale mint for the OG's || Moet nog testen of het goe dgaat met de total suplly | function mintPresaleToken(uint16 _amount) public payable {
require( presaleActive, "Presale is not active" );
uint16 reservedAmt = presaleAddresses[msg.sender];
require( reservedAmt > 0, "No tokens reserved for your address" );
require( _amount < reser... | 0.8.7 |
//Mint function | function mint(uint16 _amount) public payable {
require( saleActive,"Sale is not active" );
require( _amount < maxBatch, "You can only Mint 10 tokens at once" );
require( totalMints + _amount < totalCount,"Cannot mint more than max supply" );
require( msg.value == price * _amount,"Wro... | 0.8.7 |
/**
* @dev This is the function to make a signature of the shareholder under arbitration agreement.
* The identity of a person (ETH address) who make a signature has to be verified via Cryptonomica.net verification.
* This verification identifies the physical person who owns the key of ETH address. It this physic... | function signDisputeResolutionAgreement(
uint _shareholderId,
string memory _signatoryName,
string memory _signatoryRegistrationNumber,
string memory _signatoryAddress
) private {
require(
addressIsVerifiedByCryptonomica(msg.sender),
"Signer ... | 0.5.11 |
/*
* @notice This function starts dividend payout round, and can be started from ANY address if the time has come.
*/ | function startDividendsPayments() public returns (bool success) {
require(
dividendsRound[dividendsRoundsCounter].roundIsRunning == false,
"Already running"
);
// dividendsRound[dividendsRoundsCounter].roundFinishedOnUnixTime is zero for first round
// s... | 0.5.11 |
/*
* Function to add funds to reward transactions distributing dividends in this round/
*/ | function fundDividendsPayout() public payable returns (bool success){
/* We allow this only for running round */
require(
dividendsRound[dividendsRoundsCounter].roundIsRunning,
"Dividends payout is not running"
);
dividendsRound[dividendsRoundsCounter].w... | 0.5.11 |
/*
* dev: Private function, that calls 'tokenFallback' function if token receiver is a contract.
*/ | function _erc223Call(address _to, uint _value, bytes memory _data) private returns (bool success) {
uint codeLength;
assembly {
// Retrieve the size of the code on target address, this needs assembly .
codeLength := extcodesize(_to)
}
if (codeLength > 0) {... | 0.5.11 |
/// Whitelisted entity makes changes to the notifications | function setPoolBatch(address[] calldata poolAddress, uint256[] calldata poolPercentage, NotificationType[] calldata notificationType, bool[] calldata vests) external onlyChanger {
for (uint256 i = 0; i < poolAddress.length; i++) {
setPool(poolAddress[i], poolPercentage[i], notificationType[i], vests[i]);
... | 0.5.16 |
/// Pool management, adds, updates or removes a transfer/notification | function setPool(address poolAddress, uint256 poolPercentage, NotificationType notificationType, bool vests) public onlyChanger {
require(notificationType != NotificationType.VOID, "Use valid indication");
if (notificationExists(poolAddress) && poolPercentage == 0) {
// remove
removeNotification(poo... | 0.5.16 |
/// configuration check method | function getConfig(uint256 totalAmount) external view returns(address[] memory, uint256[] memory, uint256[] memory) {
address[] memory pools = new address[](notifications.length);
uint256[] memory percentages = new uint256[](notifications.length);
uint256[] memory amounts = new uint256[](notifications.lengt... | 0.5.16 |
/// @notice Used to withdraw ETH balance of the contract, this function is dedicated
/// to contract owner according to { onlyOwner } modifier. | function withdrawEquity()
public onlyOwner nonReentrant {
uint256 balance = address(this).balance;
address[2] memory shareholders = [
ADDRESS_PBOY,
ADDRESS_JOLAN
];
uint256[2] memory _shares = [
SHARE_PBOY * balance / 100,
... | 0.8.10 |
/// @notice Used to manage authorization and reentrancy of the genesis NFT mint
/// @param _genesisId Used to increment { genesisId } and write { epochMintingRegistry } | function genesisController(uint256 _genesisId)
private {
require(epoch == 0, "error epoch");
require(genesisId <= maxGenesisSupply, "error genesisId");
require(!epochMintingRegistry[epoch][_genesisId], "error epochMintingRegistry");
/// @dev Set { _genesisId } for { epoch } as... | 0.8.10 |
/// @notice Used to protect epoch block length from difficulty bomb of the
/// Ethereum network. A difficulty bomb heavily increases the difficulty
/// on the network, likely also causing an increase in block time.
/// If the block time increases too much, the epoch generation could become
/// ... | function emergencySecure(uint256 _epoch, uint256 _epochLen, uint256 _blockMeta, uint256 _inflateRatio)
public onlyOwner {
require(epoch > 0, "error epoch");
require(_epoch > 0, "error _epoch");
require(maxTokenSupply >= tokenId, "error maxTokenSupply");
epoch = _epoch;
... | 0.8.10 |
/// @notice Used to compute blockOmega() function, { blockOmega } represents
/// the block when it won't ever be possible to mint another Dollars Nakamoto NFT.
/// It is possible to be computed because of the deterministic state of the current protocol
/// The following algorithm simulate the 10... | function computeBlockOmega()
private {
uint256 i = 0;
uint256 _blockMeta = 0;
uint256 _epochLen = epochLen;
while (i < epochMax) {
if (i > 0) _epochLen *= inflateRatio;
if (i == 9) {
blockOmega = blockGenesis + _blockMeta;
... | 0.8.10 |
/// @notice Used to regulate the epoch incrementation and block computation, known as Metas
/// @dev When epoch=0, the { blockOmega } will be computed
/// When epoch!=0 the block length { epochLen } will be multiplied
/// by { inflateRatio } thus making the block length required for each
/// epoch longer... | function epochRegulator()
private {
if (epoch == 0) computeBlockOmega();
if (epoch > 0) epochLen *= inflateRatio;
blockMeta += epochLen;
emit Meta(epoch, blockMeta);
epoch++;
if (block.number >= blockMeta && epoch < epochMax) {
epochR... | 0.8.10 |
/// @notice Used to add/remove address from { _allowList } | function setBatchGenesisAllowance(address[] memory batch)
public onlyOwner {
uint len = batch.length;
require(len > 0, "error len");
uint i = 0;
while (i < len) {
_allowList[batch[i]] = _allowList[batch[i]] ?
false : true;
i++;
... | 0.8.10 |
/// @notice Used to fetch all { tokenIds } from { owner } | function exposeHeldIds(address owner)
public view returns(uint[] memory) {
uint tokenCount = balanceOf(owner);
uint[] memory tokenIds = new uint[](tokenCount);
uint i = 0;
while (i < tokenCount) {
tokenIds[i] = tokenOfOwnerByIndex(owner, i);
i++;
... | 0.8.10 |
/**
* @dev Deposit a quantity of bAsset into the platform. Credited aTokens
* remain here in the vault. Can only be called by whitelisted addresses
* (mAsset and corresponding BasketManager)
* @param _bAsset Address for the bAsset
* @param _amount Units of bAsset to deposit
* @... | function deposit(
address _bAsset,
uint256 _amount,
bool _hasTxFee
) external override onlyLP nonReentrant returns (uint256 quantityDeposited) {
require(_amount > 0, "Must deposit something");
IAaveATokenV2 aToken = _getATokenFor(_bAsset);
quantityDeposited = _amoun... | 0.8.6 |
/** @dev Withdraws _totalAmount from the lending pool, sending _amount to user */ | function _withdraw(
address _receiver,
address _bAsset,
uint256 _amount,
uint256 _totalAmount,
bool _hasTxFee
) internal {
require(_totalAmount > 0, "Must withdraw something");
IAaveATokenV2 aToken = _getATokenFor(_bAsset);
if (_hasTxFee) {
... | 0.8.6 |
/**
* @dev Withdraw a quantity of bAsset from the cache.
* @param _receiver Address to which the bAsset should be sent
* @param _bAsset Address of the bAsset
* @param _amount Units of bAsset to withdraw
*/ | function withdrawRaw(
address _receiver,
address _bAsset,
uint256 _amount
) external override onlyLP nonReentrant {
require(_amount > 0, "Must withdraw something");
require(_receiver != address(0), "Must specify recipient");
IERC20(_bAsset).safeTransfer(_receiver, _a... | 0.8.6 |
/*
* @param _withdrawalAddress address to which funds from this contract will be sent
*/ | function setWithdrawalAddress(address payable _withdrawalAddress) public onlyAdmin returns (bool success) {
require(
!withdrawalAddressFixed,
"Withdrawal address already fixed"
);
require(
_withdrawalAddress != address(0),
"Wrong address... | 0.5.11 |
/**
* @param _withdrawalAddress Address to which funds from this contract will be sent.
*
* @dev This function can be called one time only.
*/ | function fixWithdrawalAddress(address _withdrawalAddress) external onlyAdmin returns (bool success) {
// prevents event if already fixed
require(
!withdrawalAddressFixed,
"Can't change, address fixed"
);
// check, to prevent fixing wrong address
... | 0.5.11 |
/**
* @dev This function can be called by any user or contract.
* Possible warning:
check for reentrancy vulnerability http://solidity.readthedocs.io/en/develop/security-considerations.html#re-entrancy
* Since we are making a withdrawal to our own contract/address only there is no possible attack using reentran... | function withdrawAllToWithdrawalAddress() external returns (bool success) {
// http://solidity.readthedocs.io/en/develop/security-considerations.html#sending-and-receiving-ether
// about <address>.send(uint256 amount) and <address>.transfer(uint256 amount)
// see: http://solidity.readthedoc... | 0.5.11 |
/*
* @dev This function creates new shares contracts.
* @param _description Description of the project or organization (can be short text or link to web page)
* @param _name Name of the token, as required by ERC20.
* @param _symbol Symbol for the token, as required by ERC20.
* @param _totalSupply Total supply... | function createCryptoSharesContract(
string calldata _description,
string calldata _name,
string calldata _symbol,
uint _totalSupply,
uint _dividendsPeriodInSeconds
) external payable returns (bool success){
require(
msg.value >= price,
... | 0.5.11 |
// Only positions with locked veFXS can accrue yield. Otherwise, expired-locked veFXS
// is de-facto rewards for FXS. | function eligibleCurrentVeFXS(address account) public view returns (uint256) {
uint256 curr_vefxs_bal = veFXS.balanceOf(account);
IveFXS.LockedBalance memory curr_locked_bal_pack = veFXS.locked(account);
// Only unexpired veFXS should be eligible
if (int256(curr_locked_bal_pack.... | 0.8.4 |
//public payable | function presale( uint quantity ) external payable {
require( isPresaleActive, "Presale is not active" );
require( quantity <= MAX_ORDER, "Order too big" );
require( msg.value >= PRESALE_PRICE * quantity, "Ether sent is not correct" );
require( accessList[msg.se... | 0.8.7 |
//delegated payable | function burnFrom( address owner, uint[] calldata tokenIds ) external payable onlyDelegates{
for(uint i; i < tokenIds.length; ++i ){
require( _exists( tokenIds[i] ), "Burn for nonexistent token" );
require( _owners[ tokenIds[i] ] == owner, "Owner mismatch" );
_burn( tokenIds[i] );
}
} | 0.8.7 |
//delegated nonpayable | function resurrect( uint[] calldata tokenIds, address[] calldata recipients ) external onlyDelegates{
require(tokenIds.length == recipients.length, "Must provide equal tokenIds and recipients" );
address to;
uint tokenId;
address zero = address(0);
for(uint i; i < tokenIds.length; ++i ){
... | 0.8.7 |
// If the period expired, renew it | function retroCatchUp() internal {
// Failsafe check
require(block.timestamp > periodFinish, "Period has not expired yet!");
// Ensure the provided yield amount is not more than the balance in the contract.
// This keeps the yield rate in the right range, preventing overflows due to
... | 0.8.4 |
/**
* @dev Burns a specific amount of tokens from another address.
* @param _value The amount of tokens to be burned.
* @param _from The address which you want to burn tokens from.
*/ | function burnFrom(address _from, uint _value) public returns (bool success) {
require((balances[_from] > _value) && (_value <= allowed[_from][msg.sender]));
var _allowance = allowed[_from][msg.sender];
balances[_from] = balances[_from].sub(_value);
totalSupply = totalSupply.sub(_valu... | 0.4.23 |
/**
* @dev Returns ceil(a / b).
*/ | function ceil(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
if(a % b == 0) {
return c;
}
else {
return c + 1;
}
} | 0.5.4 |
// *************** Signature ********************** // | function getSignHash(bytes memory _data, uint256 _nonce) internal view returns(bytes32) {
// use EIP 191
// 0x1900 + this logic address + data + nonce of signing key
bytes32 msgHash = keccak256(abi.encodePacked(byte(0x19), byte(0), address(this), _data, _nonce));
bytes32 prefixedHash... | 0.5.4 |
/* get signer address from data
* @dev Gets an address encoded as the first argument in transaction data
* @param b The byte array that should have an address as first argument
* @returns a The address retrieved from the array
*/ | function getSignerAddress(bytes memory _b) internal pure returns (address _a) {
require(_b.length >= 36, "invalid bytes");
// solium-disable-next-line security/no-inline-assembly
assembly {
let mask := 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
_a := and(mask, mload(... | 0.5.4 |
// get method id, first 4 bytes of data | function getMethodId(bytes memory _b) internal pure returns (bytes4 _a) {
require(_b.length >= 4, "invalid data");
// solium-disable-next-line security/no-inline-assembly
assembly {
// 32 bytes is the length of the bytes array
_a := mload(add(_b, 32))
}
... | 0.5.4 |
/**
* @dev This method makes it possible for the wallet to comply to interfaces expecting the wallet to
* implement specific static methods. It delegates the static call to a target contract if the data corresponds
* to an enabled method, or logs the call otherwise.
*/ | function() external payable {
if(msg.data.length > 0) {
address logic = enabled[msg.sig];
if(logic == address(0)) {
emit Received(msg.value, msg.sender, msg.data);
}
else {
require(LogicManager(manager).isAuthorized(logic), "... | 0.5.4 |
/**
* @notice Approves this contract to transfer `amount` tokens from the `msg.sender`
* and stakes these tokens. Only the owner of tokens (i.e. the staker) may call.
* @dev This contract does not need to be approve()'d in advance - see EIP-2612
* @param owner - The owner of tokens being staked (i.e. the `msg.sende... | function permitAndStake(
address owner,
uint256 amount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s,
bytes4 stakeType,
bytes calldata data
) external returns (uint256) {
require(owner == msg.sender, "Staking: owner must be msg.sender");
... | 0.8.4 |
/**
* @notice Claims staked token
* @param stakeID - ID of the stake to claim
* @param data - Arbitrary data for "RewardMaster" (zero, if inapplicable)
* @param _isForced - Do not revert if "RewardMaster" fails
*/ | function unstake(
uint256 stakeID,
bytes calldata data,
bool _isForced
) external stakeExist(msg.sender, stakeID) {
Stake memory _stake = stakes[msg.sender][stakeID];
require(_stake.claimedAt == 0, "Staking: Stake claimed");
require(_stake.lockedTill < safe32TimeNow(... | 0.8.4 |
/**
* @notice Updates vote delegation
* @param stakeID - ID of the stake to delegate votes uber
* @param to - address to delegate to
*/ | function delegate(uint256 stakeID, address to)
public
stakeExist(msg.sender, stakeID)
{
require(
to != GLOBAL_ACCOUNT,
"Staking: Can't delegate to GLOBAL_ACCOUNT"
);
Stake memory s = stakes[msg.sender][stakeID];
require(s.claimedAt == 0, "Stak... | 0.8.4 |
/// Only for the owner functions
/// @notice Adds a new stake type with given terms
/// @dev May be only called by the {OWNER} | function addTerms(bytes4 stakeType, Terms memory _terms)
external
onlyOwner
nonZeroStakeType(stakeType)
{
Terms memory existingTerms = terms[stakeType];
require(!_isDefinedTerms(existingTerms), "Staking:E1");
require(_terms.isEnabled, "Staking:E2");
uint256 _... | 0.8.4 |
/// This function is from Nick Johnson's string utils library | function memcpy(uint dest, uint src, uint len) private pure {
// Copy word-length chunks while possible
for(; len >= 32; len -= 32) {
assembly {
mstore(dest, mload(src))
}
dest += 32;
src += 32;
}
// Copy remainin... | 0.7.4 |
// This famous algorithm is called "exponentiation by squaring"
// and calculates x^n with x as fixed-point and n as regular unsigned.
//
// It's O(log n), instead of O(n) for naive repeated multiplication.
//
// These facts are why it works:
//
// If n is even, then x^n = (x^2)^(n/2).
// If n is odd, then x^n = x *... | function rpow(uint x, uint n) internal pure returns (uint z) {
z = n % 2 != 0 ? x : RAY;
for (n /= 2; n != 0; n /= 2) {
x = rmul(x, x);
if (n % 2 != 0) {
z = rmul(z, x);
}
}
} | 0.4.25 |
/**
* @dev Transfer tokens from one address to another
* @param src address The address which you want to send tokens from
* @param dst address The address which you want to transfer to
* @param wad uint256 the amount of tokens to be transferred
*/ | function transferFrom(address src, address dst, uint wad)
public
returns (bool)
{
if (src != msg.sender) {
_approvals[src][msg.sender] = sub(_approvals[src][msg.sender], wad);
}
_balances[src] = sub(_balances[src], wad);
_balanc... | 0.4.25 |
/* ========== USER MUTATIVE FUNCTIONS ========== */ | function deposit(uint _amount) external nonReentrant {
_updateReward(msg.sender);
uint _pool = balance();
token.safeTransferFrom(msg.sender, address(this), _amount);
uint shares = 0;
if (totalSupply() == 0) {
shares = _amount;
} else {
shares = (_amount.mul(totalSup... | 0.6.12 |
// No rebalance implementation for lower fees and faster swaps | function withdraw(uint _shares) public nonReentrant {
_updateReward(msg.sender);
uint r = (balance().mul(_shares)).div(totalSupply());
_burn(msg.sender, _shares);
// Check balance
uint b = token.balanceOf(address(this));
if (b < r) {
uint _withdraw = r.sub(b);
I... | 0.6.12 |
// Keepers call farm() to send funds to strategy | function farm() external onlyKeeper {
uint _bal = available();
uint keeperFee = _bal.mul(farmKeeperFeeMin).div(MAX);
if (keeperFee > 0) {
token.safeTransfer(msg.sender, keeperFee);
}
uint amountLessFee = _bal.sub(keeperFee);
token.safeTransfer(controller, amountLessFee);
... | 0.6.12 |
// Keepers call harvest() to claim rewards from strategy
// harvest() is marked as onlyEOA to prevent sandwich/MEV attack to collect most rewards through a flash-deposit() follow by a claim | function harvest() external onlyKeeper {
uint _rewardBefore = rewardToken.balanceOf(address(this));
IController(controller).harvest(address(this));
uint _rewardAfter = rewardToken.balanceOf(address(this));
uint harvested = _rewardAfter.sub(_rewardBefore);
uint keeperFee = harvested.mul(ha... | 0.6.12 |
// Writes are allowed only if the accessManager approves | function setAttribute(address _who, bytes32 _attribute, uint256 _value, bytes32 _notes) public {
require(confirmWrite(_attribute, msg.sender));
attributes[_who][_attribute] = AttributeData(_value, _notes, msg.sender, block.timestamp);
emit SetAttribute(_who, _attribute, _value, _notes, msg.se... | 0.5.8 |
/**
* @notice Deposit funds into contract.
* @dev the amount of deposit is determined by allowance of this contract
*/ | function depositToken(address _user) public {
uint256 allowance = StakeToken(token).allowance(_user, address(this));
uint256 oldBalance = userTokenBalance[_user];
uint256 newBalance = oldBalance.add(allowance);
require(StakeToken(token).transferFrom(_user, address(this), allowanc... | 0.5.1 |
/// @notice Send `_amount` tokens to `_to` from `_from` on the condition it
/// is approved by `_from`
/// @param _from The address holding the tokens being transferred
/// @param _to The address of the recipient
/// @param _amount The amount of tokens to be transferred
/// @return True if the transfer was successful | function transferFrom(address _from, address _to, uint256 _amount
) public returns (bool success) {
// The controller of this contract can move tokens around at will,
// this is important to recognize! Confirm that you trust the
// controller of this contract, which in most situation... | 0.4.24 |
/// @notice `msg.sender` approves `_spender` to spend `_amount` tokens on
/// its behalf. This is a modified version of the ERC20 approve function
/// to be a little bit safer
/// @param _spender The address of the account able to transfer the tokens
/// @param _amount The amount of tokens to be approved for transfer... | function approve(address _spender, uint256 _amount) public returns (bool success) {
require(transfersEnabled);
// 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 r... | 0.4.24 |
////////////////
/// @dev Queries the balance of `_owner` at a specific `_blockNumber`
/// @param _owner The address from which the balance will be retrieved
/// @param _blockNumber The block number when the balance is queried
/// @return The balance at `_blockNumber` | function balanceOfAt(address _owner, uint256 _blockNumber) public view
returns (uint256) {
// These next few lines are used when the balance of the token is
// requested before a check point was ever created for this token, it
// requires that the `parentToken.balanceOfAt` be que... | 0.4.24 |
/// @notice Total amount of tokens at a specific `_blockNumber`.
/// @param _blockNumber The block number when the totalSupply is queried
/// @return The total amount of tokens at `_blockNumber` | function totalSupplyAt(uint256 _blockNumber) public view returns(uint256) {
// These next few lines are used when the totalSupply of the token is
// requested before a check point was ever created for this token, it
// requires that the `parentToken.totalSupplyAt` be queried at the
... | 0.4.24 |
////////////////
/// @notice Generates `_amount` tokens that are assigned to `_owner`
/// @param _owner The address that will be assigned the new tokens
/// @param _amount The quantity of tokens generated
/// @return True if the tokens are generated correctly | function generateTokens(address _owner, uint256 _amount
) public onlyController returns (bool) {
uint256 curTotalSupply = totalSupply();
require(curTotalSupply + _amount >= curTotalSupply); // Check for overflow
uint256 previousBalanceTo = balanceOf(_owner);
require(previousBala... | 0.4.24 |
/// @notice Burns `_amount` tokens from `_owner`
/// @param _owner The address that will lose the tokens
/// @param _amount The quantity of tokens to burn
/// @return True if the tokens are burned correctly | function destroyTokens(address _owner, uint256 _amount
) onlyController public returns (bool) {
uint256 curTotalSupply = totalSupply();
require(curTotalSupply >= _amount);
uint256 previousBalanceFrom = balanceOf(_owner);
require(previousBalanceFrom >= _amount);
updateVa... | 0.4.24 |
////////////////
/// @dev `getValueAt` retrieves the number of tokens at a given block number
/// @param checkpoints The history of values being queried
/// @param _block The block number to retrieve the value at
/// @return The number of tokens being queried | function getValueAt(Checkpoint[] storage checkpoints, uint256 _block
) view internal returns (uint256) {
if (checkpoints.length == 0) return 0;
// Shortcut for the actual value
if (_block >= checkpoints[checkpoints.length-1].fromBlock)
return checkpoints[checkpoints.length... | 0.4.24 |
/// @dev `updateValueAtNow` used to update the `balances` map and the
/// `totalSupplyHistory`
/// @param checkpoints The history of data being updated
/// @param _value The new number of tokens | function updateValueAtNow(Checkpoint[] storage checkpoints, uint256 _value
) internal {
if ((checkpoints.length == 0) || (checkpoints[checkpoints.length - 1].fromBlock < block.number)) {
Checkpoint storage newCheckPoint = checkpoints[checkpoints.length++];
newCheckPoint.fromBloc... | 0.4.24 |
/**
* @notice `msg.sender` transfers `_amount` to `_to` contract and then tokenFallback() function is triggered in the `_to` contract.
* @param _to The address of the contract able to receive the tokens
* @param _amount The amount of tokens to be transferred
* @param _data The payload to be treated by `_to` co... | function transferAndCall(address _to, uint _amount, bytes _data) public returns (bool) {
require(transfer(_to, _amount));
emit Transfer(msg.sender, _to, _amount, _data);
// call receiver
if (isContract(_to)) {
ERC677Receiver(_to).tokenFallback(msg.sender, _amount, _d... | 0.4.24 |
/**
* @notice Sets the locks of an array of addresses.
* @dev Must be called while minting (enableTransfers = false). Sizes of `_holder` and `_lockups` must be the same.
* @param _holders The array of investor addresses
* @param _lockups The array of timestamps until which corresponding address must be locked
... | function setLocks(address[] _holders, uint256[] _lockups) public onlyController {
require(_holders.length == _lockups.length);
require(_holders.length < 256);
require(transfersEnabled == false);
for (uint8 i = 0; i < _holders.length; i++) {
address holder = _holders[i]... | 0.4.24 |
/**
* @notice Finishes minting process and throws out the controller.
* @dev Owner can not finish minting without setting up address for burning tokens.
* @param _burnable The address to burn tokens from
*/ | function finishMinting(address _burnable) public onlyController() {
require(_burnable != address(0x0)); // burnable address must be set
assert(totalSupply() <= maxSupply); // ensure hard cap
enableTransfers(true); // turn-on transfers
changeController(address(0x0)); // ensure no new ... | 0.4.24 |
/**
* @notice Burns `_amount` tokens from pre-defined "burnable" address.
* @param _amount The amount of tokens to burn
* @return True if the tokens are burned correctly
*/ | function burn(uint256 _amount) public onlyOwner returns (bool) {
require(burnable != address(0x0)); // burnable address must be set
uint256 currTotalSupply = totalSupply();
uint256 previousBalance = balanceOf(burnable);
require(currTotalSupply >= _amount);
require(previo... | 0.4.24 |
// View function to see pending CHKs on frontend. | function pendingChk(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accChkPerShare = pool.accChkPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
// con... | 0.6.12 |
// =================================== Constructor ============================================= | function JubsICO ()public {
//Address
walletETH = 0x6eA3ec9339839924a520ff57a0B44211450A8910;
icoWallet = 0x357ace6312BF8B519424cD3FfdBB9990634B8d3E;
preIcoWallet = 0x7c54dC4F3328197AC89a53d4b8cDbE35a56656f7;
teamWallet = 0x06BC5305016E9972F4cB3F6a3Ef2C734D417788a;
... | 0.4.19 |
// if supply provided is 0, then default assigned | function svb(uint supply) {
if (supply > 0) {
totalSupply = supply;
} else {
totalSupply = totalSupplyDefault;
}
owner = msg.sender;
demurringFeeOwner = owner;
transferFeeOwner = owner;
balances[this] = totalSupply;
} | 0.4.15 |
// charge demurring fee for previuos period
// fee is not applied to owners | function chargeDemurringFee(address addr) internal {
if (addr != owner && addr != transferFeeOwner && addr != demurringFeeOwner && balances[addr] > 0 && now > timestamps[addr] + 60) {
var mins = (now - timestamps[addr]) / 60;
var fee = balances[addr] * mins * demurringFeeNum / demurri... | 0.4.15 |
// fee is not applied to owners | function chargeTransferFee(address addr, uint amount) internal returns (uint) {
if (addr != owner && addr != transferFeeOwner && addr != demurringFeeOwner && balances[addr] > 0) {
var fee = amount * transferFeeNum / transferFeeDenum;
if (fee < minFee) {
fee = minFee;
... | 0.4.15 |
/**
* @dev Notifies Fragments contract about a new rebase cycle.
* @param supplyDelta The number of new fragment tokens to add into circulation via expansion.
* @return The total number of fragments after the supply adjustment.
*/ | function rebase(uint256 epoch_, int256 supplyDelta)
external
onlyOwner
returns (uint256)
{
// console.log(symbol(), ": starting total supply ", epoch, _totalSupply.div(10**18));
// console.log("gonsPerFragment: ", epoch, _gonsPerFragment);
epoch = epoch_;
... | 0.6.12 |
/**
* @dev Transfer tokens to a specified address.
* @param to The address to transfer to.
* @param value The amount to be transferred.
* @return True on success, false otherwise.
*/ | function transfer(address to, uint256 value)
public
override
validRecipient(to)
returns (bool)
{
uint256 gonValue = value.mul(_gonsPerFragment);
_gonBalances[_currentBalances][msg.sender] = _gonBalances[_currentBalances][msg.sender].sub(gonValue);
_gonBalances... | 0.6.12 |
/**
* @dev Decrease the amount of tokens that an owner has allowed to a spender.
*
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/ | function decreaseAllowance(address spender, uint256 subtractedValue)
public
returns (bool)
{
uint256 oldValue = _allowedFragments[msg.sender][spender];
if (subtractedValue >= oldValue) {
_allowedFragments[msg.sender][spender] = 0;
} else {
_allowedFrag... | 0.6.12 |
// following the pattern of uniswap so there can be a pool factory | function initialize(
address owner_,
address payoutToken_,
uint256 epochLength_,
uint8 multiplier_,
address oracle_,
address underlying_
) public isOwner {
owner = owner_;
payoutToken = IERC20(payoutToken_);
oracle = IPriceOracleGetter(oracle_)... | 0.6.12 |
/**
calculate the percent change defined as an 18 precision decimal (1e18 is 100%)
*/ | function percentChangeMax100(uint256 diff, uint256 base)
internal
view
returns (uint256)
{
if (base == 0) {
return 0; // ignore zero price
}
uint256 percent = (diff * 10**18).mul(10**18).div(base.mul(10**18)).mul(uint256(multiplier));
if (percent >... | 0.6.12 |
// TODO: this provides an arbitrage opportunity to withdraw
// before the end of a period. This should be a lockup. | function liquidate() public checkEpoch {
// TODO: only allow this after the lockout period
address user_ = msg.sender;
uint256 upBal = up.balanceOf(user_);
uint256 downBal = down.balanceOf(user_);
up.liquidate(address(user_));
down.liquidate(address(user_));
up... | 0.6.12 |
/// Returns an estimation of the fees and bootstrap a guardian will be entitled to for a duration of time
/// The estimation is based on the current system state and there for only provides an estimation
/// @param guardian is the guardian address
/// @param duration is the amount of time in seconds for which the estim... | function estimateFutureFeesAndBootstrapRewards(address guardian, uint256 duration) external override view returns (uint256 estimatedFees, uint256 estimatedBootstrapRewards) {
(FeesAndBootstrap memory guardianFeesAndBootstrapNow,) = getGuardianFeesAndBootstrap(guardian, block.timestamp);
(FeesAndBootst... | 0.6.12 |
/// Transfers the guardian Fees balance to their account
/// @dev One may withdraw for another guardian
/// @param guardian is the guardian address | function withdrawFees(address guardian) external override onlyWhenActive {
updateGuardianFeesAndBootstrap(guardian);
uint256 amount = feesAndBootstrap[guardian].feeBalance;
feesAndBootstrap[guardian].feeBalance = 0;
uint96 withdrawnFees = feesAndBootstrap[guardian].withdrawnFees.ad... | 0.6.12 |
/// Returns the current global Fees and Bootstrap rewards state
/// @dev calculated to the latest block, may differ from the state read
/// @return certifiedFeesPerMember represents the fees a certified committee member from day 0 would have receive
/// @return generalFeesPerMember represents the fees a non-certified ... | function getFeesAndBootstrapState() external override view returns (
uint256 certifiedFeesPerMember,
uint256 generalFeesPerMember,
uint256 certifiedBootstrapPerMember,
uint256 generalBootstrapPerMember,
uint256 lastAssigned
) {
(uint generalCommitteeSize, uint ... | 0.6.12 |
/// Returns the current guardian Fees and Bootstrap rewards state
/// @dev calculated to the latest block, may differ from the state read
/// @return feeBalance is the guardian fees balance
/// @return lastFeesPerMember is the FeesPerMember on the last update based on the guardian certification state
/// @return boot... | function getFeesAndBootstrapData(address guardian) external override view returns (
uint256 feeBalance,
uint256 lastFeesPerMember,
uint256 bootstrapBalance,
uint256 lastBootstrapPerMember,
uint256 withdrawnFees,
uint256 withdrawnBootstrap,
bool certified
... | 0.6.12 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.