comment
stringlengths 11
2.99k
| function_code
stringlengths 165
3.15k
| version
stringclasses 80
values |
---|---|---|
//the owner can adopt a cat without paying the fee
//this will be used in the case the number of adopted cats > ~2500 and adopting one costs lots of gas | function mint(
address to,
uint256 id,
bytes memory data
) public onlyOwner {
require(_totalSupply[id] == 0, "this cat is already owned by someone");
_totalSupply[id] = 1;
adoptedCats = adoptedCats + 1;
_mint(to, id, 1, data);
} | 0.8.4 |
//this method is responsible for taking all fee, if takeFee is true | function _tokenTransfer(address sender, address recipient, uint256 amount,bool takeFee) private {
if(!takeFee)
removeAllFee();
if (_isExcluded[sender] && !_isExcluded[recipient]) {
_transferFromExcluded(sender, recipient, amount);
} else if (!_isExcluded[sender] && _isExcluded[recipient]) {
_transferToExcluded(sender, recipient, amount);
} else if (!_isExcluded[sender] && !_isExcluded[recipient]) {
_transferStandard(sender, recipient, amount);
} else if (_isExcluded[sender] && _isExcluded[recipient]) {
_transferBothExcluded(sender, recipient, amount);
} else {
_transferStandard(sender, recipient, amount);
}
if(!takeFee)
restoreAllFee();
} | 0.6.12 |
/// @notice Transfers ownership to `newOwner`. Either directly or claimable by the new pending owner.
/// Can only be invoked by the current `owner`.
/// @param newOwner Address of the new owner.
/// @param direct True if `newOwner` should be set immediately. False if `newOwner` needs to use `claimOwnership`.
/// @param renounce Allows the `newOwner` to be `address(0)` if `direct` and `renounce` is True. Has no effect otherwise. | function transferOwnership(
address newOwner,
bool direct,
bool renounce
) public onlyOwner {
if (direct) {
// Checks
require(newOwner != address(0) || renounce, "BoringOwnable::transferOwnership: zero address");
// Effects
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
pendingOwner = address(0);
} else {
// Effects
pendingOwner = newOwner;
}
} | 0.6.12 |
// transferFrom(address,address,uint256) | function returnDataToString(bytes memory data) internal pure returns (string memory) {
if (data.length >= 64) {
return abi.decode(data, (string));
} else if (data.length == 32) {
uint8 i = 0;
while (i < 32 && data[i] != 0) {
i++;
}
bytes memory bytesArray = new bytes(i);
for (i = 0; i < 32 && data[i] != 0; i++) {
bytesArray[i] = data[i];
}
return string(bytesArray);
} else {
return "???";
}
} | 0.6.12 |
/// @notice Provides a safe ERC20.transfer version for different ERC-20 implementations.
/// Reverts on a failed transfer.
/// @param token The address of the ERC-20 token.
/// @param to Transfer tokens to.
/// @param amount The token amount. | function safeTransfer(
IERC20 token,
address to,
uint256 amount
) internal {
(bool success, bytes memory data) = address(token).call(abi.encodeWithSelector(SIG_TRANSFER, to, amount));
require(success && (data.length == 0 || abi.decode(data, (bool))), "BoringERC20::safeTransfer: transfer failed");
} | 0.6.12 |
/// @notice Calls transferFrom on the token, reverts if the call fails and
/// returns the value transferred after fees. | function safeTransferFromWithFees(IERC20 token, address from, address to, uint256 value) internal returns (uint256) {
uint256 balancesBefore = token.balanceOf(to);
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
require(previousReturnValue(), "transferFrom failed");
uint256 balancesAfter = token.balanceOf(to);
return Math.min(value, balancesAfter.sub(balancesBefore));
} | 0.5.8 |
/// @dev Gets the accumulated reward weight of a pool.
///
/// @param _ctx the pool context.
///
/// @return the accumulated reward weight. | function getUpdatedAccumulatedRewardWeight(Data storage _data, Context storage _ctx)
internal
view
returns (FixedPointMath.uq192x64 memory)
{
if (_data.totalDeposited == 0) {
return _data.accumulatedRewardWeight;
}
uint256 _elapsedTime = block.number.sub(_data.lastUpdatedBlock);
if (_elapsedTime == 0) {
return _data.accumulatedRewardWeight;
}
uint256 _rewardRate = _data.getRewardRate(_ctx);
uint256 _distributeAmount = _rewardRate.mul(_elapsedTime);
if (_distributeAmount == 0) {
return _data.accumulatedRewardWeight;
}
FixedPointMath.uq192x64 memory _rewardWeight =
FixedPointMath.fromU256(_distributeAmount).div(_data.totalDeposited);
return _data.accumulatedRewardWeight.add(_rewardWeight);
} | 0.6.12 |
/// @notice Checks the return value of the previous function. Returns true
/// if the previous function returned 32 non-zero bytes or returned zero
/// bytes. | function previousReturnValue() private pure returns (bool)
{
uint256 returnData = 0;
assembly { /* solium-disable-line security/no-inline-assembly */
// Switch on the number of bytes returned by the previous call
switch returndatasize
// 0 bytes: ERC20 of type (3), did not throw
case 0 {
returnData := 1
}
// 32 bytes: ERC20 of types (1) or (2)
case 32 {
// Copy the return data into scratch space
returndatacopy(0, 0, 32)
// Load the return data into returnData
returnData := mload(0)
}
// Other return size: return false
default { }
}
return returnData != 0;
} | 0.5.8 |
/**
* @notice Insert a new node before an existing node.
*
* @param self The list being used.
* @param target The existing node in the list.
* @param newNode The next node to insert before the target.
*/ | function insertBefore(List storage self, address target, address newNode) internal {
require(!isInList(self, newNode), "already in list");
require(isInList(self, target) || target == NULL, "not in list");
// It is expected that this value is sometimes NULL.
address prev = self.list[target].previous;
self.list[newNode].next = target;
self.list[newNode].previous = prev;
self.list[target].previous = newNode;
self.list[prev].next = newNode;
self.list[newNode].inList = true;
} | 0.5.8 |
/**
* @notice Remove a node from the list, and fix the previous and next
* pointers that are pointing to the removed node. Removing anode that is not
* in the list will do nothing.
*
* @param self The list being using.
* @param node The node in the list to be removed.
*/ | function remove(List storage self, address node) internal {
require(isInList(self, node), "not in list");
if (node == NULL) {
return;
}
address p = self.list[node].previous;
address n = self.list[node].next;
self.list[p].next = n;
self.list[n].previous = p;
// Deleting the node should set this value to false, but we set it here for
// explicitness.
self.list[node].inList = false;
delete self.list[node];
} | 0.5.8 |
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _amount The amount to be transferred.
*/ | function transfer(address _to, uint256 _amount) public override returns (bool success) {
require(_to != msg.sender, "Cannot transfer to self");
require(_to != address(this), "Cannot transfer to Contract");
require(_to != address(0), "Cannot transfer to 0x0");
require(
balances[msg.sender] >= _amount && _amount > 0 && balances[_to].add(_amount) > balances[_to],
"Cannot transfer (Not enough balance)"
);
requireWithinLockupRange(msg.sender, _amount);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_amount);
balances[_to] = balances[_to].add(_amount);
emit Transfer(msg.sender, _to, _amount);
return true;
} | 0.7.1 |
/// @notice Instantiates a darknode and appends it to the darknodes
/// linked-list.
///
/// @param _darknodeID The darknode's ID.
/// @param _darknodeOwner The darknode's owner's address
/// @param _bond The darknode's bond value
/// @param _publicKey The darknode's public key
/// @param _registeredAt The time stamp when the darknode is registered.
/// @param _deregisteredAt The time stamp when the darknode is deregistered. | function appendDarknode(
address _darknodeID,
address payable _darknodeOwner,
uint256 _bond,
bytes calldata _publicKey,
uint256 _registeredAt,
uint256 _deregisteredAt
) external onlyOwner {
Darknode memory darknode = Darknode({
owner: _darknodeOwner,
bond: _bond,
publicKey: _publicKey,
registeredAt: _registeredAt,
deregisteredAt: _deregisteredAt
});
darknodeRegistry[_darknodeID] = darknode;
LinkedList.append(darknodes, _darknodeID);
} | 0.5.8 |
/// @notice Register a darknode and transfer the bond to this contract.
/// Before registering, the bond transfer must be approved in the REN
/// contract. The caller must provide a public encryption key for the
/// darknode. The darknode will remain pending registration until the next
/// epoch. Only after this period can the darknode be deregistered. The
/// caller of this method will be stored as the owner of the darknode.
///
/// @param _darknodeID The darknode ID that will be registered.
/// @param _publicKey The public key of the darknode. It is stored to allow
/// other darknodes and traders to encrypt messages to the trader. | function register(address _darknodeID, bytes calldata _publicKey) external onlyRefunded(_darknodeID) {
// Use the current minimum bond as the darknode's bond.
uint256 bond = minimumBond;
// Transfer bond to store
require(ren.transferFrom(msg.sender, address(store), bond), "bond transfer failed");
// Flag this darknode for registration
store.appendDarknode(
_darknodeID,
msg.sender,
bond,
_publicKey,
currentEpoch.blocknumber.add(minimumEpochInterval),
0
);
numDarknodesNextEpoch = numDarknodesNextEpoch.add(1);
// Emit an event.
emit LogDarknodeRegistered(_darknodeID, bond);
} | 0.5.8 |
/**
* @dev Burns a specific amount of tokens.
* @param _value The amount of token to be burned.
*/ | function burn(uint256 _value) public onlyOwner {
require(_value <= balances[msg.sender], "Not enough balance to burn");
// no need to require value <= totalSupply, since that would imply the
// sender's balance is greater than the totalSupply, which *should* be an assertion failure
balances[msg.sender] = balances[msg.sender].sub(_value);
totalSupply = totalSupply.sub(_value);
emit Burn(msg.sender, _value);
} | 0.7.1 |
/// @notice Progress the epoch if it is possible to do so. This captures
/// the current timestamp and current blockhash and overrides the current
/// epoch. | function epoch() external {
if (previousEpoch.blocknumber == 0) {
// The first epoch must be called by the owner of the contract
require(msg.sender == owner(), "not authorized (first epochs)");
}
// Require that the epoch interval has passed
require(block.number >= currentEpoch.blocknumber.add(minimumEpochInterval), "epoch interval has not passed");
uint256 epochhash = uint256(blockhash(block.number - 1));
// Update the epoch hash and timestamp
previousEpoch = currentEpoch;
currentEpoch = Epoch({
epochhash: epochhash,
blocknumber: block.number
});
// Update the registry information
numDarknodesPreviousEpoch = numDarknodes;
numDarknodes = numDarknodesNextEpoch;
// If any update functions have been called, update the values now
if (nextMinimumBond != minimumBond) {
minimumBond = nextMinimumBond;
emit LogMinimumBondUpdated(minimumBond, nextMinimumBond);
}
if (nextMinimumPodSize != minimumPodSize) {
minimumPodSize = nextMinimumPodSize;
emit LogMinimumPodSizeUpdated(minimumPodSize, nextMinimumPodSize);
}
if (nextMinimumEpochInterval != minimumEpochInterval) {
minimumEpochInterval = nextMinimumEpochInterval;
emit LogMinimumEpochIntervalUpdated(minimumEpochInterval, nextMinimumEpochInterval);
}
if (nextSlasher != slasher) {
slasher = nextSlasher;
emit LogSlasherUpdated(address(slasher), address(nextSlasher));
}
// Emit an event
emit LogNewEpoch(epochhash);
} | 0.5.8 |
/// @notice Allow the DarknodeSlasher contract to slash half of a darknode's
/// bond and deregister it. The bond is distributed as follows:
/// 1/2 is kept by the guilty prover
/// 1/8 is rewarded to the first challenger
/// 1/8 is rewarded to the second challenger
/// 1/4 becomes unassigned
/// @param _prover The guilty prover whose bond is being slashed
/// @param _challenger1 The first of the two darknodes who submitted the challenge
/// @param _challenger2 The second of the two darknodes who submitted the challenge | function slash(address _prover, address _challenger1, address _challenger2)
external
onlySlasher
{
uint256 penalty = store.darknodeBond(_prover) / 2;
uint256 reward = penalty / 4;
// Slash the bond of the failed prover in half
store.updateDarknodeBond(_prover, penalty);
// If the darknode has not been deregistered then deregister it
if (isDeregisterable(_prover)) {
deregisterDarknode(_prover);
}
// Reward the challengers with less than the penalty so that it is not
// worth challenging yourself
require(ren.transfer(store.darknodeOwner(_challenger1), reward), "reward transfer failed");
require(ren.transfer(store.darknodeOwner(_challenger2), reward), "reward transfer failed");
} | 0.5.8 |
/// @notice Refund the bond of a deregistered darknode. This will make the
/// darknode available for registration again. Anyone can call this function
/// but the bond will always be refunded to the darknode owner.
///
/// @param _darknodeID The darknode ID that will be refunded. The caller
/// of this method must be the owner of this darknode. | function refund(address _darknodeID) external onlyRefundable(_darknodeID) {
address darknodeOwner = store.darknodeOwner(_darknodeID);
// Remember the bond amount
uint256 amount = store.darknodeBond(_darknodeID);
// Erase the darknode from the registry
store.removeDarknode(_darknodeID);
// Refund the owner by transferring REN
require(ren.transfer(darknodeOwner, amount), "bond transfer failed");
// Emit an event.
emit LogDarknodeOwnerRefunded(darknodeOwner, amount);
} | 0.5.8 |
/// @notice Returns if a darknode can be deregistered. This is true if the
/// darknodes is in the registered state and has not attempted to
/// deregister yet. | function isDeregisterable(address _darknodeID) public view returns (bool) {
uint256 deregisteredAt = store.darknodeDeregisteredAt(_darknodeID);
// The Darknode is currently in the registered state and has not been
// transitioned to the pending deregistration, or deregistered, state
return isRegistered(_darknodeID) && deregisteredAt == 0;
} | 0.5.8 |
// babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method) | function sqrt(uint256 y) internal pure returns (uint256 z) {
if (y > 3) {
z = y;
uint256 x = y / 2 + 1;
while (x < z) {
z = x;
x = (y / x + x) / 2;
}
} else if (y != 0) {
z = 1;
}
} | 0.6.12 |
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IBEP20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/ | function safeApprove(
IBEP20 token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
'SafeBEP20: approve from non-zero to non-zero allowance'
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
} | 0.6.12 |
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/ | function _callOptionalReturn(IBEP20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, 'SafeBEP20: low-level call failed');
if (returndata.length > 0) {
// Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), 'SafeBEP20: BEP20 operation did not succeed');
}
} | 0.6.12 |
/// @notice Returns if a darknode was in the registered state for a given
/// epoch.
/// @param _darknodeID The ID of the darknode
/// @param _epoch One of currentEpoch, previousEpoch | function isRegisteredInEpoch(address _darknodeID, Epoch memory _epoch) private view returns (bool) {
uint256 registeredAt = store.darknodeRegisteredAt(_darknodeID);
uint256 deregisteredAt = store.darknodeDeregisteredAt(_darknodeID);
bool registered = registeredAt != 0 && registeredAt <= _epoch.blocknumber;
bool notDeregistered = deregisteredAt == 0 || deregisteredAt > _epoch.blocknumber;
// The Darknode has been registered and has not yet been deregistered,
// although it might be pending deregistration
return registered && notDeregistered;
} | 0.5.8 |
/// @notice Returns a list of darknodes registered for either the current
/// or the previous epoch. See `getDarknodes` for documentation on the
/// parameters `_start` and `_count`.
/// @param _usePreviousEpoch If true, use the previous epoch, otherwise use
/// the current epoch. | function getDarknodesFromEpochs(address _start, uint256 _count, bool _usePreviousEpoch) private view returns (address[] memory) {
uint256 count = _count;
if (count == 0) {
count = numDarknodes;
}
address[] memory nodes = new address[](count);
// Begin with the first node in the list
uint256 n = 0;
address next = _start;
if (next == address(0)) {
next = store.begin();
}
// Iterate until all registered Darknodes have been collected
while (n < count) {
if (next == address(0)) {
break;
}
// Only include Darknodes that are currently registered
bool includeNext;
if (_usePreviousEpoch) {
includeNext = isRegisteredInPreviousEpoch(next);
} else {
includeNext = isRegistered(next);
}
if (!includeNext) {
next = store.next(next);
continue;
}
nodes[n] = next;
next = store.next(next);
n += 1;
}
return nodes;
} | 0.5.8 |
/// @notice Blacklists a darknode from participating in reward allocation.
/// If the darknode is whitelisted, it is removed from the whitelist
/// and the number of whitelisted nodes is decreased.
///
/// @param _darknode The address of the darknode to blacklist | function blacklist(address _darknode) external onlyOwner {
require(!isBlacklisted(_darknode), "darknode already blacklisted");
darknodeBlacklist[_darknode] = now;
// Unwhitelist if necessary
if (isWhitelisted(_darknode)) {
darknodeWhitelist[_darknode] = 0;
// Use SafeMath when subtracting to avoid underflows
darknodeWhitelistLength = darknodeWhitelistLength.sub(1);
}
} | 0.5.8 |
// Return reward multiplier over the given _from to _to block. | function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) {
if (_to <= bonusEndBlock) {
return _to.sub(_from);
} else if (_from >= bonusEndBlock) {
return 0;
} else {
return bonusEndBlock.sub(_from);
}
} | 0.6.12 |
// View function to see pending Reward on frontend. | function pendingReward(address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[0];
UserInfo storage user = userInfo[_user];
uint256 accCakePerShare = pool.accCakePerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 cakeReward = multiplier.mul(rewardPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accCakePerShare = accCakePerShare.add(cakeReward.mul(1e12).div(lpSupply));
}
return user.amount.mul(accCakePerShare).div(1e12).sub(user.rewardDebt);
} | 0.6.12 |
// Update reward variables of the given pool to be up-to-date. | function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 cakeReward = multiplier.mul(rewardPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
pool.accCakePerShare = pool.accCakePerShare.add(cakeReward.mul(1e12).div(lpSupply));
pool.lastRewardBlock = block.number;
} | 0.6.12 |
// Stake SYRUP tokens to SmartChef | function deposit(uint256 _amount) public {
PoolInfo storage pool = poolInfo[0];
UserInfo storage user = userInfo[msg.sender];
// require (_amount.add(user.amount) <= maxStaking, 'exceed max stake');
updatePool(0);
if (user.amount > 0) {
uint256 pending = user.amount.mul(pool.accCakePerShare).div(1e12).sub(user.rewardDebt);
if(pending > 0) {
rewardToken.safeTransfer(address(msg.sender), pending);
}
}
if(_amount > 0) {
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
uint256 localDepositFee = 0;
if(depositFee > 0){
localDepositFee = _amount.mul(depositFee).div(10000);
pool.lpToken.safeTransfer(feeReceiver, localDepositFee);
}
user.amount = user.amount.add(_amount).sub(localDepositFee);
}
user.rewardDebt = user.amount.mul(pool.accCakePerShare).div(1e12);
emit Deposit(msg.sender, _amount);
} | 0.6.12 |
// Withdraw SYRUP tokens from STAKING. | function withdraw(uint256 _amount) public {
PoolInfo storage pool = poolInfo[0];
UserInfo storage user = userInfo[msg.sender];
require(user.amount >= _amount, "withdraw: not good");
updatePool(0);
uint256 pending = user.amount.mul(pool.accCakePerShare).div(1e12).sub(user.rewardDebt);
if(pending > 0) {
rewardToken.safeTransfer(address(msg.sender), pending);
}
if(_amount > 0) {
user.amount = user.amount.sub(_amount);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
}
user.rewardDebt = user.amount.mul(pool.accCakePerShare).div(1e12);
emit Withdraw(msg.sender, _amount);
} | 0.6.12 |
/**
* @dev Returns the subtraction of two signed integers, reverting on
* overflow.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/ | function sub(int256 a, int256 b) internal pure returns (int256) {
int256 c = a - b;
require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow");
return c;
} | 0.6.12 |
/**
* @dev Returns the addition of two signed integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/ | function add(int256 a, int256 b) internal pure returns (int256) {
int256 c = a + b;
require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow");
return c;
} | 0.6.12 |
/// @notice Transfers `amount` tokens from `msg.sender` to `to`.
/// @param to The address to move the tokens.
/// @param amount of the tokens to move.
/// @return (bool) Returns True if succeeded. | function transfer(address to, uint256 amount) public returns (bool) {
// If `amount` is 0, or `msg.sender` is `to` nothing happens
if (amount != 0) {
uint256 srcBalance = balanceOf[msg.sender];
require(srcBalance >= amount, "ERC20::transfer: balance too low");
if (msg.sender != to) {
require(to != address(0), "ERC20::transfer: no zero address"); // Moved down so low balance calls safe some gas
balanceOf[msg.sender] = srcBalance - amount; // Underflow is checked
balanceOf[to] += amount; // Can't overflow because totalSupply would be greater than 2^256-1
}
}
emit Transfer(msg.sender, to, amount);
return true;
} | 0.6.12 |
/// @notice Transfers `amount` tokens from `from` to `to`. Caller needs approval for `from`.
/// @param from Address to draw tokens from.
/// @param to The address to move the tokens.
/// @param amount The token amount to move.
/// @return (bool) Returns True if succeeded. | function transferFrom(
address from,
address to,
uint256 amount
) public returns (bool) {
// If `amount` is 0, or `from` is `to` nothing happens
if (amount != 0) {
uint256 srcBalance = balanceOf[from];
require(srcBalance >= amount, "ERC20::transferFrom: balance too low");
if (from != to) {
uint256 spenderAllowance = allowance[from][msg.sender];
// If allowance is infinite, don't decrease it to save on gas (breaks with EIP-20).
if (spenderAllowance != type(uint256).max) {
require(spenderAllowance >= amount, "ERC20::transferFrom: allowance too low");
allowance[from][msg.sender] = spenderAllowance - amount; // Underflow is checked
}
require(to != address(0), "ERC20::transferFrom: no zero address"); // Moved down so other failed calls safe some gas
balanceOf[from] = srcBalance - amount; // Underflow is checked
balanceOf[to] += amount; // Can't overflow because totalSupply would be greater than 2^256-1
}
}
emit Transfer(from, to, amount);
return true;
} | 0.6.12 |
/// @notice Approves `value` from `owner_` to be spend by `spender`.
/// @param owner_ Address of the owner.
/// @param spender The address of the spender that gets approved to draw from `owner_`.
/// @param value The maximum collective amount that `spender` can draw.
/// @param deadline This permit must be redeemed before this deadline (UTC timestamp in seconds). | function permit(
address owner_,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external {
require(owner_ != address(0), "ERC20::permit: Owner cannot be 0");
require(block.timestamp < deadline, "ERC20: Expired");
require(
ecrecover(
_getDigest(
keccak256(abi.encode(PERMIT_SIGNATURE_HASH, owner_, spender, value, nonces[owner_]++, deadline))
),
v,
r,
s
) == owner_,
"ERC20::permit: Invalid Signature"
);
allowance[owner_][spender] = value;
emit Approval(owner_, spender, value);
} | 0.6.12 |
/// @notice Add a new LP to the pool. Can only be called by the owner.
/// DO NOT add the same LP token more than once. Rewards will be messed up if you do.
/// @param allocPoint AP of the new pool.
/// @param _pid Pid on MCV2 | function addPool(uint256 _pid, uint256 allocPoint) public onlyOwner {
require(poolInfo[_pid].lastRewardBlock == 0, "ALCXRewarder::add: cannot add existing pool");
uint256 lastRewardBlock = block.number;
totalAllocPoint = totalAllocPoint.add(allocPoint);
poolInfo[_pid] = PoolInfo({
allocPoint: allocPoint.to64(),
lastRewardBlock: lastRewardBlock.to64(),
accTokenPerShare: 0
});
poolIds.push(_pid);
emit PoolAdded(_pid, allocPoint);
} | 0.6.12 |
/// @notice Update reward variables of the given pool.
/// @param pid The index of the pool. See `poolInfo`.
/// @return pool Returns the pool that was updated. | function updatePool(uint256 pid) public returns (PoolInfo memory pool) {
pool = poolInfo[pid];
if (block.number > pool.lastRewardBlock) {
uint256 lpSupply = MC_V2.lpToken(pid).balanceOf(address(MC_V2));
if (lpSupply > 0) {
uint256 blocks = block.number.sub(pool.lastRewardBlock);
uint256 tokenReward = blocks.mul(tokenPerBlock).mul(pool.allocPoint) / totalAllocPoint;
pool.accTokenPerShare = pool.accTokenPerShare.add(
(tokenReward.mul(ACC_TOKEN_PRECISION) / lpSupply).to128()
);
}
pool.lastRewardBlock = block.number.to64();
poolInfo[pid] = pool;
emit PoolUpdated(pid, pool.lastRewardBlock, lpSupply, pool.accTokenPerShare);
}
} | 0.6.12 |
/// @notice View function to see pending Token
/// @param _pid The index of the pool. See `poolInfo`.
/// @param _user Address of user.
/// @return pending SUSHI reward for a given user. | function pendingToken(uint256 _pid, address _user) public view returns (uint256 pending) {
PoolInfo memory pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accTokenPerShare = pool.accTokenPerShare;
uint256 lpSupply = MC_V2.lpToken(_pid).balanceOf(address(MC_V2));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 blocks = block.number.sub(pool.lastRewardBlock);
uint256 tokenReward = blocks.mul(tokenPerBlock).mul(pool.allocPoint) / totalAllocPoint;
accTokenPerShare = accTokenPerShare.add(tokenReward.mul(ACC_TOKEN_PRECISION) / lpSupply);
}
pending = (user.amount.mul(accTokenPerShare) / ACC_TOKEN_PRECISION).sub(user.rewardDebt);
} | 0.6.12 |
/**
* @dev token purchase with pay Land tokens
* @param beneficiary Recipient of the token purchase
* @param tokenId uint256 ID of the token to be purchase
*/ | function buyToken(address beneficiary, uint256 tokenId) public payable{
require(beneficiary != address(0), "Presale: beneficiary is the zero address");
require(weiPerToken() == msg.value, "Presale: Not enough Eth");
require(!_cellToken.exists(tokenId), "Presale: token already minted");
require(tokenId < 11520, "Presale: tokenId must be less than max token count");
(uint256 x, uint256 y) = cellById(tokenId);
require(x < 38 || x > 53 || y < 28 || y > 43, "Presale: tokenId should not be in the unsold range");
_wallet.transfer(msg.value);
_cellToken.mint(beneficiary, tokenId);
emit TokensPurchased(msg.sender, beneficiary, tokenId);
} | 0.8.0 |
/**
* @dev batch token purchase with pay our ERC20 tokens
* @param beneficiary Recipient of the token purchase
* @param tokenIds uint256 IDs of the token to be purchase
*/ | function buyBatchTokens(address beneficiary, uint256[] memory tokenIds) public payable{
require(beneficiary != address(0), "Presale: beneficiary is the zero address");
uint256 weiAmount = weiPerToken() * tokenIds.length;
require(weiAmount == msg.value, "Presale: Not enough Eth");
for (uint256 i = 0; i < tokenIds.length; ++i) {
require(!_cellToken.exists(tokenIds[i]), "Presale: token already minted");
require(tokenIds[i] < 11520, "Presale: tokenId must be less than max token count");
(uint256 x, uint256 y) = cellById(tokenIds[i]);
require(x < 38 || x > 53 || y < 28 || y > 43, "Presale: tokenId should not be in the unsold range");
}
_wallet.transfer(msg.value);
for (uint256 i = 0; i < tokenIds.length; ++i) {
_cellToken.mint(beneficiary, tokenIds[i]);
emit TokensPurchased(msg.sender, beneficiary, tokenIds[i]);
}
} | 0.8.0 |
/* ========== MUTATIVE FUNCTIONS ========== */ | function handleKeeperIncentive(
bytes32 _contractName,
uint8 _i,
address _keeper
) external {
require(msg.sender == controllerContracts[_contractName], "Can only be called by the controlling contract");
require(
IStaking(_getContract(keccak256("PopLocker"))).balanceOf(_keeper) >= requiredKeeperStake,
"not enough pop at stake"
);
Incentive memory incentive = incentives[_contractName][_i];
if (!incentive.openToEveryone) {
_requireRole(KEEPER_ROLE, _keeper);
}
if (incentive.enabled && incentive.reward <= incentiveBudget && incentive.reward > 0) {
incentiveBudget = incentiveBudget - incentive.reward;
uint256 amountToBurn = (incentive.reward * burnRate) / 1e18;
uint256 incentivePayout = incentive.reward - amountToBurn;
IERC20(_getContract(keccak256("POP"))).safeTransfer(_keeper, incentivePayout);
_burn(amountToBurn);
}
} | 0.8.1 |
/* ========== RESTRICTED FUNCTIONS ========== */ | function updateIncentive(
bytes32 _contractName,
uint8 _i,
uint256 _reward,
bool _enabled,
bool _openToEveryone
) external onlyRole(DAO_ROLE) {
Incentive storage incentive = incentives[_contractName][_i];
uint256 oldReward = incentive.reward;
bool oldOpenToEveryone = incentive.openToEveryone;
incentive.reward = _reward;
incentive.enabled = _enabled;
incentive.openToEveryone = _openToEveryone;
emit IncentiveChanged(_contractName, oldReward, _reward, oldOpenToEveryone, _openToEveryone);
} | 0.8.1 |
// Update reward variables of the given pool to be up-to-date.
// No new RLY are minted, distribution is dependent on sufficient RLY tokens being sent to this contract | function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 multiplier = block.number.sub(pool.lastRewardBlock);
uint256 rallyReward = multiplier.mul(rallyPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
pool.accRallyPerShare = pool.accRallyPerShare.add(rallyReward.mul(1e12).div(lpSupply));
pool.lastRewardBlock = block.number;
} | 0.6.12 |
/**
* @notice Delegates votes from signatory to `delegatee`
* @param delegatee The address to delegate votes to
* @param nonce The contract state required to match the signature
* @param expiry The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/ | function delegateBySig(
address delegatee,
uint256 nonce,
uint256 expiry,
uint8 v,
bytes32 r,
bytes32 s
) external {
bytes32 domainSeparator =
keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this)));
bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry));
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "SUSHI::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "SUSHI::delegateBySig: invalid nonce");
require(now <= expiry, "SUSHI::delegateBySig: signature expired");
return _delegate(signatory, delegatee);
} | 0.6.12 |
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/ | function getPriorVotes(address account, uint256 blockNumber) external view returns (uint256) {
require(blockNumber < block.number, "SUSHI::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
} | 0.6.12 |
//TEAM Withdraw | function withdraw() public onlyOwner {
uint256 balance = address(this).balance;
require(balance > 0, "Insufficent balance");
uint256 witdrawAmount = calculateWithdraw(budgetDev1,(balance * 25) / 100);
if (witdrawAmount>0){
budgetDev1 -= witdrawAmount;
_withdraw(DEV1, witdrawAmount);
}
witdrawAmount = calculateWithdraw(budgetCommunityWallet,(balance * 75) / 100);
if (witdrawAmount>0){
budgetCommunityWallet -= witdrawAmount;
_withdraw(CommunityWallet, witdrawAmount);
}
} | 0.8.12 |
/// @dev Creates a new pool.
///
/// The created pool will need to have its reward weight initialized before it begins generating rewards.
///
/// @param _token The token the pool will accept for staking.
///
/// @return the identifier for the newly created pool. | function createPool(IERC20 _token) external onlyGovernance returns (uint256) {
require(tokenPoolIds[_token] == 0, "StakingPools: token already has a pool");
uint256 _poolId = _pools.length();
_pools.push(
Pool.Data({
token: _token,
totalDeposited: 0,
rewardWeight: 0,
accumulatedRewardWeight: FixedPointMath.uq192x64(0),
lastUpdatedBlock: block.number
})
);
tokenPoolIds[_token] = _poolId + 1;
emit PoolCreated(_poolId, _token);
return _poolId;
} | 0.6.12 |
/// @dev Sets the reward weights of all of the pools.
///
/// @param _rewardWeights The reward weights of all of the pools. | function setRewardWeights(uint256[] calldata _rewardWeights) external onlyGovernance {
require(_rewardWeights.length == _pools.length(), "StakingPools: weights length mismatch");
_updatePools();
uint256 _totalRewardWeight = _ctx.totalRewardWeight;
for (uint256 _poolId = 0; _poolId < _pools.length(); _poolId++) {
Pool.Data storage _pool = _pools.get(_poolId);
uint256 _currentRewardWeight = _pool.rewardWeight;
if (_currentRewardWeight == _rewardWeights[_poolId]) {
continue;
}
// FIXME
_totalRewardWeight = _totalRewardWeight.sub(_currentRewardWeight).add(_rewardWeights[_poolId]);
_pool.rewardWeight = _rewardWeights[_poolId];
emit PoolRewardWeightUpdated(_poolId, _rewardWeights[_poolId]);
}
_ctx.totalRewardWeight = _totalRewardWeight;
} | 0.6.12 |
/// @dev Stakes tokens into a pool.
///
/// The pool and stake MUST be updated before calling this function.
///
/// @param _poolId the pool to deposit tokens into.
/// @param _depositAmount the amount of tokens to deposit. | function _deposit(uint256 _poolId, uint256 _depositAmount) internal {
Pool.Data storage _pool = _pools.get(_poolId);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_pool.totalDeposited = _pool.totalDeposited.add(_depositAmount);
_stake.totalDeposited = _stake.totalDeposited.add(_depositAmount);
_pool.token.safeTransferFrom(msg.sender, address(this), _depositAmount);
emit TokensDeposited(msg.sender, _poolId, _depositAmount);
} | 0.6.12 |
/**
* @notice delegate all calls to implementation contract
* @dev reverts if implementation address contains no code, for compatibility with metamorphic contracts
* @dev memory location in use by assembly may be unsafe in other contexts
*/ | fallback() external payable virtual {
address implementation = _getImplementation();
require(
implementation.isContract(),
'Proxy: implementation must be contract'
);
assembly {
calldatacopy(0, 0, calldatasize())
let result := delegatecall(
gas(),
implementation,
0,
calldatasize(),
0,
0
)
returndatacopy(0, 0, returndatasize())
switch result
case 0 {
revert(0, returndatasize())
}
default {
return(0, returndatasize())
}
}
} | 0.8.9 |
/**
* @dev Internal function that burns an amount of the token of a given
* account, deducting from the sender's allowance for said account. Uses the
* internal burn function.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/ | function _burnFrom(address account, uint256 value) internal {
require(value <= _allowed[account][msg.sender]);
// Should https://github.com/OpenZeppelin/zeppelin-solidity/issues/707 be accepted,
// this function needs to emit an event with the updated approval.
_allowed[account][msg.sender] = _allowed[account][msg.sender].sub(
value);
_burn(account, value);
} | 0.4.25 |
/**
* @dev low level token purchase ***DO NOT OVERRIDE***
* @param beneficiary Address performing the token purchase
*/ | function buyTokens(address beneficiary) public payable {
uint256 weiAmount = msg.value;
_preValidatePurchase(beneficiary, weiAmount);
// calculate token amount to be created
uint256 tokens = _getTokenAmount(weiAmount);
// update state
_weiRaised = _weiRaised.add(weiAmount);
_processPurchase(beneficiary, tokens);
emit TokensPurchased(
msg.sender,
beneficiary,
weiAmount,
tokens
);
_updatePurchasingState(beneficiary, weiAmount);
_forwardFunds();
_postValidatePurchase(beneficiary, weiAmount);
} | 0.4.25 |
/**
* calculate a percentage with parts per notation.
* the value returned will be in terms of 10e precision
*/ | function percent(uint numerator, uint denominator, uint precision) private pure returns(uint quotient) {
// caution, keep this a private function so the numbers are safe
uint _numerator = (numerator * 10 ** (precision+1));
// with rounding of last digit
uint _quotient = ((_numerator / denominator)) / 10;
return ( _quotient);
} | 0.4.25 |
/**
* @dev wallet can send funds
*/ | function sendTo(address _payee, uint256 _amount) private {
require(_payee != 0 && _payee != address(this), "Burning tokens and self transfer not allowed");
require(_amount > 0, "Must transfer greater than zero");
_payee.transfer(_amount);
emit Sent(_payee, _amount, address(this).balance);
} | 0.4.25 |
/**
* @dev function for the player to cash in tokens
*/ | function redeemTokens(address _player, address _tokenAddress) public returns (bool success) {
require(acceptedToken(_tokenAddress), "Token must be a registered token");
require(block.timestamp >= closeDate, "Game must be closed");
require(gameDone == true, "Can't redeem tokens until results have been uploaded");
// instantiate a token contract instance from the deployed address
IPickFlixToken _token = IPickFlixToken(_tokenAddress);
// check token allowance player has given to GameMaster contract
uint256 _allowedValue = _token.allowance(_player, address(this));
// transfer tokens to GameMaster
_token.transferFrom(_player, address(this), _allowedValue);
// check balance of tokens actually transfered
uint256 _transferedTokens = _allowedValue;
// calculate the percentage of the total token supply represented by the transfered tokens
uint256 _playerPercentage = percent(_transferedTokens, _token.totalSupply(), 4);
// calculate the particular player's rewards, as a percentage of total player rewards for the movie
uint256 _playerRewards = movies[_tokenAddress].totalPlayerRewards.mul(_playerPercentage).div(10**4);
// pay out ETH to the player
sendTo(_player, _playerRewards);
// return that the function succeeded
return true;
} | 0.4.25 |
// this calculates how much Ether to reward for each game token | function calculateTotalPlayerRewardsPerMovie(uint256 _boxOfficeTotal) public view returns (uint256) {
// 234 means 23.4%, using parts-per notation with three decimals of precision
uint256 _boxOfficePercentage = percent(_boxOfficeTotal, totalBoxOffice, 4);
// calculate the Ether rewards available for each movie
uint256 _rewards = totalPlayerRewards.mul(_boxOfficePercentage).div(10**4);
return _rewards;
} | 0.4.25 |
/**
* @dev add box office results and token addresses for the movies, and calculate game results
*/ | function calculateGameResults(address[] _tokenAddresses, uint256[] _boxOfficeTotals) public onlyOwner {
// check that there are as many box office totals as token addresses
require(_tokenAddresses.length == _boxOfficeTotals.length, "Must have box office results per token");
// calculate Oracle Fee and amount of Ether available for player rewards
require(gameDone == false, "Can only submit results once");
require(block.timestamp >= closeDate, "Game must have ended before results can be entered");
oracleFee = calculateOracleFee();
totalPlayerRewards = calculateTotalPlayerRewards();
totalBoxOffice = calculateTotalBoxOffice(_boxOfficeTotals);
// create Movies (see: Movie struct) and calculate player rewards
for (uint256 i = 0; i < _tokenAddresses.length; i++) {
tokensIssued = tokensIssued.add(calculateTokensIssued(_tokenAddresses[i]));
movies[_tokenAddresses[i]] = Movie(_boxOfficeTotals[i], calculateTotalPlayerRewardsPerMovie(_boxOfficeTotals[i]), true);
}
// The owner will be the Factory that deploys this contract.
owner().transfer(oracleFee);
gameDone = true;
} | 0.4.25 |
// Create a new game master and add it to the factories game list | function createGame(string gameName, uint closeDate, uint oracleFeePercent) public onlyOwner returns (address){
address gameMaster = new PickflixGameMaster(gameName, closeDate, oracleFeePercent);
games.push(Game({
gameName: gameName,
gameMaster: gameMaster,
openDate: block.timestamp,
closeDate: closeDate
}));
return gameMaster;
} | 0.4.25 |
// Create a token and associate it with a game | function createTokenForGame(uint gameIndex, string tokenName, string tokenSymbol, uint rate, string externalID) public onlyOwner returns (address) {
Game storage game = games[gameIndex];
address token = new PickFlixToken(tokenName, tokenSymbol, rate, game.gameMaster, game.closeDate, externalID);
gameTokens[game.gameMaster].push(token);
return token;
} | 0.4.25 |
/*
* mintFreeDoodle
* mints a free daijuking using a Doodles token - can only be claimed once per wallet
*/ | function mintFreeDoodle() public payable IsSaleActive IsFreeMintActive {
uint256 supply = TotalSupplyFix.current();
require(supply <= maxGenCount, "All Genesis Daijukingz were claimed!");
require(mintFreeDoodleList(msg.sender) >= 1, "You don't own any Doodles!");
require((supply + 1) <= maxFreeMints, "All the free mints have been claimed!");
require(freeMintList[msg.sender] < 1, "You already claimed your free daijuking!");
require(!breedingEnabled, "Minting genesis has been disabled!");
_safeMint(msg.sender, supply);
TotalSupplyFix.increment();
freeMintList[msg.sender] = 1;
balanceGenesis[msg.sender]++;
genCount++;
freeMintCount += 1;
} | 0.8.11 |
/*
* mintFreeGiveaway
* this is for the giveaway winners - allows you to mint a free daijuking
*/ | function mintFreeGiveaway() public payable IsSaleActive IsFreeMintActive {
uint256 supply = TotalSupplyFix.current();
require(supply <= maxGenCount, "All Genesis Daijukingz were claimed!");
require((supply + 1) <= maxGivewayMint, "All giveaway mints were claimed!");
require(giveawayMintList[msg.sender] >= 1, "You don't have any free mints left!");
require(!breedingEnabled, "Minting genesis has been disabled!");
_safeMint(msg.sender, supply);
TotalSupplyFix.increment();
giveawayMintList[msg.sender] = 0;
balanceGenesis[msg.sender]++;
genCount++;
giveawayMintCount += 1;
} | 0.8.11 |
// Add a new lp to the pool. Can only be called by the owner.
// XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. | function add(
uint256 _allocPoint,
IERC20 _lpToken,
bool _withUpdate
) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(
PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accSushiPerShare: 0 })
);
} | 0.6.12 |
// Migrate lp token to another lp contract. Can be called by anyone. We trust that migrator contract is good. | function migrate(uint256 _pid) public {
require(address(migrator) != address(0), "migrate: no migrator");
PoolInfo storage pool = poolInfo[_pid];
IERC20 lpToken = pool.lpToken;
uint256 bal = lpToken.balanceOf(address(this));
lpToken.safeApprove(address(migrator), bal);
IERC20 newLpToken = migrator.migrate(lpToken);
require(bal == newLpToken.balanceOf(address(this)), "migrate: bad");
pool.lpToken = newLpToken;
} | 0.6.12 |
/*
* mint
* mints the daijuking using ETH as the payment token
*/ | function mint(uint256 numberOfMints) public payable IsSaleActive {
uint256 supply = TotalSupplyFix.current();
require(numberOfMints > 0 && numberOfMints < 11, "Invalid purchase amount");
if (block.timestamp <= freeEndTimestamp) {
require(supply.add(numberOfMints) <= (maxGenCount - (maxFreeMints + maxGivewayMint)), "Purchase would exceed max supply");
} else {
require(supply.add(numberOfMints) <= maxGenCount, "Purchase would exceed max supply");
}
require(price.mul(numberOfMints) == msg.value, "Ether value sent is not correct");
require(!breedingEnabled, "Minting genesis has been disabled!");
for (uint256 i; i < numberOfMints; i++) {
_safeMint(msg.sender, supply + i);
balanceGenesis[msg.sender]++;
genCount++;
TotalSupplyFix.increment();
}
} | 0.8.11 |
// View function to see pending SUSHIs on frontend. | function pendingSushi(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accSushiPerShare = pool.accSushiPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 sushiReward = multiplier.mul(sushiPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accSushiPerShare = accSushiPerShare.add(sushiReward.mul(1e12).div(lpSupply));
}
return user.amount.mul(accSushiPerShare).div(1e12).sub(user.rewardDebt);
} | 0.6.12 |
/*
* mintWithSOS
* allows the user to mint a daijuking using the $SOS token
* note: user must approve it before this can be called
*/ | function mintWithSOS(uint256 numberOfMints) public payable IsSaleActive {
uint256 supply = TotalSupplyFix.current();
require(numberOfMints > 0 && numberOfMints < 11, "Invalid purchase amount");
require(supply.add(numberOfMints) <= maxGenCount, "Purchase would exceed max supply");
require(sosPrice.mul(numberOfMints) < SOS.balanceOf(msg.sender), "Not enough SOS to mint!");
require(!breedingEnabled, "Minting genesis has been disabled!");
SOS.transferFrom(msg.sender, sosWallet, sosPrice.mul(numberOfMints));
for (uint256 i; i < numberOfMints; i++) {
_safeMint(msg.sender, supply + i);
balanceGenesis[msg.sender]++;
genCount++;
TotalSupplyFix.increment();
}
} | 0.8.11 |
// Deposit LP tokens to MasterChef for SUSHI allocation. | function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
if (user.amount > 0) {
uint256 pending = user.amount.mul(pool.accSushiPerShare).div(1e12).sub(user.rewardDebt);
safeSushiTransfer(msg.sender, pending);
}
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
user.amount = user.amount.add(_amount);
user.rewardDebt = user.amount.mul(pool.accSushiPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
} | 0.6.12 |
// Withdraw LP tokens from MasterChef. | function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "withdraw: not good");
updatePool(_pid);
uint256 pending = user.amount.mul(pool.accSushiPerShare).div(1e12).sub(user.rewardDebt);
safeSushiTransfer(msg.sender, pending);
user.amount = user.amount.sub(_amount);
user.rewardDebt = user.amount.mul(pool.accSushiPerShare).div(1e12);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
emit Withdraw(msg.sender, _pid, _amount);
} | 0.6.12 |
/*
* breed
* allows you to create a daijuking using 2 parents and some $COLORWASTE, 18+ only
* note: selecting is automatic from the DAPP, but if you use the contract make sure they are two unique token id's that aren't children...
*/ | function breed(uint256 parent1, uint256 parent2) public DaijuOwner(parent1) DaijuOwner(parent2) {
uint256 supply = TotalSupplyFix.current();
require(breedingEnabled, "Breeding isn't enabled yet!");
require(supply < maxSupply, "Cannot breed any more baby Daijus");
require(parent1 < genCount && parent2 < genCount, "Cannot breed with baby Daijus (thats sick bro)");
require(parent1 != parent2, "Must select two unique parents");
// burns the tokens for the breeding cost
CW.burn(msg.sender, breedPrice + increasePerBreed * babyCount);
// adds the baby to the total supply and counter
babyCount++;
TotalSupplyFix.increment();
// mints the baby daijuking and adds it to the balance for the wallet
_safeMint(msg.sender, supply);
balanceBaby[msg.sender]++;
} | 0.8.11 |
/* Send coins */ | function transfer(address _to, uint256 _value) {
if (balanceOf[msg.sender] < _value) throw; // Check if the sender has enough
if (balanceOf[_to] + _value < balanceOf[_to]) throw; // Check for overflows
balanceOf[msg.sender] -= _value; // Subtract from the sender
balanceOf[_to] += _value; // Add the same to the recipient
} | 0.4.11 |
/// @notice Returns the metadata of this (MetaProxy) contract.
/// Only relevant with contracts created via the MetaProxy.
/// @dev This function is aimed to be invoked with- & without a call. | function getMetadata () public pure returns (
address bridge,
address vault
) {
assembly {
// calldata layout:
// [ arbitrary data... ] [ metadata... ] [ size of metadata 32 bytes ]
bridge := calldataload(sub(calldatasize(), 96))
vault := calldataload(sub(calldatasize(), 64))
}
} | 0.7.6 |
/// @notice Executes a set of contract calls `actions` if there is a valid
/// permit on the rollup bridge for `proposalId` and `actions`. | function execute (bytes32 proposalId, bytes memory actions) external {
(address bridge, address vault) = getMetadata();
require(executed[proposalId] == false, 'already executed');
require(
IBridge(bridge).executionPermit(vault, proposalId) == keccak256(actions),
'wrong permit'
);
// mark it as executed
executed[proposalId] = true;
// execute
assembly {
// Note: we use `callvalue()` instead of `0`
let ptr := add(actions, 32)
let max := add(ptr, mload(actions))
for { } lt(ptr, max) { } {
let addr := mload(ptr)
ptr := add(ptr, 32)
let size := mload(ptr)
ptr := add(ptr, 32)
let success := call(gas(), addr, callvalue(), ptr, size, callvalue(), callvalue())
if iszero(success) {
// failed, copy the error
returndatacopy(callvalue(), callvalue(), returndatasize())
revert(callvalue(), returndatasize())
}
ptr := add(ptr, size)
}
}
} | 0.7.6 |
/*
* reserve
* mints the reserved amount
*/ | function reserve(uint256 count) public onlyOwner {
uint256 supply = TotalSupplyFix.current();
require(reserveCount + count < reserveMax, "cannot reserve more");
for (uint256 i = 0; i < count; i++) {
_safeMint(msg.sender, supply + i);
balanceGenesis[msg.sender]++;
genCount++;
TotalSupplyFix.increment();
reserveCount++;
}
} | 0.8.11 |
/*
* getTypes
* gets the tokens provided and returns the genesis and baby daijukingz
*
* genesis is 0
* baby is 1
*/ | function getTypes(uint256[] memory list) external view returns(uint256[] memory) {
uint256[] memory typeList = new uint256[](list.length);
for (uint256 i; i < list.length; i++){
if (list[i] >= genCount) {
typeList[i] = 1;
} else {
typeList[i] = 0;
}
}
return typeList;
} | 0.8.11 |
/*
* walletOfOwner
* returns the tokens that the user owns
*/ | function walletOfOwner(address owner) public view returns(uint256[] memory) {
uint256 tokenCount = balanceOf(owner);
uint256 supply = TotalSupplyFix.current();
uint256 index = 0;
uint256[] memory tokensId = new uint256[](tokenCount);
for (uint256 i; i < supply; i++) {
if (ownerOf(i) == owner) {
tokensId[index] = i;
index++;
}
}
return tokensId;
} | 0.8.11 |
/// @notice Add a new LP to the pool. Can only be called by the owner.
/// DO NOT add the same LP token more than once. Rewards will be messed up if you do.
/// @param allocPoint AP of the new pool.
/// @param _lpToken Address of the LP ERC-20 token.
/// @param _rewarder Address of the rewarder delegate. | function add(
uint256 allocPoint,
IERC20 _lpToken,
IRewarder _rewarder
) public onlyOwner {
uint256 lastRewardBlock = block.number;
totalAllocPoint = totalAllocPoint.add(allocPoint);
lpToken.push(_lpToken);
rewarder.push(_rewarder);
poolInfo.push(
PoolInfo({ allocPoint: allocPoint.to64(), lastRewardBlock: lastRewardBlock.to64(), accSushiPerShare: 0 })
);
emit LogPoolAddition(lpToken.length.sub(1), allocPoint, _lpToken, _rewarder);
} | 0.6.12 |
/// @notice Update the given pool's SUSHI allocation point and `IRewarder` contract. Can only be called by the owner.
/// @param _pid The index of the pool. See `poolInfo`.
/// @param _allocPoint New AP of the pool.
/// @param _rewarder Address of the rewarder delegate.
/// @param overwrite True if _rewarder should be `set`. Otherwise `_rewarder` is ignored. | function set(
uint256 _pid,
uint256 _allocPoint,
IRewarder _rewarder,
bool overwrite
) public onlyOwner {
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
poolInfo[_pid].allocPoint = _allocPoint.to64();
if (overwrite) {
rewarder[_pid] = _rewarder;
}
emit LogSetPool(_pid, _allocPoint, overwrite ? _rewarder : rewarder[_pid], overwrite);
} | 0.6.12 |
/// @notice Migrate LP token to another LP contract through the `migrator` contract.
/// @param _pid The index of the pool. See `poolInfo`. | function migrate(uint256 _pid) public {
require(address(migrator) != address(0), "MasterChefV2: no migrator set");
IERC20 _lpToken = lpToken[_pid];
uint256 bal = _lpToken.balanceOf(address(this));
_lpToken.approve(address(migrator), bal);
IERC20 newLpToken = migrator.migrate(_lpToken);
require(bal == newLpToken.balanceOf(address(this)), "MasterChefV2: migrated balance must match");
lpToken[_pid] = newLpToken;
} | 0.6.12 |
/// @notice View function to see pending SUSHI on frontend.
/// @param _pid The index of the pool. See `poolInfo`.
/// @param _user Address of user.
/// @return pending SUSHI reward for a given user. | function pendingSushi(uint256 _pid, address _user) external view returns (uint256 pending) {
PoolInfo memory pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accSushiPerShare = pool.accSushiPerShare;
uint256 lpSupply = lpToken[_pid].balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 blocks = block.number.sub(pool.lastRewardBlock);
uint256 sushiReward = blocks.mul(sushiPerBlock()).mul(pool.allocPoint) / totalAllocPoint;
accSushiPerShare = accSushiPerShare.add(sushiReward.mul(ACC_SUSHI_PRECISION) / lpSupply);
}
pending = int256(user.amount.mul(accSushiPerShare) / ACC_SUSHI_PRECISION).sub(user.rewardDebt).toUInt256();
} | 0.6.12 |
/// @notice Deposit LP tokens to MCV2 for SUSHI allocation.
/// @param pid The index of the pool. See `poolInfo`.
/// @param amount LP token amount to deposit.
/// @param to The receiver of `amount` deposit benefit. | function deposit(
uint256 pid,
uint256 amount,
address to
) public {
PoolInfo memory pool = updatePool(pid);
UserInfo storage user = userInfo[pid][to];
// Effects
user.amount = user.amount.add(amount);
user.rewardDebt = user.rewardDebt.add(int256(amount.mul(pool.accSushiPerShare) / ACC_SUSHI_PRECISION));
// Interactions
IRewarder _rewarder = rewarder[pid];
if (address(_rewarder) != address(0)) {
_rewarder.onSushiReward(pid, to, to, 0, user.amount);
}
lpToken[pid].safeTransferFrom(msg.sender, address(this), amount);
emit Deposit(msg.sender, pid, amount, to);
} | 0.6.12 |
/// @notice Withdraw LP tokens from MCV2.
/// @param pid The index of the pool. See `poolInfo`.
/// @param amount LP token amount to withdraw.
/// @param to Receiver of the LP tokens. | function withdraw(
uint256 pid,
uint256 amount,
address to
) public {
PoolInfo memory pool = updatePool(pid);
UserInfo storage user = userInfo[pid][msg.sender];
// Effects
user.rewardDebt = user.rewardDebt.sub(int256(amount.mul(pool.accSushiPerShare) / ACC_SUSHI_PRECISION));
user.amount = user.amount.sub(amount);
// Interactions
IRewarder _rewarder = rewarder[pid];
if (address(_rewarder) != address(0)) {
_rewarder.onSushiReward(pid, msg.sender, to, 0, user.amount);
}
lpToken[pid].safeTransfer(to, amount);
emit Withdraw(msg.sender, pid, amount, to);
} | 0.6.12 |
/// @notice Harvest proceeds for transaction sender to `to`.
/// @param pid The index of the pool. See `poolInfo`.
/// @param to Receiver of SUSHI rewards. | function harvest(uint256 pid, address to) public {
PoolInfo memory pool = updatePool(pid);
UserInfo storage user = userInfo[pid][msg.sender];
int256 accumulatedSushi = int256(user.amount.mul(pool.accSushiPerShare) / ACC_SUSHI_PRECISION);
uint256 _pendingSushi = accumulatedSushi.sub(user.rewardDebt).toUInt256();
// Effects
user.rewardDebt = accumulatedSushi;
// Interactions
if (_pendingSushi != 0) {
SUSHI.safeTransfer(to, _pendingSushi);
}
IRewarder _rewarder = rewarder[pid];
if (address(_rewarder) != address(0)) {
_rewarder.onSushiReward(pid, msg.sender, to, _pendingSushi, user.amount);
}
emit Harvest(msg.sender, pid, _pendingSushi);
} | 0.6.12 |
/// @notice Withdraw LP tokens from MCV2 and harvest proceeds for transaction sender to `to`.
/// @param pid The index of the pool. See `poolInfo`.
/// @param amount LP token amount to withdraw.
/// @param to Receiver of the LP tokens and SUSHI rewards. | function withdrawAndHarvest(
uint256 pid,
uint256 amount,
address to
) public {
PoolInfo memory pool = updatePool(pid);
UserInfo storage user = userInfo[pid][msg.sender];
int256 accumulatedSushi = int256(user.amount.mul(pool.accSushiPerShare) / ACC_SUSHI_PRECISION);
uint256 _pendingSushi = accumulatedSushi.sub(user.rewardDebt).toUInt256();
// Effects
user.rewardDebt = accumulatedSushi.sub(int256(amount.mul(pool.accSushiPerShare) / ACC_SUSHI_PRECISION));
user.amount = user.amount.sub(amount);
// Interactions
SUSHI.safeTransfer(to, _pendingSushi);
IRewarder _rewarder = rewarder[pid];
if (address(_rewarder) != address(0)) {
_rewarder.onSushiReward(pid, msg.sender, to, _pendingSushi, user.amount);
}
lpToken[pid].safeTransfer(to, amount);
emit Withdraw(msg.sender, pid, amount, to);
emit Harvest(msg.sender, pid, _pendingSushi);
} | 0.6.12 |
/// @notice Withdraw without caring about rewards. EMERGENCY ONLY.
/// @param pid The index of the pool. See `poolInfo`.
/// @param to Receiver of the LP tokens. | function emergencyWithdraw(uint256 pid, address to) public {
UserInfo storage user = userInfo[pid][msg.sender];
uint256 amount = user.amount;
user.amount = 0;
user.rewardDebt = 0;
IRewarder _rewarder = rewarder[pid];
if (address(_rewarder) != address(0)) {
_rewarder.onSushiReward(pid, msg.sender, to, 0, 0);
}
// Note: transfer can fail or succeed if `amount` is zero.
lpToken[pid].safeTransfer(to, amount);
emit EmergencyWithdraw(msg.sender, pid, amount, to);
} | 0.6.12 |
/*
* Calculates total inflation percentage then mints new Sets to the fee recipient. Position units are
* then adjusted down (in magnitude) in order to ensure full collateralization. Callable by anyone.
*
* @param _setToken Address of SetToken
*/ | function accrueFee(ISetToken _setToken)
public
nonReentrant
onlyValidAndInitializedSet(_setToken)
{
uint256 managerFee;
uint256 protocolFee;
if (_streamingFeePercentage(_setToken) > 0) {
uint256 inflationFeePercentage = _calculateStreamingFee(_setToken);
// Calculate incentiveFee inflation
uint256 feeQuantity = _calculateStreamingFeeInflation(_setToken, inflationFeePercentage);
// Mint new Sets to manager and protocol
(managerFee, protocolFee) = _mintManagerAndProtocolFee(_setToken, feeQuantity);
_editPositionMultiplier(_setToken, inflationFeePercentage);
}
// solhint-disable-next-line not-rely-on-time
feeStates[_setToken].lastStreamingFeeTimestamp = block.timestamp;
emit FeeActualized(address(_setToken), managerFee, protocolFee);
} | 0.7.6 |
/**
* SET MANAGER ONLY. Initialize module with SetToken and set the fee state for the SetToken. Passed
* _settings will have lastStreamingFeeTimestamp over-written.
*
* @param _setToken Address of SetToken
* @param _settings FeeState struct defining fee parameters
*/ | function initialize(ISetToken _setToken, FeeState memory _settings)
external
onlySetManager(_setToken, msg.sender)
onlyValidAndPendingSet(_setToken)
{
require(_settings.feeRecipient != address(0), "Fee Recipient must be non-zero address.");
require(
_settings.maxStreamingFeePercentage < PreciseUnitMath.preciseUnit(),
"Max fee must be < 100%."
);
require(
_settings.streamingFeePercentage <= _settings.maxStreamingFeePercentage,
"Fee must be <= max."
);
// solhint-disable-next-line not-rely-on-time
_settings.lastStreamingFeeTimestamp = block.timestamp;
feeStates[_setToken] = _settings;
_setToken.initializeModule();
} | 0.7.6 |
/**
* Returns the new incentive fee denominated in the number of SetTokens to mint. The calculation for the fee involves
* implying mint quantity so that the feeRecipient owns the fee percentage of the entire supply of the Set.
*
* The formula to solve for fee is:
* (feeQuantity / feeQuantity) + totalSupply = fee / scaleFactor
*
* The simplified formula utilized below is:
* feeQuantity = fee * totalSupply / (scaleFactor - fee)
*
* @param _setToken SetToken instance
* @param _feePercentage Fee levied to feeRecipient
* @return uint256 New RebalancingSet issue quantity
*/ | function _calculateStreamingFeeInflation(ISetToken _setToken, uint256 _feePercentage)
internal
view
returns (uint256)
{
uint256 totalSupply = _setToken.totalSupply();
// fee * totalSupply
uint256 a = _feePercentage.mul(totalSupply);
// ScaleFactor (10e18) - fee
uint256 b = PreciseUnitMath.preciseUnit().sub(_feePercentage);
return a.div(b);
} | 0.7.6 |
/**
* Mints sets to both the manager and the protocol. Protocol takes a percentage fee of the total amount of Sets
* minted to manager.
*
* @param _setToken SetToken instance
* @param _feeQuantity Amount of Sets to be minted as fees
* @return uint256 Amount of Sets accrued to manager as fee
* @return uint256 Amount of Sets accrued to protocol as fee
*/ | function _mintManagerAndProtocolFee(ISetToken _setToken, uint256 _feeQuantity)
internal
returns (uint256, uint256)
{
address protocolFeeRecipient = controller.feeRecipient();
uint256 protocolFee = controller.getModuleFee(address(this), PROTOCOL_STREAMING_FEE_INDEX);
uint256 protocolFeeAmount = _feeQuantity.preciseMul(protocolFee);
uint256 managerFeeAmount = _feeQuantity.sub(protocolFeeAmount);
_setToken.mint(_feeRecipient(_setToken), managerFeeAmount);
if (protocolFeeAmount > 0) {
_setToken.mint(protocolFeeRecipient, protocolFeeAmount);
}
return (managerFeeAmount, protocolFeeAmount);
} | 0.7.6 |
/**
* @dev Function to create tokens
* @param _to The address that will receive the createed tokens.
* @param _amount The amount of tokens to create. Must be less than or equal to the creatorAllowance of the caller.
* @return A boolean that indicates if the operation was successful.
*/ | function create(address _to, uint256 _amount) whenNotPaused onlyCreators notBlacklisted(msg.sender) notBlacklisted(_to) public returns (bool) {
require(_to != address(0));
require(_amount > 0);
uint256 creatingAllowedAmount = creatorAllowed[msg.sender];
require(_amount <= creatingAllowedAmount);
totalSupply = totalSupply.add(_amount);
balances[_to] = balances[_to].add(_amount);
creatorAllowed[msg.sender] = creatingAllowedAmount.sub(_amount);
emit Create(msg.sender, _to, _amount);
emit Transfer(address(0x0), _to, _amount);
return true;
} | 0.5.1 |
/**
* Atomic decrement of approved spending.
*
* Works around https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*/ | function subApproval(address _spender, uint _subtractedValue) public
returns (bool success) {
uint oldVal = allowed[msg.sender][_spender];
if (_subtractedValue > oldVal) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldVal.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
} | 0.4.13 |
/**
* Set the contract that can call release and make the token transferable.
*
* Since the owner of this contract is (or should be) the crowdsale,
* it can only be called by a corresponding exposed API in the crowdsale contract in case of input error.
*/ | function setReleaseAgent(address addr) onlyOwner inReleaseState(false) public {
// We don't do interface check here as we might want to have a normal wallet address to act as a release agent.
releaseAgent = addr;
} | 0.4.13 |
/**
* Allow the token holder to upgrade some of their tokens to a new contract.
*/ | function upgrade(uint value) public {
UpgradeState state = getUpgradeState();
// Ensure it's not called in a bad state
require(state == UpgradeState.ReadyToUpgrade || state == UpgradeState.Upgrading);
// Validate input value.
require(value != 0);
balances[msg.sender] = balances[msg.sender].sub(value);
// Take tokens out from circulation
totalSupply = totalSupply.sub(value);
totalUpgraded = totalUpgraded.add(value);
// Upgrade agent reissues the tokens
upgradeAgent.upgradeFrom(msg.sender, value);
Upgrade(msg.sender, upgradeAgent, value);
} | 0.4.13 |
/**
* Set an upgrade agent that handles the upgrade process
*/ | function setUpgradeAgent(address agent) external {
// Check whether the token is in a state that we could think of upgrading
require(canUpgrade());
require(agent != 0x0);
// Only a master can designate the next agent
require(msg.sender == upgradeMaster);
// Upgrade has already begun for an agent
require(getUpgradeState() != UpgradeState.Upgrading);
upgradeAgent = UpgradeAgent(agent);
// Bad interface
require(upgradeAgent.isUpgradeAgent());
// Make sure that token supplies match in source and target
require(upgradeAgent.originalSupply() == totalSupply);
UpgradeAgentSet(upgradeAgent);
} | 0.4.13 |
/**
* Make an investment.
*
* Crowdsale must be running for one to invest.
* We must have not pressed the emergency brake.
*
* @param receiver The Ethereum address who receives the tokens
* @param customerId (optional) UUID v4 to track the successful payments on the server side
*
*/ | function investInternal(address receiver, uint128 customerId) stopInEmergency notFinished private {
// Determine if it's a good time to accept investment from this participant
if (getState() == State.PreFunding) {
// Are we whitelisted for early deposit
require(earlyParticipantWhitelist[receiver]);
}
uint weiAmount = ceilingStrategy.weiAllowedToReceive(msg.value, weiRaised, investedAmountOf[receiver], weiFundingCap);
uint tokenAmount = pricingStrategy.calculatePrice(weiAmount, weiRaised, tokensSold, msg.sender, token.decimals());
// Dust transaction if no tokens can be given
require(tokenAmount != 0);
if (investedAmountOf[receiver] == 0) {
// A new investor
investorCount++;
}
updateInvestorFunds(tokenAmount, weiAmount, receiver, customerId);
// Pocket the money
multisigWallet.transfer(weiAmount);
// Return excess of money
uint weiToReturn = msg.value.sub(weiAmount);
if (weiToReturn > 0) {
msg.sender.transfer(weiToReturn);
}
} | 0.4.13 |
/**
* Preallocate tokens for the early investors.
*
* Preallocated tokens have been sold before the actual crowdsale opens.
* This function mints the tokens and moves the crowdsale needle.
*
* No money is exchanged, as the crowdsale team already have received the payment.
*
* @param fullTokens tokens as full tokens - decimal places added internally
* @param weiPrice Price of a single full token in wei
*
*/ | function preallocate(address receiver, uint fullTokens, uint weiPrice) public onlyOwner notFinished {
require(receiver != address(0));
uint tokenAmount = fullTokens.mul(10**uint(token.decimals()));
require(tokenAmount != 0);
uint weiAmount = weiPrice.mul(tokenAmount); // This can also be 0, in which case we give out tokens for free
updateInvestorFunds(tokenAmount, weiAmount, receiver , 0);
} | 0.4.13 |
/**
* Private function to update accounting in the crowdsale.
*/ | function updateInvestorFunds(uint tokenAmount, uint weiAmount, address receiver, uint128 customerId) private {
// Update investor
investedAmountOf[receiver] = investedAmountOf[receiver].add(weiAmount);
tokenAmountOf[receiver] = tokenAmountOf[receiver].add(tokenAmount);
// Update totals
weiRaised = weiRaised.add(weiAmount);
tokensSold = tokensSold.add(tokenAmount);
assignTokens(receiver, tokenAmount);
// Tell us that the investment was completed successfully
Invested(receiver, weiAmount, tokenAmount, customerId);
} | 0.4.13 |
/**
* Crowdfund state machine management.
*
* This function has the timed transition builtin.
* So there is no chance of the variable being stale.
*/ | function getState() public constant returns (State) {
if (finalized) return State.Finalized;
else if (block.number < startsAt) return State.PreFunding;
else if (block.number <= endsAt && !ceilingStrategy.isCrowdsaleFull(weiRaised, weiFundingCap)) return State.Funding;
else if (isMinimumGoalReached()) return State.Success;
else if (!isMinimumGoalReached() && weiRaised > 0 && loadedRefund >= weiRaised) return State.Refunding;
else return State.Failure;
} | 0.4.13 |
/** Called once by crowdsale finalize() if the sale was a success. */ | function finalizeCrowdsale(CrowdsaleToken token) {
require(msg.sender == address(crowdsale));
// How many % points of tokens the founders and others get
uint tokensSold = crowdsale.tokensSold();
uint saleBasePoints = basePointsDivisor.sub(bonusBasePoints);
allocatedBonus = tokensSold.mul(bonusBasePoints).div(saleBasePoints);
// Move tokens to the team multisig wallet
token.mint(teamMultisig, allocatedBonus);
// Make token transferable
token.releaseTokenTransfer();
} | 0.4.13 |
/**
* @dev allows a creator to destroy some of its own tokens
* Validates that caller is a creator and that sender is not blacklisted
* amount is less than or equal to the creator's account balance
* @param _amount uint256 the amount of tokens to be destroyed
*/ | function destroy(uint256 _amount) whenNotPaused onlyCreators notBlacklisted(msg.sender) public {
uint256 balance = balances[msg.sender];
require(_amount > 0);
require(balance >= _amount);
totalSupply = totalSupply.sub(_amount);
balances[msg.sender] = balance.sub(_amount);
emit Destroy(msg.sender, _amount);
emit Transfer(msg.sender, address(0), _amount);
} | 0.5.1 |
/**
* @dev gets the payload to sign when a user wants to do a metaTransfer
* @param _from uint256 address of the transferer
* @param _to uint256 address of the recipient
* @param value uint256 the amount of tokens to be transferred
* @param fee uint256 the fee paid to the relayer in uCNY
* @param nonce uint256 the metaNonce of the usere's metatransaction
*/ | function getTransferPayload(
address _from,
address _to,
uint256 value,
uint256 fee,
uint256 nonce
) public
view
returns (bytes32 payload)
{
return ECDSA.toEthSignedMessageHash(
keccak256(abi.encodePacked(
"transfer", // function specfic text
_from, // transferer.
_to, // recipient
address(this), // Token address (replay protection).
value, // Number of tokens.
fee, // fee paid to metaTransfer relayer, in uCNY
nonce // Local sender specific nonce (replay protection).
))
);
} | 0.5.1 |
/**
* @dev metaTransfer function called by relayer which executes a token transfer
* on behalf of the original sender who provided a vaild signature.
* @param _from address of the original sender
* @param _to address of the recipient
* @param value uint256 amount of uCNY being sent
* @param fee uint256 uCNY fee rewarded to the relayer
* @param metaNonce uint256 metaNonce of the original sender
* @param signature bytes signature provided by original sender
*/ | function metaTransfer(
address _from,
address _to,
uint256 value,
uint256 fee,
uint256 metaNonce,
bytes memory signature
) public returns (bool success) {
// Verify and increment nonce.
require(getMetaNonce(_from) == metaNonce);
metaNonces[_from] = metaNonces[_from].add(1);
// Verify signature.
bytes32 payload = getTransferPayload(_from,_to, value, fee, metaNonce);
require(isValidSignature(_from,payload,signature));
require(_from != address(0));
//_transfer(sender,receiver,value);
_transfer(_from,_to,value);
//send Fee to metaTx miner
_transfer(_from,msg.sender,fee);
emit MetaTransfer(msg.sender, _from,_to,value);
return true;
} | 0.5.1 |
Subsets and Splits