Unnamed: 0
int64 0
7.36k
| comments
stringlengths 3
35.2k
| code_string
stringlengths 1
527k
| code
stringlengths 1
527k
| __index_level_0__
int64 0
88.6k
|
---|---|---|---|---|
94 | // Pure function to get the name of the token.return The name of the token. / | function name() external pure returns (string memory) {
return _NAME;
}
| function name() external pure returns (string memory) {
return _NAME;
}
| 30,779 |
13 | // Repay the debts / | function repay() external {
uint _balance = underlying.balanceOf(address(this));
underlying.safeApprove(address(cy), _balance);
require(cy.repayBorrow(_balance) == 0, "repay failed");
}
| function repay() external {
uint _balance = underlying.balanceOf(address(this));
underlying.safeApprove(address(cy), _balance);
require(cy.repayBorrow(_balance) == 0, "repay failed");
}
| 79,773 |
12 | // Adds liquidity to the trading pool./At least one of nftIds or tokenAmount must be greater than zero./The caller must approve the Trading Pool contract to transfer the NFTs and ERC20 tokens./receiver The recipient of the liquidity pool tokens./nftIds The IDs of the NFTs being deposited./tokenAmount The amount of the ERC20 token being deposited./spotPrice The spot price of the liquidity pair being created./curve The pricing curve for the liquidity pair being created./delta The delta for the liquidity pair being created./fee The fee for the liquidity pair being created. | function addLiquidity(
address receiver,
DataTypes.LPType lpType,
uint256[] calldata nftIds,
uint256 tokenAmount,
uint256 spotPrice,
address curve,
uint256 delta,
uint256 fee
| function addLiquidity(
address receiver,
DataTypes.LPType lpType,
uint256[] calldata nftIds,
uint256 tokenAmount,
uint256 spotPrice,
address curve,
uint256 delta,
uint256 fee
| 43,229 |
10 | // Locks tokens into the claimable pool _amount Amount of tokens to be locked / | function _lockTokens(uint256 _amount) internal {
maxLockedTokens += _amount.mul(SCALAR); // Applies scalar for precision
(bool transferSuccess, ) = tokenAddress.call(
abi.encodeWithSignature(
"transferFrom(address,address,uint256)",
msg.sender,
address(this),
_amount
)
);
require(transferSuccess, "Cannot transfer ERC20");
}
| function _lockTokens(uint256 _amount) internal {
maxLockedTokens += _amount.mul(SCALAR); // Applies scalar for precision
(bool transferSuccess, ) = tokenAddress.call(
abi.encodeWithSignature(
"transferFrom(address,address,uint256)",
msg.sender,
address(this),
_amount
)
);
require(transferSuccess, "Cannot transfer ERC20");
}
| 11,453 |
53 | // fired after a recommit for a purchase | event Recommit(uint indexed id, address indexed user, uint count);
| event Recommit(uint indexed id, address indexed user, uint count);
| 2,095 |
7 | // Function to mint new communal token to given address with token URIto The address that will own the minted tokentokenURI string The token URI of the minted tokencommunal - set token communal, true or false return uint256 is token id of new created token | function mint(address to, string calldata, bool communal) external returns (uint256);
| function mint(address to, string calldata, bool communal) external returns (uint256);
| 45,607 |
431 | // Set the address of the Reward Control contract to be triggered to accrue ALK rewards for participants _rewardControl The address of the underlying reward control contractreturn uint 0=success, otherwise a failure (see ErrorReporter.sol for details) / | function setRewardControlAddress(address _rewardControl)
external
returns (uint256)
| function setRewardControlAddress(address _rewardControl)
external
returns (uint256)
| 74,193 |
345 | // Transactional reward | _userReward = _compoundRewards.mul(rateReward).div(100);
| _userReward = _compoundRewards.mul(rateReward).div(100);
| 14,313 |
29 | // Returns the minimum bond amount required to make an assertion. This is calculated as the final fee of thecurrency divided by the burnedBondPercentage. If burn percentage is 50% then the min bond is 2x the final fee. currency currency to calculate the minimum bond for.return minimum bond amount. / | function getMinimumBond(address currency) public view returns (uint256) {
uint256 finalFee = cachedCurrencies[currency].finalFee;
return (finalFee * 1e18) / burnedBondPercentage;
}
| function getMinimumBond(address currency) public view returns (uint256) {
uint256 finalFee = cachedCurrencies[currency].finalFee;
return (finalFee * 1e18) / burnedBondPercentage;
}
| 22,437 |
16 | // The internal function used by the `stake` and `addPool` functions./ See the `stake` public function for more details./_toPoolStakingAddress The staking address of the pool where the coins should be staked./_amount The amount of coins to be staked. | function _stake(address _toPoolStakingAddress, uint256 _amount) internal {
address staker = msg.sender;
_amount = msg.value;
_stake(_toPoolStakingAddress, staker, _amount);
}
| function _stake(address _toPoolStakingAddress, uint256 _amount) internal {
address staker = msg.sender;
_amount = msg.value;
_stake(_toPoolStakingAddress, staker, _amount);
}
| 15,145 |
2 | // Missing the given role or admin access | error Access_MissingRoleOrAdmin(bytes32 role);
| error Access_MissingRoleOrAdmin(bytes32 role);
| 37,939 |
9 | // Start address = buffer address + offset + sizeof(buffer length) | dest := add(add(bufptr, 32), off)
| dest := add(add(bufptr, 32), off)
| 18,486 |
10 | // Hippo can not be cloned more than its maximum clone number | require(hippo.numOfClones < hippo.maxNum, "It exceeds the maximum number of clones");
| require(hippo.numOfClones < hippo.maxNum, "It exceeds the maximum number of clones");
| 30,349 |
17 | // Users functions | modifier checkPermission(uint256 perm) {
require((permissions[msg.sender] & perm) > 0);
_;
}
| modifier checkPermission(uint256 perm) {
require((permissions[msg.sender] & perm) > 0);
_;
}
| 4,106 |
25 | // bet a users token against another users token | function betAgainstUser(uint _betId1, uint _betId2) public defcon3 returns(bool){
require(betBanks[_betId1].bet != emptyBet && betBanks[_betId2].bet != emptyBet);//require that both tokens are active and hold funds
require(betBanks[_betId1].owner == msg.sender || betBanks[_betId2].owner == msg.sender); //require that the user submitting is the owner of one of the tokens
require(betBanks[_betId1].owner != betBanks[_betId2].owner);//prevent a user from betting 2 tokens he owns, prevent possible exploits
require(_betId1 != _betId2);//require that user doesn't bet token against itself
//unhash the bets to calculate winner
uint bet1ConvertedAddr = uint(betBanks[_betId1].owner);
uint bet1 = (uint(betBanks[_betId1].bet)/7).sub(bet1ConvertedAddr);
uint bet2ConvertedAddr = uint(betBanks[_betId2].owner);
uint bet2 = (uint(betBanks[_betId2].bet)/7).sub(bet2ConvertedAddr);
uint take = (bet1).add(bet2);//calculate the total rewards for winning
uint fee = (take.mul(houseFee)).div(100);//calculate the fee
houseCommission = houseCommission.add(fee);//add fee to commission
if(bet1 != bet2) {//if no tie
if(bet1 > bet2) {//if betId1 wins
_payoutWinner(_betId1, _betId2, take, fee);//payout betId1
} else {
_payoutWinner(_betId2, _betId1, take, fee);//payout betId2
}
} else {//if its a tie
if(_random() == 0) {//choose a random winner
_payoutWinner(_betId1, _betId2, take, fee);//payout betId1
} else {
_payoutWinner(_betId2, _betId1, take, fee);//payout betId2
}
}
return true;
}
| function betAgainstUser(uint _betId1, uint _betId2) public defcon3 returns(bool){
require(betBanks[_betId1].bet != emptyBet && betBanks[_betId2].bet != emptyBet);//require that both tokens are active and hold funds
require(betBanks[_betId1].owner == msg.sender || betBanks[_betId2].owner == msg.sender); //require that the user submitting is the owner of one of the tokens
require(betBanks[_betId1].owner != betBanks[_betId2].owner);//prevent a user from betting 2 tokens he owns, prevent possible exploits
require(_betId1 != _betId2);//require that user doesn't bet token against itself
//unhash the bets to calculate winner
uint bet1ConvertedAddr = uint(betBanks[_betId1].owner);
uint bet1 = (uint(betBanks[_betId1].bet)/7).sub(bet1ConvertedAddr);
uint bet2ConvertedAddr = uint(betBanks[_betId2].owner);
uint bet2 = (uint(betBanks[_betId2].bet)/7).sub(bet2ConvertedAddr);
uint take = (bet1).add(bet2);//calculate the total rewards for winning
uint fee = (take.mul(houseFee)).div(100);//calculate the fee
houseCommission = houseCommission.add(fee);//add fee to commission
if(bet1 != bet2) {//if no tie
if(bet1 > bet2) {//if betId1 wins
_payoutWinner(_betId1, _betId2, take, fee);//payout betId1
} else {
_payoutWinner(_betId2, _betId1, take, fee);//payout betId2
}
} else {//if its a tie
if(_random() == 0) {//choose a random winner
_payoutWinner(_betId1, _betId2, take, fee);//payout betId1
} else {
_payoutWinner(_betId2, _betId1, take, fee);//payout betId2
}
}
return true;
}
| 11,343 |
136 | // Emits an {Approval} event. Requirements: - `owner` cannot be the zero address. - `spender` cannot be the zero address./ | function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
| function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
| 36,389 |
101 | // Token Geyser A smart-contract based mechanism to distribute tokens over time, inspired loosely by Compound and Uniswap.Distribution tokens are added to a locked pool in the contract and become unlocked over time according to a once-configurable unlock schedule. Once unlocked, they are available to be claimed by users.A user may deposit tokens to accrue ownership share over the unlocked pool. This owner share is a function of the number of tokens deposited as well as the length of time deposited. Specifically, a user's share of the currently-unlocked pool equals their "deposit-seconds" divided by the global "deposit-seconds". This aligns the new | contract TokenGeyser is IStaking, Ownable {
using SafeMath for uint256;
event Staked(address indexed user, uint256 amount, uint256 total, bytes data);
event Unstaked(address indexed user, uint256 amount, uint256 total, bytes data);
event TokensClaimed(address indexed user, uint256 amount);
event TokensLocked(uint256 amount, uint256 durationSec, uint256 total);
// amount: Unlocked tokens, total: Total locked tokens
event TokensUnlocked(uint256 amount, uint256 total);
TokenPool private _stakingPool;
TokenPool private _unlockedPool;
TokenPool private _lockedPool;
//
// Time-bonus params
//
uint256 public constant BONUS_DECIMALS = 2;
uint256 public startBonus = 0;
uint256 public bonusPeriodSec = 0;
//
// Global accounting state
//
uint256 public totalLockedShares = 0;
uint256 public totalStakingShares = 0;
uint256 private _totalStakingShareSeconds = 0;
uint256 private _lastAccountingTimestampSec = now;
uint256 private _maxUnlockSchedules = 0;
uint256 private _initialSharesPerToken = 0;
//
// User accounting state
//
// Represents a single stake for a user. A user may have multiple.
struct Stake {
uint256 stakingShares;
uint256 timestampSec;
}
// Caches aggregated values from the User->Stake[] map to save computation.
// If lastAccountingTimestampSec is 0, there's no entry for that user.
struct UserTotals {
uint256 stakingShares;
uint256 stakingShareSeconds;
uint256 lastAccountingTimestampSec;
}
// Aggregated staking values per user
mapping(address => UserTotals) private _userTotals;
// The collection of stakes for each user. Ordered by timestamp, earliest to latest.
mapping(address => Stake[]) private _userStakes;
//
// Locked/Unlocked Accounting state
//
struct UnlockSchedule {
uint256 initialLockedShares;
uint256 unlockedShares;
uint256 lastUnlockTimestampSec;
uint256 endAtSec;
uint256 durationSec;
}
UnlockSchedule[] public unlockSchedules;
/**
* @param stakingToken The token users deposit as stake.
* @param distributionToken The token users receive as they unstake.
* @param maxUnlockSchedules Max number of unlock stages, to guard against hitting gas limit.
* @param startBonus_ Starting time bonus, BONUS_DECIMALS fixed point.
* e.g. 25% means user gets 25% of max distribution tokens.
* @param bonusPeriodSec_ Length of time for bonus to increase linearly to max.
* @param initialSharesPerToken Number of shares to mint per staking token on first stake.
*/
constructor(IERC20 stakingToken, IERC20 distributionToken, uint256 maxUnlockSchedules,
uint256 startBonus_, uint256 bonusPeriodSec_, uint256 initialSharesPerToken) public {
// The start bonus must be some fraction of the max. (i.e. <= 100%)
require(startBonus_ <= 10**BONUS_DECIMALS, 'TokenGeyser: start bonus too high');
// If no period is desired, instead set startBonus = 100%
// and bonusPeriod to a small value like 1sec.
require(bonusPeriodSec_ != 0, 'TokenGeyser: bonus period is zero');
require(initialSharesPerToken > 0, 'TokenGeyser: initialSharesPerToken is zero');
_stakingPool = new TokenPool(stakingToken);
_unlockedPool = new TokenPool(distributionToken);
_lockedPool = new TokenPool(distributionToken);
startBonus = startBonus_;
bonusPeriodSec = bonusPeriodSec_;
_maxUnlockSchedules = maxUnlockSchedules;
_initialSharesPerToken = initialSharesPerToken;
}
/**
* Re-set constructor parameters in case of errors
*/
function resetConstructor(uint256 maxUnlockSchedules, uint256 startBonus_, uint256 bonusPeriodSec_, uint256 initialSharesPerToken) external onlyOwner{
startBonus = startBonus_;
bonusPeriodSec = bonusPeriodSec_;
_maxUnlockSchedules = maxUnlockSchedules;
_initialSharesPerToken = initialSharesPerToken;
}
/**
* @return The token users deposit as stake.
*/
function getStakingToken() public view returns (IERC20) {
return _stakingPool.token();
}
/**
* @return The token users receive as they unstake.
*/
function getDistributionToken() public view returns (IERC20) {
assert(_unlockedPool.token() == _lockedPool.token());
return _unlockedPool.token();
}
/**
* @dev Transfers amount of deposit tokens from the user.
* @param amount Number of deposit tokens to stake.
*/
function stake(uint256 amount) external {
_stakeFor(msg.sender, msg.sender, amount);
}
/**
* @dev Transfers amount of deposit tokens from the caller on behalf of user.
* @param user User address who gains credit for this stake operation.
* @param amount Number of deposit tokens to stake.
*/
function stakeFor(address user, uint256 amount) external onlyOwner {
_stakeFor(msg.sender, user, amount);
}
/**
* @dev Private implementation of staking methods.
* @param staker User address who deposits tokens to stake.
* @param beneficiary User address who gains credit for this stake operation.
* @param amount Number of deposit tokens to stake.
*/
function _stakeFor(address staker, address beneficiary, uint256 amount) private {
require(amount > 0, 'TokenGeyser: stake amount is zero');
require(beneficiary != address(0), 'TokenGeyser: beneficiary is zero address');
require(totalStakingShares == 0 || totalStaked() > 0,
'TokenGeyser: Invalid state. Staking shares exist, but no staking tokens do');
uint256 mintedStakingShares = (totalStakingShares > 0)
? totalStakingShares.mul(amount).div(totalStaked())
: amount.mul(_initialSharesPerToken);
require(mintedStakingShares > 0, 'TokenGeyser: Stake amount is too small');
updateAccounting();
// 1. User Accounting
UserTotals storage totals = _userTotals[beneficiary];
totals.stakingShares = totals.stakingShares.add(mintedStakingShares);
totals.lastAccountingTimestampSec = now;
Stake memory newStake = Stake(mintedStakingShares, now);
_userStakes[beneficiary].push(newStake);
// 2. Global Accounting
totalStakingShares = totalStakingShares.add(mintedStakingShares);
// Already set in updateAccounting()
// _lastAccountingTimestampSec = now;
// interactions
require(_stakingPool.token().transferFrom(staker, address(_stakingPool), amount),
'TokenGeyser: transfer into staking pool failed');
emit Staked(beneficiary, amount, totalStakedFor(beneficiary), "");
}
/**
* @dev Unstakes a certain amount of previously deposited tokens. User also receives their
* alotted number of distribution tokens.
* @param amount Number of deposit tokens to unstake / withdraw.
*/
function unstake(uint256 amount) external {
_unstake(amount);
}
/**
* @param amount Number of deposit tokens to unstake / withdraw.
* @return The total number of distribution tokens that would be rewarded.
*/
function unstakeQuery(uint256 amount) public returns (uint256) {
return _unstake(amount);
}
/**
* @dev Unstakes a certain amount of previously deposited tokens. User also receives their
* alotted number of distribution tokens.
* @param amount Number of deposit tokens to unstake / withdraw.
* @return The total number of distribution tokens rewarded.
*/
function _unstake(uint256 amount) private returns (uint256) {
updateAccounting();
// checks
require(amount > 0, 'TokenGeyser: unstake amount is zero');
require(totalStakedFor(msg.sender) >= amount,
'TokenGeyser: unstake amount is greater than total user stakes');
uint256 stakingSharesToBurn = totalStakingShares.mul(amount).div(totalStaked());
require(stakingSharesToBurn > 0, 'TokenGeyser: Unable to unstake amount this small');
// 1. User Accounting
UserTotals storage totals = _userTotals[msg.sender];
Stake[] storage accountStakes = _userStakes[msg.sender];
// Redeem from most recent stake and go backwards in time.
uint256 stakingShareSecondsToBurn = 0;
uint256 sharesLeftToBurn = stakingSharesToBurn;
uint256 rewardAmount = 0;
while (sharesLeftToBurn > 0) {
Stake storage lastStake = accountStakes[accountStakes.length - 1];
uint256 stakeTimeSec = now.sub(lastStake.timestampSec);
uint256 newStakingShareSecondsToBurn = 0;
if (lastStake.stakingShares <= sharesLeftToBurn) {
// fully redeem a past stake
newStakingShareSecondsToBurn = lastStake.stakingShares.mul(stakeTimeSec);
rewardAmount = computeNewReward(rewardAmount, newStakingShareSecondsToBurn, stakeTimeSec);
stakingShareSecondsToBurn = stakingShareSecondsToBurn.add(newStakingShareSecondsToBurn);
sharesLeftToBurn = sharesLeftToBurn.sub(lastStake.stakingShares);
accountStakes.length--;
} else {
// partially redeem a past stake
newStakingShareSecondsToBurn = sharesLeftToBurn.mul(stakeTimeSec);
rewardAmount = computeNewReward(rewardAmount, newStakingShareSecondsToBurn, stakeTimeSec);
stakingShareSecondsToBurn = stakingShareSecondsToBurn.add(newStakingShareSecondsToBurn);
lastStake.stakingShares = lastStake.stakingShares.sub(sharesLeftToBurn);
sharesLeftToBurn = 0;
}
}
totals.stakingShareSeconds = totals.stakingShareSeconds.sub(stakingShareSecondsToBurn);
totals.stakingShares = totals.stakingShares.sub(stakingSharesToBurn);
// Already set in updateAccounting
// totals.lastAccountingTimestampSec = now;
// 2. Global Accounting
_totalStakingShareSeconds = _totalStakingShareSeconds.sub(stakingShareSecondsToBurn);
totalStakingShares = totalStakingShares.sub(stakingSharesToBurn);
// Already set in updateAccounting
// _lastAccountingTimestampSec = now;
// interactions
require(_stakingPool.transfer(msg.sender, amount),
'TokenGeyser: transfer out of staking pool failed');
require(_unlockedPool.transfer(msg.sender, rewardAmount),
'TokenGeyser: transfer out of unlocked pool failed');
emit Unstaked(msg.sender, amount, totalStakedFor(msg.sender), "");
emit TokensClaimed(msg.sender, rewardAmount);
require(totalStakingShares == 0 || totalStaked() > 0,
"TokenGeyser: Error unstaking. Staking shares exist, but no staking tokens do");
return rewardAmount;
}
/**
* @dev Applies an additional time-bonus to a distribution amount. This is necessary to
* encourage long-term deposits instead of constant unstake/restakes.
* The bonus-multiplier is the result of a linear function that starts at startBonus and
* ends at 100% over bonusPeriodSec, then stays at 100% thereafter.
* @param currentRewardTokens The current number of distribution tokens already alotted for this
* unstake op. Any bonuses are already applied.
* @param stakingShareSeconds The stakingShare-seconds that are being burned for new
* distribution tokens.
* @param stakeTimeSec Length of time for which the tokens were staked. Needed to calculate
* the time-bonus.
* @return Updated amount of distribution tokens to award, with any bonus included on the
* newly added tokens.
*/
function computeNewReward(uint256 currentRewardTokens,
uint256 stakingShareSeconds,
uint256 stakeTimeSec) private view returns (uint256) {
uint256 newRewardTokens =
totalUnlocked()
.mul(stakingShareSeconds)
.div(_totalStakingShareSeconds);
if (stakeTimeSec >= bonusPeriodSec) {
return currentRewardTokens.add(newRewardTokens);
}
uint256 oneHundredPct = 10**BONUS_DECIMALS;
uint256 bonusedReward =
startBonus
.add(oneHundredPct.sub(startBonus).mul(stakeTimeSec).div(bonusPeriodSec))
.mul(newRewardTokens)
.div(oneHundredPct);
return currentRewardTokens.add(bonusedReward);
}
// getUserTotals, getTotalStakingShareSeconds, getLastAccountingTimestamp functions added for Flow Protocol
/**
* @param addr The user to look up staking information for.
* @return The UserStakes for this address.
*/
function getUserStakes(address addr) public view returns (Stake[] memory){
Stake[] memory userStakes = _userStakes[addr];
return userStakes;
}
/**
* @param addr The user to look up staking information for.
* @return The UserTotals for this address.
*/
function getUserTotals(address addr) public view returns (UserTotals memory) {
UserTotals memory userTotals = _userTotals[addr];
return userTotals;
}
/**
* @return The total staking share seconds.
*/
function getTotalStakingShareSeconds() public view returns (uint256) {
return _totalStakingShareSeconds;
}
/**
* @return The last global accounting timestamp.
*/
function getLastAccountingTimestamp() public view returns (uint256) {
return _lastAccountingTimestampSec;
}
/**
* @param addr The user to look up staking information for.
* @return The number of staking tokens deposited for addr.
*/
function totalStakedFor(address addr) public view returns (uint256) {
return totalStakingShares > 0 ?
totalStaked().mul(_userTotals[addr].stakingShares).div(totalStakingShares) : 0;
}
/**
* @return The total number of deposit tokens staked globally, by all users.
*/
function totalStaked() public view returns (uint256) {
return _stakingPool.balance();
}
/**
* @dev Note that this application has a staking token as well as a distribution token, which
* may be different. This function is required by EIP-900.
* @return The deposit token used for staking.
*/
function token() external view returns (address) {
return address(getStakingToken());
}
/**
* @dev A globally callable function to update the accounting state of the system.
* Global state and state for the caller are updated.
* @return [0] balance of the locked pool
* @return [1] balance of the unlocked pool
* @return [2] caller's staking share seconds
* @return [3] global staking share seconds
* @return [4] Rewards caller has accumulated, optimistically assumes max time-bonus.
* @return [5] block timestamp
*/
function updateAccounting() public returns (
uint256, uint256, uint256, uint256, uint256, uint256) {
unlockTokens();
// Global accounting
uint256 newStakingShareSeconds =
now
.sub(_lastAccountingTimestampSec)
.mul(totalStakingShares);
_totalStakingShareSeconds = _totalStakingShareSeconds.add(newStakingShareSeconds);
_lastAccountingTimestampSec = now;
// User Accounting
UserTotals storage totals = _userTotals[msg.sender];
uint256 newUserStakingShareSeconds =
now
.sub(totals.lastAccountingTimestampSec)
.mul(totals.stakingShares);
totals.stakingShareSeconds =
totals.stakingShareSeconds
.add(newUserStakingShareSeconds);
totals.lastAccountingTimestampSec = now;
uint256 totalUserRewards = (_totalStakingShareSeconds > 0)
? totalUnlocked().mul(totals.stakingShareSeconds).div(_totalStakingShareSeconds)
: 0;
return (
totalLocked(),
totalUnlocked(),
totals.stakingShareSeconds,
_totalStakingShareSeconds,
totalUserRewards,
now
);
}
/**
* @return Total number of locked distribution tokens.
*/
function totalLocked() public view returns (uint256) {
return _lockedPool.balance();
}
/**
* @return Total number of unlocked distribution tokens.
*/
function totalUnlocked() public view returns (uint256) {
return _unlockedPool.balance();
}
/**
* @return Number of unlock schedules.
*/
function unlockScheduleCount() public view returns (uint256) {
return unlockSchedules.length;
}
/**
* @dev This funcion allows the contract owner to add more locked distribution tokens, along
* with the associated "unlock schedule". These locked tokens immediately begin unlocking
* linearly over the duraction of durationSec timeframe.
* @param amount Number of distribution tokens to lock. These are transferred from the caller.
* @param durationSec Length of time to linear unlock the tokens.
*/
function lockTokens(uint256 amount, uint256 durationSec) external onlyOwner {
require(unlockSchedules.length < _maxUnlockSchedules,
'TokenGeyser: reached maximum unlock schedules');
// Update lockedTokens amount before using it in computations after.
updateAccounting();
uint256 lockedTokens = totalLocked();
uint256 mintedLockedShares = (lockedTokens > 0)
? totalLockedShares.mul(amount).div(lockedTokens)
: amount.mul(_initialSharesPerToken);
UnlockSchedule memory schedule;
schedule.initialLockedShares = mintedLockedShares;
schedule.lastUnlockTimestampSec = now;
schedule.endAtSec = now.add(durationSec);
schedule.durationSec = durationSec;
unlockSchedules.push(schedule);
totalLockedShares = totalLockedShares.add(mintedLockedShares);
require(_lockedPool.token().transferFrom(msg.sender, address(_lockedPool), amount),
'TokenGeyser: transfer into locked pool failed');
emit TokensLocked(amount, durationSec, totalLocked());
}
/**
* @dev Moves distribution tokens from the locked pool to the unlocked pool, according to the
* previously defined unlock schedules. Publicly callable.
* @return Number of newly unlocked distribution tokens.
*/
function unlockTokens() public returns (uint256) {
uint256 unlockedTokens = 0;
uint256 lockedTokens = totalLocked();
if (totalLockedShares == 0) {
unlockedTokens = lockedTokens;
} else {
uint256 unlockedShares = 0;
for (uint256 s = 0; s < unlockSchedules.length; s++) {
unlockedShares = unlockedShares.add(unlockScheduleShares(s));
}
unlockedTokens = unlockedShares.mul(lockedTokens).div(totalLockedShares);
totalLockedShares = totalLockedShares.sub(unlockedShares);
}
if (unlockedTokens > 0) {
require(_lockedPool.transfer(address(_unlockedPool), unlockedTokens),
'TokenGeyser: transfer out of locked pool failed');
emit TokensUnlocked(unlockedTokens, totalLocked());
}
return unlockedTokens;
}
/**
* @dev Returns the number of unlockable shares from a given schedule. The returned value
* depends on the time since the last unlock. This function updates schedule accounting,
* but does not actually transfer any tokens.
* @param s Index of the unlock schedule.
* @return The number of unlocked shares.
*/
function unlockScheduleShares(uint256 s) private returns (uint256) {
UnlockSchedule storage schedule = unlockSchedules[s];
if(schedule.unlockedShares >= schedule.initialLockedShares) {
return 0;
}
uint256 sharesToUnlock = 0;
// Special case to handle any leftover dust from integer division
if (now >= schedule.endAtSec) {
sharesToUnlock = (schedule.initialLockedShares.sub(schedule.unlockedShares));
schedule.lastUnlockTimestampSec = schedule.endAtSec;
} else {
sharesToUnlock = now.sub(schedule.lastUnlockTimestampSec)
.mul(schedule.initialLockedShares)
.div(schedule.durationSec);
schedule.lastUnlockTimestampSec = now;
}
schedule.unlockedShares = schedule.unlockedShares.add(sharesToUnlock);
return sharesToUnlock;
}
} | contract TokenGeyser is IStaking, Ownable {
using SafeMath for uint256;
event Staked(address indexed user, uint256 amount, uint256 total, bytes data);
event Unstaked(address indexed user, uint256 amount, uint256 total, bytes data);
event TokensClaimed(address indexed user, uint256 amount);
event TokensLocked(uint256 amount, uint256 durationSec, uint256 total);
// amount: Unlocked tokens, total: Total locked tokens
event TokensUnlocked(uint256 amount, uint256 total);
TokenPool private _stakingPool;
TokenPool private _unlockedPool;
TokenPool private _lockedPool;
//
// Time-bonus params
//
uint256 public constant BONUS_DECIMALS = 2;
uint256 public startBonus = 0;
uint256 public bonusPeriodSec = 0;
//
// Global accounting state
//
uint256 public totalLockedShares = 0;
uint256 public totalStakingShares = 0;
uint256 private _totalStakingShareSeconds = 0;
uint256 private _lastAccountingTimestampSec = now;
uint256 private _maxUnlockSchedules = 0;
uint256 private _initialSharesPerToken = 0;
//
// User accounting state
//
// Represents a single stake for a user. A user may have multiple.
struct Stake {
uint256 stakingShares;
uint256 timestampSec;
}
// Caches aggregated values from the User->Stake[] map to save computation.
// If lastAccountingTimestampSec is 0, there's no entry for that user.
struct UserTotals {
uint256 stakingShares;
uint256 stakingShareSeconds;
uint256 lastAccountingTimestampSec;
}
// Aggregated staking values per user
mapping(address => UserTotals) private _userTotals;
// The collection of stakes for each user. Ordered by timestamp, earliest to latest.
mapping(address => Stake[]) private _userStakes;
//
// Locked/Unlocked Accounting state
//
struct UnlockSchedule {
uint256 initialLockedShares;
uint256 unlockedShares;
uint256 lastUnlockTimestampSec;
uint256 endAtSec;
uint256 durationSec;
}
UnlockSchedule[] public unlockSchedules;
/**
* @param stakingToken The token users deposit as stake.
* @param distributionToken The token users receive as they unstake.
* @param maxUnlockSchedules Max number of unlock stages, to guard against hitting gas limit.
* @param startBonus_ Starting time bonus, BONUS_DECIMALS fixed point.
* e.g. 25% means user gets 25% of max distribution tokens.
* @param bonusPeriodSec_ Length of time for bonus to increase linearly to max.
* @param initialSharesPerToken Number of shares to mint per staking token on first stake.
*/
constructor(IERC20 stakingToken, IERC20 distributionToken, uint256 maxUnlockSchedules,
uint256 startBonus_, uint256 bonusPeriodSec_, uint256 initialSharesPerToken) public {
// The start bonus must be some fraction of the max. (i.e. <= 100%)
require(startBonus_ <= 10**BONUS_DECIMALS, 'TokenGeyser: start bonus too high');
// If no period is desired, instead set startBonus = 100%
// and bonusPeriod to a small value like 1sec.
require(bonusPeriodSec_ != 0, 'TokenGeyser: bonus period is zero');
require(initialSharesPerToken > 0, 'TokenGeyser: initialSharesPerToken is zero');
_stakingPool = new TokenPool(stakingToken);
_unlockedPool = new TokenPool(distributionToken);
_lockedPool = new TokenPool(distributionToken);
startBonus = startBonus_;
bonusPeriodSec = bonusPeriodSec_;
_maxUnlockSchedules = maxUnlockSchedules;
_initialSharesPerToken = initialSharesPerToken;
}
/**
* Re-set constructor parameters in case of errors
*/
function resetConstructor(uint256 maxUnlockSchedules, uint256 startBonus_, uint256 bonusPeriodSec_, uint256 initialSharesPerToken) external onlyOwner{
startBonus = startBonus_;
bonusPeriodSec = bonusPeriodSec_;
_maxUnlockSchedules = maxUnlockSchedules;
_initialSharesPerToken = initialSharesPerToken;
}
/**
* @return The token users deposit as stake.
*/
function getStakingToken() public view returns (IERC20) {
return _stakingPool.token();
}
/**
* @return The token users receive as they unstake.
*/
function getDistributionToken() public view returns (IERC20) {
assert(_unlockedPool.token() == _lockedPool.token());
return _unlockedPool.token();
}
/**
* @dev Transfers amount of deposit tokens from the user.
* @param amount Number of deposit tokens to stake.
*/
function stake(uint256 amount) external {
_stakeFor(msg.sender, msg.sender, amount);
}
/**
* @dev Transfers amount of deposit tokens from the caller on behalf of user.
* @param user User address who gains credit for this stake operation.
* @param amount Number of deposit tokens to stake.
*/
function stakeFor(address user, uint256 amount) external onlyOwner {
_stakeFor(msg.sender, user, amount);
}
/**
* @dev Private implementation of staking methods.
* @param staker User address who deposits tokens to stake.
* @param beneficiary User address who gains credit for this stake operation.
* @param amount Number of deposit tokens to stake.
*/
function _stakeFor(address staker, address beneficiary, uint256 amount) private {
require(amount > 0, 'TokenGeyser: stake amount is zero');
require(beneficiary != address(0), 'TokenGeyser: beneficiary is zero address');
require(totalStakingShares == 0 || totalStaked() > 0,
'TokenGeyser: Invalid state. Staking shares exist, but no staking tokens do');
uint256 mintedStakingShares = (totalStakingShares > 0)
? totalStakingShares.mul(amount).div(totalStaked())
: amount.mul(_initialSharesPerToken);
require(mintedStakingShares > 0, 'TokenGeyser: Stake amount is too small');
updateAccounting();
// 1. User Accounting
UserTotals storage totals = _userTotals[beneficiary];
totals.stakingShares = totals.stakingShares.add(mintedStakingShares);
totals.lastAccountingTimestampSec = now;
Stake memory newStake = Stake(mintedStakingShares, now);
_userStakes[beneficiary].push(newStake);
// 2. Global Accounting
totalStakingShares = totalStakingShares.add(mintedStakingShares);
// Already set in updateAccounting()
// _lastAccountingTimestampSec = now;
// interactions
require(_stakingPool.token().transferFrom(staker, address(_stakingPool), amount),
'TokenGeyser: transfer into staking pool failed');
emit Staked(beneficiary, amount, totalStakedFor(beneficiary), "");
}
/**
* @dev Unstakes a certain amount of previously deposited tokens. User also receives their
* alotted number of distribution tokens.
* @param amount Number of deposit tokens to unstake / withdraw.
*/
function unstake(uint256 amount) external {
_unstake(amount);
}
/**
* @param amount Number of deposit tokens to unstake / withdraw.
* @return The total number of distribution tokens that would be rewarded.
*/
function unstakeQuery(uint256 amount) public returns (uint256) {
return _unstake(amount);
}
/**
* @dev Unstakes a certain amount of previously deposited tokens. User also receives their
* alotted number of distribution tokens.
* @param amount Number of deposit tokens to unstake / withdraw.
* @return The total number of distribution tokens rewarded.
*/
function _unstake(uint256 amount) private returns (uint256) {
updateAccounting();
// checks
require(amount > 0, 'TokenGeyser: unstake amount is zero');
require(totalStakedFor(msg.sender) >= amount,
'TokenGeyser: unstake amount is greater than total user stakes');
uint256 stakingSharesToBurn = totalStakingShares.mul(amount).div(totalStaked());
require(stakingSharesToBurn > 0, 'TokenGeyser: Unable to unstake amount this small');
// 1. User Accounting
UserTotals storage totals = _userTotals[msg.sender];
Stake[] storage accountStakes = _userStakes[msg.sender];
// Redeem from most recent stake and go backwards in time.
uint256 stakingShareSecondsToBurn = 0;
uint256 sharesLeftToBurn = stakingSharesToBurn;
uint256 rewardAmount = 0;
while (sharesLeftToBurn > 0) {
Stake storage lastStake = accountStakes[accountStakes.length - 1];
uint256 stakeTimeSec = now.sub(lastStake.timestampSec);
uint256 newStakingShareSecondsToBurn = 0;
if (lastStake.stakingShares <= sharesLeftToBurn) {
// fully redeem a past stake
newStakingShareSecondsToBurn = lastStake.stakingShares.mul(stakeTimeSec);
rewardAmount = computeNewReward(rewardAmount, newStakingShareSecondsToBurn, stakeTimeSec);
stakingShareSecondsToBurn = stakingShareSecondsToBurn.add(newStakingShareSecondsToBurn);
sharesLeftToBurn = sharesLeftToBurn.sub(lastStake.stakingShares);
accountStakes.length--;
} else {
// partially redeem a past stake
newStakingShareSecondsToBurn = sharesLeftToBurn.mul(stakeTimeSec);
rewardAmount = computeNewReward(rewardAmount, newStakingShareSecondsToBurn, stakeTimeSec);
stakingShareSecondsToBurn = stakingShareSecondsToBurn.add(newStakingShareSecondsToBurn);
lastStake.stakingShares = lastStake.stakingShares.sub(sharesLeftToBurn);
sharesLeftToBurn = 0;
}
}
totals.stakingShareSeconds = totals.stakingShareSeconds.sub(stakingShareSecondsToBurn);
totals.stakingShares = totals.stakingShares.sub(stakingSharesToBurn);
// Already set in updateAccounting
// totals.lastAccountingTimestampSec = now;
// 2. Global Accounting
_totalStakingShareSeconds = _totalStakingShareSeconds.sub(stakingShareSecondsToBurn);
totalStakingShares = totalStakingShares.sub(stakingSharesToBurn);
// Already set in updateAccounting
// _lastAccountingTimestampSec = now;
// interactions
require(_stakingPool.transfer(msg.sender, amount),
'TokenGeyser: transfer out of staking pool failed');
require(_unlockedPool.transfer(msg.sender, rewardAmount),
'TokenGeyser: transfer out of unlocked pool failed');
emit Unstaked(msg.sender, amount, totalStakedFor(msg.sender), "");
emit TokensClaimed(msg.sender, rewardAmount);
require(totalStakingShares == 0 || totalStaked() > 0,
"TokenGeyser: Error unstaking. Staking shares exist, but no staking tokens do");
return rewardAmount;
}
/**
* @dev Applies an additional time-bonus to a distribution amount. This is necessary to
* encourage long-term deposits instead of constant unstake/restakes.
* The bonus-multiplier is the result of a linear function that starts at startBonus and
* ends at 100% over bonusPeriodSec, then stays at 100% thereafter.
* @param currentRewardTokens The current number of distribution tokens already alotted for this
* unstake op. Any bonuses are already applied.
* @param stakingShareSeconds The stakingShare-seconds that are being burned for new
* distribution tokens.
* @param stakeTimeSec Length of time for which the tokens were staked. Needed to calculate
* the time-bonus.
* @return Updated amount of distribution tokens to award, with any bonus included on the
* newly added tokens.
*/
function computeNewReward(uint256 currentRewardTokens,
uint256 stakingShareSeconds,
uint256 stakeTimeSec) private view returns (uint256) {
uint256 newRewardTokens =
totalUnlocked()
.mul(stakingShareSeconds)
.div(_totalStakingShareSeconds);
if (stakeTimeSec >= bonusPeriodSec) {
return currentRewardTokens.add(newRewardTokens);
}
uint256 oneHundredPct = 10**BONUS_DECIMALS;
uint256 bonusedReward =
startBonus
.add(oneHundredPct.sub(startBonus).mul(stakeTimeSec).div(bonusPeriodSec))
.mul(newRewardTokens)
.div(oneHundredPct);
return currentRewardTokens.add(bonusedReward);
}
// getUserTotals, getTotalStakingShareSeconds, getLastAccountingTimestamp functions added for Flow Protocol
/**
* @param addr The user to look up staking information for.
* @return The UserStakes for this address.
*/
function getUserStakes(address addr) public view returns (Stake[] memory){
Stake[] memory userStakes = _userStakes[addr];
return userStakes;
}
/**
* @param addr The user to look up staking information for.
* @return The UserTotals for this address.
*/
function getUserTotals(address addr) public view returns (UserTotals memory) {
UserTotals memory userTotals = _userTotals[addr];
return userTotals;
}
/**
* @return The total staking share seconds.
*/
function getTotalStakingShareSeconds() public view returns (uint256) {
return _totalStakingShareSeconds;
}
/**
* @return The last global accounting timestamp.
*/
function getLastAccountingTimestamp() public view returns (uint256) {
return _lastAccountingTimestampSec;
}
/**
* @param addr The user to look up staking information for.
* @return The number of staking tokens deposited for addr.
*/
function totalStakedFor(address addr) public view returns (uint256) {
return totalStakingShares > 0 ?
totalStaked().mul(_userTotals[addr].stakingShares).div(totalStakingShares) : 0;
}
/**
* @return The total number of deposit tokens staked globally, by all users.
*/
function totalStaked() public view returns (uint256) {
return _stakingPool.balance();
}
/**
* @dev Note that this application has a staking token as well as a distribution token, which
* may be different. This function is required by EIP-900.
* @return The deposit token used for staking.
*/
function token() external view returns (address) {
return address(getStakingToken());
}
/**
* @dev A globally callable function to update the accounting state of the system.
* Global state and state for the caller are updated.
* @return [0] balance of the locked pool
* @return [1] balance of the unlocked pool
* @return [2] caller's staking share seconds
* @return [3] global staking share seconds
* @return [4] Rewards caller has accumulated, optimistically assumes max time-bonus.
* @return [5] block timestamp
*/
function updateAccounting() public returns (
uint256, uint256, uint256, uint256, uint256, uint256) {
unlockTokens();
// Global accounting
uint256 newStakingShareSeconds =
now
.sub(_lastAccountingTimestampSec)
.mul(totalStakingShares);
_totalStakingShareSeconds = _totalStakingShareSeconds.add(newStakingShareSeconds);
_lastAccountingTimestampSec = now;
// User Accounting
UserTotals storage totals = _userTotals[msg.sender];
uint256 newUserStakingShareSeconds =
now
.sub(totals.lastAccountingTimestampSec)
.mul(totals.stakingShares);
totals.stakingShareSeconds =
totals.stakingShareSeconds
.add(newUserStakingShareSeconds);
totals.lastAccountingTimestampSec = now;
uint256 totalUserRewards = (_totalStakingShareSeconds > 0)
? totalUnlocked().mul(totals.stakingShareSeconds).div(_totalStakingShareSeconds)
: 0;
return (
totalLocked(),
totalUnlocked(),
totals.stakingShareSeconds,
_totalStakingShareSeconds,
totalUserRewards,
now
);
}
/**
* @return Total number of locked distribution tokens.
*/
function totalLocked() public view returns (uint256) {
return _lockedPool.balance();
}
/**
* @return Total number of unlocked distribution tokens.
*/
function totalUnlocked() public view returns (uint256) {
return _unlockedPool.balance();
}
/**
* @return Number of unlock schedules.
*/
function unlockScheduleCount() public view returns (uint256) {
return unlockSchedules.length;
}
/**
* @dev This funcion allows the contract owner to add more locked distribution tokens, along
* with the associated "unlock schedule". These locked tokens immediately begin unlocking
* linearly over the duraction of durationSec timeframe.
* @param amount Number of distribution tokens to lock. These are transferred from the caller.
* @param durationSec Length of time to linear unlock the tokens.
*/
function lockTokens(uint256 amount, uint256 durationSec) external onlyOwner {
require(unlockSchedules.length < _maxUnlockSchedules,
'TokenGeyser: reached maximum unlock schedules');
// Update lockedTokens amount before using it in computations after.
updateAccounting();
uint256 lockedTokens = totalLocked();
uint256 mintedLockedShares = (lockedTokens > 0)
? totalLockedShares.mul(amount).div(lockedTokens)
: amount.mul(_initialSharesPerToken);
UnlockSchedule memory schedule;
schedule.initialLockedShares = mintedLockedShares;
schedule.lastUnlockTimestampSec = now;
schedule.endAtSec = now.add(durationSec);
schedule.durationSec = durationSec;
unlockSchedules.push(schedule);
totalLockedShares = totalLockedShares.add(mintedLockedShares);
require(_lockedPool.token().transferFrom(msg.sender, address(_lockedPool), amount),
'TokenGeyser: transfer into locked pool failed');
emit TokensLocked(amount, durationSec, totalLocked());
}
/**
* @dev Moves distribution tokens from the locked pool to the unlocked pool, according to the
* previously defined unlock schedules. Publicly callable.
* @return Number of newly unlocked distribution tokens.
*/
function unlockTokens() public returns (uint256) {
uint256 unlockedTokens = 0;
uint256 lockedTokens = totalLocked();
if (totalLockedShares == 0) {
unlockedTokens = lockedTokens;
} else {
uint256 unlockedShares = 0;
for (uint256 s = 0; s < unlockSchedules.length; s++) {
unlockedShares = unlockedShares.add(unlockScheduleShares(s));
}
unlockedTokens = unlockedShares.mul(lockedTokens).div(totalLockedShares);
totalLockedShares = totalLockedShares.sub(unlockedShares);
}
if (unlockedTokens > 0) {
require(_lockedPool.transfer(address(_unlockedPool), unlockedTokens),
'TokenGeyser: transfer out of locked pool failed');
emit TokensUnlocked(unlockedTokens, totalLocked());
}
return unlockedTokens;
}
/**
* @dev Returns the number of unlockable shares from a given schedule. The returned value
* depends on the time since the last unlock. This function updates schedule accounting,
* but does not actually transfer any tokens.
* @param s Index of the unlock schedule.
* @return The number of unlocked shares.
*/
function unlockScheduleShares(uint256 s) private returns (uint256) {
UnlockSchedule storage schedule = unlockSchedules[s];
if(schedule.unlockedShares >= schedule.initialLockedShares) {
return 0;
}
uint256 sharesToUnlock = 0;
// Special case to handle any leftover dust from integer division
if (now >= schedule.endAtSec) {
sharesToUnlock = (schedule.initialLockedShares.sub(schedule.unlockedShares));
schedule.lastUnlockTimestampSec = schedule.endAtSec;
} else {
sharesToUnlock = now.sub(schedule.lastUnlockTimestampSec)
.mul(schedule.initialLockedShares)
.div(schedule.durationSec);
schedule.lastUnlockTimestampSec = now;
}
schedule.unlockedShares = schedule.unlockedShares.add(sharesToUnlock);
return sharesToUnlock;
}
} | 9,845 |
64 | // Gyouji: Kuma Matsuri | uint256 taxGonValue = gonValue.div(100).mul(_taxFeeKumaGyouji);
_gonBalances[from] = _gonBalances[from].sub(gonValue);
_gonBalances[to] = _gonBalances[to].add(gonValue.sub(taxGonValue));
_gonBalances[address(this)] = _gonBalances[address(this)].add(
taxGonValue
);
emit Transfer(
from,
to,
| uint256 taxGonValue = gonValue.div(100).mul(_taxFeeKumaGyouji);
_gonBalances[from] = _gonBalances[from].sub(gonValue);
_gonBalances[to] = _gonBalances[to].add(gonValue.sub(taxGonValue));
_gonBalances[address(this)] = _gonBalances[address(this)].add(
taxGonValue
);
emit Transfer(
from,
to,
| 21,885 |
2 | // Reentrancy Guard | bool private _entered;
bool public _eventSend;
Destinations public destinations;
uint256 public nextCycleStartTime;
bool private isLogicContract;
modifier onlyAdmin() {
| bool private _entered;
bool public _eventSend;
Destinations public destinations;
uint256 public nextCycleStartTime;
bool private isLogicContract;
modifier onlyAdmin() {
| 31,812 |
27 | // Returns orders array length. / | function getOrdersLength() public view override returns (uint256) {
return orders.length;
}
| function getOrdersLength() public view override returns (uint256) {
return orders.length;
}
| 20,563 |
20 | // Call overridden function Modify in this contract | Modify(description, price);
| Modify(description, price);
| 10,998 |
427 | // 所有 | // function MaxAssetToTarget(address user) external view returns(uint256) {
// uint256 buildRatio = mConfig.getUint(mConfig.BUILD_RATIO());
// uint256 totalCollateral = collaterSys.GetUserTotalCollateralInUsd(user);
// }
| // function MaxAssetToTarget(address user) external view returns(uint256) {
// uint256 buildRatio = mConfig.getUint(mConfig.BUILD_RATIO());
// uint256 totalCollateral = collaterSys.GetUserTotalCollateralInUsd(user);
// }
| 42,877 |
69 | // List of token default partitions (for ERC20 compatibility). | bytes32 internal _defaultPartition;
| bytes32 internal _defaultPartition;
| 2,160 |
74 | // Withdrawing ETH | if (_currency == address(0)) {
payable(owner()).transfer(_amount);
} else {
| if (_currency == address(0)) {
payable(owner()).transfer(_amount);
} else {
| 73,895 |
11 | // Enter the NFT raffle | function enterRaffle(uint256 _numTickets) external payable nftHeld {
if (block.timestamp > endTime) {
revert RaffleNotOpen();
}
if (_numTickets <= 0) {
revert InvalidTicketAmount();
}
if (msg.value < ticketFee * _numTickets) {
revert InsufficientAmount();
}
for (uint256 i = 0; i < _numTickets; i++) {
players.push(payable(msg.sender));
}
playerTickets[msg.sender] += _numTickets;
emit RaffleEntered(msg.sender, _numTickets);
}
| function enterRaffle(uint256 _numTickets) external payable nftHeld {
if (block.timestamp > endTime) {
revert RaffleNotOpen();
}
if (_numTickets <= 0) {
revert InvalidTicketAmount();
}
if (msg.value < ticketFee * _numTickets) {
revert InsufficientAmount();
}
for (uint256 i = 0; i < _numTickets; i++) {
players.push(payable(msg.sender));
}
playerTickets[msg.sender] += _numTickets;
emit RaffleEntered(msg.sender, _numTickets);
}
| 24,762 |
307 | // Emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel) | emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel);
return uint(Error.NO_ERROR);
| emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel);
return uint(Error.NO_ERROR);
| 30,959 |
14 | // Meta-transactions override for OpenSea. / | function _msgSender() internal override view returns (address) {
return ContextMixin.msgSender();
}
| function _msgSender() internal override view returns (address) {
return ContextMixin.msgSender();
}
| 10,660 |
240 | // Calculates time elapsed rounded down to the nearest interestPeriod / | function calculateEffectiveTimeElapsedForNewLender(
Position storage position,
uint256 timestamp
)
private
view
returns (uint256)
| function calculateEffectiveTimeElapsedForNewLender(
Position storage position,
uint256 timestamp
)
private
view
returns (uint256)
| 24,510 |
15 | // Number of NFTs minted | uint256 public nftCount = 0;
| uint256 public nftCount = 0;
| 8,479 |
37 | // Bid in an active auction. _auctionId The ID of the auction to bid in._bidAmount The bid amount in the currency specified by the auction. / | function bidInAuction(uint256 _auctionId, uint256 _bidAmount) external payable;
| function bidInAuction(uint256 _auctionId, uint256 _bidAmount) external payable;
| 26,778 |
44 | // Import and refactor of Synthetix StakingRewarder/Calculates and pays out rewards/bitbeckers/MVP release/ @custom:source This is an experimental contract. @custom:source https:github.com/Synthetixio/synthetix/blob/develop/contracts/StakingRewards.sol | contract Rewarder is ReentrancyGuard, Pausable, IRewarder, AccessControl {
bytes32 public constant CONFIG_ROLE = keccak256("CONFIG_ROLE");
bytes32 public constant REWARD_MINTER_ROLE = keccak256("REWARD_MINTER_ROLE");
using Counters for Counters.Counter;
using SafeMath for uint256;
using SafeERC20 for IERC20;
address public token;
address public stoa;
address public treasury;
uint256 public sagePathThreshold;
mapping(address => Staker) private _stakers;
mapping(address => mapping(uint256 => Stake)) public _stakes;
mapping(uint256 => StakePool) public _stakingPools;
uint256 private _totalStaked;
uint256 private _totalAllocationPoints = 100;
Counters.Counter public sagepathUsers;
Counters.Counter public low;
Counters.Counter public mid;
Counters.Counter public high;
Counters.Counter public stoic;
struct Staker {
bool exists;
uint256 totalBalance;
bool sagePathUser;
uint256 sagepathTimestamp;
}
struct Stake {
bool exists;
uint256 balance;
uint256 timestamp;
uint256 rewards;
uint256 userRewardPerTokenPaid;
}
struct StakePool {
bool exists;
uint256 balance;
uint256 lastUpdateTime;
uint256 allocationPoints;
uint256 rewardPerTokenStored;
uint256 rewardRate;
}
constructor(
address _owner,
address _tokenAddress,
address _stoaData,
address _treasuryAddress,
uint256 _sagePathThreshold
) {
token = _tokenAddress;
stoa = _stoaData;
treasury = _treasuryAddress;
sagePathThreshold = _sagePathThreshold;
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
_grantRole(DEFAULT_ADMIN_ROLE, _owner);
}
// Event
event AvailableRewardsUpdated(uint256 added, uint256 totalSupply);
event RewardPaid(string rewardType, address account, uint256 amount);
event BatchRewardPaid(string rewardType, uint256 accountCount, uint256 amount, uint256 firstSecondOfDay);
event Staked(address indexed user, uint256 amount, uint256 duration);
event Withdrawn(address indexed user, uint256 amount, uint256 duration);
event Recovered(address token, uint256 amount);
event SagePathUpdated(uint256 threshold);
event StakingPoolUpdated(uint256 duration, bool exists, uint256 allocationPoints);
// Views
function rewardsToken() external view returns (address _rewardsToken) {
return token;
}
// Base rewards
function getBaseReward(address user) public view returns (uint256 rewardAmount) {
uint256 timeSinceLastClaim = block.timestamp.sub(_stoa().getLastClaimed(user));
uint256 periodsSinceLastClaimed = _stoa().getPeriodsSince(_stoa().getLastClaimed(user));
uint256 periodIndex = _stoa().getPeriodIndex();
uint256 periodDuration = _stoa().getPeriodDuration();
rewardAmount = 0;
if (timeSinceLastClaim <= 0) {
return rewardAmount;
}
if (periodsSinceLastClaimed == 0 || periodIndex == 1) {
rewardAmount += _stoa().getBaseRewardRateForPeriod(periodIndex).div(_stoa().getUserCount(periodIndex)).mul(
timeSinceLastClaim
);
} else {
for (uint256 i = periodsSinceLastClaimed; i > 0; i--) {
uint256 _period = periodIndex - i;
if (i == periodsSinceLastClaimed) {
uint256 timeInFirstPeriod = timeSinceLastClaim % periodDuration;
rewardAmount += _stoa().getBaseRewardRateForPeriod(_period).div(_stoa().getUserCount(_period)).mul(
timeInFirstPeriod
);
} else {
rewardAmount += _stoa().getBaseRewardRateForPeriod(_period).div(_stoa().getUserCount(_period)).mul(
periodDuration
);
}
}
rewardAmount += _stoa().getBaseRewardRateForPeriod(periodIndex).div(_stoa().getUserCount(periodIndex)).mul(
periodDuration
);
}
return rewardAmount;
}
// Staking
function totalStaked() external view returns (uint256 amount) {
amount = _totalStaked;
}
function getStakedBalance(address account, uint256 duration) public view returns (uint256 totalBalance) {
totalBalance = _stakes[account][duration].balance;
}
function getStakingReward(address user, uint256 duration)
external
view
override
returns (uint256 totalAvailable, uint256 rewardAmount)
{
return rewardsEarned(user, duration);
}
function rewardsEarned(address user, uint256 duration)
internal
view
onlyValidStakeDuration(duration)
returns (uint256 totalAvailable, uint256 rewardAmount)
{
Stake storage _stake = _stakes[user][duration];
totalAvailable = 0;
rewardAmount = 0;
if (!_stake.exists && !isSagePathUser(user)) {
return (totalAvailable, rewardAmount);
}
uint256 timeStaked = block.timestamp - _stake.timestamp;
totalAvailable =
((_stake.balance * (_getRewardPerToken(duration) - _stake.userRewardPerTokenPaid)) / 1e18) +
_stake.rewards;
rewardAmount = totalAvailable;
if (!_isActiveUser(user) || (duration == 0 && timeStaked <= 30 days) || (timeStaked < duration * 1 days)) {
rewardAmount = totalAvailable / 2;
}
return (totalAvailable, rewardAmount);
}
// Accomplishment
function getAccomplishmentReward(address user) public view returns (uint256 totalAvailable, uint256 rewardAmount) {
totalAvailable = 0;
rewardAmount = 0;
if (!isSagePathUser(user)) {
return (totalAvailable, rewardAmount);
}
uint256 periodsSinceLastClaimed = _stoa().getPeriodsSince(_stoa().getLastClaimed(user));
uint256 _periodIndex = _stoa().getPeriodIndex();
if (periodsSinceLastClaimed > 0) {
for (uint256 i = periodsSinceLastClaimed; i >= 1; --i) {
totalAvailable += _calculateAccomplishmentReward(user, _periodIndex - i);
}
rewardAmount = totalAvailable;
}
if (!_isActiveUser(user)) {
rewardAmount = totalAvailable / 2;
}
return (totalAvailable, rewardAmount);
}
// Sage path
function isSagePathUser(address user) public view returns (bool isIndeed) {
return _meetsSagePathThreshold(user);
}
function getSagepathCount() public view returns (uint256 sagepathCount) {
return sagepathUsers.current();
}
// Mutative functions
// Claims
function claimRewards(uint256[] calldata stakingPools) public nonReentrant onlySagePath whenNotPaused {
uint256 stakingRewards = 0;
(, uint256 accomplishmentRewards) = getAccomplishmentReward(msg.sender);
for (uint256 i = 0; i < stakingPools.length; i++) {
// Get pool
uint256 duration = stakingPools[i];
StakePool storage stakingPool = _stakingPools[duration];
require(stakingPool.exists, "Staking pool does not exist");
// Update rewards
stakingPool.rewardPerTokenStored = _getRewardPerToken(duration);
stakingPool.lastUpdateTime = block.timestamp;
if (msg.sender != address(0)) {
Stake storage _stake = _stakes[msg.sender][duration];
(, uint256 rewardAmount) = rewardsEarned(msg.sender, duration);
_stake.rewards = 0;
_stake.userRewardPerTokenPaid = stakingPool.rewardPerTokenStored;
stakingRewards += rewardAmount;
}
}
uint256 totalRewards = stakingRewards + accomplishmentRewards;
_stoa().notifyRewardsPaid(msg.sender, totalRewards, _stoa().getPeriodIndex());
_token().mintReward(msg.sender, totalRewards);
emit RewardPaid("StakingRewards", msg.sender, stakingRewards);
emit RewardPaid("AccomplishmentRewards", msg.sender, accomplishmentRewards);
}
function batchClaimBaseRewards(
address[] calldata users,
uint256[] calldata amounts,
uint256 firstSecondOfDay,
uint256 periodIndex
) external nonReentrant onlyRole(REWARD_MINTER_ROLE) whenNotPaused {
require(firstSecondOfDay <= (block.timestamp - 1 days), "Only past rewards");
uint256 totalSpent = 0;
for (uint256 i = 0; i < users.length; i++) {
_stoa().notifyRewardsPaid(users[i], amounts[i], periodIndex);
_token().mintReward(users[i], amounts[i]);
totalSpent += amounts[i];
}
emit BatchRewardPaid("BatchRewards", users.length, totalSpent, firstSecondOfDay);
}
// Staking
function stake(uint256 amount, uint256 duration)
external
nonReentrant
whenNotPaused
onlyValidStakeDuration(duration)
updateReward(msg.sender, duration)
{
require(amount > 0, "Cannot stake 0");
//Stake
Stake storage _stake = _stakes[msg.sender][duration];
if (duration > 0) {
require(!_stake.exists, "Already staked");
}
_stake.balance += amount;
_stake.exists = true;
_stake.timestamp = block.timestamp;
//Stakepool
_stakingPools[duration].balance += amount;
_totalStaked += amount;
//Staker
Staker storage staker = _stakers[msg.sender];
if (!staker.exists) {
staker.exists = true;
}
staker.totalBalance += amount;
//Sagepath
if (!staker.sagePathUser && _meetsSagePathThreshold(msg.sender)) {
staker.sagePathUser = true;
staker.sagepathTimestamp = block.timestamp;
sagepathUsers.increment();
}
IERC20(token).safeTransferFrom(msg.sender, address(this), amount);
emit Staked(msg.sender, amount, duration);
}
function withdraw(uint256 amount, uint256 duration) public nonReentrant updateReward(msg.sender, duration) {
require(amount > 0, "Cannot withdraw 0");
//Stake
Stake storage _stake = _stakes[msg.sender][duration];
require(_stake.exists, "Nothing staked");
require(
_stake.balance > 0 && amount <= _stake.balance,
"Cannot withdraw more than staked in this pool, if any"
);
_stake.balance -= amount;
if (_stake.balance == 0) {
_stake.exists = false;
}
// Stakepool
StakePool storage stakePool = _stakingPools[duration];
stakePool.balance -= amount;
//Staker
Staker storage staker = _stakers[msg.sender];
staker.totalBalance -= amount;
_totalStaked -= amount;
if (staker.sagePathUser == true && !_meetsSagePathThreshold(msg.sender)) {
staker.sagePathUser = false;
staker.sagepathTimestamp = 0;
sagepathUsers.decrement();
}
IERC20(token).safeTransfer(msg.sender, amount);
emit Withdrawn(msg.sender, amount, duration);
}
function exit(uint256[] calldata stakingPools) external whenNotPaused {
if (_meetsSagePathThreshold(msg.sender)) {
claimRewards(stakingPools);
}
for (uint256 i = 0; i < stakingPools.length; i++) {
uint256 duration = stakingPools[i];
withdraw(_stakes[msg.sender][duration].balance, duration);
}
}
// Internal
function _meetsSagePathThreshold(address user) internal view returns (bool passed) {
return _stakes[user][0].balance >= sagePathThreshold;
}
function _calculateAccomplishmentReward(address user, uint256 periodIndex) internal view returns (uint256 amount) {
uint256 lvl = _stoa().getAccomplishmentLevel(user, periodIndex);
(uint256 bronze, uint256 silver, uint256 gold) = _stoa().getAccomplishments(periodIndex);
if (lvl == 1) {
return amount = _stoa().getAccomplishmentRewardsForPeriod(periodIndex).mul(15).div(100).div(bronze);
}
if (lvl == 2) {
return amount = _stoa().getAccomplishmentRewardsForPeriod(periodIndex).mul(30).div(100).div(silver);
}
if (lvl == 3) {
return amount = _stoa().getAccomplishmentRewardsForPeriod(periodIndex).mul(55).div(100).div(gold);
}
return amount = 0;
}
function _getRewardRateForStakingPool(uint256 duration, uint256 allocationPoints)
internal
view
returns (uint256 rewardRate)
{
rewardRate = duration == 0
? _stoa().getStakingRewardRateForPeriod(_stoa().getPeriodIndex())
: _stoa()
.getCommitmentRewardsForPeriod(_stoa().getPeriodIndex())
.mul(allocationPoints)
.div(_totalAllocationPoints)
.div(_stoa().getPeriodDuration());
}
function _isActiveUser(address user) internal view returns (bool isActive) {
(, uint256 timestamp) = _stoa().getLatestMeditation(user, _stoa().getPeriodIndex());
return block.timestamp - timestamp <= 7 days;
}
function _getRewardPerToken(uint256 duration) internal view returns (uint256) {
StakePool storage stakingPool = _stakingPools[duration];
if (stakingPool.balance == 0) {
return stakingPool.rewardPerTokenStored;
}
return
stakingPool.rewardPerTokenStored +
(((block.timestamp - stakingPool.lastUpdateTime) * stakingPool.rewardRate * 1e18) / stakingPool.balance);
}
// Config
function setSagePathThreshold(uint256 _value) public onlyRole(CONFIG_ROLE) {
sagePathThreshold = _value;
emit SagePathUpdated(sagePathThreshold);
}
function updateStakingPool(
uint256 duration,
bool exists,
uint256 allocationPoints
) external onlyRole(CONFIG_ROLE) {
StakePool storage stakePool = _stakingPools[duration];
stakePool.exists = exists;
stakePool.allocationPoints = allocationPoints;
stakePool.lastUpdateTime = block.timestamp;
stakePool.rewardRate = _getRewardRateForStakingPool(duration, allocationPoints);
emit StakingPoolUpdated(duration, exists, allocationPoints);
}
function pause() external onlyRole(CONFIG_ROLE) {
_pause();
}
function unPause() external onlyRole(CONFIG_ROLE) {
_unpause();
}
// Modifiers
modifier updateReward(address user, uint256 duration) {
StakePool storage stakingPool = _stakingPools[duration];
require(stakingPool.exists, "Staking pool does not exist");
stakingPool.rewardPerTokenStored = _getRewardPerToken(duration);
stakingPool.lastUpdateTime = block.timestamp;
if (user != address(0)) {
Stake storage _stake = _stakes[user][duration];
(uint256 totalAvailable, ) = rewardsEarned(user, duration);
_stake.rewards = totalAvailable;
_stake.userRewardPerTokenPaid = stakingPool.rewardPerTokenStored;
}
_;
}
modifier onlySagePath() {
require(isSagePathUser(msg.sender), "Not a sage path user");
_;
}
modifier onlyValidStakeDuration(uint256 duration) {
require(_stakingPools[duration].exists, "Invalid staking period duration");
_;
}
// System
function _stoa() internal view returns (ISTOA) {
return ISTOA(stoa);
}
function _treasury() internal view returns (address) {
return treasury;
}
function _token() internal view returns (IStoaToken) {
return IStoaToken(token);
}
}
| contract Rewarder is ReentrancyGuard, Pausable, IRewarder, AccessControl {
bytes32 public constant CONFIG_ROLE = keccak256("CONFIG_ROLE");
bytes32 public constant REWARD_MINTER_ROLE = keccak256("REWARD_MINTER_ROLE");
using Counters for Counters.Counter;
using SafeMath for uint256;
using SafeERC20 for IERC20;
address public token;
address public stoa;
address public treasury;
uint256 public sagePathThreshold;
mapping(address => Staker) private _stakers;
mapping(address => mapping(uint256 => Stake)) public _stakes;
mapping(uint256 => StakePool) public _stakingPools;
uint256 private _totalStaked;
uint256 private _totalAllocationPoints = 100;
Counters.Counter public sagepathUsers;
Counters.Counter public low;
Counters.Counter public mid;
Counters.Counter public high;
Counters.Counter public stoic;
struct Staker {
bool exists;
uint256 totalBalance;
bool sagePathUser;
uint256 sagepathTimestamp;
}
struct Stake {
bool exists;
uint256 balance;
uint256 timestamp;
uint256 rewards;
uint256 userRewardPerTokenPaid;
}
struct StakePool {
bool exists;
uint256 balance;
uint256 lastUpdateTime;
uint256 allocationPoints;
uint256 rewardPerTokenStored;
uint256 rewardRate;
}
constructor(
address _owner,
address _tokenAddress,
address _stoaData,
address _treasuryAddress,
uint256 _sagePathThreshold
) {
token = _tokenAddress;
stoa = _stoaData;
treasury = _treasuryAddress;
sagePathThreshold = _sagePathThreshold;
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
_grantRole(DEFAULT_ADMIN_ROLE, _owner);
}
// Event
event AvailableRewardsUpdated(uint256 added, uint256 totalSupply);
event RewardPaid(string rewardType, address account, uint256 amount);
event BatchRewardPaid(string rewardType, uint256 accountCount, uint256 amount, uint256 firstSecondOfDay);
event Staked(address indexed user, uint256 amount, uint256 duration);
event Withdrawn(address indexed user, uint256 amount, uint256 duration);
event Recovered(address token, uint256 amount);
event SagePathUpdated(uint256 threshold);
event StakingPoolUpdated(uint256 duration, bool exists, uint256 allocationPoints);
// Views
function rewardsToken() external view returns (address _rewardsToken) {
return token;
}
// Base rewards
function getBaseReward(address user) public view returns (uint256 rewardAmount) {
uint256 timeSinceLastClaim = block.timestamp.sub(_stoa().getLastClaimed(user));
uint256 periodsSinceLastClaimed = _stoa().getPeriodsSince(_stoa().getLastClaimed(user));
uint256 periodIndex = _stoa().getPeriodIndex();
uint256 periodDuration = _stoa().getPeriodDuration();
rewardAmount = 0;
if (timeSinceLastClaim <= 0) {
return rewardAmount;
}
if (periodsSinceLastClaimed == 0 || periodIndex == 1) {
rewardAmount += _stoa().getBaseRewardRateForPeriod(periodIndex).div(_stoa().getUserCount(periodIndex)).mul(
timeSinceLastClaim
);
} else {
for (uint256 i = periodsSinceLastClaimed; i > 0; i--) {
uint256 _period = periodIndex - i;
if (i == periodsSinceLastClaimed) {
uint256 timeInFirstPeriod = timeSinceLastClaim % periodDuration;
rewardAmount += _stoa().getBaseRewardRateForPeriod(_period).div(_stoa().getUserCount(_period)).mul(
timeInFirstPeriod
);
} else {
rewardAmount += _stoa().getBaseRewardRateForPeriod(_period).div(_stoa().getUserCount(_period)).mul(
periodDuration
);
}
}
rewardAmount += _stoa().getBaseRewardRateForPeriod(periodIndex).div(_stoa().getUserCount(periodIndex)).mul(
periodDuration
);
}
return rewardAmount;
}
// Staking
function totalStaked() external view returns (uint256 amount) {
amount = _totalStaked;
}
function getStakedBalance(address account, uint256 duration) public view returns (uint256 totalBalance) {
totalBalance = _stakes[account][duration].balance;
}
function getStakingReward(address user, uint256 duration)
external
view
override
returns (uint256 totalAvailable, uint256 rewardAmount)
{
return rewardsEarned(user, duration);
}
function rewardsEarned(address user, uint256 duration)
internal
view
onlyValidStakeDuration(duration)
returns (uint256 totalAvailable, uint256 rewardAmount)
{
Stake storage _stake = _stakes[user][duration];
totalAvailable = 0;
rewardAmount = 0;
if (!_stake.exists && !isSagePathUser(user)) {
return (totalAvailable, rewardAmount);
}
uint256 timeStaked = block.timestamp - _stake.timestamp;
totalAvailable =
((_stake.balance * (_getRewardPerToken(duration) - _stake.userRewardPerTokenPaid)) / 1e18) +
_stake.rewards;
rewardAmount = totalAvailable;
if (!_isActiveUser(user) || (duration == 0 && timeStaked <= 30 days) || (timeStaked < duration * 1 days)) {
rewardAmount = totalAvailable / 2;
}
return (totalAvailable, rewardAmount);
}
// Accomplishment
function getAccomplishmentReward(address user) public view returns (uint256 totalAvailable, uint256 rewardAmount) {
totalAvailable = 0;
rewardAmount = 0;
if (!isSagePathUser(user)) {
return (totalAvailable, rewardAmount);
}
uint256 periodsSinceLastClaimed = _stoa().getPeriodsSince(_stoa().getLastClaimed(user));
uint256 _periodIndex = _stoa().getPeriodIndex();
if (periodsSinceLastClaimed > 0) {
for (uint256 i = periodsSinceLastClaimed; i >= 1; --i) {
totalAvailable += _calculateAccomplishmentReward(user, _periodIndex - i);
}
rewardAmount = totalAvailable;
}
if (!_isActiveUser(user)) {
rewardAmount = totalAvailable / 2;
}
return (totalAvailable, rewardAmount);
}
// Sage path
function isSagePathUser(address user) public view returns (bool isIndeed) {
return _meetsSagePathThreshold(user);
}
function getSagepathCount() public view returns (uint256 sagepathCount) {
return sagepathUsers.current();
}
// Mutative functions
// Claims
function claimRewards(uint256[] calldata stakingPools) public nonReentrant onlySagePath whenNotPaused {
uint256 stakingRewards = 0;
(, uint256 accomplishmentRewards) = getAccomplishmentReward(msg.sender);
for (uint256 i = 0; i < stakingPools.length; i++) {
// Get pool
uint256 duration = stakingPools[i];
StakePool storage stakingPool = _stakingPools[duration];
require(stakingPool.exists, "Staking pool does not exist");
// Update rewards
stakingPool.rewardPerTokenStored = _getRewardPerToken(duration);
stakingPool.lastUpdateTime = block.timestamp;
if (msg.sender != address(0)) {
Stake storage _stake = _stakes[msg.sender][duration];
(, uint256 rewardAmount) = rewardsEarned(msg.sender, duration);
_stake.rewards = 0;
_stake.userRewardPerTokenPaid = stakingPool.rewardPerTokenStored;
stakingRewards += rewardAmount;
}
}
uint256 totalRewards = stakingRewards + accomplishmentRewards;
_stoa().notifyRewardsPaid(msg.sender, totalRewards, _stoa().getPeriodIndex());
_token().mintReward(msg.sender, totalRewards);
emit RewardPaid("StakingRewards", msg.sender, stakingRewards);
emit RewardPaid("AccomplishmentRewards", msg.sender, accomplishmentRewards);
}
function batchClaimBaseRewards(
address[] calldata users,
uint256[] calldata amounts,
uint256 firstSecondOfDay,
uint256 periodIndex
) external nonReentrant onlyRole(REWARD_MINTER_ROLE) whenNotPaused {
require(firstSecondOfDay <= (block.timestamp - 1 days), "Only past rewards");
uint256 totalSpent = 0;
for (uint256 i = 0; i < users.length; i++) {
_stoa().notifyRewardsPaid(users[i], amounts[i], periodIndex);
_token().mintReward(users[i], amounts[i]);
totalSpent += amounts[i];
}
emit BatchRewardPaid("BatchRewards", users.length, totalSpent, firstSecondOfDay);
}
// Staking
function stake(uint256 amount, uint256 duration)
external
nonReentrant
whenNotPaused
onlyValidStakeDuration(duration)
updateReward(msg.sender, duration)
{
require(amount > 0, "Cannot stake 0");
//Stake
Stake storage _stake = _stakes[msg.sender][duration];
if (duration > 0) {
require(!_stake.exists, "Already staked");
}
_stake.balance += amount;
_stake.exists = true;
_stake.timestamp = block.timestamp;
//Stakepool
_stakingPools[duration].balance += amount;
_totalStaked += amount;
//Staker
Staker storage staker = _stakers[msg.sender];
if (!staker.exists) {
staker.exists = true;
}
staker.totalBalance += amount;
//Sagepath
if (!staker.sagePathUser && _meetsSagePathThreshold(msg.sender)) {
staker.sagePathUser = true;
staker.sagepathTimestamp = block.timestamp;
sagepathUsers.increment();
}
IERC20(token).safeTransferFrom(msg.sender, address(this), amount);
emit Staked(msg.sender, amount, duration);
}
function withdraw(uint256 amount, uint256 duration) public nonReentrant updateReward(msg.sender, duration) {
require(amount > 0, "Cannot withdraw 0");
//Stake
Stake storage _stake = _stakes[msg.sender][duration];
require(_stake.exists, "Nothing staked");
require(
_stake.balance > 0 && amount <= _stake.balance,
"Cannot withdraw more than staked in this pool, if any"
);
_stake.balance -= amount;
if (_stake.balance == 0) {
_stake.exists = false;
}
// Stakepool
StakePool storage stakePool = _stakingPools[duration];
stakePool.balance -= amount;
//Staker
Staker storage staker = _stakers[msg.sender];
staker.totalBalance -= amount;
_totalStaked -= amount;
if (staker.sagePathUser == true && !_meetsSagePathThreshold(msg.sender)) {
staker.sagePathUser = false;
staker.sagepathTimestamp = 0;
sagepathUsers.decrement();
}
IERC20(token).safeTransfer(msg.sender, amount);
emit Withdrawn(msg.sender, amount, duration);
}
function exit(uint256[] calldata stakingPools) external whenNotPaused {
if (_meetsSagePathThreshold(msg.sender)) {
claimRewards(stakingPools);
}
for (uint256 i = 0; i < stakingPools.length; i++) {
uint256 duration = stakingPools[i];
withdraw(_stakes[msg.sender][duration].balance, duration);
}
}
// Internal
function _meetsSagePathThreshold(address user) internal view returns (bool passed) {
return _stakes[user][0].balance >= sagePathThreshold;
}
function _calculateAccomplishmentReward(address user, uint256 periodIndex) internal view returns (uint256 amount) {
uint256 lvl = _stoa().getAccomplishmentLevel(user, periodIndex);
(uint256 bronze, uint256 silver, uint256 gold) = _stoa().getAccomplishments(periodIndex);
if (lvl == 1) {
return amount = _stoa().getAccomplishmentRewardsForPeriod(periodIndex).mul(15).div(100).div(bronze);
}
if (lvl == 2) {
return amount = _stoa().getAccomplishmentRewardsForPeriod(periodIndex).mul(30).div(100).div(silver);
}
if (lvl == 3) {
return amount = _stoa().getAccomplishmentRewardsForPeriod(periodIndex).mul(55).div(100).div(gold);
}
return amount = 0;
}
function _getRewardRateForStakingPool(uint256 duration, uint256 allocationPoints)
internal
view
returns (uint256 rewardRate)
{
rewardRate = duration == 0
? _stoa().getStakingRewardRateForPeriod(_stoa().getPeriodIndex())
: _stoa()
.getCommitmentRewardsForPeriod(_stoa().getPeriodIndex())
.mul(allocationPoints)
.div(_totalAllocationPoints)
.div(_stoa().getPeriodDuration());
}
function _isActiveUser(address user) internal view returns (bool isActive) {
(, uint256 timestamp) = _stoa().getLatestMeditation(user, _stoa().getPeriodIndex());
return block.timestamp - timestamp <= 7 days;
}
function _getRewardPerToken(uint256 duration) internal view returns (uint256) {
StakePool storage stakingPool = _stakingPools[duration];
if (stakingPool.balance == 0) {
return stakingPool.rewardPerTokenStored;
}
return
stakingPool.rewardPerTokenStored +
(((block.timestamp - stakingPool.lastUpdateTime) * stakingPool.rewardRate * 1e18) / stakingPool.balance);
}
// Config
function setSagePathThreshold(uint256 _value) public onlyRole(CONFIG_ROLE) {
sagePathThreshold = _value;
emit SagePathUpdated(sagePathThreshold);
}
function updateStakingPool(
uint256 duration,
bool exists,
uint256 allocationPoints
) external onlyRole(CONFIG_ROLE) {
StakePool storage stakePool = _stakingPools[duration];
stakePool.exists = exists;
stakePool.allocationPoints = allocationPoints;
stakePool.lastUpdateTime = block.timestamp;
stakePool.rewardRate = _getRewardRateForStakingPool(duration, allocationPoints);
emit StakingPoolUpdated(duration, exists, allocationPoints);
}
function pause() external onlyRole(CONFIG_ROLE) {
_pause();
}
function unPause() external onlyRole(CONFIG_ROLE) {
_unpause();
}
// Modifiers
modifier updateReward(address user, uint256 duration) {
StakePool storage stakingPool = _stakingPools[duration];
require(stakingPool.exists, "Staking pool does not exist");
stakingPool.rewardPerTokenStored = _getRewardPerToken(duration);
stakingPool.lastUpdateTime = block.timestamp;
if (user != address(0)) {
Stake storage _stake = _stakes[user][duration];
(uint256 totalAvailable, ) = rewardsEarned(user, duration);
_stake.rewards = totalAvailable;
_stake.userRewardPerTokenPaid = stakingPool.rewardPerTokenStored;
}
_;
}
modifier onlySagePath() {
require(isSagePathUser(msg.sender), "Not a sage path user");
_;
}
modifier onlyValidStakeDuration(uint256 duration) {
require(_stakingPools[duration].exists, "Invalid staking period duration");
_;
}
// System
function _stoa() internal view returns (ISTOA) {
return ISTOA(stoa);
}
function _treasury() internal view returns (address) {
return treasury;
}
function _token() internal view returns (IStoaToken) {
return IStoaToken(token);
}
}
| 22,525 |
424 | // Oracle which gives the price of any given asset / | PriceOracle public oracle;
| PriceOracle public oracle;
| 7,598 |
3,794 | // 1899 | entry "neurocomputationally" : ENG_ADVERB
| entry "neurocomputationally" : ENG_ADVERB
| 22,735 |
124 | // Update dev address by the previous dev. | function dev(address _devaddr) public {
require(msg.sender == devaddr, "dev: wut?");
devaddr = _devaddr;
}
| function dev(address _devaddr) public {
require(msg.sender == devaddr, "dev: wut?");
devaddr = _devaddr;
}
| 6,097 |
143 | // function when someone gambles a.k.a sends ether to the contract | function buy() whenNotPaused payable public{
// No arguments are necessary, all
// information is already part of
// the transaction. The keyword payable
// is required for the function to
// be able to receive Ether.
// If the bet is not equal to the ante + the oracle price,
// send the money back.
require (msg.value >= ante + oracle_price);//give it back, revert state changes, abnormal stop
require (player_count <2); //make sure that the counter was reset
if(msg.value > (ante+oracle_price)) {
msg.sender.transfer(msg.value - ante - oracle_price); //If any extra eteher gets transferred return it back to the sender
}
player_count +=1;
if (player_count == 1) {
players.player1 = msg.sender;
}
if (player_count == 2) {
players.player2 = msg.sender;
ShowPlayers (players.player1,players.player2);
update();
player_count =0;
}
}
| function buy() whenNotPaused payable public{
// No arguments are necessary, all
// information is already part of
// the transaction. The keyword payable
// is required for the function to
// be able to receive Ether.
// If the bet is not equal to the ante + the oracle price,
// send the money back.
require (msg.value >= ante + oracle_price);//give it back, revert state changes, abnormal stop
require (player_count <2); //make sure that the counter was reset
if(msg.value > (ante+oracle_price)) {
msg.sender.transfer(msg.value - ante - oracle_price); //If any extra eteher gets transferred return it back to the sender
}
player_count +=1;
if (player_count == 1) {
players.player1 = msg.sender;
}
if (player_count == 2) {
players.player2 = msg.sender;
ShowPlayers (players.player1,players.player2);
update();
player_count =0;
}
}
| 51,840 |
27 | // Event fired each time an oracle submits a response | event FlightStatusInfo(
address airline,
string flight,
uint256 timestamp,
uint8 status
);
event OracleReport(
address airline,
string flight,
| event FlightStatusInfo(
address airline,
string flight,
uint256 timestamp,
uint8 status
);
event OracleReport(
address airline,
string flight,
| 308 |
0 | // restrict functions to just owner address | modifier onlyOwner {
AppStorage storage app = VotingPowerStorage.appStorage();
require(msg.sender == app.owner, "only owner");
_;
}
| modifier onlyOwner {
AppStorage storage app = VotingPowerStorage.appStorage();
require(msg.sender == app.owner, "only owner");
_;
}
| 8,495 |
62 | // | * function increaseAllowance(address spender, uint addedValue) public whenNotPaused returns (bool success) {
* return super.increaseAllowance(spender, addedValue);
* }
| * function increaseAllowance(address spender, uint addedValue) public whenNotPaused returns (bool success) {
* return super.increaseAllowance(spender, addedValue);
* }
| 24,288 |
30 | // Send this function the petIds of 6 of your Wild Hard (3 star pets) to receive 1 four star pet. | 45,973 |
||
0 | // Your subscription ID. | uint64 s_subscriptionId;
| uint64 s_subscriptionId;
| 19,710 |
13 | // Returns number of confirmations of a transaction./transactionId Transaction ID./ return Number of confirmations. | function getConfirmationCount(uint transactionId)
public
constant
delegated
returns (uint)
| function getConfirmationCount(uint transactionId)
public
constant
delegated
returns (uint)
| 31,788 |
197 | // import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { AddressArrayUtils } from "contracts/lib/AddressArrayUtils.sol"; import { ExplicitERC20 } from "contracts/lib/ExplicitERC20.sol"; import { IController } from "contracts/interfaces/IController.sol"; import { IModule } from "contracts/interfaces/IModule.sol"; import { ISetToken } from "contracts/interfaces/ISetToken.sol"; import { Invoke } from "contracts/protocol/lib/Invoke.sol"; import { Position } from "contracts/protocol/lib/Position.sol"; import { PreciseUnitMath } from "contracts/lib/PreciseUnitMath.sol"; import { ResourceIdentifier } from "contracts/protocol/lib/ResourceIdentifier.sol"; import { SafeCast } from "@openzeppelin/contracts/utils/SafeCast.sol"; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import { SignedSafeMath } from "@openzeppelin/contracts/math/SignedSafeMath.sol"; | using AddressArrayUtils for address[];
using Invoke for ISetToken;
using Position for ISetToken;
using PreciseUnitMath for uint256;
using ResourceIdentifier for IController;
using SafeCast for int256;
using SafeCast for uint256;
using SafeMath for uint256;
using SignedSafeMath for int256;
| using AddressArrayUtils for address[];
using Invoke for ISetToken;
using Position for ISetToken;
using PreciseUnitMath for uint256;
using ResourceIdentifier for IController;
using SafeCast for int256;
using SafeCast for uint256;
using SafeMath for uint256;
using SignedSafeMath for int256;
| 6,386 |
15 | // / | constructor(
uint256 tradeFee_,
address factory_,
address sushiRouter_
| constructor(
uint256 tradeFee_,
address factory_,
address sushiRouter_
| 1,967 |
16 | // 10% fees are for dev/dao/projects | token.mint(msg.sender, _reward);
emit Mined(nftId, _reward, msg.sender);
| token.mint(msg.sender, _reward);
emit Mined(nftId, _reward, msg.sender);
| 60,454 |
169 | // Minting costs | function setMintRate(uint256 _mintRate) public onlyOwner {
mintRate = _mintRate;
}
| function setMintRate(uint256 _mintRate) public onlyOwner {
mintRate = _mintRate;
}
| 24,183 |
38 | // leftTakerAssetAmountRemaining == rightMakerAssetAmountRemaining Case 3: Both orders are fully filled. Technically, this could be captured by the above cases, but this calculation will be more precise since it does not include rounding. | matchedFillResults = _calculateCompleteFillBoth(
leftMakerAssetAmountRemaining,
leftTakerAssetAmountRemaining,
rightMakerAssetAmountRemaining,
rightTakerAssetAmountRemaining
);
| matchedFillResults = _calculateCompleteFillBoth(
leftMakerAssetAmountRemaining,
leftTakerAssetAmountRemaining,
rightMakerAssetAmountRemaining,
rightTakerAssetAmountRemaining
);
| 47,941 |
21 | // function onERC721Received( address operator,address from,uint256 tokenId, | // bytes calldata data) external view override returns (bytes4) {
// require(address(whitelistedNftContract) == _msgSender());
// return IERC721Receiver.onERC721Received.selector;
// }
| // bytes calldata data) external view override returns (bytes4) {
// require(address(whitelistedNftContract) == _msgSender());
// return IERC721Receiver.onERC721Received.selector;
// }
| 7,956 |
113 | // Withdraw all assets from strategy sending assets to Vault. / | function withdrawAll() external;
| function withdrawAll() external;
| 5,694 |
56 | // src/IStakingRewards.sol/ pragma solidity 0.8.9; / | interface IStakingRewards {
// Views
function balanceOf(address account) external view returns (uint);
function earned(address account) external view returns (uint);
function getRewardForDuration() external view returns (uint);
function lastTimeRewardApplicable() external view returns (uint);
function rewardPerToken() external view returns (uint);
// function rewardsDistribution() external view returns (address);
// function rewardsToken() external view returns (address);
function totalSupply() external view returns (uint);
// Mutative
function exit() external;
function getReward() external;
function stake(uint amount) external;
function withdraw(uint amount) external;
}
| interface IStakingRewards {
// Views
function balanceOf(address account) external view returns (uint);
function earned(address account) external view returns (uint);
function getRewardForDuration() external view returns (uint);
function lastTimeRewardApplicable() external view returns (uint);
function rewardPerToken() external view returns (uint);
// function rewardsDistribution() external view returns (address);
// function rewardsToken() external view returns (address);
function totalSupply() external view returns (uint);
// Mutative
function exit() external;
function getReward() external;
function stake(uint amount) external;
function withdraw(uint amount) external;
}
| 27,207 |
130 | // Function to stop minting new tokens. return True if the operation was successful./ | function finishMinting() public onlyOwner canMint returns (bool) {
mintingFinished = true;
emit MintFinished();
return true;
}
| function finishMinting() public onlyOwner canMint returns (bool) {
mintingFinished = true;
emit MintFinished();
return true;
}
| 3,296 |
1 | // Check if the caller is the proxy admin. / | modifier onlyProxyAdmin(IGraphProxy _proxy) {
require(msg.sender == _proxy.admin(), "Caller must be the proxy admin");
_;
}
| modifier onlyProxyAdmin(IGraphProxy _proxy) {
require(msg.sender == _proxy.admin(), "Caller must be the proxy admin");
_;
}
| 1,553 |
184 | // Set setEulersFused. Can only be called by the owner. | function setEulersFused(uint256 _newEulersFused) public onlyOwner {
eulersFused = _newEulersFused;
}
| function setEulersFused(uint256 _newEulersFused) public onlyOwner {
eulersFused = _newEulersFused;
}
| 38,743 |
160 | // Get the current valid order for the asset or fail | Order memory order = _getValidOrder(_nftAddress, _assetId);
| Order memory order = _getValidOrder(_nftAddress, _assetId);
| 17,205 |
6 | // TODO: Create all Auctions through here. Right now we do it manually. This will be smoother. It will give us control over id's too (see next lineTODO: make Token IDS to be unique. By sha3 hash. so they can be stored in the graph. right now we just hardcode 1234 as the ID in migrations | function newAuction(uint256 id, string name) public{
// address newContract =
new Auction(msg.sender, id, name, this);
// acc = newContract;
}
| function newAuction(uint256 id, string name) public{
// address newContract =
new Auction(msg.sender, id, name, this);
// acc = newContract;
}
| 514 |
71 | // Position Manager cannot be zero. | error PositionManagerCannotBeZero();
| error PositionManagerCannotBeZero();
| 9,502 |
47 | // Interface for auction contract | bytes4 private constant InterfaceSignature_MarsGenesisAuction =
bytes4(keccak256('landIdIsForSale(uint256 tokenId)')) ^
bytes4(keccak256('landNoLongerForSale(uint256)'));
Counters.Counter private _promoTokenIdTracker;
Counters.Counter private _tokenIdTracker;
| bytes4 private constant InterfaceSignature_MarsGenesisAuction =
bytes4(keccak256('landIdIsForSale(uint256 tokenId)')) ^
bytes4(keccak256('landNoLongerForSale(uint256)'));
Counters.Counter private _promoTokenIdTracker;
Counters.Counter private _tokenIdTracker;
| 53,395 |
12 | // A modifier that defines a protected initializer function that can be invoked at most once. In its scope,`onlyInitializing` functions can be used to initialize parent contracts. Similar to `reinitializer(1)`, except that functions marked with `initializer` can be nested in the context of aconstructor. | * Emits an {Initialized} event.
*/
modifier initializer() {
bool isTopLevelCall = !_initializing;
require(
(isTopLevelCall && _initialized < 1) ||
(!Address.isContract(address(this)) && _initialized == 1),
'Initializable: contract is already initialized'
);
_initialized = 1;
if (isTopLevelCall) {
_initializing = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
emit Initialized(1);
}
}
| * Emits an {Initialized} event.
*/
modifier initializer() {
bool isTopLevelCall = !_initializing;
require(
(isTopLevelCall && _initialized < 1) ||
(!Address.isContract(address(this)) && _initialized == 1),
'Initializable: contract is already initialized'
);
_initialized = 1;
if (isTopLevelCall) {
_initializing = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
emit Initialized(1);
}
}
| 25,489 |
67 | // /uint256 t = self.endWithdrawalTime - self.startTime;uint256 s = now - self.startTime;uint256 pa = self.pricePurchasedAt[msg.sender];uint256 pu = self.tokensPerEth;uint256 multiplierPercent =(100(t - s))/t;self.pricePurchasedAt = pa-((pa-pu)/3) | uint256 timeLeft;
timeLeft = self.endWithdrawalTime.sub(now);
uint256 multiplierPercent = (timeLeft.mul(100)) / (self.endWithdrawalTime.sub(self.startTime));
refundWei = (multiplierPercent.mul(self.hasContributed[msg.sender])) / 100;
self.valuationSums[self.personalCaps[msg.sender]] = self.valuationSums[self.personalCaps[msg.sender]].sub(refundWei);
self.numBidsAtValuation[self.personalCaps[msg.sender]] = self.numBidsAtValuation[self.personalCaps[msg.sender]].sub(1);
| uint256 timeLeft;
timeLeft = self.endWithdrawalTime.sub(now);
uint256 multiplierPercent = (timeLeft.mul(100)) / (self.endWithdrawalTime.sub(self.startTime));
refundWei = (multiplierPercent.mul(self.hasContributed[msg.sender])) / 100;
self.valuationSums[self.personalCaps[msg.sender]] = self.valuationSums[self.personalCaps[msg.sender]].sub(refundWei);
self.numBidsAtValuation[self.personalCaps[msg.sender]] = self.numBidsAtValuation[self.personalCaps[msg.sender]].sub(1);
| 65,261 |
51 | // Emitted when an offer is cancelled. | event CancelledOffer(address indexed offeror, uint256 indexed offerId);
| event CancelledOffer(address indexed offeror, uint256 indexed offerId);
| 27,265 |
0 | // Constructor / | constructor(address _admins)
Fees(_admins)
public
| constructor(address _admins)
Fees(_admins)
public
| 31,418 |
9 | // token is relisted on Fractional with an initial reserve price equal to 2x the price of the token | uint8 internal constant RESALE_MULTIPLIER = 2;
| uint8 internal constant RESALE_MULTIPLIER = 2;
| 38,243 |
10 | // Access modifier for CEO-only or CFO-only functionality | modifier onlyCeoOrCfo() {
require(
msg.sender != address(0) &&
(
msg.sender == ceoAddress ||
msg.sender == cfoAddress
),
"only CEO or CFO is allowed to perform this operation"
);
_;
}
| modifier onlyCeoOrCfo() {
require(
msg.sender != address(0) &&
(
msg.sender == ceoAddress ||
msg.sender == cfoAddress
),
"only CEO or CFO is allowed to perform this operation"
);
_;
}
| 20,927 |
31 | // The amount to deposit for registration or extension/ Note: the price moves quickly depending on what other addresses do./ The current price might change after you send a `deposit()` transaction/ before the transaction is executed. | function currentPrice() public view returns (uint256) {
require(now >= set_price_at, "An underflow in price computation");
uint256 seconds_passed = now - set_price_at;
return decayedPrice(set_price, seconds_passed);
}
| function currentPrice() public view returns (uint256) {
require(now >= set_price_at, "An underflow in price computation");
uint256 seconds_passed = now - set_price_at;
return decayedPrice(set_price, seconds_passed);
}
| 78,731 |
50 | // returns amount of users by address to ever stake via the contract | function getUserCount()
public
view
returns(uint)
| function getUserCount()
public
view
returns(uint)
| 32,425 |
165 | // Gets the initial ETH balance, so swap won't touch any staked ETH | uint256 initialETHBalance = address(this).balance;
_swapTokenForETH(swapToken);
uint256 newETH=(address(this).balance - initialETHBalance);
| uint256 initialETHBalance = address(this).balance;
_swapTokenForETH(swapToken);
uint256 newETH=(address(this).balance - initialETHBalance);
| 40,316 |
94 | // DEDUCT FROM SENDER, CREDIT BENEFICIARY | balances[msg.sender] = balances[msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer(msg.sender, to, tokens);
return true;
| balances[msg.sender] = balances[msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer(msg.sender, to, tokens);
return true;
| 47,440 |
197 | // Gets some minimal info of a previously submitted block that's kept onchain./A DEX can use this function to implement a payment receipt verification/contract with a challange-response scheme./blockIdx The block index. | function getBlockInfo(uint blockIdx)
external
virtual
view
returns (ExchangeData.BlockInfo memory);
| function getBlockInfo(uint blockIdx)
external
virtual
view
returns (ExchangeData.BlockInfo memory);
| 31,492 |
60 | // total remaining payout is decreased | totalRemainingPayout -= info.payout;
| totalRemainingPayout -= info.payout;
| 7,105 |
6 | // Updates data / | function update(address assetToken) external override {
/*
* Reads data from oracle
*/
(,int price,,uint256 latestUpdate,) = _priceFeeds[assetToken].latestRoundData();
/*
* Updates price
*/
price *= 1e10;
_prices[assetToken] = uint256(price);
/*
* Updates volatility
* Volatility will read just one price per day
*/
(,, uint256 day) = BokkyPooBahsDateTimeLibrary.timestampToDate(latestUpdate);
if (day != _volatilities[assetToken].latestDay){
_calculateVolatility(assetToken);
_volatilities[assetToken].latestDay = day;
}
emit OracleUpdated(assetToken, _prices[assetToken], _riskFreeRate, _volatilities[assetToken].volatility);
}
| function update(address assetToken) external override {
/*
* Reads data from oracle
*/
(,int price,,uint256 latestUpdate,) = _priceFeeds[assetToken].latestRoundData();
/*
* Updates price
*/
price *= 1e10;
_prices[assetToken] = uint256(price);
/*
* Updates volatility
* Volatility will read just one price per day
*/
(,, uint256 day) = BokkyPooBahsDateTimeLibrary.timestampToDate(latestUpdate);
if (day != _volatilities[assetToken].latestDay){
_calculateVolatility(assetToken);
_volatilities[assetToken].latestDay = day;
}
emit OracleUpdated(assetToken, _prices[assetToken], _riskFreeRate, _volatilities[assetToken].volatility);
}
| 2,840 |
13 | // Library for converting numbers into strings and other string operations./Solady (https:github.com/vectorized/solady/blob/main/src/utils/LibString.sol)/Modified from Solmate (https:github.com/transmissions11/solmate/blob/main/src/utils/LibString.sol) | library LibString {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CUSTOM ERRORS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The `length` of the output is too small to contain all the hex digits.
error HexLengthInsufficient();
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CONSTANTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The constant returned when the `search` is not found in the string.
uint256 internal constant NOT_FOUND = type(uint256).max;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* DECIMAL OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns the base 10 decimal representation of `value`.
function toString(uint256 value) internal pure returns (string memory str) {
/// @solidity memory-safe-assembly
assembly {
// The maximum value of a uint256 contains 78 digits (1 byte per digit), but
// we allocate 0xa0 bytes to keep the free memory pointer 32-byte word aligned.
// We will need 1 word for the trailing zeros padding, 1 word for the length,
// and 3 words for a maximum of 78 digits.
str := add(mload(0x40), 0x80)
// Update the free memory pointer to allocate.
mstore(0x40, add(str, 0x20))
// Zeroize the slot after the string.
mstore(str, 0)
// Cache the end of the memory to calculate the length later.
let end := str
let w := not(0) // Tsk.
// We write the string from rightmost digit to leftmost digit.
// The following is essentially a do-while loop that also handles the zero case.
for { let temp := value } 1 {} {
str := add(str, w) // `sub(str, 1)`.
// Write the character to the pointer.
// The ASCII index of the '0' character is 48.
mstore8(str, add(48, mod(temp, 10)))
// Keep dividing `temp` until zero.
temp := div(temp, 10)
if iszero(temp) { break }
}
let length := sub(end, str)
// Move the pointer 32 bytes leftwards to make room for the length.
str := sub(str, 0x20)
// Store the length.
mstore(str, length)
}
}
| library LibString {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CUSTOM ERRORS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The `length` of the output is too small to contain all the hex digits.
error HexLengthInsufficient();
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CONSTANTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The constant returned when the `search` is not found in the string.
uint256 internal constant NOT_FOUND = type(uint256).max;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* DECIMAL OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns the base 10 decimal representation of `value`.
function toString(uint256 value) internal pure returns (string memory str) {
/// @solidity memory-safe-assembly
assembly {
// The maximum value of a uint256 contains 78 digits (1 byte per digit), but
// we allocate 0xa0 bytes to keep the free memory pointer 32-byte word aligned.
// We will need 1 word for the trailing zeros padding, 1 word for the length,
// and 3 words for a maximum of 78 digits.
str := add(mload(0x40), 0x80)
// Update the free memory pointer to allocate.
mstore(0x40, add(str, 0x20))
// Zeroize the slot after the string.
mstore(str, 0)
// Cache the end of the memory to calculate the length later.
let end := str
let w := not(0) // Tsk.
// We write the string from rightmost digit to leftmost digit.
// The following is essentially a do-while loop that also handles the zero case.
for { let temp := value } 1 {} {
str := add(str, w) // `sub(str, 1)`.
// Write the character to the pointer.
// The ASCII index of the '0' character is 48.
mstore8(str, add(48, mod(temp, 10)))
// Keep dividing `temp` until zero.
temp := div(temp, 10)
if iszero(temp) { break }
}
let length := sub(end, str)
// Move the pointer 32 bytes leftwards to make room for the length.
str := sub(str, 0x20)
// Store the length.
mstore(str, length)
}
}
| 17,998 |
17 | // We use < for ownerIndexEnd and tokenBalanceOwner because tokenOfOwnerByIndex is 0-indexed while the token balance is 1-indexed | require(ownerIndexStart >= 0 && ownerIndexEnd < tokenBalanceOwner, "INDEX_OUT_OF_RANGE");
| require(ownerIndexStart >= 0 && ownerIndexEnd < tokenBalanceOwner, "INDEX_OUT_OF_RANGE");
| 67,617 |
234 | // Transfer the investment asset to the fund. Does not follow the checks-effects-interactions pattern, but it is preferred to have the final state of the VaultProxy prior to running __postBuySharesHook(). | ERC20(_denominationAsset).safeTransferFrom(msg.sender, _vaultProxy, _investmentAmount);
| ERC20(_denominationAsset).safeTransferFrom(msg.sender, _vaultProxy, _investmentAmount);
| 18,579 |
15 | // Set token IDs for lootbox classes | _setTokenIdsForClass(_option, 0, _commonItems);
_setTokenIdsForClass(_option, 1, _rareItems);
_setTokenIdsForClass(_option, 2, _epicItems);
| _setTokenIdsForClass(_option, 0, _commonItems);
_setTokenIdsForClass(_option, 1, _rareItems);
_setTokenIdsForClass(_option, 2, _epicItems);
| 39,823 |
45 | // Ensures networkWeight is set by the end of the Referendum stage, even if 0 votes are cast. | proposal.networkWeight = getLockedGold().getTotalLockedGold();
emit ProposalApproved(proposalId);
return true;
| proposal.networkWeight = getLockedGold().getTotalLockedGold();
emit ProposalApproved(proposalId);
return true;
| 24,142 |
210 | // Calculate tax and after-tax amount | uint256 taxRate = calculateTax();
uint256 taxedAmount = amount.mul(taxRate).div(100);
uint256 stakedAmount = amount.sub(taxedAmount);
| uint256 taxRate = calculateTax();
uint256 taxedAmount = amount.mul(taxRate).div(100);
uint256 stakedAmount = amount.sub(taxedAmount);
| 18,556 |
5 | // Sets {REDEEM_ADDRESS_USER} attribute for redeemAddress as `_account`. Sets {USER_REDEEM_ADDRESS} attribute for `_account` as redeemAddress. Emits a {RegisterNewUser} event. Requirements: - `_account` should not be a registered as user.- number of redeem address should not be greater than max availables. / | function registerNewUser(address _account, string calldata _id)
public
onlyOwner
{
require(!_isUser(_account), "user exist");
require(usersById[_id] == address(0), "id already taken");
redemptionAddressCount++;
require(
REDEMPTION_ADDRESS_COUNT > redemptionAddressCount,
| function registerNewUser(address _account, string calldata _id)
public
onlyOwner
{
require(!_isUser(_account), "user exist");
require(usersById[_id] == address(0), "id already taken");
redemptionAddressCount++;
require(
REDEMPTION_ADDRESS_COUNT > redemptionAddressCount,
| 35,885 |
39 | // Checks whether royalty info can be set in the given execution context. | function _canSetRoyaltyInfo() internal view override returns (bool) {
return hasRole(DEFAULT_ADMIN_ROLE, msg.sender);
}
| function _canSetRoyaltyInfo() internal view override returns (bool) {
return hasRole(DEFAULT_ADMIN_ROLE, msg.sender);
}
| 15,734 |
59 | // Adds two `Signed`s, reverting on overflow. a a FixedPoint.Signed. b a FixedPoint.Signed.return the sum of `a` and `b`. / | function add(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
return Signed(a.rawValue.add(b.rawValue));
}
| function add(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
return Signed(a.rawValue.add(b.rawValue));
}
| 1,158 |
480 | // `tokenId` が発行されていれば true を返します. / | function exists(uint256 tokenId) external view virtual returns (bool) {
return _exists(tokenId);
}
| function exists(uint256 tokenId) external view virtual returns (bool) {
return _exists(tokenId);
}
| 31,984 |
63 | // Token Issuance // Know if new tokens can be issued in the future.return bool 'true' if tokens can still be issued by the issuer, 'false' if they can't anymore. / | function isIssuable() external view override returns (bool) {
return _isIssuable;
}
| function isIssuable() external view override returns (bool) {
return _isIssuable;
}
| 37,105 |
5 | // ! lk.sol | (c) 2019 Develop by BelovITLab LLC (smartcontract.ru), author @stupidlovejoy | License: MIT / | library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if(a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "SafeMath: modulo by zero");
return a % b;
}
}
| library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if(a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "SafeMath: modulo by zero");
return a % b;
}
}
| 10,592 |
4 | // buy resource using `ETH` with exact resource amount,/ resource must be valuate by `WETH`./resource resource contract address./prePath pre path for exchange resource./ for exampleif prePath is [`tokenA`, `tokenB`, `tokenC`],/ make sure [`tokenA`, `tokenB`, `tokenC` `resource.token()`] is existing in `IUniswapV2Router02`/amountOut resource amount out./deadline swap deadline./data data to call/ return value `ETH` used for purchase. | function buyExactTokenValuatedResourceByETH(
IResource resource,
address[] memory prePath,
uint256 amountOut,
uint256 deadline,
bytes memory data
) external payable returns (uint256 value);
| function buyExactTokenValuatedResourceByETH(
IResource resource,
address[] memory prePath,
uint256 amountOut,
uint256 deadline,
bytes memory data
) external payable returns (uint256 value);
| 40,307 |
52 | // gets the SPT emission rate for a node - nodes are locked into the emission rate that was active at the time of registration | function nodeEmissionRate(uint256 regTime) public view override returns (uint256) {
uint256 band1 = EMISSION_START + (SECONDS_IN_A_YEAR * 1);
if(regTime <= band1) {
return EMISSION_PER_DAY_YEARS[0];
}
uint256 band2 = EMISSION_START + (SECONDS_IN_A_YEAR * 2);
if(regTime <= band2) {
return EMISSION_PER_DAY_YEARS[1];
}
return EMISSION_PER_DAY_YEARS[2];
}
| function nodeEmissionRate(uint256 regTime) public view override returns (uint256) {
uint256 band1 = EMISSION_START + (SECONDS_IN_A_YEAR * 1);
if(regTime <= band1) {
return EMISSION_PER_DAY_YEARS[0];
}
uint256 band2 = EMISSION_START + (SECONDS_IN_A_YEAR * 2);
if(regTime <= band2) {
return EMISSION_PER_DAY_YEARS[1];
}
return EMISSION_PER_DAY_YEARS[2];
}
| 39,442 |
16 | // Finally, we are writing the faucet contract.We can see that DaiFaucet inherits the mortal contract, which in turn inherits the owned contract.This way, we have modularised our contracts for their specific functions and added our totalcontrol over it. Inside the contract we have two events that will watch and log every timethere is a Withdrawal and a Deposit to/from this contract. | contract DaiFaucet is mortal {
event Withdrawal(address indexed to, uint amount);
event Deposit(address indexed from, uint amount);
// We have added the withdraw function that will take care to send Dai to anyone who calls this function.
// As you can see, we have added 2 conditions for the withdrawal:
// - Require that the withdraw_amount is less or equal to 0.1 Dai
// - Require that we have more Dai in the faucet than the withdraw_amount.
// Give out Dai to anyone who asks
function withdraw(uint withdraw_amount) public {
// Limit withdrawal amount
require(withdraw_amount <= 0.1 ether);
require(daitoken.balanceOf(address(this)) >= withdraw_amount,
"Insufficient balance in faucet for withdrawal request");
// And of course, we log this transaction with the Withdrawal event.
// Send the amount to the address that requested it
daitoken.transfer(msg.sender, withdraw_amount);
// Only after these conditions are met we can transfer 0.1 Dai to the function caller.
// And of course, we log this transaction with the Withdrawal event.
// The way we send Dai to the function caller is by using the above defined DaiToken
// interface to allow us to make the transfer.
emit Withdrawal(msg.sender, withdraw_amount);
}
// The unnamed function is here to receive any incoming payments our contracts gets and
//log the Deposit event.
// Accept any incoming amount
function () external payable {
emit Deposit(msg.sender, msg.value);
}
}
| contract DaiFaucet is mortal {
event Withdrawal(address indexed to, uint amount);
event Deposit(address indexed from, uint amount);
// We have added the withdraw function that will take care to send Dai to anyone who calls this function.
// As you can see, we have added 2 conditions for the withdrawal:
// - Require that the withdraw_amount is less or equal to 0.1 Dai
// - Require that we have more Dai in the faucet than the withdraw_amount.
// Give out Dai to anyone who asks
function withdraw(uint withdraw_amount) public {
// Limit withdrawal amount
require(withdraw_amount <= 0.1 ether);
require(daitoken.balanceOf(address(this)) >= withdraw_amount,
"Insufficient balance in faucet for withdrawal request");
// And of course, we log this transaction with the Withdrawal event.
// Send the amount to the address that requested it
daitoken.transfer(msg.sender, withdraw_amount);
// Only after these conditions are met we can transfer 0.1 Dai to the function caller.
// And of course, we log this transaction with the Withdrawal event.
// The way we send Dai to the function caller is by using the above defined DaiToken
// interface to allow us to make the transfer.
emit Withdrawal(msg.sender, withdraw_amount);
}
// The unnamed function is here to receive any incoming payments our contracts gets and
//log the Deposit event.
// Accept any incoming amount
function () external payable {
emit Deposit(msg.sender, msg.value);
}
}
| 50,626 |
135 | // Safe yfin transfer function, just in case if rounding error causes pool to not have enough YFINs. | function safeYfinTransfer(address _to, uint256 _amount) internal {
uint256 yfinBal = yfin.balanceOf(address(this));
if (_amount > yfinBal) {
yfin.transfer(_to, yfinBal);
} else {
yfin.transfer(_to, _amount);
}
}
| function safeYfinTransfer(address _to, uint256 _amount) internal {
uint256 yfinBal = yfin.balanceOf(address(this));
if (_amount > yfinBal) {
yfin.transfer(_to, yfinBal);
} else {
yfin.transfer(_to, _amount);
}
}
| 84,843 |
13 | // MINT |
uint256 x = random(50, 420, supply); //starting x/y position
uint256 y = random(500, 920, supply);
uint256 leafs = random(1, 25, supply);
uint256 background = random(0, backgroungColors.length - 1, supply);
infos[supply] = Character(
block.number,
msg.sender,
name,
x,
|
uint256 x = random(50, 420, supply); //starting x/y position
uint256 y = random(500, 920, supply);
uint256 leafs = random(1, 25, supply);
uint256 background = random(0, backgroungColors.length - 1, supply);
infos[supply] = Character(
block.number,
msg.sender,
name,
x,
| 22,081 |
142 | // Used to have strongly-typed access to internal mutative functions in dTrade | interface IdTradeInternal {
function emitExchangeTracking(
bytes32 trackingCode,
bytes32 toCurrencyKey,
uint256 toAmount
) external;
function emitSynthExchange(
address account,
bytes32 fromCurrencyKey,
uint256 fromAmount,
bytes32 toCurrencyKey,
uint256 toAmount,
address toAddress
) external;
function emitExchangeReclaim(
address account,
bytes32 currencyKey,
uint256 amount
) external;
function emitExchangeRebate(
address account,
bytes32 currencyKey,
uint256 amount
) external;
}
| interface IdTradeInternal {
function emitExchangeTracking(
bytes32 trackingCode,
bytes32 toCurrencyKey,
uint256 toAmount
) external;
function emitSynthExchange(
address account,
bytes32 fromCurrencyKey,
uint256 fromAmount,
bytes32 toCurrencyKey,
uint256 toAmount,
address toAddress
) external;
function emitExchangeReclaim(
address account,
bytes32 currencyKey,
uint256 amount
) external;
function emitExchangeRebate(
address account,
bytes32 currencyKey,
uint256 amount
) external;
}
| 13,446 |
58 | // Register new liquidity added to the future _amount the liquidity amount added must be called from the future contract / | function registerNewFutureLiquidity(uint256 _amount) external;
| function registerNewFutureLiquidity(uint256 _amount) external;
| 52,509 |
34 | // Claimable Protocol Smart contract allow recipients to claim ERC20 tokens according to an initial cliff and a vesting period Formual: - claimable at cliff: (cliff / vesting)amount - claimable at time t after cliff (t0 = start time) (t - t0) / vestingamount - multiple claims, last claim at t1, claim at t: (t - t1) / vestingamount or (t - t0) / vestingamount - claimed / | contract Claimable is Context {
using SafeMath for uint256;
/// @notice unique claim ticket id, auto-increment
uint256 public currentId;
/// @notice claim ticket
/// @dev payable is not needed for ERC20, need more work to support Ether
struct Ticket {
address token; // ERC20 token address
address payable grantor; // grantor address
address payable beneficiary;
uint256 cliff; // cliff time from creation in days
uint256 vesting; // vesting period in days
uint256 amount; // initial funding amount
uint256 claimed; // amount already claimed
uint256 balance; // current balance
uint256 createdAt; // begin time
uint256 lastClaimedAt;
uint256 numClaims;
bool irrevocable; // cannot be revoked
bool isRevoked; // return balance to grantor
uint256 revokedAt; // revoke timestamp
// mapping (uint256
// => mapping (uint256 => uint256)) claims; // claimId => lastClaimAt => amount
}
/// @dev address => id[]
/// @dev this is expensive but make it easy to create management UI
mapping (address => uint256[]) private grantorTickets;
mapping (address => uint256[]) private beneficiaryTickets;
/**
* Claim tickets
*/
/// @notice id => Ticket
mapping (uint256 => Ticket) public tickets;
event TicketCreated(uint256 id, address token, uint256 amount, bool irrevocable);
event Claimed(uint256 id, address token, uint256 amount);
event Revoked(uint256 id, uint256 amount);
modifier canView(uint256 _id) {
Ticket memory ticket = tickets[_id];
require(ticket.grantor == _msgSender() || ticket.beneficiary == _msgSender(), "Only grantor or beneficiary can view.");
_;
}
modifier notRevoked(uint256 _id) {
Ticket memory ticket = tickets[_id];
require(ticket.isRevoked == false, "Ticket is already revoked");
_;
}
/// @dev show all my grantor tickets
function myGrantorTickets() public view returns (uint256[] memory myTickets) {
myTickets = grantorTickets[_msgSender()];
}
/// @dev show all my beneficiary tickets
function myBeneficiaryTickets() public view returns (uint256[] memory myTickets) {
myTickets = beneficiaryTickets[_msgSender()];
}
/// @notice special cases: cliff = period: all claimable after the cliff
function create(address _token, address payable _beneficiary, uint256 _cliff, uint256 _vesting, uint256 _amount, bool _irrevocable) public returns (uint256 ticketId) {
/// @dev sender needs to approve this contract to fund the claim
require(_beneficiary != address(0), "Beneficiary is required");
require(_amount > 0, "Amount is required");
require(_vesting >= _cliff, "Vesting period should be equal or longer to the cliff");
ERC20 token = ERC20(_token);
require(token.balanceOf(_msgSender()) >= _amount, "Insufficient balance");
require(token.transferFrom(_msgSender(), address(this), _amount), "Funding failed.");
ticketId = ++currentId;
Ticket storage ticket = tickets[ticketId];
ticket.token = _token;
ticket.grantor = _msgSender();
ticket.beneficiary = _beneficiary;
ticket.cliff = _cliff;
ticket.vesting = _vesting;
ticket.amount = _amount;
ticket.balance = _amount;
ticket.createdAt = block.timestamp;
ticket.irrevocable = _irrevocable;
grantorTickets[_msgSender()].push(ticketId);
beneficiaryTickets[_beneficiary].push(ticketId);
emit TicketCreated(ticketId, _token, _amount, _irrevocable);
}
/// @notice claim available balance, only beneficiary can call
function claim(uint256 _id) notRevoked(_id) public returns (bool success) {
Ticket storage ticket = tickets[_id];
require(ticket.beneficiary == _msgSender(), "Only beneficiary can claim.");
require(ticket.balance > 0, "Ticket has no balance.");
ERC20 token = ERC20(ticket.token);
uint256 amount = available(_id);
require(amount > 0, "Nothing to claim.");
require(token.transfer(_msgSender(), amount), "Claim failed");
ticket.claimed = SafeMath.add(ticket.claimed, amount);
ticket.balance = SafeMath.sub(ticket.balance, amount);
ticket.lastClaimedAt = block.timestamp;
ticket.numClaims = SafeMath.add(ticket.numClaims, 1);
emit Claimed(_id, ticket.token, amount);
success = true;
}
/// @notice revoke ticket, balance returns to grantor, only grantor can call
function revoke(uint256 _id) notRevoked(_id) public returns (bool success) {
Ticket storage ticket = tickets[_id];
require(ticket.grantor == _msgSender(), "Only grantor can revoke.");
require(ticket.irrevocable == false, "Ticket is irrevocable.");
require(ticket.balance > 0, "Ticket has no balance.");
ERC20 token = ERC20(ticket.token);
require(token.transfer(_msgSender(), ticket.balance), "Return balance failed");
ticket.isRevoked = true;
ticket.balance = 0;
emit Revoked(_id, ticket.balance);
success = true;
}
/// @dev checks the ticket has cliffed or not
function hasCliffed(uint256 _id) canView(_id) public view returns (bool) {
Ticket memory ticket = tickets[_id];
if (ticket.cliff == 0) {
return true;
}
return block.timestamp > SafeMath.add(ticket.createdAt, SafeMath.mul(ticket.cliff, 86400)); // in seconds 24 x 60 x 60
}
/// @dev calculates the available balances excluding cliff and claims
function unlocked(uint256 _id) canView(_id) public view returns (uint256 amount) {
Ticket memory ticket = tickets[_id];
uint256 timeLapsed = SafeMath.sub(block.timestamp, ticket.createdAt); // in seconds
uint256 vestingInSeconds = SafeMath.mul(ticket.vesting, 86400); // in seconds: 24 x 60 x 60
amount = SafeMath.div(
SafeMath.mul(timeLapsed, ticket.amount),
vestingInSeconds
);
}
/// @notice check available claims, only grantor or beneficiary can call
function available(uint256 _id) canView(_id) notRevoked(_id) public view returns (uint256 amount) {
Ticket memory ticket = tickets[_id];
require(ticket.balance > 0, "Ticket has no balance.");
if (hasCliffed(_id)) {
amount = SafeMath.sub(unlocked(_id), ticket.claimed);
} else {
amount = 0;
}
}
} | contract Claimable is Context {
using SafeMath for uint256;
/// @notice unique claim ticket id, auto-increment
uint256 public currentId;
/// @notice claim ticket
/// @dev payable is not needed for ERC20, need more work to support Ether
struct Ticket {
address token; // ERC20 token address
address payable grantor; // grantor address
address payable beneficiary;
uint256 cliff; // cliff time from creation in days
uint256 vesting; // vesting period in days
uint256 amount; // initial funding amount
uint256 claimed; // amount already claimed
uint256 balance; // current balance
uint256 createdAt; // begin time
uint256 lastClaimedAt;
uint256 numClaims;
bool irrevocable; // cannot be revoked
bool isRevoked; // return balance to grantor
uint256 revokedAt; // revoke timestamp
// mapping (uint256
// => mapping (uint256 => uint256)) claims; // claimId => lastClaimAt => amount
}
/// @dev address => id[]
/// @dev this is expensive but make it easy to create management UI
mapping (address => uint256[]) private grantorTickets;
mapping (address => uint256[]) private beneficiaryTickets;
/**
* Claim tickets
*/
/// @notice id => Ticket
mapping (uint256 => Ticket) public tickets;
event TicketCreated(uint256 id, address token, uint256 amount, bool irrevocable);
event Claimed(uint256 id, address token, uint256 amount);
event Revoked(uint256 id, uint256 amount);
modifier canView(uint256 _id) {
Ticket memory ticket = tickets[_id];
require(ticket.grantor == _msgSender() || ticket.beneficiary == _msgSender(), "Only grantor or beneficiary can view.");
_;
}
modifier notRevoked(uint256 _id) {
Ticket memory ticket = tickets[_id];
require(ticket.isRevoked == false, "Ticket is already revoked");
_;
}
/// @dev show all my grantor tickets
function myGrantorTickets() public view returns (uint256[] memory myTickets) {
myTickets = grantorTickets[_msgSender()];
}
/// @dev show all my beneficiary tickets
function myBeneficiaryTickets() public view returns (uint256[] memory myTickets) {
myTickets = beneficiaryTickets[_msgSender()];
}
/// @notice special cases: cliff = period: all claimable after the cliff
function create(address _token, address payable _beneficiary, uint256 _cliff, uint256 _vesting, uint256 _amount, bool _irrevocable) public returns (uint256 ticketId) {
/// @dev sender needs to approve this contract to fund the claim
require(_beneficiary != address(0), "Beneficiary is required");
require(_amount > 0, "Amount is required");
require(_vesting >= _cliff, "Vesting period should be equal or longer to the cliff");
ERC20 token = ERC20(_token);
require(token.balanceOf(_msgSender()) >= _amount, "Insufficient balance");
require(token.transferFrom(_msgSender(), address(this), _amount), "Funding failed.");
ticketId = ++currentId;
Ticket storage ticket = tickets[ticketId];
ticket.token = _token;
ticket.grantor = _msgSender();
ticket.beneficiary = _beneficiary;
ticket.cliff = _cliff;
ticket.vesting = _vesting;
ticket.amount = _amount;
ticket.balance = _amount;
ticket.createdAt = block.timestamp;
ticket.irrevocable = _irrevocable;
grantorTickets[_msgSender()].push(ticketId);
beneficiaryTickets[_beneficiary].push(ticketId);
emit TicketCreated(ticketId, _token, _amount, _irrevocable);
}
/// @notice claim available balance, only beneficiary can call
function claim(uint256 _id) notRevoked(_id) public returns (bool success) {
Ticket storage ticket = tickets[_id];
require(ticket.beneficiary == _msgSender(), "Only beneficiary can claim.");
require(ticket.balance > 0, "Ticket has no balance.");
ERC20 token = ERC20(ticket.token);
uint256 amount = available(_id);
require(amount > 0, "Nothing to claim.");
require(token.transfer(_msgSender(), amount), "Claim failed");
ticket.claimed = SafeMath.add(ticket.claimed, amount);
ticket.balance = SafeMath.sub(ticket.balance, amount);
ticket.lastClaimedAt = block.timestamp;
ticket.numClaims = SafeMath.add(ticket.numClaims, 1);
emit Claimed(_id, ticket.token, amount);
success = true;
}
/// @notice revoke ticket, balance returns to grantor, only grantor can call
function revoke(uint256 _id) notRevoked(_id) public returns (bool success) {
Ticket storage ticket = tickets[_id];
require(ticket.grantor == _msgSender(), "Only grantor can revoke.");
require(ticket.irrevocable == false, "Ticket is irrevocable.");
require(ticket.balance > 0, "Ticket has no balance.");
ERC20 token = ERC20(ticket.token);
require(token.transfer(_msgSender(), ticket.balance), "Return balance failed");
ticket.isRevoked = true;
ticket.balance = 0;
emit Revoked(_id, ticket.balance);
success = true;
}
/// @dev checks the ticket has cliffed or not
function hasCliffed(uint256 _id) canView(_id) public view returns (bool) {
Ticket memory ticket = tickets[_id];
if (ticket.cliff == 0) {
return true;
}
return block.timestamp > SafeMath.add(ticket.createdAt, SafeMath.mul(ticket.cliff, 86400)); // in seconds 24 x 60 x 60
}
/// @dev calculates the available balances excluding cliff and claims
function unlocked(uint256 _id) canView(_id) public view returns (uint256 amount) {
Ticket memory ticket = tickets[_id];
uint256 timeLapsed = SafeMath.sub(block.timestamp, ticket.createdAt); // in seconds
uint256 vestingInSeconds = SafeMath.mul(ticket.vesting, 86400); // in seconds: 24 x 60 x 60
amount = SafeMath.div(
SafeMath.mul(timeLapsed, ticket.amount),
vestingInSeconds
);
}
/// @notice check available claims, only grantor or beneficiary can call
function available(uint256 _id) canView(_id) notRevoked(_id) public view returns (uint256 amount) {
Ticket memory ticket = tickets[_id];
require(ticket.balance > 0, "Ticket has no balance.");
if (hasCliffed(_id)) {
amount = SafeMath.sub(unlocked(_id), ticket.claimed);
} else {
amount = 0;
}
}
} | 12,476 |
180 | // Void disputable action `_disputableActionId`This hook must be implemented by Disputable apps. We provide a base implementation to ensure that the `onlyAgreement` modifieris included. Subclasses should implement the internal implementation of the hook._disputableActionId Identifier of the action to be voided/ | function onDisputableActionVoided(uint256 _disputableActionId) external onlyAgreement {
_onDisputableActionVoided(_disputableActionId);
}
| function onDisputableActionVoided(uint256 _disputableActionId) external onlyAgreement {
_onDisputableActionVoided(_disputableActionId);
}
| 58,176 |
37 | // global pending rewards counter | pendingRewards = pendingRewards.add(amount);
| pendingRewards = pendingRewards.add(amount);
| 20,246 |
48 | // remove players from match | function removeFromMatch(uint256 matchId, address[] memory players)
public
virtual
override
onlyRole(DEFAULT_ADMIN_ROLE)
| function removeFromMatch(uint256 matchId, address[] memory players)
public
virtual
override
onlyRole(DEFAULT_ADMIN_ROLE)
| 3,450 |
9 | // Add to whitelist by updating the Merkle tree rootrootCaller must be contract owner / | function updateRoot(bytes32 _root) external onlyRole(DEFAULT_ADMIN_ROLE) {
root = _root;
}
| function updateRoot(bytes32 _root) external onlyRole(DEFAULT_ADMIN_ROLE) {
root = _root;
}
| 36,276 |
200 | // Get number of transaction roots | let transactionRootsLength := selectTransactionRootsLength(blockHeader)
| let transactionRootsLength := selectTransactionRootsLength(blockHeader)
| 21,527 |
20 | // at the end, we increment the stakes of the team selected with the player bet | if (player == 1) {
totalBetOne += msg.value;
} else {
| if (player == 1) {
totalBetOne += msg.value;
} else {
| 10,302 |
4 | // Set Methods / | function setAddress(bytes32 key, address value) public {
_addressStorage[msg.sender][key] = value;
}
| function setAddress(bytes32 key, address value) public {
_addressStorage[msg.sender][key] = value;
}
| 49,632 |
193 | // Snapshots are created by the internal {updateValueAtNow} function.To get the total supply at the time of a snapshot, call the function {totalSupplyAt} with a block number.To get the balance of an account at the time of a snapshot, call the {balanceOfAt} function with a block number Inspired by Jordi Baylina's MiniMeToken to record historical balances: https:github.com/Giveth/minime/blob/ea04d950eea153a04c51fa510b068b9dded390cb/contracts/MiniMeToken.sol |
using SafeMath for uint256;
|
using SafeMath for uint256;
| 2,870 |
266 | // If they don't have any debt ownership, they don't have any fees | if (initialDebtOwnership == 0) return result;
| if (initialDebtOwnership == 0) return result;
| 6,043 |
215 | // View function to see pending HYPEs on frontend single token. | function pendingHYPE_single(uint256 _pid, address _user) external view returns (uint256) {
SinglePoolInfo storage pool = poolInfo_single[_pid];
UserInfo storage user = userInfo_single[_pid][_user];
uint256 accHYPEPerShare = pool.accHYPEPerShare;
uint256 sSupply = pool.sToken.balanceOf(address(this));
uint256 currentRewardBlock = block.number;
if (pool.setEndBlock && currentRewardBlock > pool.singleTokenEndBlock) {
currentRewardBlock = pool.singleTokenEndBlock;
}
if (block.number > pool.lastRewardBlock && sSupply != 0) {
uint256 multiplier = getMultiplier_single(_pid, pool.lastRewardBlock, currentRewardBlock);
uint256 HYPEReward = multiplier.mul(pool.singlePerBlock);
accHYPEPerShare = accHYPEPerShare.add(HYPEReward.mul(1e12).div(sSupply));
}
return user.amount.mul(accHYPEPerShare).div(1e12).sub(user.rewardDebt);
}
| function pendingHYPE_single(uint256 _pid, address _user) external view returns (uint256) {
SinglePoolInfo storage pool = poolInfo_single[_pid];
UserInfo storage user = userInfo_single[_pid][_user];
uint256 accHYPEPerShare = pool.accHYPEPerShare;
uint256 sSupply = pool.sToken.balanceOf(address(this));
uint256 currentRewardBlock = block.number;
if (pool.setEndBlock && currentRewardBlock > pool.singleTokenEndBlock) {
currentRewardBlock = pool.singleTokenEndBlock;
}
if (block.number > pool.lastRewardBlock && sSupply != 0) {
uint256 multiplier = getMultiplier_single(_pid, pool.lastRewardBlock, currentRewardBlock);
uint256 HYPEReward = multiplier.mul(pool.singlePerBlock);
accHYPEPerShare = accHYPEPerShare.add(HYPEReward.mul(1e12).div(sSupply));
}
return user.amount.mul(accHYPEPerShare).div(1e12).sub(user.rewardDebt);
}
| 9,143 |
5 | // See {Pausable} and {Pausable-_unpause}. Requirements: - the caller must have the `PAUSER_ROLE`. / | function unpause() public onlyRole(PAUSER_ROLE) {
_unpause();
}
| function unpause() public onlyRole(PAUSER_ROLE) {
_unpause();
}
| 34,702 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.