comment stringlengths 11 2.99k | function_code stringlengths 165 3.15k | version stringclasses 80
values |
|---|---|---|
/**
* @dev Returns an URI for a contract
*/ | function toString(address _addr) public pure returns (string memory) {
bytes32 value = bytes32(uint256(_addr));
bytes memory alphabet = "0123456789abcdef";
bytes memory str = new bytes(42);
str[0] = "0";
str[1] = "x";
for (uint i = 0; i < 20; i++) {
s... | 0.5.16 |
/**
* @dev copies the reserves from the old converter to the new one.
* note that this will not work for an unlimited number of reserves due to block gas limit constraints.
*
* @param _oldConverter old converter contract address
* @param _newConverter new converter contract address
*/ | function copyReserves(IConverter _oldConverter, IConverter _newConverter) private {
uint16 reserveTokenCount = _oldConverter.connectorTokenCount();
for (uint16 i = 0; i < reserveTokenCount; i++) {
IERC20 reserveAddress = _oldConverter.connectorTokens(i);
(, uint32 weight, ,... | 0.6.12 |
/**
* @dev transfers the balance of each reserve in the old converter to the new one.
* note that the function assumes that the new converter already has the exact same number of reserves
* also, this will not work for an unlimited number of reserves due to block gas limit constraints.
*
* @param _oldConverte... | function transferReserveBalancesVersion45(ILegacyConverterVersion45 _oldConverter, IConverter _newConverter)
private
{
uint256 reserveBalance;
uint16 reserveTokenCount = _oldConverter.connectorTokenCount();
for (uint16 i = 0; i < reserveTokenCount; i++) {
IERC20 r... | 0.6.12 |
// using a static call to identify converter version
// can't rely on the version number since the function had a different signature in older converters | function isV28OrHigherConverter(IConverter _converter) internal view returns (bool) {
bytes memory data = abi.encodeWithSelector(IS_V28_OR_HIGHER_FUNC_SELECTOR);
(bool success, bytes memory returnData) = address(_converter).staticcall{ gas: 4000 }(data);
if (success && returnData.length == ... | 0.6.12 |
//migrate to new controller contract in case of some mistake in the contract and transfer there all the tokens and eth. It can be done only after code review by Etherama developers. | function migrateToNewControllerContract(address newControllerAddr) onlyAdministrator public {
require(newControllerAddr != address(0x0) && isActualContractVer);
isActive = false;
core.setNewControllerAddress(newControllerAddr);
uint256 mntpTokenAmount = getMntpBalance()... | 0.4.25 |
// MAGEO EXTRA URIs | function getPersistentURI(uint256 tokenId) public view returns (string memory) {
require(_exists(tokenId), "Persistent uri query for nonexistent token");
string memory uri = persistentURIs[tokenId];
if (bytes(uri).length == 0) {
return tokenURI(tokenId);
}
... | 0.8.9 |
//Initialize or completely overrite existing list of contributors | function setContributors(address[] calldata _contributors, uint16[] calldata contShares) public onlyOwner {
//revert if caller has mismtached sizes of arrays
require(_contributors.length == contShares.length, "length not the same");
uint16 oldShares = 0;
contributors = _contributors;
... | 0.6.12 |
//Change shares of a contributor or sets | function addContributor(address _con, uint16 _share) public onlyOwner {
require (_share <= 1000, "share more than 100%");
uint16 oldShares = 0;
if (shares[_con].exists) {
oldShares = shares[_con].numOfShares;
//set new number of shares for existing contributor
... | 0.6.12 |
/**
* @dev Function to withdraw game LOOMI to ERC-20 LOOMI.
*/ | function withdrawLoomi(uint256 amount) public nonReentrant whenNotPaused {
require(!isWithdrawPaused, "Withdraw Paused");
require(getUserBalance(_msgSender()) >= amount, "Insufficient balance");
uint256 tax = withdrawTaxCollectionStopped ? 0 : (amount * withdrawTaxAmount) / 100;
spentAmount[_ms... | 0.8.7 |
/**
* @dev Function to spend user balance. Can be called by other authorised contracts. To be used for internal purchases of other NFTs, etc.
*/ | function spendLoomi(address user, uint256 amount) external onlyAuthorised nonReentrant {
require(getUserBalance(user) >= amount, "Insufficient balance");
uint256 tax = spendTaxCollectionStopped ? 0 : (amount * spendTaxAmount) / 100;
spentAmount[user] += amount;
activeTaxCollectedAmount += tax;
... | 0.8.7 |
/**
* @dev Function to claim tokens from the tax accumulated pot. Can be only called by an authorised contracts.
*/ | function claimLoomiTax(address user, uint256 amount) public onlyAuthorised nonReentrant {
require(activeTaxCollectedAmount >= amount, "Insufficiend tax balance");
activeTaxCollectedAmount -= amount;
depositedAmount[user] += amount;
bribesDistributed += amount;
emit ClaimTax(
_msg... | 0.8.7 |
/**
* @notice ERC777 hook invoked when this contract receives a token.
*/ | function tokensReceived(
address _operator,
address _from,
address _to,
uint256 _amount,
bytes calldata _userData,
bytes calldata _operatorData
) external {
if (_from == address(depositPbtc)) return;
require(msg.sender == address(pbtc), "RewardedPbtcSb... | 0.5.16 |
/**
* @notice Remove Gauge tokens from Modified Unipool (earning PNT),
* withdraw pBTC/sbtcCRV (earning CRV) from the Gauge and then
* remove liquidty from pBTC/sBTC Curve Metapool and then
* transfer all back to the msg.sender.
* User must approve this contract to to withdraw the c... | function unstake() public returns (bool) {
uint256 gaugeTokenSenderBalance = modifiedUnipool.balanceOf(msg.sender);
require(
modifiedUnipool.allowance(msg.sender, address(this)) >= gaugeTokenSenderBalance,
"RewardedPbtcSbtcCurveMetapool: amount not approved"
);
mo... | 0.5.16 |
/**
* @notice Add liquidity into Curve pBTC/SBTC Metapool,
* put the minted pBTC/sbtcCRV tokens into the Gauge in
* order to earn CRV and then put the Liquidi Gauge tokens
* into Unipool in order to get the PNT reward.
*
* @param _user user address
* @param _amount pBTC amount to put into... | function _stakeFor(address _user, uint256 _amount) internal returns (bool) {
uint256 maxAllowedMinAmount = _amount - ((_amount * allowedSlippage) / (SLIPPAGE_BASE_UNIT * 100));
pbtc.safeApprove(address(depositPbtc), _amount);
uint256 metaTokenAmount = depositPbtc.add_liquidity([_amount, 0, 0, 0]... | 0.5.16 |
// Add a new lp to the pool. Can only be called by the owner.
// This is assumed to not be a restaking pool.
// Restaking can be added later or with addWithRestaking() instead of add() | function add(uint256 _allocPoint, IERC20 _lpToken, uint256 _withdrawFee, bool _withUpdate) public onlyOwner {
require(poolIsAdded[address(_lpToken)] == false, 'add: pool already added');
poolIsAdded[address(_lpToken)] = true;
if (_withUpdate) {
massUpdatePools();
}
... | 0.6.12 |
// Set a new restaking adapter. | function setRestaking(uint256 _pid, IStakingAdapter _adapter, bool _claim) public onlyOwner validAdapter(_adapter) {
if (_claim) {
updatePool(_pid);
}
if (isRestaking(_pid)) {
withdrawRestakedLP(_pid);
}
PoolInfo storage pool = poolInfo[_pid];
... | 0.6.12 |
// View function to see our pending OTHERs on frontend (whatever the restaked reward token is) | function pendingOther(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accOtherPerShare = pool.accOtherPerShare;
uint256 lpSupply = pool.adapter.balance();
if (lpS... | 0.6.12 |
// as above but for any restaking token | function safeOtherTransfer(address _to, uint256 _amount, uint256 _pid) internal {
PoolInfo storage pool = poolInfo[_pid];
uint256 otherBal = pool.otherToken.balanceOf(address(this));
if (_amount > otherBal) {
pool.otherToken.transfer(_to, otherBal);
} else {
... | 0.6.12 |
// called every pool update. | function updatePhase() internal {
if (phase == address(tidal) && tidal.totalSupply() >= TIDAL_CAP){
phase = address(riptide);
}
else if (phase == address(riptide) && tidal.totalSupply() < TIDAL_VERTEX) {
phase = address(tidal);
}
} | 0.6.12 |
/* https://elgame.cc */ | function getLevel(uint value) public pure returns (uint) {
if (value >= 1 ether && value <= 5 ether) {
return 1;
}
if (value >= 6 ether && value <= 10 ether) {
return 2;
}
if (value >= 11 ether && value <= 15 ether) {
return 3;
}
if (value >= 16 ether && value <= 30 ether) {
return... | 0.5.17 |
/**
* @dev transfer to array of wallets
* @param addresses wallet address array
* @param values value to transfer array
*/ | function transferBatch(address[] memory addresses, uint256[] memory values) public {
require((addresses.length != 0 && values.length != 0));
require(addresses.length == values.length);
/// @notice Check if the tokens are enough
require(getTotalAmount(values) <= balanceOf(msg.sender));
for (uint8 j =... | 0.5.7 |
/// @dev query latest and oldest observations from uniswap pool
/// @param pool address of uniswap pool
/// @param latestIndex index of latest observation in the pool
/// @param observationCardinality size of observation queue in the pool
/// @return oldestObservation
/// @return latestObservation | function getObservationBoundary(address pool, uint16 latestIndex, uint16 observationCardinality)
internal
view
returns (Observation memory oldestObservation, Observation memory latestObservation)
{
uint16 oldestIndex = (latestIndex + 1) % observationCardinality;
oldestObserva... | 0.8.4 |
/// @dev view slot0 infomations from uniswap pool
/// @param pool address of uniswap
/// @return slot0 a Slot0 struct with necessary info, see Slot0 struct above | function getSlot0(address pool)
internal
view
returns (Slot0 memory slot0) {
(
uint160 sqrtPriceX96,
int24 tick,
uint16 observationIndex,
uint16 observationCardinality,
,
,
) = IUniswapV3Pool(pool).... | 0.8.4 |
// note if we call this interface, we must ensure that the
// oldest observation preserved in pool is older than 2h ago | function _getAvgTickFromTarget(address pool, uint32 targetTimestamp, int56 latestTickCumu, uint32 latestTimestamp)
private
view
returns (int24 tick)
{
uint32[] memory secondsAgo = new uint32[](1);
secondsAgo[0] = uint32(block.timestamp) - targetTimestamp;
int56[] me... | 0.8.4 |
// ------------------------------------------------------------------------
// Claim VRF tokens daily, requires an Eth Verify account
// ------------------------------------------------------------------------ | function claimTokens() public{
require(activated);
//progress the day if needed
if(dayStartTime<now.sub(timestep)){
uint daysPassed=(now.sub(dayStartTime)).div(timestep);
dayStartTime=dayStartTime.add(daysPassed.mul(timestep));
claimedYesterday=claimedTo... | 0.4.24 |
/**
* mint tokens
*
* add `_value` tokens from the system irreversibly
*
* @param _value the amount of money to mint
*/ | function mint(uint256 _value) public returns (bool success) {
require((msg.sender == owner));
// Only the owner can do this
balanceOf[msg.sender] += _value;
// add coin for sender
totalSupply += _value;
// Updates totalSupply
emit Mint(_value);
ret... | 0.6.1 |
/**
* @dev When accumulated SpaceMon tokens have last been claimed for a Kami index
*/ | function lastClaim(uint256 tokenIndex) public view returns (uint256) {
require(IKami(_kamiAddress).ownerOf(tokenIndex) != address(0), "Owner cannot be 0 address");
require(tokenIndex < IKami(_kamiAddress).totalSupply(), "NFT at index has not been minted yet");
uint256 lastClaimed = uint256(... | 0.7.6 |
/**
* @dev Accumulated Power tokens for a Kami token index.
*/ | function accumulated(uint256 tokenIndex) public view returns (uint256) {
require(block.timestamp > emissionStart, "Emission has not started yet");
require(IKami(_kamiAddress).ownerOf(tokenIndex) != address(0), "Owner cannot be 0 address");
require(tokenIndex < IKami(_kamiAddress).totalSupply(... | 0.7.6 |
/**
* @dev Mints SpaceMon
*/ | function mintSpaceMon(uint256 tokenQuantity) public payable {
require(block.timestamp >= monSaleStartTimestamp, "Sorry, you cannot buy SpaceMon at the moment");
require(currentMintedAmount <= mintedCap,"All SpaceMon has been sold unfortunately");
require(tokenQuantity > 0, "SpaceMon amount ca... | 0.7.6 |
/// @notice This function allows the sender to stake
/// an amount (maximum 10) of UnissouToken, when the
/// token is staked, it is burned from the circulating
/// supply and placed into the staking pool
///
/// @dev The function iterate through {stakeholders} to
/// know if the sender is already a stakeholder. If th... | function stake(
uint256 _amount
) public virtual isAmountValid(
_amount,
balanceOf(msg.sender)
) isAmountNotZero(
_amount
) {
uint256 i = 0;
bool isStakeholder = false;
uint256 len = stakeholders.length;
while (i < len) {
if (stakeholders[i].owner == msg.sender) {
isS... | 0.6.12 |
/// @notice This function unstacks the sender staked
/// balance depending on the requested {_amount}, if the
/// {_amount} exceeded the staked supply of the sender,
/// the whole staked supply of the sender will be unstacked
/// and withdrawn to the sender wallet without exceeding it.
///
/// @dev Like stake() functio... | function unstake(
uint256 _amount
) public virtual isAmountNotZero(
_amount
) isAbleToUnstake(
_amount
) {
uint256 i = 0;
bool isStakeholder = false;
uint256 len = stakeholders.length;
while (i < len) {
if (stakeholders[i].owner == msg.sender) {
isStakeholder = true;
... | 0.6.12 |
/// @notice This function allows the sender to compute
/// his reward earned by staking {UnissouToken}. When you
/// request a withdraw, the function updates the reward's
/// value of the sender stakeholding onto the Ethereum
/// blockchain, allowing him to spend the reward for NFTs.
///
/// @dev The same principe as o... | function withdraw()
public virtual {
uint256 i = 0;
bool isStakeholder = false;
uint256 len = stakeholders.length;
while (i < len) {
if (stakeholders[i].owner == msg.sender) {
isStakeholder = true;
break;
}
i++;
}
require(
isStakeholder,
"SC:650"
... | 0.6.12 |
/// @notice This function allows the sender to spend {_amount}
/// of his rewards gained from his stake.
///
/// @dev To reduce the potential numbers of transaction, the
/// {_computeReward()} function is also executed into this function.
/// Like that you can spend your reward without doing a double
/// transaction l... | function spend(
uint256 _amount
) public virtual {
uint256 i = 0;
bool isStakeholder = false;
uint256 len = stakeholders.length;
while (i < len) {
if (stakeholders[i].owner == msg.sender) {
isStakeholder = true;
break;
}
i++;
}
require(
isStakeholde... | 0.6.12 |
/**********************************************************************************************
// calcSingleInGivenPoolOut //
// tAi = tokenAmountIn //(pS + pAo)\ / 1 \\ //
// pS = poolSupply ... | function calcSingleInGivenPoolOut(
uint tokenBalanceIn,
uint tokenWeightIn,
uint poolSupply,
uint totalWeight,
uint poolAmountOut,
uint swapFee
)
public pure
returns (uint tokenAmountIn)
{
uint normalizedWeight = bdiv(tokenWeightIn, totalWe... | 0.5.7 |
/**********************************************************************************************
// calcPoolInGivenSingleOut //
// pAi = poolAmountIn // / tAo \\ / wO \ \ //
// bO = tokenBalanceOut ... | function calcPoolInGivenSingleOut(
uint tokenBalanceOut,
uint tokenWeightOut,
uint poolSupply,
uint totalWeight,
uint tokenAmountOut,
uint swapFee
)
public pure
returns (uint poolAmountIn)
{
// charge swap fee on the output token side
... | 0.5.7 |
/**
* registerUser associates a Monetha user's ethereum address with his nickname and trust score
* @param _userAddress address of user's wallet
* @param _name corresponds to use's nickname
* @param _starScore represents user's star score
* @param _reputationScore represents user's reputation score
* ... | function registerUser(address _userAddress, string _name, uint256 _starScore, uint256 _reputationScore, uint256 _signedDealsCount, string _nickname, bool _isVerified)
external onlyOwner
{
User storage user = users[_userAddress];
user.name = _name;
user.starScore = _starScore;
... | 0.4.25 |
/**
* updateTrustScoreInBulk updates the trust score of Monetha users in bulk
*/ | function updateTrustScoreInBulk(address[] _userAddresses, uint256[] _starScores, uint256[] _reputationScores)
external onlyOwner
{
require(_userAddresses.length == _starScores.length);
require(_userAddresses.length == _reputationScores.length);
for (uint256 i = 0; i < _userAdd... | 0.4.25 |
/**
* updateUserDetailsInBulk updates details of Monetha users in bulk
*/ | function updateUserDetailsInBulk(address[] _userAddresses, uint256[] _starScores, uint256[] _reputationScores, uint256[] _signedDealsCount, bool[] _isVerified)
external onlyOwner
{
require(_userAddresses.length == _starScores.length);
require(_userAddresses.length == _reputationScores.le... | 0.4.25 |
/**
* updateUser updates single user details
*/ | function updateUser(address _userAddress, string _updatedName, uint256 _updatedStarScore, uint256 _updatedReputationScore, uint256 _updatedSignedDealsCount, string _updatedNickname, bool _updatedIsVerified)
external onlyOwner
{
users[_userAddress].name = _updatedName;
users[_userAddress]... | 0.4.25 |
// Timestamp functions based on
// https://github.com/pipermerriam/ethereum-datetime/blob/master/contracts/DateTime.sol | function toTimestamp(uint16 year, uint8 month, uint8 day)
internal pure returns (uint timestamp) {
uint16 i;
// Year
timestamp += (year - ORIGIN_YEAR) * 1 years;
timestamp += (leapYearsBefore(year) - leapYearsBefore(ORIGIN_YEAR)) * 1 days;
// Month
uint8[12... | 0.4.19 |
/**
* @notice Transfers vested tokens to beneficiary.
* @param token ERC20 token which is being vested
*/ | function claim(IERC20 token) public {
require(_start > 0, "TokenVesting: start is not set");
uint256 unreleased = _releasableAmount(token);
require(unreleased > 0, "TokenVesting: no tokens are due");
_released[address(token)] = _released[address(token)].add(unreleased);
token.safeTransf... | 0.5.16 |
// Use storage keyword so that we write this to persistent storage. | function initBonus(BonusData storage data)
internal
{
data.factors = [uint256(300), 250, 200, 150, 100, 50, 0];
data.cutofftimes = [toTimestamp(2018, 9, 1),
toTimestamp(2018, 9, 8),
toTimestamp(2018, 9, 15),
... | 0.4.19 |
/*
Let's at least allow some minting of tokens!
@param beneficiary - who should receive it
@param tokenId - the id of the 721 token
*/ | function mint
(
address beneficiary,
uint tType
)
public
onlyMinter()
returns (uint tokenId)
{
uint index = tokensByType[tType].length;
require (index < tokenTypeSupply[tType], "Token supply limit reached");
tokenId = getTokenId(tType, index);
tokens... | 0.5.0 |
//this creates the contract and stores the owner. it also passes in 3 addresses to be used later during the lifetime of the contract. | function QCOToken(
address _stateControl
, address _whitelistControl
, address _withdrawControl
, address _tokenAssignmentControl
, address _teamControl
, address _reserves)
public
{
stateControl = _stateControl;
whitelistControl = _whitelistControl;
... | 0.4.19 |
//this is the main funding function, it updates the balances of tokens during the ICO.
//no particular incentive schemes have been implemented here
//it is only accessible during the "ICO" phase. | function() payable
public
requireState(States.Ico)
{
require(whitelist[msg.sender] == true);
require(msg.value > 0);
// We have reports that some wallet contracts may end up sending a single null-byte.
// Still reject calls of unknown functions, which are always at lea... | 0.4.19 |
// ICO contract configuration function
// new_ETH_QCO is the new rate of ETH in QCO to use when no bonus applies
// newEndBlock is the absolute block number at which the ICO must stop. It must be set after now + silence period. | function updateEthICOVariables(uint256 _new_ETH_QCO, uint256 _newEndBlock)
public
onlyStateControl
{
require(state == States.Initial || state == States.ValuationSet);
require(_new_ETH_QCO > 0);
require(block.number < _newEndBlock);
endBlock = _newEndBlock;
// ... | 0.4.19 |
//in case of a failed/aborted ICO every investor can get back their money | function requestRefund()
public
requireState(States.Aborted)
{
require(ethPossibleRefunds[msg.sender] > 0);
//there is no need for updateAccount(msg.sender) since the token never became active.
uint256 payout = ethPossibleRefunds[msg.sender];
//reverse calculate the am... | 0.4.19 |
/**
* @dev One time initialization function
* @param _token SNP token address
* @param _liquidity SNP/USDC LP token address
* @param _vesting public vesting contract address
*/ | function init(
address _token,
address _liquidity,
address _vesting
) external onlyOwner {
require(_token != address(0), "_token address cannot be 0");
require(_liquidity != address(0), "_liquidity address cannot be 0");
require(_vesting != address(0), "_vesting addre... | 0.8.6 |
/**
* @dev Updates reward in selected pool
* @param _account address for which rewards will be updated
* @param _lp true=lpStaking, false=tokenStaking
*/ | function _updateReward(address _account, bool _lp) internal {
uint256 newRewardPerTokenStored = currentRewardPerTokenStored(_lp);
// if statement protects against loss in initialization case
if (newRewardPerTokenStored > 0) {
StakingData storage sd = _lp ? lpStaking : tokenStaking;
... | 0.8.6 |
/**
* @dev Add tokens for staking from vesting contract
* @param _account address that call claimAndStake in vesting
* @param _amount number of tokens sent to contract
*/ | function onClaimAndStake(address _account, uint256 _amount)
external
nonReentrant
updateReward(_account, false)
updateSuperRewards(_account)
{
require(msg.sender == vestingAddress, "Only vesting contract");
require(!tokenStake[_account].isWithdrawing, "Cannot when wit... | 0.8.6 |
/**
* @dev Add tokens to staking contract by using permit to set allowance
* @param _amount of tokens to stake
* @param _deadline of permit signature
* @param _approveMax allowance for the token
*/ | function addTokenStakeWithPermit(
uint256 _amount,
uint256 _deadline,
bool _approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external {
uint256 value = _approveMax ? type(uint256).max : _amount;
IERC20(tokenAddress).permit(msg.sender, address(this), value, ... | 0.8.6 |
/**
* @dev Internal add stake function
* @param _account selected staked tokens are credited to this address
* @param _amount of staked tokens
* @param _lp true=LP token, false=SNP token
*/ | function _addStake(
address _account,
uint256 _amount,
bool _lp
) internal nonReentrant updateReward(_account, _lp) updateSuperRewards(_account) {
require(_amount > 0, "Zero Amount");
Stake storage s = _lp ? liquidityStake[_account] : tokenStake[_account];
require(!s.... | 0.8.6 |
/**
* @dev Restake earned tokens and add them to token stake (instead of claiming)
* If have LP stake but not token stake - token stake will be created.
*/ | function restake() external hasStake updateRewards(msg.sender) updateSuperRewards(msg.sender) {
Stake storage ts = tokenStake[msg.sender];
Stake storage ls = liquidityStake[msg.sender];
require(!ts.isWithdrawing, "Cannot when withdrawing");
uint256 rewards = ts.rewards + ls.rewards;
... | 0.8.6 |
/**
* @dev Internal claim function. First updates rewards in normal and super pools
* and then transfers.
* @param _account claim rewards for this address
* @param _recipient claimed tokens are sent to this address
*/ | function _claim(address _account, address _recipient) internal nonReentrant hasStake updateRewards(_account) updateSuperRewards(_account) {
uint256 rewards = tokenStake[_account].rewards + liquidityStake[_account].rewards;
require(rewards > 0, "Nothing to claim");
delete tokenStake[_account].r... | 0.8.6 |
/**
* @dev Internal request unstake function. Update normal and super rewards for the user first.
* @param _account User address
* @param _lp true=it is LP stake
*/ | function _requestUnstake(address _account, bool _lp)
internal
hasPoolStake(_account, _lp)
updateReward(_account, _lp)
updateSuperRewards(_account)
{
Stake storage s = _lp ? liquidityStake[_account] : tokenStake[_account];
require(!s.isWithdrawing, "Cannot when withdra... | 0.8.6 |
/**
* @dev Withdraw stake for msg.sender from both stakes (if possible)
*/ | function unstake() external nonReentrant hasStake canUnstake {
bool success;
uint256 reward;
uint256 tokens;
uint256 rewards;
(reward, success) = _unstake(msg.sender, false);
rewards += reward;
if (success) {
tokens += tokenStake[msg.sender].tokens;
... | 0.8.6 |
/**
* @dev Internal unstake function, withdraw staked LP tokens
* @param _account address of account to transfer LP tokens
* @param _lp true = LP stake
* @return stake rewards amount
* @return bool true if success
*/ | function _unstake(address _account, bool _lp) internal returns (uint256, bool) {
Stake memory s = _lp ? liquidityStake[_account] : tokenStake[_account];
if (!s.isWithdrawing) return (0, false);
if (s.withdrawalPossibleAt > block.timestamp) return (0, false);
data.totalRewardsClaimed += ... | 0.8.6 |
/**
* @dev Unstake requested stake at any time accepting 10% penalty fee
*/ | function unstakeWithFee() external nonReentrant hasStake cantUnstake {
Stake memory ts = tokenStake[msg.sender];
Stake memory ls = liquidityStake[msg.sender];
uint256 tokens;
uint256 rewards;
if (ls.isWithdrawing) {
uint256 lpTokens = _minusFee(ls.tokens); //remainin... | 0.8.6 |
/**
* @dev Set Super Staker status if possible for selected pool.
* Update super reward pools.
* @param _account address of account to set super
* @param _lp true=LP stake super staker, false=token stake super staker
*/ | function _setSuper(address _account, bool _lp)
internal
hasPoolStake(_account, _lp)
canBeSuper(_account, _lp)
updateSuperRewards(address(0))
{
Stake storage s = _lp ? liquidityStake[_account] : tokenStake[_account];
StakingData storage sd = _lp ? lpStaking : tokenStak... | 0.8.6 |
/**
* @dev Calculates the amount of unclaimed rewards per token since last update,
* and sums with stored to give the new cumulative reward per token
* @param _lp true=lpStaking, false=tokenStaking
* @return 'Reward' per staked token
*/ | function currentRewardPerTokenStored(bool _lp) public view returns (uint256) {
StakingData memory sd = _lp ? lpStaking : tokenStaking;
uint256 stakedTokens = sd.stakedTokens;
uint256 rewardPerTokenStored = sd.rewardPerTokenStored;
// If there is no staked tokens, avoid div(0)
if ... | 0.8.6 |
/**
* @dev Calculates the amount of unclaimed rewards a user has earned
* @param _account user address
* @param _lp true=liquidityStake, false=tokenStake
* @return Total reward amount earned
*/ | function _earned(address _account, bool _lp) internal view returns (uint256) {
Stake memory s = _lp ? liquidityStake[_account] : tokenStake[_account];
if (s.isWithdrawing) return s.rewards;
// current rate per token - rate user previously received
uint256 rewardPerTokenStored = currentRe... | 0.8.6 |
/**
* @dev Check if staker can set super staker status on token or LP stake
* @param _account address to check
* @return token true if can set super staker on token stake
* @return lp true if can set super staker on LP stake
*/ | function canSetSuper(address _account) external view returns (bool token, bool lp) {
Stake memory ts = tokenStake[_account];
Stake memory ls = liquidityStake[_account];
if (ts.tokens > 0 && block.timestamp >= ts.superStakerPossibleAt && !ts.isSuperStaker && !ts.isWithdrawing) token = true;
... | 0.8.6 |
/**
* @dev Notifies the contract that new rewards have been added.
* Calculates an updated rewardRate based on the rewards in period.
* @param _reward Units of SNP token that have been added to the token pool
* @param _lpReward Units of SNP token that have been added to the lp pool
*/ | function notifyRewardAmount(uint256 _reward, uint256 _lpReward) external onlyRewardsDistributor updateRewards(address(0)) {
uint256 currentTime = block.timestamp;
// pull tokens
require(_transferFrom(tokenAddress, msg.sender, _reward + _lpReward) == _reward + _lpReward, "Exclude Rewarder from f... | 0.8.6 |
/**
* @dev Just exchage your MILK2 for one(1) SHAKE.
* Caller must have MILK2 on his/her balance, see `currShakePrice`
* Each call will increase SHAKE price with one step, see `SHAKE_PRICE_STEP`.
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Function can be called after `START_FROM_BLOCK`
*/ | function getOneShake() external {
require(block.number >= START_FROM_BLOCK, "Please wait for start block");
IERC20 milk2Token = IERC20(MILK_ADDRESS);
require(milk2Token.balanceOf(msg.sender) >= currShakePrice, "There is no enough MILK2");
require(milk2Token.burn(msg.sender, currS... | 0.6.12 |
/**
* @dev Just exchange your SHAKE for MILK2.
* Caller must have SHAKE on his/her balance.
* `_amount` is amount of user's SHAKE that he/she want burn for get MILK2
* Note that one need use `_amount` without decimals.
*
* Note that MILK2 amount will calculate from the reduced by one step `currShakePrice`... | function getMilkForShake(uint16 _amount) external {
require(block.number >= START_FROM_BLOCK, "Please wait for start block");
IERC20 shakeToken = IERC20(SHAKE_ADDRESS);
require(shakeToken.balanceOf(msg.sender) >= uint256(_amount)*10**18, "There is no enough SHAKE");
requi... | 0.6.12 |
/**
* @dev Returns the key-value pair stored at position `index` in the map. O(1).
*
* Note that there are no guarantees on the ordering of entries inside the
* array, and it may change when more entries are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/ | function _at(Map storage map, uint256 index)
private
view
returns (bytes32, bytes32)
{
require(
map._entries.length > index,
"EnumerableMap: index out of bounds"
);
MapEntry storage entry = map._entries[index];
return (entry._key, entr... | 0.8.9 |
// Enter the bar. Pay some SUSHIs. Earn some shares. | function enter(uint256 _amount) public {
uint256 totalSushi = sushi.balanceOf(address(this));
uint256 totalShares = totalSupply();
if (totalShares == 0 || totalSushi == 0) {
_mint(msg.sender, _amount);
} else {
uint256 what = _amount.mul(totalShares).div(tot... | 0.6.2 |
//wraping all buy or mint function in one function: | function mint(uint256 _countNfts) public payable whenNotPaused {
uint NFTsPrice = NFTPrice * _countNfts;
address to = msg.sender;
require(totalSupply() + _countNfts <= NFTMaxSupply, "NFT: Max Supply reached");
require(_countNfts > 0, "NFT: No of NFTs must be greater then zero");
... | 0.8.2 |
/// @notice Get the overall info for the mining contract. | function getMiningContractInfo()
external
view
returns (
address uniToken_,
address lockToken_,
uint24 fee_,
uint256 lockBoostMultiplier_,
address iziTokenAddr_,
uint256 lastTouchBlock_,
uint256 totalVLiquidity_,... | 0.8.4 |
/// @notice new a token status when touched. | function _newTokenStatus(TokenStatus memory newTokenStatus) internal {
tokenStatus[newTokenStatus.nftId] = newTokenStatus;
TokenStatus storage t = tokenStatus[newTokenStatus.nftId];
t.lastTouchBlock = lastTouchBlock;
t.lastTouchAccRewardPerShare = new uint256[](rewardInfosLen);
... | 0.8.4 |
/// @notice update a token status when touched | function _updateTokenStatus(
uint256 tokenId,
uint256 validVLiquidity,
uint256 nIZI
) internal {
TokenStatus storage t = tokenStatus[tokenId];
// when not boost, validVL == vL
t.validVLiquidity = validVLiquidity;
t.nIZI = nIZI;
t.lastTouchBlock = las... | 0.8.4 |
/// @notice Update reward variables to be up-to-date. | function _updateVLiquidity(uint256 vLiquidity, bool isAdd) internal {
if (isAdd) {
totalVLiquidity = totalVLiquidity + vLiquidity;
} else {
totalVLiquidity = totalVLiquidity - vLiquidity;
}
// max lockBoostMultiplier is 3
require(totalVLiquidity <= FixedP... | 0.8.4 |
/// @notice Update the global status. | function _updateGlobalStatus() internal {
if (block.number <= lastTouchBlock) {
return;
}
if (lastTouchBlock >= endBlock) {
return;
}
uint256 currBlockNumber = Math.min(block.number, endBlock);
if (totalVLiquidity == 0) {
lastTouchBlock... | 0.8.4 |
/// @dev get sqrtPrice of pool(uniToken/tokenSwap/fee)
/// and compute tick range converted from [TICK_MIN, PriceUni] or [PriceUni, TICK_MAX]
/// @return sqrtPriceX96 current sqrtprice value viewed from uniswap pool, is a 96-bit fixed point number
/// note this value might mean price of lockToken/uniToken (if uni... | function _getPriceAndTickRange()
private
view
returns (
uint160 sqrtPriceX96,
int24 tickLeft,
int24 tickRight
)
{
(int24 avgTick, uint160 avgSqrtPriceX96, int24 currTick, ) = swapPool
.getAvgTickPriceWithin2Hour();
int24... | 0.8.4 |
// fill INonfungiblePositionManager.MintParams struct to call INonfungiblePositionManager.mint(...) | function _mintUniswapParam(
uint256 uniAmount,
int24 tickLeft,
int24 tickRight,
uint256 deadline
)
private
view
returns (INonfungiblePositionManager.MintParams memory params)
{
params.fee = rewardPool.fee;
params.tickLower = tickLeft;
... | 0.8.4 |
/// @notice deposit iZi to an nft token
/// @param tokenId nft already deposited
/// @param deltaNIZI amount of izi to deposit | function depositIZI(uint256 tokenId, uint256 deltaNIZI)
external
nonReentrant
{
require(owners[tokenId] == msg.sender, "NOT OWNER or NOT EXIST");
require(address(iziToken) != address(0), "NOT BOOST");
require(deltaNIZI > 0, "DEPOSIT IZI MUST BE POSITIVE");
_collectRew... | 0.8.4 |
/// @notice Widthdraw a single position.
/// @param tokenId The related position id.
/// @param noReward true if use want to withdraw without reward | function withdraw(uint256 tokenId, bool noReward) external nonReentrant {
require(owners[tokenId] == msg.sender, "NOT OWNER OR NOT EXIST");
if (noReward) {
_updateGlobalStatus();
} else {
_collectReward(tokenId);
}
TokenStatus storage t = tokenStatus[toke... | 0.8.4 |
/// @notice Collect pending reward for a single position.
/// @param tokenId The related position id. | function _collectReward(uint256 tokenId) internal {
TokenStatus memory t = tokenStatus[tokenId];
_updateGlobalStatus();
for (uint256 i = 0; i < rewardInfosLen; i++) {
// multiplied by Q128 before
uint256 _reward = (t.validVLiquidity * (rewardInfos[i].accRewardPerShare - ... | 0.8.4 |
/// @notice Collect all pending rewards. | function collectAllTokens() external nonReentrant {
EnumerableSet.UintSet storage ids = tokenIds[msg.sender];
for (uint256 i = 0; i < ids.length(); i++) {
require(owners[ids.at(i)] == msg.sender, "NOT OWNER");
_collectReward(ids.at(i));
INonfungiblePositionManager.Col... | 0.8.4 |
/// @notice View function to get position ids staked here for an user.
/// @param _user The related address. | function getTokenIds(address _user)
external
view
returns (uint256[] memory)
{
EnumerableSet.UintSet storage ids = tokenIds[_user];
// push could not be used in memory array
// we set the tokenIdList into a fixed-length array rather than dynamic
uint256[] memo... | 0.8.4 |
/// @notice Return reward multiplier over the given _from to _to block.
/// @param _from The start block.
/// @param _to The end block. | function _getRewardBlockNum(uint256 _from, uint256 _to)
internal
view
returns (uint256)
{
if (_from > _to) {
return 0;
}
if (_to <= endBlock) {
return _to - _from;
} else if (_from >= endBlock) {
return 0;
} else {
... | 0.8.4 |
/// @notice View function to see pending Reward for a single position.
/// @param tokenId The related position id. | function pendingReward(uint256 tokenId)
public
view
returns (uint256[] memory)
{
TokenStatus memory t = tokenStatus[tokenId];
uint256[] memory _reward = new uint256[](rewardInfosLen);
for (uint256 i = 0; i < rewardInfosLen; i++) {
uint256 tokenReward = _ge... | 0.8.4 |
/// @notice View function to see pending Rewards for an address.
/// @param _user The related address. | function pendingRewards(address _user)
external
view
returns (uint256[] memory)
{
uint256[] memory _reward = new uint256[](rewardInfosLen);
for (uint256 j = 0; j < rewardInfosLen; j++) {
_reward[j] = 0;
}
for (uint256 i = 0; i < tokenIds[_user].le... | 0.8.4 |
/// @notice If something goes wrong, we can send back user's nft and locked assets
/// @param tokenId The related position id. | function emergenceWithdraw(uint256 tokenId) external onlyOwner {
address owner = owners[tokenId];
require(owner != address(0));
INonfungiblePositionManager(uniV3NFTManager).safeTransferFrom(
address(this),
owner,
tokenId
);
TokenStatus storage... | 0.8.4 |
// takes in _encodedData and converts to seascape | function metadataIsValid (uint256 _offerId, bytes memory _encodedData,
uint8 v, bytes32 r, bytes32 s) public view returns (bool){
(uint256 imgId, uint256 generation, uint8 quality) = decodeParams(_encodedData);
bytes32 hash = this.encodeParams(_offerId, imgId, generation, quality);
address si... | 0.6.7 |
/**
* Low level baller purchase function
* @param beneficiary will recieve the tokens.
* @param teamId Integer of the team the purchased baller plays for.
* @param mdHash IPFS Hash of the metadata json file corresponding to the baller.
*/ | function buyBaller(address beneficiary, uint256 teamId, string memory mdHash) public payable {
require(beneficiary != address(0), "BallerAuction: Cannot send to 0 address.");
require(beneficiary != address(this), "BallerAuction: Cannot send to auction contract address.");
uint256 weiAmount = ms... | 0.8.3 |
//pay out unclaimed rewards | function payoutRewards() public
{
updateRewardsFor(msg.sender);
uint256 rewards = _savedRewards[msg.sender];
require(rewards > 0 && rewards <= _balances[address(this)]);
_savedRewards[msg.sender] = 0;
uint256 initalBalance_staker = _balances[msg.send... | 0.5.8 |
//exchanges or other contracts can be excluded from receiving stake rewards | function excludeAddressFromStaking(address excludeAddress, bool exclude) public
{
require(msg.sender == contractOwner);
require(excludeAddress != address(this)); //contract may never be included
require(exclude != excludedFromStaking[excludeAddress]);
updateRewardsFor(excludeAdd... | 0.5.8 |
/*
Code to facilitate book redemptions and verify if a book has been claimed for a token.
The team will decide if this is the way to go.
*/ | function redeemBook(uint256 tokenId) public {
address tokenOwner = ownerOf(tokenId);
require(tokenOwner == msg.sender, "Only token owner can redeem");
require(redeemed[tokenId] == false, "Book already redeemed with token");
redeemed[tokenId] = true;
emit redeemEvent(msg.sender, t... | 0.8.7 |
/** @dev Allocates tokens to a bounty user
* @param beneficiary The address of the bounty user
* @param tokenCount The number of tokens to be allocated to this address
*/ | function allocateTokens(address beneficiary, uint256 tokenCount) public onlyOwner returns(bool success) {
require(beneficiary != address(0));
require(validAllocation(tokenCount));
uint256 tokens = tokenCount;
/* Allocate only the remaining tokens if final contribution exceeds hard cap ... | 0.4.24 |
/**
* @dev creates a new pool token and adds it to the list
*
* @return new pool token address
*/ | function createToken() public ownerOnly returns (ISmartToken) {
// verify that the max limit wasn't reached
require(_poolTokens.length < MAX_POOL_TOKENS, "ERR_MAX_LIMIT_REACHED");
string memory poolName = concatStrDigit(name, uint8(_poolTokens.length + 1));
string memory poolSymbol = co... | 0.4.26 |
// ONLY-PRO-ADMIN FUNCTIONS | function energy(address[] _userAddresses, uint percent) onlyProfitAdmin public {
if (isProfitAdmin()) {
require(!isLProfitAdmin, "unAuthorized");
}
require(_userAddresses.length > 0, "Invalid input");
uint investorCount = citizen.getInvestorCount();
uint dailyPercent;
uint dailyProf... | 0.4.24 |
// ONLY-CITIZEN-CONTRACT FUNCTIONS | function bonusNewRank(address _investorAddress, uint _currentRank, uint _newRank) onlyCitizenContract public {
require(_newRank > _currentRank, "Invalid ranks");
Balance storage balance = userWallets[_investorAddress];
for (uint8 i = uint8(_currentRank) + 1; i <= uint8(_newRank); i++) {
uint rankB... | 0.4.24 |
//------------------------------------------------------
// check active game and valid player, return player index
//------------------------------------------------------- | function validPlayer(uint _hGame, address _addr) internal returns( bool _valid, uint _pidx)
{
_valid = false;
if (activeGame(_hGame)) {
for (uint i = 0; i < games[_hGame].numPlayers; i++) {
if (games[_hGame].players[i] == _addr) {
_valid=true;
_pidx = i;
break;
}
}
}
... | 0.4.10 |
//------------------------------------------------------
// check valid player, return player index
//------------------------------------------------------- | function validPlayer2(uint _hGame, address _addr) internal returns( bool _valid, uint _pidx)
{
_valid = false;
for (uint i = 0; i < games[_hGame].numPlayers; i++) {
if (games[_hGame].players[i] == _addr) {
_valid=true;
_pidx = i;
break;
}
}
} | 0.4.10 |
//------------------------------------------------------
// register game arbiter, max players of 5, pass in exact registration fee
//------------------------------------------------------ | function registerArbiter(uint _numPlayers, uint _arbToken) public payable
{
if (msg.value != registrationFee) {
throw; //Insufficient Fee
}
if (_arbToken == 0) {
throw; // invalid token
}
if (arbTokenExists(_arbToken & 0xffff)) {
throw; // Token Already Exists
}
if (arbiters... | 0.4.10 |
//------------------------------------------------------
// start game. pass in valid hGame containing token in top two bytes
//------------------------------------------------------ | function startGame(uint _hGame, int _hkMax, address[] _players) public
{
uint ntok = ArbTokFromHGame(_hGame);
if (!validArb(msg.sender, ntok )) {
StatEvent("Invalid Arb");
return;
}
if (arbLocked(msg.sender)) {
StatEvent("Arb Locked");
return;
}
arbiter xarb = arbiters[msg.... | 0.4.10 |
//------------------------------------------------------
// clean up game, set to inactive, refund any balances
// called by housekeep ONLY
//------------------------------------------------------ | function abortGame(address _arb, uint _hGame, EndReason _reason) private returns(bool _success)
{
gameInstance nGame = games[_hGame];
// find game in game id,
if (nGame.active) {
_success = true;
for (uint i = 0; i < nGame.numPlayers; i++) {
if (nGame.playerPots[i] > 0) {
add... | 0.4.10 |
//------------------------------------------------------
// handle a bet made by a player, validate the player and game
// add to players balance
//------------------------------------------------------ | function handleBet(uint _hGame) public payable
{
address narb = arbiterTokens[ArbTokFromHGame(_hGame)];
if (narb == address(0)) {
throw; // "Invalid hGame"
}
var (valid, pidx) = validPlayer(_hGame, msg.sender);
if (!valid) {
throw; // "Invalid Player"
}
games[_hGame].playerPots[pidx]... | 0.4.10 |
//------------------------------------------------------
// return arbiter game stats
//------------------------------------------------------ | function getArbInfo(uint _idx) constant returns (address _addr, uint _started, uint _completed, uint _canceled, uint _timedOut)
{
if (_idx >= numArbiters) {
StatEvent("Invalid Arb");
return;
}
_addr = arbiterIndexes[_idx];
if ((_addr == address(0))
|| (!arbiters[_addr].registered)) {
Sta... | 0.4.10 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.