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 |
|---|---|---|---|---|
148 | // Base interface for a contract that will be called via the GSN from {IRelayHub}.TIP: You don't need to write an implementation yourself! Inherit from {GSNRecipient} instead./ Returns the address of the {IRelayHub} instance this recipient interacts with. / | function getHubAddr() external view returns (address);
| function getHubAddr() external view returns (address);
| 34,226 |
40 | // Locks the contract for owner for the amount of time provided | function lock(uint256 time) public virtual onlyOwner {
_previousOwner = _owner;
_owner = address(0);
_lockTime = time;
emit OwnershipTransferred(_owner, address(0));
}
| function lock(uint256 time) public virtual onlyOwner {
_previousOwner = _owner;
_owner = address(0);
_lockTime = time;
emit OwnershipTransferred(_owner, address(0));
}
| 1,480 |
26 | // user&39;s withdraw will success in two cases:1. when the admin calls the approveWithdraw function; or 2. when the lock time has passed since the application;/ | function withdraw(address token, uint256 amount) public {
require(amount <= tokenList[token][msg.sender]);
if (amount > withdrawAllowance[token][msg.sender]) {
//withdraw wait over time
require(latestApply[token][msg.sender] != 0 && safeSub(block.timestamp, latestApply[token][msg.sender]) > applyWait);
withdrawAllowance[token][msg.sender] = safeAdd(withdrawAllowance[token][msg.sender], applyList[token][msg.sender]);
applyList[token][msg.sender] = 0;
}
require(amount <= withdrawAllowance[token][msg.sender]);
withdrawAllowance[token][msg.sender] = safeSub(withdrawAllowance[token][msg.sender], amount);
tokenList[token][msg.sender] = safeSub(tokenList[token][msg.sender], amount);
latestApply[token][msg.sender] = 0;
if (token == 0) {//withdraw ether
require(msg.sender.send(amount));
} else {//withdraw token
require(Token(token).transfer(msg.sender, amount));
}
Withdraw(token, msg.sender, amount, tokenList[token][msg.sender]);
}
| function withdraw(address token, uint256 amount) public {
require(amount <= tokenList[token][msg.sender]);
if (amount > withdrawAllowance[token][msg.sender]) {
//withdraw wait over time
require(latestApply[token][msg.sender] != 0 && safeSub(block.timestamp, latestApply[token][msg.sender]) > applyWait);
withdrawAllowance[token][msg.sender] = safeAdd(withdrawAllowance[token][msg.sender], applyList[token][msg.sender]);
applyList[token][msg.sender] = 0;
}
require(amount <= withdrawAllowance[token][msg.sender]);
withdrawAllowance[token][msg.sender] = safeSub(withdrawAllowance[token][msg.sender], amount);
tokenList[token][msg.sender] = safeSub(tokenList[token][msg.sender], amount);
latestApply[token][msg.sender] = 0;
if (token == 0) {//withdraw ether
require(msg.sender.send(amount));
} else {//withdraw token
require(Token(token).transfer(msg.sender, amount));
}
Withdraw(token, msg.sender, amount, tokenList[token][msg.sender]);
}
| 53,807 |
24 | // Case: Celer | if (
selector == CelerIMFacetBase.startBridgeTokensViaCelerIM.selector
) {
(, CelerIM.CelerIMData memory celerIMData) = abi.decode(
callData.slice(4, callData.length - 4),
(ILiFi.BridgeData, CelerIM.CelerIMData)
);
return
keccak256(dstCalldata) == keccak256(celerIMData.callData) &&
keccak256(callTo) == keccak256(celerIMData.callTo);
| if (
selector == CelerIMFacetBase.startBridgeTokensViaCelerIM.selector
) {
(, CelerIM.CelerIMData memory celerIMData) = abi.decode(
callData.slice(4, callData.length - 4),
(ILiFi.BridgeData, CelerIM.CelerIMData)
);
return
keccak256(dstCalldata) == keccak256(celerIMData.callData) &&
keccak256(callTo) == keccak256(celerIMData.callTo);
| 20,201 |
0 | // Tue Mar 18 2031 17:46:47 GMT+0000 | uint256 public constant START = 1636934400;
mapping(address => uint256) public rewards;
mapping(address => uint256) public lastUpdate;
| uint256 public constant START = 1636934400;
mapping(address => uint256) public rewards;
mapping(address => uint256) public lastUpdate;
| 33,627 |
11 | // Activate the contract. Discard if the contract is not the ledger owner. | function activate() public onlyOwner {
require(!isActive);
require(ledger.owner() == address(this));
isActive = true;
}
| function activate() public onlyOwner {
require(!isActive);
require(ledger.owner() == address(this));
isActive = true;
}
| 29,928 |
78 | // log event./ | Transfer_S_coupons(msg.sender, _to, _numberOfScoupons);
| Transfer_S_coupons(msg.sender, _to, _numberOfScoupons);
| 9,440 |
4 | // set the main question`_question` is question | function setQuestion(string memory _question) external onlyRole(CONFIGURATOR_ROLE) {
require(!_isStringEmpty(_question), "MarketingVoting: question is an empty string");
question = _question;
}
| function setQuestion(string memory _question) external onlyRole(CONFIGURATOR_ROLE) {
require(!_isStringEmpty(_question), "MarketingVoting: question is an empty string");
question = _question;
}
| 16,018 |
10 | // Returns the current nonce for `owner`. This value must be included whenever a signature is generated for {permit}. Every successful call to {permit} increases ``owner``'s nonce by one. This prevents a signature from being used multiple times./ | function nonces(address owner) external view returns (uint256);
| function nonces(address owner) external view returns (uint256);
| 36,121 |
384 | // BondingManager Manages bonding, transcoder and rewards/fee accounting related operations of the Livepeer protocol / | contract BondingManager is ManagerProxyTarget, IBondingManager {
using SafeMath for uint256;
using SortedDoublyLL for SortedDoublyLL.Data;
using EarningsPool for EarningsPool.Data;
using EarningsPoolLIP36 for EarningsPool.Data;
// Constants
// Occurances are replaced at compile time
// and computed to a single value if possible by the optimizer
uint256 constant MAX_FUTURE_ROUND = 2**256 - 1;
uint256 constant MAX_LOOKBACK_ROUNDS = 100;
// PreciseMathUtils.percPoints(1, 1) / MathUtils.percPoints(1, 1) => (10 ** 27) / 1000000
uint256 constant RESCALE_FACTOR = 10 ** 21;
// Address for LIP-77 execution
address constant LIP_77_ADDRESS = 0xB47D8F87c0113827d44Ad0Bc32D53823C477a89d;
// Time between unbonding and possible withdrawl in rounds
uint64 public unbondingPeriod;
// DEPRECATED - DO NOT USE
uint256 public numActiveTranscodersDEPRECATED;
// Max number of rounds that a caller can claim earnings for at once
uint256 public maxEarningsClaimsRounds;
// Represents a transcoder's current state
struct Transcoder {
uint256 lastRewardRound; // Last round that the transcoder called reward
uint256 rewardCut; // % of reward paid to transcoder by a delegator
uint256 feeShare; // % of fees paid to delegators by transcoder
uint256 pricePerSegmentDEPRECATED; // DEPRECATED - DO NOT USE
uint256 pendingRewardCutDEPRECATED; // DEPRECATED - DO NOT USE
uint256 pendingFeeShareDEPRECATED; // DEPRECATED - DO NOT USE
uint256 pendingPricePerSegmentDEPRECATED; // DEPRECATED - DO NOT USE
mapping (uint256 => EarningsPool.Data) earningsPoolPerRound; // Mapping of round => earnings pool for the round
uint256 lastActiveStakeUpdateRound; // Round for which the stake was last updated while the transcoder is active
uint256 activationRound; // Round in which the transcoder became active - 0 if inactive
uint256 deactivationRound; // Round in which the transcoder will become inactive
uint256 activeCumulativeRewards; // The transcoder's cumulative rewards that are active in the current round
uint256 cumulativeRewards; // The transcoder's cumulative rewards (earned via the its active staked rewards and its reward cut).
uint256 cumulativeFees; // The transcoder's cumulative fees (earned via the its active staked rewards and its fee share)
uint256 lastFeeRound; // Latest round in which the transcoder received fees
}
// The various states a transcoder can be in
enum TranscoderStatus { NotRegistered, Registered }
// Represents a delegator's current state
struct Delegator {
uint256 bondedAmount; // The amount of bonded tokens
uint256 fees; // The amount of fees collected
address delegateAddress; // The address delegated to
uint256 delegatedAmount; // The amount of tokens delegated to the delegator
uint256 startRound; // The round the delegator transitions to bonded phase and is delegated to someone
uint256 withdrawRoundDEPRECATED; // DEPRECATED - DO NOT USE
uint256 lastClaimRound; // The last round during which the delegator claimed its earnings
uint256 nextUnbondingLockId; // ID for the next unbonding lock created
mapping (uint256 => UnbondingLock) unbondingLocks; // Mapping of unbonding lock ID => unbonding lock
}
// The various states a delegator can be in
enum DelegatorStatus { Pending, Bonded, Unbonded }
// Represents an amount of tokens that are being unbonded
struct UnbondingLock {
uint256 amount; // Amount of tokens being unbonded
uint256 withdrawRound; // Round at which unbonding period is over and tokens can be withdrawn
}
// Keep track of the known transcoders and delegators
mapping (address => Delegator) private delegators;
mapping (address => Transcoder) private transcoders;
// DEPRECATED - DO NOT USE
// The function getTotalBonded() no longer uses this variable
// and instead calculates the total bonded value separately
uint256 private totalBondedDEPRECATED;
// DEPRECATED - DO NOT USE
SortedDoublyLL.Data private transcoderPoolDEPRECATED;
// DEPRECATED - DO NOT USE
struct ActiveTranscoderSetDEPRECATED {
address[] transcoders;
mapping (address => bool) isActive;
uint256 totalStake;
}
// DEPRECATED - DO NOT USE
mapping (uint256 => ActiveTranscoderSetDEPRECATED) public activeTranscoderSetDEPRECATED;
// The total active stake (sum of the stake of active set members) for the current round
uint256 public currentRoundTotalActiveStake;
// The total active stake (sum of the stake of active set members) for the next round
uint256 public nextRoundTotalActiveStake;
// The transcoder pool is used to keep track of the transcoders that are eligible for activation.
// The pool keeps track of the pending active set in round N and the start of round N + 1 transcoders
// in the pool are locked into the active set for round N + 1
SortedDoublyLL.Data private transcoderPoolV2;
// Flag for whether LIP-77 has been executed
bool private lip77Executed;
// Check if sender is TicketBroker
modifier onlyTicketBroker() {
_onlyTicketBroker();
_;
}
// Check if sender is RoundsManager
modifier onlyRoundsManager() {
_onlyRoundsManager();
_;
}
// Check if sender is Verifier
modifier onlyVerifier() {
_onlyVerifier();
_;
}
// Check if current round is initialized
modifier currentRoundInitialized() {
_currentRoundInitialized();
_;
}
// Automatically claim earnings from lastClaimRound through the current round
modifier autoClaimEarnings() {
_autoClaimEarnings();
_;
}
/**
* @notice BondingManager constructor. Only invokes constructor of base Manager contract with provided Controller address
* @dev This constructor will not initialize any state variables besides `controller`. The following setter functions
* should be used to initialize state variables post-deployment:
* - setUnbondingPeriod()
* - setNumActiveTranscoders()
* - setMaxEarningsClaimsRounds()
* @param _controller Address of Controller that this contract will be registered with
*/
constructor(address _controller) public Manager(_controller) {}
/**
* @notice Set unbonding period. Only callable by Controller owner
* @param _unbondingPeriod Rounds between unbonding and possible withdrawal
*/
function setUnbondingPeriod(uint64 _unbondingPeriod) external onlyControllerOwner {
unbondingPeriod = _unbondingPeriod;
emit ParameterUpdate("unbondingPeriod");
}
/**
* @notice Set maximum number of active transcoders. Only callable by Controller owner
* @param _numActiveTranscoders Number of active transcoders
*/
function setNumActiveTranscoders(uint256 _numActiveTranscoders) external onlyControllerOwner {
transcoderPoolV2.setMaxSize(_numActiveTranscoders);
emit ParameterUpdate("numActiveTranscoders");
}
/**
* @notice Set max number of rounds a caller can claim earnings for at once. Only callable by Controller owner
* @param _maxEarningsClaimsRounds Max number of rounds a caller can claim earnings for at once
*/
function setMaxEarningsClaimsRounds(uint256 _maxEarningsClaimsRounds) external onlyControllerOwner {
maxEarningsClaimsRounds = _maxEarningsClaimsRounds;
emit ParameterUpdate("maxEarningsClaimsRounds");
}
/**
* @notice Execute LIP-77. Can only be called once by Controller owner
* @param _bondedAmount The bonded amount for the LIP-77 address
*/
function executeLIP77(uint256 _bondedAmount) external onlyControllerOwner {
require(!lip77Executed, "LIP-77 already executed");
lip77Executed = true;
delegators[LIP_77_ADDRESS].bondedAmount = _bondedAmount;
address delegate = delegators[LIP_77_ADDRESS].delegateAddress;
emit Bond(delegate, delegate, LIP_77_ADDRESS, 0, _bondedAmount);
}
/**
* @notice Sets commission rates as a transcoder and if the caller is not in the transcoder pool tries to add it
* @dev Percentages are represented as numerators of fractions over MathUtils.PERC_DIVISOR
* @param _rewardCut % of reward paid to transcoder by a delegator
* @param _feeShare % of fees paid to delegators by a transcoder
*/
function transcoder(uint256 _rewardCut, uint256 _feeShare) external {
transcoderWithHint(_rewardCut, _feeShare, address(0), address(0));
}
/**
* @notice Delegate stake towards a specific address
* @param _amount The amount of tokens to stake
* @param _to The address of the transcoder to stake towards
*/
function bond(uint256 _amount, address _to) external {
bondWithHint(
_amount,
_to,
address(0),
address(0),
address(0),
address(0)
);
}
/**
* @notice Unbond an amount of the delegator's bonded stake
* @param _amount Amount of tokens to unbond
*/
function unbond(uint256 _amount) external {
unbondWithHint(_amount, address(0), address(0));
}
/**
* @notice Rebond tokens for an unbonding lock to a delegator's current delegate while a delegator is in the Bonded or Pending status
* @param _unbondingLockId ID of unbonding lock to rebond with
*/
function rebond(uint256 _unbondingLockId) external {
rebondWithHint(_unbondingLockId, address(0), address(0));
}
/**
* @notice Rebond tokens for an unbonding lock to a delegate while a delegator is in the Unbonded status
* @param _to Address of delegate
* @param _unbondingLockId ID of unbonding lock to rebond with
*/
function rebondFromUnbonded(address _to, uint256 _unbondingLockId) external {
rebondFromUnbondedWithHint(_to, _unbondingLockId, address(0), address(0));
}
/**
* @notice Withdraws tokens for an unbonding lock that has existed through an unbonding period
* @param _unbondingLockId ID of unbonding lock to withdraw with
*/
function withdrawStake(uint256 _unbondingLockId)
external
whenSystemNotPaused
currentRoundInitialized
{
Delegator storage del = delegators[msg.sender];
UnbondingLock storage lock = del.unbondingLocks[_unbondingLockId];
require(isValidUnbondingLock(msg.sender, _unbondingLockId), "invalid unbonding lock ID");
require(lock.withdrawRound <= roundsManager().currentRound(), "withdraw round must be before or equal to the current round");
uint256 amount = lock.amount;
uint256 withdrawRound = lock.withdrawRound;
// Delete unbonding lock
delete del.unbondingLocks[_unbondingLockId];
// Tell Minter to transfer stake (LPT) to the delegator
minter().trustedTransferTokens(msg.sender, amount);
emit WithdrawStake(msg.sender, _unbondingLockId, amount, withdrawRound);
}
/**
* @notice Withdraws fees to the caller
*/
function withdrawFees()
external
whenSystemNotPaused
currentRoundInitialized
autoClaimEarnings
{
uint256 fees = delegators[msg.sender].fees;
require(fees > 0, "no fees to withdraw");
delegators[msg.sender].fees = 0;
// Tell Minter to transfer fees (ETH) to the delegator
minter().trustedWithdrawETH(msg.sender, fees);
emit WithdrawFees(msg.sender);
}
/**
* @notice Mint token rewards for an active transcoder and its delegators
*/
function reward() external {
rewardWithHint(address(0), address(0));
}
/**
* @notice Update transcoder's fee pool. Only callable by the TicketBroker
* @param _transcoder Transcoder address
* @param _fees Fees to be added to the fee pool
*/
function updateTranscoderWithFees(
address _transcoder,
uint256 _fees,
uint256 _round
)
external
whenSystemNotPaused
onlyTicketBroker
{
// Silence unused param compiler warning
_round;
require(isRegisteredTranscoder(_transcoder), "transcoder must be registered");
uint256 currentRound = roundsManager().currentRound();
Transcoder storage t = transcoders[_transcoder];
uint256 lastRewardRound = t.lastRewardRound;
uint256 activeCumulativeRewards = t.activeCumulativeRewards;
// LIP-36: Add fees for the current round instead of '_round'
// https://github.com/livepeer/LIPs/issues/35#issuecomment-673659199
EarningsPool.Data storage earningsPool = t.earningsPoolPerRound[currentRound];
EarningsPool.Data memory prevEarningsPool = latestCumulativeFactorsPool(t, currentRound.sub(1));
// if transcoder hasn't called 'reward()' for '_round' its 'transcoderFeeShare', 'transcoderRewardCut' and 'totalStake'
// on the 'EarningsPool' for '_round' would not be initialized and the fee distribution wouldn't happen as expected
// for cumulative fee calculation this would result in division by zero.
if (currentRound > lastRewardRound) {
earningsPool.setCommission(
t.rewardCut,
t.feeShare
);
uint256 lastUpdateRound = t.lastActiveStakeUpdateRound;
if (lastUpdateRound < currentRound) {
earningsPool.setStake(t.earningsPoolPerRound[lastUpdateRound].totalStake);
}
// If reward() has not been called yet in the current round, then the transcoder's activeCumulativeRewards has not
// yet been set in for the round. When the transcoder calls reward() its activeCumulativeRewards will be set to its
// current cumulativeRewards. So, we can just use the transcoder's cumulativeRewards here because this will become
// the transcoder's activeCumulativeRewards if it calls reward() later on in the current round
activeCumulativeRewards = t.cumulativeRewards;
}
uint256 totalStake = earningsPool.totalStake;
if (prevEarningsPool.cumulativeRewardFactor == 0 && lastRewardRound == currentRound) {
// if transcoder called reward for 'currentRound' but not for 'currentRound - 1' (missed reward call)
// retroactively calculate what its cumulativeRewardFactor would have been for 'currentRound - 1' (cfr. previous lastRewardRound for transcoder)
// based on rewards for currentRound
IMinter mtr = minter();
uint256 rewards = PreciseMathUtils.percOf(mtr.currentMintableTokens().add(mtr.currentMintedTokens()), totalStake, currentRoundTotalActiveStake);
uint256 transcoderCommissionRewards = MathUtils.percOf(rewards, earningsPool.transcoderRewardCut);
uint256 delegatorsRewards = rewards.sub(transcoderCommissionRewards);
prevEarningsPool.cumulativeRewardFactor = PreciseMathUtils.percOf(
earningsPool.cumulativeRewardFactor,
totalStake,
delegatorsRewards.add(totalStake)
);
}
// If the previous cumulativeRewardFactor is 0 and the current round is before the LIP-71 round, set the default value to
// MathUtils.percPoints(1, 1) because we only set the default value to PreciseMathUtils.percPoints(1, 1) when storing for
// the LIP-71 round and onwards (see updateCumulativeFeeFactor() in EarningsPoolLIP36.sol)
if (prevEarningsPool.cumulativeRewardFactor == 0 && currentRound < roundsManager().lipUpgradeRound(71)) {
prevEarningsPool.cumulativeRewardFactor = MathUtils.percPoints(1, 1);
}
uint256 delegatorsFees = MathUtils.percOf(_fees, earningsPool.transcoderFeeShare);
uint256 transcoderCommissionFees = _fees.sub(delegatorsFees);
// Calculate the fees earned by the transcoder's earned rewards
uint256 transcoderRewardStakeFees = PreciseMathUtils.percOf(delegatorsFees, activeCumulativeRewards, totalStake);
// Track fees earned by the transcoder based on its earned rewards and feeShare
t.cumulativeFees = t.cumulativeFees.add(transcoderRewardStakeFees).add(transcoderCommissionFees);
// Update cumulative fee factor with new fees
// The cumulativeFeeFactor is used to calculate fees for all delegators including the transcoder (self-delegated)
// Note that delegatorsFees includes transcoderRewardStakeFees, but no delegator will claim that amount using
// the earnings claiming algorithm and instead that amount is accounted for in the transcoder's cumulativeFees field
earningsPool.updateCumulativeFeeFactor(prevEarningsPool, delegatorsFees);
t.lastFeeRound = currentRound;
}
/**
* @notice Slash a transcoder. Only callable by the Verifier
* @param _transcoder Transcoder address
* @param _finder Finder that proved a transcoder violated a slashing condition. Null address if there is no finder
* @param _slashAmount Percentage of transcoder bond to be slashed
* @param _finderFee Percentage of penalty awarded to finder. Zero if there is no finder
*/
function slashTranscoder(
address _transcoder,
address _finder,
uint256 _slashAmount,
uint256 _finderFee
)
external
whenSystemNotPaused
onlyVerifier
{
Delegator storage del = delegators[_transcoder];
if (del.bondedAmount > 0) {
uint256 penalty = MathUtils.percOf(delegators[_transcoder].bondedAmount, _slashAmount);
// If active transcoder, resign it
if (transcoderPoolV2.contains(_transcoder)) {
resignTranscoder(_transcoder);
}
// Decrease bonded stake
del.bondedAmount = del.bondedAmount.sub(penalty);
// If still bonded decrease delegate's delegated amount
if (delegatorStatus(_transcoder) == DelegatorStatus.Bonded) {
delegators[del.delegateAddress].delegatedAmount = delegators[del.delegateAddress].delegatedAmount.sub(penalty);
}
// Account for penalty
uint256 burnAmount = penalty;
// Award finder fee if there is a finder address
if (_finder != address(0)) {
uint256 finderAmount = MathUtils.percOf(penalty, _finderFee);
minter().trustedTransferTokens(_finder, finderAmount);
// Minter burns the slashed funds - finder reward
minter().trustedBurnTokens(burnAmount.sub(finderAmount));
emit TranscoderSlashed(_transcoder, _finder, penalty, finderAmount);
} else {
// Minter burns the slashed funds
minter().trustedBurnTokens(burnAmount);
emit TranscoderSlashed(_transcoder, address(0), penalty, 0);
}
} else {
emit TranscoderSlashed(_transcoder, _finder, 0, 0);
}
}
/**
* @notice Claim token pools shares for a delegator from its lastClaimRound through the end round
* @param _endRound The last round for which to claim token pools shares for a delegator
*/
function claimEarnings(uint256 _endRound) external whenSystemNotPaused currentRoundInitialized {
uint256 lastClaimRound = delegators[msg.sender].lastClaimRound;
require(lastClaimRound < _endRound, "end round must be after last claim round");
// _endRound should be equal to the current round because after LIP-36 using a past _endRound can result
// in incorrect cumulative factor values used/stored for the _endRound in updateDelegatorWithEarnings().
// The exception is when claiming through an _endRound before the LIP-36 upgrade round because cumulative factor
// values will not be used/stored in updateDelegatorWithEarnings() before the LIP-36 upgrade round.
require(
_endRound == roundsManager().currentRound() || _endRound < roundsManager().lipUpgradeRound(36),
"end round must be equal to the current round or before the LIP-36 upgrade round"
);
updateDelegatorWithEarnings(msg.sender, _endRound, lastClaimRound);
}
/**
* @notice Claim earnings for a delegator based on the snapshot taken in LIP-52
* @dev https://github.com/livepeer/LIPs/blob/master/LIPs/LIP-52.md
* @param _pendingStake the amount of pending stake for the delegator (current stake + pending rewards)
* @param _pendingFees the amount of pending fees for the delegator (current fees + pending fees)
* @param _earningsProof array of keccak256 sibling hashes on the branch of the leaf for the delegator up to the root
* @param _data (optional) raw transaction data to be executed on behalf of msg.sender after claiming snapshot earnings
*/
function claimSnapshotEarnings(
uint256 _pendingStake,
uint256 _pendingFees,
bytes32[] calldata _earningsProof,
bytes calldata _data
)
external
whenSystemNotPaused
currentRoundInitialized
{
Delegator storage del = delegators[msg.sender];
uint256 lip52Round = roundsManager().lipUpgradeRound(52);
uint256 lastClaimRound = del.lastClaimRound;
require(lastClaimRound < lip52Round, "Already claimed for LIP-52");
bytes32 leaf = keccak256(abi.encode(msg.sender, _pendingStake, _pendingFees));
require(
IMerkleSnapshot(controller.getContract(keccak256("MerkleSnapshot"))).verify(keccak256("LIP-52"), _earningsProof, leaf),
"Merkle proof is invalid"
);
emit EarningsClaimed(
del.delegateAddress,
msg.sender,
_pendingStake.sub(del.bondedAmount),
_pendingFees.sub(del.fees),
lastClaimRound.add(1),
lip52Round
);
del.lastClaimRound = lip52Round;
del.bondedAmount = _pendingStake;
del.fees = _pendingFees;
// allow for execution of subsequent claiming or staking operations
if (_data.length > 0) {
(bool success, bytes memory returnData) = address(this).delegatecall(_data);
require(success, string(returnData));
}
}
/**
* @notice Called during round initialization to set the total active stake for the round. Only callable by the RoundsManager
*/
function setCurrentRoundTotalActiveStake() external onlyRoundsManager {
currentRoundTotalActiveStake = nextRoundTotalActiveStake;
}
/**
* @notice Sets commission rates as a transcoder and if the caller is not in the transcoder pool tries to add it using an optional list hint
* @dev Percentages are represented as numerators of fractions over MathUtils.PERC_DIVISOR. If the caller is going to be added to the pool, the
* caller can provide an optional hint for the insertion position in the pool via the `_newPosPrev` and `_newPosNext` params. A linear search will
* be executed starting at the hint to find the correct position - in the best case, the hint is the correct position so no search is executed.
* See SortedDoublyLL.sol for details on list hints
* @param _rewardCut % of reward paid to transcoder by a delegator
* @param _feeShare % of fees paid to delegators by a transcoder
* @param _newPosPrev Address of previous transcoder in pool if the caller joins the pool
* @param _newPosNext Address of next transcoder in pool if the caller joins the pool
*/
function transcoderWithHint(uint256 _rewardCut, uint256 _feeShare, address _newPosPrev, address _newPosNext)
public
whenSystemNotPaused
currentRoundInitialized
{
require(
!roundsManager().currentRoundLocked(),
"can't update transcoder params, current round is locked"
);
require(MathUtils.validPerc(_rewardCut), "invalid rewardCut percentage");
require(MathUtils.validPerc(_feeShare), "invalid feeShare percentage");
require(isRegisteredTranscoder(msg.sender), "transcoder must be registered");
Transcoder storage t = transcoders[msg.sender];
uint256 currentRound = roundsManager().currentRound();
require(
!isActiveTranscoder(msg.sender) || t.lastRewardRound == currentRound,
"caller can't be active or must have already called reward for the current round"
);
t.rewardCut = _rewardCut;
t.feeShare = _feeShare;
if (!transcoderPoolV2.contains(msg.sender)) {
tryToJoinActiveSet(msg.sender, delegators[msg.sender].delegatedAmount, currentRound.add(1), _newPosPrev, _newPosNext);
}
emit TranscoderUpdate(msg.sender, _rewardCut, _feeShare);
}
/**
* @notice Delegate stake towards a specific address and updates the transcoder pool using optional list hints if needed
* @dev If the caller is decreasing the stake of its old delegate in the transcoder pool, the caller can provide an optional hint
* for the insertion position of the old delegate via the `_oldDelegateNewPosPrev` and `_oldDelegateNewPosNext` params.
* If the caller is delegating to a delegate that is in the transcoder pool, the caller can provide an optional hint for the
* insertion position of the delegate via the `_currDelegateNewPosPrev` and `_currDelegateNewPosNext` params.
* In both cases, a linear search will be executed starting at the hint to find the correct position. In the best case, the hint
* is the correct position so no search is executed. See SortedDoublyLL.sol for details on list hints
* @param _amount The amount of tokens to stake.
* @param _to The address of the transcoder to stake towards
* @param _oldDelegateNewPosPrev The address of the previous transcoder in the pool for the old delegate
* @param _oldDelegateNewPosNext The address of the next transcoder in the pool for the old delegate
* @param _currDelegateNewPosPrev The address of the previous transcoder in the pool for the current delegate
* @param _currDelegateNewPosNext The address of the next transcoder in the pool for the current delegate
*/
function bondWithHint(
uint256 _amount,
address _to,
address _oldDelegateNewPosPrev,
address _oldDelegateNewPosNext,
address _currDelegateNewPosPrev,
address _currDelegateNewPosNext
)
public
whenSystemNotPaused
currentRoundInitialized
autoClaimEarnings
{
Delegator storage del = delegators[msg.sender];
uint256 currentRound = roundsManager().currentRound();
// Amount to delegate
uint256 delegationAmount = _amount;
// Current delegate
address currentDelegate = del.delegateAddress;
if (delegatorStatus(msg.sender) == DelegatorStatus.Unbonded) {
// New delegate
// Set start round
// Don't set start round if delegator is in pending state because the start round would not change
del.startRound = currentRound.add(1);
// Unbonded state = no existing delegate and no bonded stake
// Thus, delegation amount = provided amount
} else if (currentDelegate != address(0) && currentDelegate != _to) {
// A registered transcoder cannot delegate its bonded stake toward another address
// because it can only be delegated toward itself
// In the future, if delegation towards another registered transcoder as an already
// registered transcoder becomes useful (i.e. for transitive delegation), this restriction
// could be removed
require(!isRegisteredTranscoder(msg.sender), "registered transcoders can't delegate towards other addresses");
// Changing delegate
// Set start round
del.startRound = currentRound.add(1);
// Update amount to delegate with previous delegation amount
delegationAmount = delegationAmount.add(del.bondedAmount);
decreaseTotalStake(currentDelegate, del.bondedAmount, _oldDelegateNewPosPrev, _oldDelegateNewPosNext);
}
Transcoder storage newDelegate = transcoders[_to];
EarningsPool.Data storage currPool = newDelegate.earningsPoolPerRound[currentRound];
if (currPool.cumulativeRewardFactor == 0) {
currPool.cumulativeRewardFactor = cumulativeFactorsPool(newDelegate, newDelegate.lastRewardRound).cumulativeRewardFactor;
}
if (currPool.cumulativeFeeFactor == 0) {
currPool.cumulativeFeeFactor = cumulativeFactorsPool(newDelegate, newDelegate.lastFeeRound).cumulativeFeeFactor;
}
// cannot delegate to someone without having bonded stake
require(delegationAmount > 0, "delegation amount must be greater than 0");
// Update delegate
del.delegateAddress = _to;
// Update bonded amount
del.bondedAmount = del.bondedAmount.add(_amount);
increaseTotalStake(_to, delegationAmount, _currDelegateNewPosPrev, _currDelegateNewPosNext);
if (_amount > 0) {
// Transfer the LPT to the Minter
livepeerToken().transferFrom(msg.sender, address(minter()), _amount);
}
emit Bond(_to, currentDelegate, msg.sender, _amount, del.bondedAmount);
}
/**
* @notice Unbond an amount of the delegator's bonded stake and updates the transcoder pool using an optional list hint if needed
* @dev If the caller remains in the transcoder pool, the caller can provide an optional hint for its insertion position in the
* pool via the `_newPosPrev` and `_newPosNext` params. A linear search will be executed starting at the hint to find the correct position.
* In the best case, the hint is the correct position so no search is executed. See SortedDoublyLL.sol details on list hints
* @param _amount Amount of tokens to unbond
* @param _newPosPrev Address of previous transcoder in pool if the caller remains in the pool
* @param _newPosNext Address of next transcoder in pool if the caller remains in the pool
*/
function unbondWithHint(uint256 _amount, address _newPosPrev, address _newPosNext)
public
whenSystemNotPaused
currentRoundInitialized
autoClaimEarnings
{
require(delegatorStatus(msg.sender) == DelegatorStatus.Bonded, "caller must be bonded");
Delegator storage del = delegators[msg.sender];
require(_amount > 0, "unbond amount must be greater than 0");
require(_amount <= del.bondedAmount, "amount is greater than bonded amount");
address currentDelegate = del.delegateAddress;
uint256 currentRound = roundsManager().currentRound();
uint256 withdrawRound = currentRound.add(unbondingPeriod);
uint256 unbondingLockId = del.nextUnbondingLockId;
// Create new unbonding lock
del.unbondingLocks[unbondingLockId] = UnbondingLock({
amount: _amount,
withdrawRound: withdrawRound
});
// Increment ID for next unbonding lock
del.nextUnbondingLockId = unbondingLockId.add(1);
// Decrease delegator's bonded amount
del.bondedAmount = del.bondedAmount.sub(_amount);
if (del.bondedAmount == 0) {
// Delegator no longer delegated to anyone if it does not have a bonded amount
del.delegateAddress = address(0);
// Delegator does not have a start round if it is no longer delegated to anyone
del.startRound = 0;
if (transcoderPoolV2.contains(msg.sender)) {
resignTranscoder(msg.sender);
}
}
// If msg.sender was resigned this statement will only decrease delegators[currentDelegate].delegatedAmount
decreaseTotalStake(currentDelegate, _amount, _newPosPrev, _newPosNext);
emit Unbond(currentDelegate, msg.sender, unbondingLockId, _amount, withdrawRound);
}
/**
* @notice Rebond tokens for an unbonding lock to a delegator's current delegate while a delegator is in the Bonded or Pending status and updates
* the transcoder pool using an optional list hint if needed
* @dev If the delegate is in the transcoder pool, the caller can provide an optional hint for the delegate's insertion position in the
* pool via the `_newPosPrev` and `_newPosNext` params. A linear search will be executed starting at the hint to find the correct position.
* In the best case, the hint is the correct position so no search is executed. See SortedDoublyLL.sol details on list hints
* @param _unbondingLockId ID of unbonding lock to rebond with
* @param _newPosPrev Address of previous transcoder in pool if the delegate is in the pool
* @param _newPosNext Address of next transcoder in pool if the delegate is in the pool
*/
function rebondWithHint(
uint256 _unbondingLockId,
address _newPosPrev,
address _newPosNext
)
public
whenSystemNotPaused
currentRoundInitialized
autoClaimEarnings
{
require(delegatorStatus(msg.sender) != DelegatorStatus.Unbonded, "caller must be bonded");
// Process rebond using unbonding lock
processRebond(msg.sender, _unbondingLockId, _newPosPrev, _newPosNext);
}
/**
* @notice Rebond tokens for an unbonding lock to a delegate while a delegator is in the Unbonded status and updates the transcoder pool using
* an optional list hint if needed
* @dev If the delegate joins the transcoder pool, the caller can provide an optional hint for the delegate's insertion position in the
* pool via the `_newPosPrev` and `_newPosNext` params. A linear search will be executed starting at the hint to find the correct position.
* In the best case, the hint is the correct position so no search is executed. See SortedDoublyLL.sol for details on list hints
* @param _to Address of delegate
* @param _unbondingLockId ID of unbonding lock to rebond with
* @param _newPosPrev Address of previous transcoder in pool if the delegate joins the pool
* @param _newPosNext Address of next transcoder in pool if the delegate joins the pool
*/
function rebondFromUnbondedWithHint(
address _to,
uint256 _unbondingLockId,
address _newPosPrev,
address _newPosNext
)
public
whenSystemNotPaused
currentRoundInitialized
autoClaimEarnings
{
require(delegatorStatus(msg.sender) == DelegatorStatus.Unbonded, "caller must be unbonded");
// Set delegator's start round and transition into Pending state
delegators[msg.sender].startRound = roundsManager().currentRound().add(1);
// Set delegator's delegate
delegators[msg.sender].delegateAddress = _to;
// Process rebond using unbonding lock
processRebond(msg.sender, _unbondingLockId, _newPosPrev, _newPosNext);
}
/**
* @notice Mint token rewards for an active transcoder and its delegators and update the transcoder pool using an optional list hint if needed
* @dev If the caller is in the transcoder pool, the caller can provide an optional hint for its insertion position in the
* pool via the `_newPosPrev` and `_newPosNext` params. A linear search will be executed starting at the hint to find the correct position.
* In the best case, the hint is the correct position so no search is executed. See SortedDoublyLL.sol for details on list hints
* @param _newPosPrev Address of previous transcoder in pool if the caller is in the pool
* @param _newPosNext Address of next transcoder in pool if the caller is in the pool
*/
function rewardWithHint(address _newPosPrev, address _newPosNext) public whenSystemNotPaused currentRoundInitialized {
uint256 currentRound = roundsManager().currentRound();
require(isActiveTranscoder(msg.sender), "caller must be an active transcoder");
require(transcoders[msg.sender].lastRewardRound != currentRound, "caller has already called reward for the current round");
Transcoder storage t = transcoders[msg.sender];
EarningsPool.Data storage earningsPool = t.earningsPoolPerRound[currentRound];
// Set last round that transcoder called reward
earningsPool.setCommission(t.rewardCut, t.feeShare);
// If transcoder didn't receive stake updates during the previous round and hasn't called reward for > 1 round
// the 'totalStake' on its 'EarningsPool' for the current round wouldn't be initialized
// Thus we sync the the transcoder's stake to when it was last updated
// 'updateTrancoderWithRewards()' will set the update round to 'currentRound +1' so this synchronization shouldn't occur frequently
uint256 lastUpdateRound = t.lastActiveStakeUpdateRound;
if (lastUpdateRound < currentRound) {
earningsPool.setStake(t.earningsPoolPerRound[lastUpdateRound].totalStake);
}
// Create reward based on active transcoder's stake relative to the total active stake
// rewardTokens = (current mintable tokens for the round * active transcoder stake) / total active stake
uint256 rewardTokens = minter().createReward(earningsPool.totalStake, currentRoundTotalActiveStake);
updateTranscoderWithRewards(msg.sender, rewardTokens, currentRound, _newPosPrev, _newPosNext);
// Set last round that transcoder called reward
t.lastRewardRound = currentRound;
emit Reward(msg.sender, rewardTokens);
}
/**
* @notice Returns pending bonded stake for a delegator from its lastClaimRound through an end round
* @param _delegator Address of delegator
* @param _endRound The last round to compute pending stake from
* @return Pending bonded stake for '_delegator' since last claiming rewards
*/
function pendingStake(address _delegator, uint256 _endRound) public view returns (uint256) {
// _endRound should be equal to the current round because after LIP-36 using a past _endRound can result
// in incorrect cumulative factor values used for the _endRound in pendingStakeAndFees().
// The exception is when calculating stake through an _endRound before the LIP-36 upgrade round because cumulative factor
// values will not be used in pendingStakeAndFees() before the LIP-36 upgrade round.
uint256 endRound = _endRound;
if (endRound >= roundsManager().lipUpgradeRound(36)) {
endRound = roundsManager().currentRound();
}
(
uint256 stake,
) = pendingStakeAndFees(_delegator, endRound);
return stake;
}
/**
* @notice Returns pending fees for a delegator from its lastClaimRound through an end round
* @param _delegator Address of delegator
* @param _endRound The last round to compute pending fees from
* @return Pending fees for '_delegator' since last claiming fees
*/
function pendingFees(address _delegator, uint256 _endRound) public view returns (uint256) {
// _endRound should be equal to the current round because after LIP-36 using a past _endRound can result
// in incorrect cumulative factor values used for the _endRound in pendingStakeAndFees().
// The exception is when calculating fees through an _endRound before the LIP-36 upgrade round because cumulative factor
// values will not be used in pendingStakeAndFees() before the LIP-36 upgrade round.
uint256 endRound = _endRound;
if (endRound >= roundsManager().lipUpgradeRound(36)) {
endRound = roundsManager().currentRound();
}
(
,
uint256 fees
) = pendingStakeAndFees(_delegator, endRound);
return fees;
}
/**
* @notice Returns total bonded stake for a transcoder
* @param _transcoder Address of transcoder
* @return total bonded stake for a delegator
*/
function transcoderTotalStake(address _transcoder) public view returns (uint256) {
return delegators[_transcoder].delegatedAmount;
}
/**
* @notice Computes transcoder status
* @param _transcoder Address of transcoder
* @return registered or not registered transcoder status
*/
function transcoderStatus(address _transcoder) public view returns (TranscoderStatus) {
if (isRegisteredTranscoder(_transcoder)) return TranscoderStatus.Registered;
return TranscoderStatus.NotRegistered;
}
/**
* @notice Computes delegator status
* @param _delegator Address of delegator
* @return bonded, unbonded or pending delegator status
*/
function delegatorStatus(address _delegator) public view returns (DelegatorStatus) {
Delegator storage del = delegators[_delegator];
if (del.bondedAmount == 0) {
// Delegator unbonded all its tokens
return DelegatorStatus.Unbonded;
} else if (del.startRound > roundsManager().currentRound()) {
// Delegator round start is in the future
return DelegatorStatus.Pending;
} else {
// Delegator round start is now or in the past
// del.startRound != 0 here because if del.startRound = 0 then del.bondedAmount = 0 which
// would trigger the first if clause
return DelegatorStatus.Bonded;
}
}
/**
* @notice Return transcoder information
* @param _transcoder Address of transcoder
* @return lastRewardRound Trancoder's last reward round
* @return rewardCut Transcoder's reward cut
* @return feeShare Transcoder's fee share
* @return lastActiveStakeUpdateRound Round in which transcoder's stake was last updated while active
* @return activationRound Round in which transcoder became active
* @return deactivationRound Round in which transcoder will no longer be active
* @return activeCumulativeRewards Transcoder's cumulative rewards that are currently active
* @return cumulativeRewards Transcoder's cumulative rewards (earned via its active staked rewards and its reward cut)
* @return cumulativeFees Transcoder's cumulative fees (earned via its active staked rewards and its fee share)
* @return lastFeeRound Latest round that the transcoder received fees
*/
function getTranscoder(
address _transcoder
)
public
view
returns (uint256 lastRewardRound, uint256 rewardCut, uint256 feeShare, uint256 lastActiveStakeUpdateRound, uint256 activationRound, uint256 deactivationRound, uint256 activeCumulativeRewards, uint256 cumulativeRewards, uint256 cumulativeFees, uint256 lastFeeRound)
{
Transcoder storage t = transcoders[_transcoder];
lastRewardRound = t.lastRewardRound;
rewardCut = t.rewardCut;
feeShare = t.feeShare;
lastActiveStakeUpdateRound = t.lastActiveStakeUpdateRound;
activationRound = t.activationRound;
deactivationRound = t.deactivationRound;
activeCumulativeRewards = t.activeCumulativeRewards;
cumulativeRewards = t.cumulativeRewards;
cumulativeFees = t.cumulativeFees;
lastFeeRound = t.lastFeeRound;
}
/**
* @notice Return transcoder's earnings pool for a given round
* @param _transcoder Address of transcoder
* @param _round Round number
* @return rewardPool Reward pool for delegators (only used before LIP-36)
* @return feePool Fee pool for delegators (only used before LIP-36)
* @return totalStake Transcoder's total stake in '_round'
* @return claimableStake Remaining stake that can be used to claim from the pool (only used before LIP-36)
* @return transcoderRewardCut Transcoder's reward cut for '_round'
* @return transcoderFeeShare Transcoder's fee share for '_round'
* @return transcoderRewardPool Transcoder's rewards for '_round' (only used before LIP-36)
* @return transcoderFeePool Transcoder's fees for '_round' (only used before LIP-36)
* @return hasTranscoderRewardFeePool True if there is a split reward/fee pool for the transcoder (only used before LIP-36)
* @return cumulativeRewardFactor The cumulative reward factor for delegator rewards calculation (only used after LIP-36)
* @return cumulativeFeeFactor The cumulative fee factor for delegator fees calculation (only used after LIP-36)
*/
function getTranscoderEarningsPoolForRound(
address _transcoder,
uint256 _round
)
public
view
returns (uint256 rewardPool, uint256 feePool, uint256 totalStake, uint256 claimableStake, uint256 transcoderRewardCut, uint256 transcoderFeeShare, uint256 transcoderRewardPool, uint256 transcoderFeePool, bool hasTranscoderRewardFeePool, uint256 cumulativeRewardFactor, uint256 cumulativeFeeFactor)
{
EarningsPool.Data storage earningsPool = transcoders[_transcoder].earningsPoolPerRound[_round];
rewardPool = earningsPool.rewardPool;
feePool = earningsPool.feePool;
totalStake = earningsPool.totalStake;
claimableStake = earningsPool.claimableStake;
transcoderRewardCut = earningsPool.transcoderRewardCut;
transcoderFeeShare = earningsPool.transcoderFeeShare;
transcoderRewardPool = earningsPool.transcoderRewardPool;
transcoderFeePool = earningsPool.transcoderFeePool;
hasTranscoderRewardFeePool = earningsPool.hasTranscoderRewardFeePool;
cumulativeRewardFactor = earningsPool.cumulativeRewardFactor;
cumulativeFeeFactor = earningsPool.cumulativeFeeFactor;
}
/**
* @notice Return delegator info
* @param _delegator Address of delegator
* @return total amount bonded by '_delegator'
* @return amount of fees collected by '_delegator'
* @return address '_delegator' has bonded to
* @return total amount delegated to '_delegator'
* @return round in which bond for '_delegator' became effective
* @return round for which '_delegator' has last claimed earnings
* @return ID for the next unbonding lock created for '_delegator'
*/
function getDelegator(
address _delegator
)
public
view
returns (uint256 bondedAmount, uint256 fees, address delegateAddress, uint256 delegatedAmount, uint256 startRound, uint256 lastClaimRound, uint256 nextUnbondingLockId)
{
Delegator storage del = delegators[_delegator];
bondedAmount = del.bondedAmount;
fees = del.fees;
delegateAddress = del.delegateAddress;
delegatedAmount = del.delegatedAmount;
startRound = del.startRound;
lastClaimRound = del.lastClaimRound;
nextUnbondingLockId = del.nextUnbondingLockId;
}
/**
* @notice Return delegator's unbonding lock info
* @param _delegator Address of delegator
* @param _unbondingLockId ID of unbonding lock
* @return amount of stake locked up by unbonding lock
* @return round in which 'amount' becomes available for withdrawal
*/
function getDelegatorUnbondingLock(
address _delegator,
uint256 _unbondingLockId
)
public
view
returns (uint256 amount, uint256 withdrawRound)
{
UnbondingLock storage lock = delegators[_delegator].unbondingLocks[_unbondingLockId];
return (lock.amount, lock.withdrawRound);
}
/**
* @notice Returns max size of transcoder pool
* @return transcoder pool max size
*/
function getTranscoderPoolMaxSize() public view returns (uint256) {
return transcoderPoolV2.getMaxSize();
}
/**
* @notice Returns size of transcoder pool
* @return transcoder pool current size
*/
function getTranscoderPoolSize() public view returns (uint256) {
return transcoderPoolV2.getSize();
}
/**
* @notice Returns transcoder with most stake in pool
* @return address for transcoder with highest stake in transcoder pool
*/
function getFirstTranscoderInPool() public view returns (address) {
return transcoderPoolV2.getFirst();
}
/**
* @notice Returns next transcoder in pool for a given transcoder
* @param _transcoder Address of a transcoder in the pool
* @return address for the transcoder after '_transcoder' in transcoder pool
*/
function getNextTranscoderInPool(address _transcoder) public view returns (address) {
return transcoderPoolV2.getNext(_transcoder);
}
/**
* @notice Return total bonded tokens
* @return total active stake for the current round
*/
function getTotalBonded() public view returns (uint256) {
return currentRoundTotalActiveStake;
}
/**
* @notice Return whether a transcoder is active for the current round
* @param _transcoder Transcoder address
* @return true if transcoder is active
*/
function isActiveTranscoder(address _transcoder) public view returns (bool) {
Transcoder storage t = transcoders[_transcoder];
uint256 currentRound = roundsManager().currentRound();
return t.activationRound <= currentRound && currentRound < t.deactivationRound;
}
/**
* @notice Return whether a transcoder is registered
* @param _transcoder Transcoder address
* @return true if transcoder is self-bonded
*/
function isRegisteredTranscoder(address _transcoder) public view returns (bool) {
Delegator storage d = delegators[_transcoder];
return d.delegateAddress == _transcoder && d.bondedAmount > 0;
}
/**
* @notice Return whether an unbonding lock for a delegator is valid
* @param _delegator Address of delegator
* @param _unbondingLockId ID of unbonding lock
* @return true if unbondingLock for ID has a non-zero withdraw round
*/
function isValidUnbondingLock(address _delegator, uint256 _unbondingLockId) public view returns (bool) {
// A unbonding lock is only valid if it has a non-zero withdraw round (the default value is zero)
return delegators[_delegator].unbondingLocks[_unbondingLockId].withdrawRound > 0;
}
/**
* @notice Return an EarningsPool.Data struct with cumulative factors for a given round that are rescaled if needed
* @param _transcoder Storage pointer to a transcoder struct
* @param _round The round to fetch the cumulative factors for
*/
function cumulativeFactorsPool(Transcoder storage _transcoder, uint256 _round) internal view returns (EarningsPool.Data memory pool) {
pool.cumulativeRewardFactor = _transcoder.earningsPoolPerRound[_round].cumulativeRewardFactor;
pool.cumulativeFeeFactor = _transcoder.earningsPoolPerRound[_round].cumulativeFeeFactor;
uint256 lip71Round = roundsManager().lipUpgradeRound(71);
// If we are at or after the LIP-71 round then all cumulative factor values should be scaled using PreciseMathUtils.percPoints(1, 1)
// If a cumulative factor was stored before the LIP-71 round it will still be scaled using MathUtils.percPoints(1, 1)
// So, once we are at or after the LIP-71 round, if we read a cumulative factor for a round before the LIP-71 round, we rescale
// the value by RESCALE_FACTOR so that the end value is scaled by PreciseMathUtils.percPoints(1, 1)
if (roundsManager().currentRound() >= lip71Round) {
if (_round < lip71Round) {
pool.cumulativeRewardFactor = pool.cumulativeRewardFactor.mul(RESCALE_FACTOR);
pool.cumulativeFeeFactor = pool.cumulativeFeeFactor.mul(RESCALE_FACTOR);
} else {
// There was a bug in bondWithHint() that allowed cumulative factors to be stored after LIP-71 round to still be scaled using MathUtils.percPoints(1, 1)
// If we read a cumulativeRewardFactor for a round after the LIP-71 round and it is less than PreciseMathUtils.percPoints(1, 1), it was
// affected by this bug so we rescale it by RESCALE_FACTOR
if (pool.cumulativeRewardFactor < PreciseMathUtils.percPoints(1, 1)) {
pool.cumulativeRewardFactor = pool.cumulativeRewardFactor.mul(RESCALE_FACTOR);
}
// If cumulativeFeeFactor was previously rescaled, then its minimum value non-zero value is RESCALE_FACTOR
// If prior to rescaling:
// - cumulativeFeeFactor = 0, then after rescaling it would be 0
// - cumulativeFeeFactor >= 1, then after rescaling it would be >= RESCALE_FACTOR
// So, if we read a cumulativeFeeFactor for a round after the LIP-71 round and it is less than RESCALE_FACTOR its value is either 0, in which case
// it is still safe to rescale, or > 0, in which case it needs to be rescaled
if (pool.cumulativeFeeFactor < RESCALE_FACTOR) {
pool.cumulativeFeeFactor = pool.cumulativeFeeFactor.mul(RESCALE_FACTOR);
}
}
}
return pool;
}
/**
* @notice Return an EarningsPool.Data struct with the latest cumulative factors for a given round
* @param _transcoder Storage pointer to a transcoder struct
* @param _round The round to fetch the latest cumulative factors for
* @return pool An EarningsPool.Data populated with the latest cumulative factors for _round
*/
function latestCumulativeFactorsPool(Transcoder storage _transcoder, uint256 _round) internal view returns (EarningsPool.Data memory pool) {
pool = cumulativeFactorsPool(_transcoder, _round);
uint256 lastRewardRound = _transcoder.lastRewardRound;
// Only use the cumulativeRewardFactor for lastRewardRound if lastRewardRound is before _round
if (pool.cumulativeRewardFactor == 0 && lastRewardRound < _round) {
pool.cumulativeRewardFactor = cumulativeFactorsPool(_transcoder, lastRewardRound).cumulativeRewardFactor;
}
uint256 lastFeeRound = _transcoder.lastFeeRound;
// Only use the cumulativeFeeFactor for lastFeeRound if lastFeeRound is before _round
if (pool.cumulativeFeeFactor == 0 && lastFeeRound < _round) {
pool.cumulativeFeeFactor = cumulativeFactorsPool(_transcoder, lastFeeRound).cumulativeFeeFactor;
}
return pool;
}
/**
* @notice Return a delegator's cumulative stake and fees using the LIP-36 earnings claiming algorithm
* @param _transcoder Storage pointer to a transcoder struct for a delegator's delegate
* @param _startRound The round for the start cumulative factors
* @param _endRound The round for the end cumulative factors
* @param _stake The delegator's initial stake before including earned rewards
* @param _fees The delegator's initial fees before including earned fees
* @return (cStake, cFees) where cStake is the delegator's cumulative stake including earned rewards and cFees is the delegator's cumulative fees including earned fees
*/
function delegatorCumulativeStakeAndFees(
Transcoder storage _transcoder,
uint256 _startRound,
uint256 _endRound,
uint256 _stake,
uint256 _fees
)
internal
view
returns (uint256 cStake, uint256 cFees)
{
// Fetch start cumulative factors
EarningsPool.Data memory startPool = cumulativeFactorsPool(_transcoder, _startRound);
// We can lookback for a cumulativeRewardFactor if the start cumulativeRewardFactor is 0
// Do not lookback if the latest cumulativeRewardFactor is 0 because that indicates that the factor was never > 0 for the transcoder in the past
bool lookbackCumulativeRewardFactor = _transcoder.earningsPoolPerRound[_transcoder.lastRewardRound].cumulativeRewardFactor > 0 && startPool.cumulativeRewardFactor == 0;
// We can lookback for a cumulativeFeeFactor if the start cumulativeFeeFactor is 0
// Do not lookback if the latest cumulativeFeeFactor is 0 because that indicates that the factor was never > 0 for the transcoder in the past
bool lookbackCumulativeFeeFactor = _transcoder.earningsPoolPerRound[_transcoder.lastFeeRound].cumulativeFeeFactor > 0 && startPool.cumulativeFeeFactor == 0;
// The lookback loop will only be needed for a few accounts delegated to transcoders before the update that ensures start factors are always initialized
// If we need a cumulativeRewardFactor OR cumulativeFeeFactor lookback up to min(MAX_LOOKBACK_ROUNDS, _startRound) # of rounds
uint256 lip36Round = roundsManager().lipUpgradeRound(36);
for (uint256 lookback = 1; lookback <= MAX_LOOKBACK_ROUNDS && lookback <= _startRound && (lookbackCumulativeRewardFactor || lookbackCumulativeFeeFactor); lookback++) {
uint256 lookbackRound = _startRound.sub(lookback);
// Cannot lookback past the LIP-36 upgrade round
if (lookbackRound < lip36Round) {
break;
}
EarningsPool.Data storage pool = _transcoder.earningsPoolPerRound[lookbackRound];
// Short-circuit in the following conditionals by running the boolean check before the storage check
if (lookbackCumulativeRewardFactor && pool.cumulativeRewardFactor > 0) {
startPool.cumulativeRewardFactor = cumulativeFactorsPool(_transcoder, lookbackRound).cumulativeRewardFactor;
lookbackCumulativeRewardFactor = false;
}
if (lookbackCumulativeFeeFactor && pool.cumulativeFeeFactor > 0) {
startPool.cumulativeFeeFactor = cumulativeFactorsPool(_transcoder, lookbackRound).cumulativeFeeFactor;
lookbackCumulativeFeeFactor = false;
}
}
// If the start cumulativeRewardFactor is 0 and we are before the LIP-71 round, set the default value to
// MathUtils.percPoints(1, 1) because we only set the default value to PreciseMathUtils.percPoints(1, 1) from LIP-71 round
// and onward
if (startPool.cumulativeRewardFactor == 0) {
startPool.cumulativeRewardFactor = roundsManager().currentRound() < roundsManager().lipUpgradeRound(71) ?
MathUtils.percPoints(1, 1) : PreciseMathUtils.percPoints(1, 1);
}
// Fetch end cumulative factors
EarningsPool.Data memory endPool = latestCumulativeFactorsPool(_transcoder, _endRound);
// If the end cumulativeRewardFactor is 0 and we are before the LIP-71 round, set the default value to
// MathUtils.percPoints(1, 1) because we only set the default value to PreciseMathUtils.percPoints(1, 1) from LIP-71 round
// and onward
if (endPool.cumulativeRewardFactor == 0) {
endPool.cumulativeRewardFactor = roundsManager().currentRound() < roundsManager().lipUpgradeRound(71) ?
MathUtils.percPoints(1, 1) : PreciseMathUtils.percPoints(1, 1);
}
cFees = _fees.add(
PreciseMathUtils.percOf(
_stake,
endPool.cumulativeFeeFactor.sub(startPool.cumulativeFeeFactor),
startPool.cumulativeRewardFactor
)
);
cStake = PreciseMathUtils.percOf(
_stake,
endPool.cumulativeRewardFactor,
startPool.cumulativeRewardFactor
);
return (cStake, cFees);
}
/**
* @notice Return the pending stake and fees for a delegator
* @param _delegator Address of a delegator
* @param _endRound The last round to claim earnings for when calculating the pending stake and fees
* @return (stake, fees) where stake is the delegator's pending stake and fees is the delegator's pending fees
*/
function pendingStakeAndFees(address _delegator, uint256 _endRound) internal view returns (uint256 stake, uint256 fees) {
Delegator storage del = delegators[_delegator];
Transcoder storage t = transcoders[del.delegateAddress];
fees = del.fees;
stake = del.bondedAmount;
uint256 startRound = del.lastClaimRound.add(1);
address delegateAddr = del.delegateAddress;
bool isTranscoder = _delegator == delegateAddr;
uint256 lip36Round = roundsManager().lipUpgradeRound(36);
while (startRound <= _endRound && startRound <= lip36Round) {
EarningsPool.Data storage earningsPool = t.earningsPoolPerRound[startRound];
// If earningsPool.hasTranscoderRewardFeePool is not set during lip36Round then the transcoder did not call
// reward during lip36Round before the upgrade. In this case, if the transcoder calls reward in lip36Round
// the delegator can use the LIP-36 earnings claiming algorithm to claim for lip36Round
if (startRound == lip36Round && !earningsPool.hasTranscoderRewardFeePool) {
break;
}
if (earningsPool.hasClaimableShares()) {
// Calculate and add fee pool share from this round
fees = fees.add(earningsPool.feePoolShare(stake, isTranscoder));
// Calculate new bonded amount with rewards from this round. Updated bonded amount used
// to calculate fee pool share in next round
stake = stake.add(earningsPool.rewardPoolShare(stake, isTranscoder));
}
startRound = startRound.add(1);
}
// If the transcoder called reward during lip36Round the upgrade, then startRound = lip36Round
// Otherwise, startRound = lip36Round + 1
// If the start round is greater than the end round, we've already claimed for the end round so we do not
// need to execute the LIP-36 earnings claiming algorithm. This could be the case if:
// - _endRound < lip36Round i.e. we are not claiming through the lip36Round
// - _endRound == lip36Round AND startRound = lip36Round + 1 i.e we already claimed through the lip36Round
// The LIP-36 earnings claiming algorithm uses the cumulative factors from the delegator's lastClaimRound i.e. startRound - 1
// and from the specified _endRound
// We only need to execute this algorithm if the end round >= lip36Round
if (_endRound >= lip36Round) {
// Make sure there is a round to claim i.e. end round - (start round - 1) > 0
if (startRound <= _endRound) {
(
stake,
fees
) = delegatorCumulativeStakeAndFees(t, startRound.sub(1), _endRound, stake, fees);
}
// cumulativeRewards and cumulativeFees will track *all* rewards/fees earned by the transcoder
// so it is important that this is only executed with the end round as the current round or else
// the returned stake and fees will reflect rewards/fees earned in the future relative to the end round
if (isTranscoder) {
stake = stake.add(t.cumulativeRewards);
fees = fees.add(t.cumulativeFees);
}
}
return (stake, fees);
}
/**
* @dev Increase the total stake for a delegate and updates its 'lastActiveStakeUpdateRound'
* @param _delegate The delegate to increase the stake for
* @param _amount The amount to increase the stake for '_delegate' by
*/
function increaseTotalStake(address _delegate, uint256 _amount, address _newPosPrev, address _newPosNext) internal {
if (isRegisteredTranscoder(_delegate)) {
uint256 currStake = transcoderTotalStake(_delegate);
uint256 newStake = currStake.add(_amount);
uint256 currRound = roundsManager().currentRound();
uint256 nextRound = currRound.add(1);
// If the transcoder is already in the active set update its stake and return
if (transcoderPoolV2.contains(_delegate)) {
transcoderPoolV2.updateKey(_delegate, newStake, _newPosPrev, _newPosNext);
nextRoundTotalActiveStake = nextRoundTotalActiveStake.add(_amount);
Transcoder storage t = transcoders[_delegate];
// currStake (the transcoder's delegatedAmount field) will reflect the transcoder's stake from lastActiveStakeUpdateRound
// because it is updated every time lastActiveStakeUpdateRound is updated
// The current active total stake is set to currStake to ensure that the value can be used in updateTranscoderWithRewards()
// and updateTranscoderWithFees() when lastActiveStakeUpdateRound > currentRound
if (t.lastActiveStakeUpdateRound < currRound) {
t.earningsPoolPerRound[currRound].setStake(currStake);
}
t.earningsPoolPerRound[nextRound].setStake(newStake);
t.lastActiveStakeUpdateRound = nextRound;
} else {
// Check if the transcoder is eligible to join the active set in the update round
tryToJoinActiveSet(_delegate, newStake, nextRound, _newPosPrev, _newPosNext);
}
}
// Increase delegate's delegated amount
delegators[_delegate].delegatedAmount = delegators[_delegate].delegatedAmount.add(_amount);
}
/**
* @dev Decrease the total stake for a delegate and updates its 'lastActiveStakeUpdateRound'
* @param _delegate The transcoder to decrease the stake for
* @param _amount The amount to decrease the stake for '_delegate' by
*/
function decreaseTotalStake(address _delegate, uint256 _amount, address _newPosPrev, address _newPosNext) internal {
if (transcoderPoolV2.contains(_delegate)) {
uint256 currStake = transcoderTotalStake(_delegate);
uint256 newStake = currStake.sub(_amount);
uint256 currRound = roundsManager().currentRound();
uint256 nextRound = currRound.add(1);
transcoderPoolV2.updateKey(_delegate, newStake, _newPosPrev, _newPosNext);
nextRoundTotalActiveStake = nextRoundTotalActiveStake.sub(_amount);
Transcoder storage t = transcoders[_delegate];
// currStake (the transcoder's delegatedAmount field) will reflect the transcoder's stake from lastActiveStakeUpdateRound
// because it is updated every time lastActiveStakeUpdateRound is updated
// The current active total stake is set to currStake to ensure that the value can be used in updateTranscoderWithRewards()
// and updateTranscoderWithFees() when lastActiveStakeUpdateRound > currentRound
if (t.lastActiveStakeUpdateRound < currRound) {
t.earningsPoolPerRound[currRound].setStake(currStake);
}
t.lastActiveStakeUpdateRound = nextRound;
t.earningsPoolPerRound[nextRound].setStake(newStake);
}
// Decrease old delegate's delegated amount
delegators[_delegate].delegatedAmount = delegators[_delegate].delegatedAmount.sub(_amount);
}
/**
* @dev Tries to add a transcoder to active transcoder pool, evicts the active transcoder with the lowest stake if the pool is full
* @param _transcoder The transcoder to insert into the transcoder pool
* @param _totalStake The total stake for '_transcoder'
* @param _activationRound The round in which the transcoder should become active
*/
function tryToJoinActiveSet(
address _transcoder,
uint256 _totalStake,
uint256 _activationRound,
address _newPosPrev,
address _newPosNext
)
internal
{
uint256 pendingNextRoundTotalActiveStake = nextRoundTotalActiveStake;
if (transcoderPoolV2.isFull()) {
address lastTranscoder = transcoderPoolV2.getLast();
uint256 lastStake = transcoderTotalStake(lastTranscoder);
// If the pool is full and the transcoder has less stake than the least stake transcoder in the pool
// then the transcoder is unable to join the active set for the next round
if (_totalStake <= lastStake) {
return;
}
// Evict the least stake transcoder from the active set for the next round
// Not zeroing 'Transcoder.lastActiveStakeUpdateRound' saves gas (5k when transcoder is evicted and 20k when transcoder is reinserted)
// There should be no side-effects as long as the value is properly updated on stake updates
// Not zeroing the stake on the current round's 'EarningsPool' saves gas and should have no side effects as long as
// 'EarningsPool.setStake()' is called whenever a transcoder becomes active again.
transcoderPoolV2.remove(lastTranscoder);
transcoders[lastTranscoder].deactivationRound = _activationRound;
pendingNextRoundTotalActiveStake = pendingNextRoundTotalActiveStake.sub(lastStake);
emit TranscoderDeactivated(lastTranscoder, _activationRound);
}
transcoderPoolV2.insert(_transcoder, _totalStake, _newPosPrev, _newPosNext);
pendingNextRoundTotalActiveStake = pendingNextRoundTotalActiveStake.add(_totalStake);
Transcoder storage t = transcoders[_transcoder];
t.lastActiveStakeUpdateRound = _activationRound;
t.activationRound = _activationRound;
t.deactivationRound = MAX_FUTURE_ROUND;
t.earningsPoolPerRound[_activationRound].setStake(_totalStake);
nextRoundTotalActiveStake = pendingNextRoundTotalActiveStake;
emit TranscoderActivated(_transcoder, _activationRound);
}
/**
* @dev Remove a transcoder from the pool and deactivate it
*/
function resignTranscoder(address _transcoder) internal {
// Not zeroing 'Transcoder.lastActiveStakeUpdateRound' saves gas (5k when transcoder is evicted and 20k when transcoder is reinserted)
// There should be no side-effects as long as the value is properly updated on stake updates
// Not zeroing the stake on the current round's 'EarningsPool' saves gas and should have no side effects as long as
// 'EarningsPool.setStake()' is called whenever a transcoder becomes active again.
transcoderPoolV2.remove(_transcoder);
nextRoundTotalActiveStake = nextRoundTotalActiveStake.sub(transcoderTotalStake(_transcoder));
uint256 deactivationRound = roundsManager().currentRound().add(1);
transcoders[_transcoder].deactivationRound = deactivationRound;
emit TranscoderDeactivated(_transcoder, deactivationRound);
}
/**
* @dev Update a transcoder with rewards and update the transcoder pool with an optional list hint if needed.
* See SortedDoublyLL.sol for details on list hints
* @param _transcoder Address of transcoder
* @param _rewards Amount of rewards
* @param _round Round that transcoder is updated
* @param _newPosPrev Address of previous transcoder in pool if the transcoder is in the pool
* @param _newPosNext Address of next transcoder in pool if the transcoder is in the pool
*/
function updateTranscoderWithRewards(
address _transcoder,
uint256 _rewards,
uint256 _round,
address _newPosPrev,
address _newPosNext
)
internal
{
Transcoder storage t = transcoders[_transcoder];
EarningsPool.Data storage earningsPool = t.earningsPoolPerRound[_round];
EarningsPool.Data memory prevEarningsPool = cumulativeFactorsPool(t, t.lastRewardRound);
// If the previous cumulativeRewardFactor is 0 and we are before the LIP-71 round, set the default value to
// MathUtils.percPoints(1, 1) because we only set the default value to PreciseMathUtils.percPoints(1, 1) when storing for
// the LIP-71 round and onwards (see updateCumulativeRewardFactor() in EarningsPoolLIP36.sol)
if (prevEarningsPool.cumulativeRewardFactor == 0 && _round < roundsManager().lipUpgradeRound(71)) {
prevEarningsPool.cumulativeRewardFactor = MathUtils.percPoints(1, 1);
}
t.activeCumulativeRewards = t.cumulativeRewards;
uint256 transcoderCommissionRewards = MathUtils.percOf(_rewards, earningsPool.transcoderRewardCut);
uint256 delegatorsRewards = _rewards.sub(transcoderCommissionRewards);
// Calculate the rewards earned by the transcoder's earned rewards
uint256 transcoderRewardStakeRewards = PreciseMathUtils.percOf(delegatorsRewards, t.activeCumulativeRewards, earningsPool.totalStake);
// Track rewards earned by the transcoder based on its earned rewards and rewardCut
t.cumulativeRewards = t.cumulativeRewards.add(transcoderRewardStakeRewards).add(transcoderCommissionRewards);
// Update cumulative reward factor with new rewards
// The cumulativeRewardFactor is used to calculate rewards for all delegators including the transcoder (self-delegated)
// Note that delegatorsRewards includes transcoderRewardStakeRewards, but no delegator will claim that amount using
// the earnings claiming algorithm and instead that amount is accounted for in the transcoder's cumulativeRewards field
earningsPool.updateCumulativeRewardFactor(prevEarningsPool, delegatorsRewards);
// Update transcoder's total stake with rewards
increaseTotalStake(_transcoder, _rewards, _newPosPrev, _newPosNext);
}
/**
* @dev Update a delegator with token pools shares from its lastClaimRound through a given round
* @param _delegator Delegator address
* @param _endRound The last round for which to update a delegator's stake with earnings pool shares
* @param _lastClaimRound The round for which a delegator has last claimed earnings
*/
function updateDelegatorWithEarnings(address _delegator, uint256 _endRound, uint256 _lastClaimRound) internal {
Delegator storage del = delegators[_delegator];
uint256 startRound = _lastClaimRound.add(1);
uint256 currentBondedAmount = del.bondedAmount;
uint256 currentFees = del.fees;
uint256 lip36Round = roundsManager().lipUpgradeRound(36);
// Only will have earnings to claim if you have a delegate
// If not delegated, skip the earnings claim process
if (del.delegateAddress != address(0)) {
if (startRound <= lip36Round) {
// Cannot claim earnings for more than maxEarningsClaimsRounds before LIP-36
// This is a number to cause transactions to fail early if
// we know they will require too much gas to loop through all the necessary rounds to claim earnings
// The user should instead manually invoke `claimEarnings` to split up the claiming process
// across multiple transactions
uint256 endLoopRound = _endRound <= lip36Round ? _endRound : lip36Round;
require(endLoopRound.sub(_lastClaimRound) <= maxEarningsClaimsRounds, "too many rounds to claim through");
}
(
currentBondedAmount,
currentFees
) = pendingStakeAndFees(_delegator, _endRound);
// Only execute cumulative factor logic after LIP-36 upgrade round
// After LIP-36 upgrade round the following code block should only be executed if _endRound is the current round
// See claimEarnings() and autoClaimEarnings()
if (_endRound >= lip36Round) {
// Check whether the endEarningsPool is initialised
// If it is not initialised set it's cumulative factors so that they can be used when a delegator
// next claims earnings as the start cumulative factors (see delegatorCumulativeStakeAndFees())
Transcoder storage t = transcoders[del.delegateAddress];
EarningsPool.Data storage endEarningsPool = t.earningsPoolPerRound[_endRound];
if (endEarningsPool.cumulativeRewardFactor == 0) {
uint256 lastRewardRound = t.lastRewardRound;
if (lastRewardRound < _endRound) {
endEarningsPool.cumulativeRewardFactor = cumulativeFactorsPool(t, lastRewardRound).cumulativeRewardFactor;
}
}
if (endEarningsPool.cumulativeFeeFactor == 0) {
uint256 lastFeeRound = t.lastFeeRound;
if (lastFeeRound < _endRound) {
endEarningsPool.cumulativeFeeFactor = cumulativeFactorsPool(t, lastFeeRound).cumulativeFeeFactor;
}
}
if (del.delegateAddress == _delegator) {
t.cumulativeFees = 0;
t.cumulativeRewards = 0;
// activeCumulativeRewards is not cleared here because the next reward() call will set it to cumulativeRewards
}
}
}
emit EarningsClaimed(
del.delegateAddress,
_delegator,
currentBondedAmount.sub(del.bondedAmount),
currentFees.sub(del.fees),
startRound,
_endRound
);
del.lastClaimRound = _endRound;
// Rewards are bonded by default
del.bondedAmount = currentBondedAmount;
del.fees = currentFees;
}
/**
* @dev Update the state of a delegator and its delegate by processing a rebond using an unbonding lock and update the transcoder pool with an optional
* list hint if needed. See SortedDoublyLL.sol for details on list hints
* @param _delegator Address of delegator
* @param _unbondingLockId ID of unbonding lock to rebond with
* @param _newPosPrev Address of previous transcoder in pool if the delegate is already in or joins the pool
* @param _newPosNext Address of next transcoder in pool if the delegate is already in or joins the pool
*/
function processRebond(address _delegator, uint256 _unbondingLockId, address _newPosPrev, address _newPosNext) internal {
Delegator storage del = delegators[_delegator];
UnbondingLock storage lock = del.unbondingLocks[_unbondingLockId];
require(isValidUnbondingLock(_delegator, _unbondingLockId), "invalid unbonding lock ID");
uint256 amount = lock.amount;
// Increase delegator's bonded amount
del.bondedAmount = del.bondedAmount.add(amount);
// Delete lock
delete del.unbondingLocks[_unbondingLockId];
increaseTotalStake(del.delegateAddress, amount, _newPosPrev, _newPosNext);
emit Rebond(del.delegateAddress, _delegator, _unbondingLockId, amount);
}
/**
* @dev Return LivepeerToken interface
* @return Livepeer token contract registered with Controller
*/
function livepeerToken() internal view returns (ILivepeerToken) {
return ILivepeerToken(controller.getContract(keccak256("LivepeerToken")));
}
/**
* @dev Return Minter interface
* @return Minter contract registered with Controller
*/
function minter() internal view returns (IMinter) {
return IMinter(controller.getContract(keccak256("Minter")));
}
/**
* @dev Return RoundsManager interface
* @return RoundsManager contract registered with Controller
*/
function roundsManager() internal view returns (IRoundsManager) {
return IRoundsManager(controller.getContract(keccak256("RoundsManager")));
}
function _onlyTicketBroker() internal view {
require(
msg.sender == controller.getContract(keccak256("TicketBroker")),
"caller must be TicketBroker"
);
}
function _onlyRoundsManager() internal view {
require(
msg.sender == controller.getContract(keccak256("RoundsManager")),
"caller must be RoundsManager"
);
}
function _onlyVerifier() internal view {
require(msg.sender == controller.getContract(keccak256("Verifier")), "caller must be Verifier");
}
function _currentRoundInitialized() internal view {
require(roundsManager().currentRoundInitialized(), "current round is not initialized");
}
function _autoClaimEarnings() internal {
uint256 currentRound = roundsManager().currentRound();
uint256 lastClaimRound = delegators[msg.sender].lastClaimRound;
if (lastClaimRound < currentRound) {
updateDelegatorWithEarnings(msg.sender, currentRound, lastClaimRound);
}
}
} | contract BondingManager is ManagerProxyTarget, IBondingManager {
using SafeMath for uint256;
using SortedDoublyLL for SortedDoublyLL.Data;
using EarningsPool for EarningsPool.Data;
using EarningsPoolLIP36 for EarningsPool.Data;
// Constants
// Occurances are replaced at compile time
// and computed to a single value if possible by the optimizer
uint256 constant MAX_FUTURE_ROUND = 2**256 - 1;
uint256 constant MAX_LOOKBACK_ROUNDS = 100;
// PreciseMathUtils.percPoints(1, 1) / MathUtils.percPoints(1, 1) => (10 ** 27) / 1000000
uint256 constant RESCALE_FACTOR = 10 ** 21;
// Address for LIP-77 execution
address constant LIP_77_ADDRESS = 0xB47D8F87c0113827d44Ad0Bc32D53823C477a89d;
// Time between unbonding and possible withdrawl in rounds
uint64 public unbondingPeriod;
// DEPRECATED - DO NOT USE
uint256 public numActiveTranscodersDEPRECATED;
// Max number of rounds that a caller can claim earnings for at once
uint256 public maxEarningsClaimsRounds;
// Represents a transcoder's current state
struct Transcoder {
uint256 lastRewardRound; // Last round that the transcoder called reward
uint256 rewardCut; // % of reward paid to transcoder by a delegator
uint256 feeShare; // % of fees paid to delegators by transcoder
uint256 pricePerSegmentDEPRECATED; // DEPRECATED - DO NOT USE
uint256 pendingRewardCutDEPRECATED; // DEPRECATED - DO NOT USE
uint256 pendingFeeShareDEPRECATED; // DEPRECATED - DO NOT USE
uint256 pendingPricePerSegmentDEPRECATED; // DEPRECATED - DO NOT USE
mapping (uint256 => EarningsPool.Data) earningsPoolPerRound; // Mapping of round => earnings pool for the round
uint256 lastActiveStakeUpdateRound; // Round for which the stake was last updated while the transcoder is active
uint256 activationRound; // Round in which the transcoder became active - 0 if inactive
uint256 deactivationRound; // Round in which the transcoder will become inactive
uint256 activeCumulativeRewards; // The transcoder's cumulative rewards that are active in the current round
uint256 cumulativeRewards; // The transcoder's cumulative rewards (earned via the its active staked rewards and its reward cut).
uint256 cumulativeFees; // The transcoder's cumulative fees (earned via the its active staked rewards and its fee share)
uint256 lastFeeRound; // Latest round in which the transcoder received fees
}
// The various states a transcoder can be in
enum TranscoderStatus { NotRegistered, Registered }
// Represents a delegator's current state
struct Delegator {
uint256 bondedAmount; // The amount of bonded tokens
uint256 fees; // The amount of fees collected
address delegateAddress; // The address delegated to
uint256 delegatedAmount; // The amount of tokens delegated to the delegator
uint256 startRound; // The round the delegator transitions to bonded phase and is delegated to someone
uint256 withdrawRoundDEPRECATED; // DEPRECATED - DO NOT USE
uint256 lastClaimRound; // The last round during which the delegator claimed its earnings
uint256 nextUnbondingLockId; // ID for the next unbonding lock created
mapping (uint256 => UnbondingLock) unbondingLocks; // Mapping of unbonding lock ID => unbonding lock
}
// The various states a delegator can be in
enum DelegatorStatus { Pending, Bonded, Unbonded }
// Represents an amount of tokens that are being unbonded
struct UnbondingLock {
uint256 amount; // Amount of tokens being unbonded
uint256 withdrawRound; // Round at which unbonding period is over and tokens can be withdrawn
}
// Keep track of the known transcoders and delegators
mapping (address => Delegator) private delegators;
mapping (address => Transcoder) private transcoders;
// DEPRECATED - DO NOT USE
// The function getTotalBonded() no longer uses this variable
// and instead calculates the total bonded value separately
uint256 private totalBondedDEPRECATED;
// DEPRECATED - DO NOT USE
SortedDoublyLL.Data private transcoderPoolDEPRECATED;
// DEPRECATED - DO NOT USE
struct ActiveTranscoderSetDEPRECATED {
address[] transcoders;
mapping (address => bool) isActive;
uint256 totalStake;
}
// DEPRECATED - DO NOT USE
mapping (uint256 => ActiveTranscoderSetDEPRECATED) public activeTranscoderSetDEPRECATED;
// The total active stake (sum of the stake of active set members) for the current round
uint256 public currentRoundTotalActiveStake;
// The total active stake (sum of the stake of active set members) for the next round
uint256 public nextRoundTotalActiveStake;
// The transcoder pool is used to keep track of the transcoders that are eligible for activation.
// The pool keeps track of the pending active set in round N and the start of round N + 1 transcoders
// in the pool are locked into the active set for round N + 1
SortedDoublyLL.Data private transcoderPoolV2;
// Flag for whether LIP-77 has been executed
bool private lip77Executed;
// Check if sender is TicketBroker
modifier onlyTicketBroker() {
_onlyTicketBroker();
_;
}
// Check if sender is RoundsManager
modifier onlyRoundsManager() {
_onlyRoundsManager();
_;
}
// Check if sender is Verifier
modifier onlyVerifier() {
_onlyVerifier();
_;
}
// Check if current round is initialized
modifier currentRoundInitialized() {
_currentRoundInitialized();
_;
}
// Automatically claim earnings from lastClaimRound through the current round
modifier autoClaimEarnings() {
_autoClaimEarnings();
_;
}
/**
* @notice BondingManager constructor. Only invokes constructor of base Manager contract with provided Controller address
* @dev This constructor will not initialize any state variables besides `controller`. The following setter functions
* should be used to initialize state variables post-deployment:
* - setUnbondingPeriod()
* - setNumActiveTranscoders()
* - setMaxEarningsClaimsRounds()
* @param _controller Address of Controller that this contract will be registered with
*/
constructor(address _controller) public Manager(_controller) {}
/**
* @notice Set unbonding period. Only callable by Controller owner
* @param _unbondingPeriod Rounds between unbonding and possible withdrawal
*/
function setUnbondingPeriod(uint64 _unbondingPeriod) external onlyControllerOwner {
unbondingPeriod = _unbondingPeriod;
emit ParameterUpdate("unbondingPeriod");
}
/**
* @notice Set maximum number of active transcoders. Only callable by Controller owner
* @param _numActiveTranscoders Number of active transcoders
*/
function setNumActiveTranscoders(uint256 _numActiveTranscoders) external onlyControllerOwner {
transcoderPoolV2.setMaxSize(_numActiveTranscoders);
emit ParameterUpdate("numActiveTranscoders");
}
/**
* @notice Set max number of rounds a caller can claim earnings for at once. Only callable by Controller owner
* @param _maxEarningsClaimsRounds Max number of rounds a caller can claim earnings for at once
*/
function setMaxEarningsClaimsRounds(uint256 _maxEarningsClaimsRounds) external onlyControllerOwner {
maxEarningsClaimsRounds = _maxEarningsClaimsRounds;
emit ParameterUpdate("maxEarningsClaimsRounds");
}
/**
* @notice Execute LIP-77. Can only be called once by Controller owner
* @param _bondedAmount The bonded amount for the LIP-77 address
*/
function executeLIP77(uint256 _bondedAmount) external onlyControllerOwner {
require(!lip77Executed, "LIP-77 already executed");
lip77Executed = true;
delegators[LIP_77_ADDRESS].bondedAmount = _bondedAmount;
address delegate = delegators[LIP_77_ADDRESS].delegateAddress;
emit Bond(delegate, delegate, LIP_77_ADDRESS, 0, _bondedAmount);
}
/**
* @notice Sets commission rates as a transcoder and if the caller is not in the transcoder pool tries to add it
* @dev Percentages are represented as numerators of fractions over MathUtils.PERC_DIVISOR
* @param _rewardCut % of reward paid to transcoder by a delegator
* @param _feeShare % of fees paid to delegators by a transcoder
*/
function transcoder(uint256 _rewardCut, uint256 _feeShare) external {
transcoderWithHint(_rewardCut, _feeShare, address(0), address(0));
}
/**
* @notice Delegate stake towards a specific address
* @param _amount The amount of tokens to stake
* @param _to The address of the transcoder to stake towards
*/
function bond(uint256 _amount, address _to) external {
bondWithHint(
_amount,
_to,
address(0),
address(0),
address(0),
address(0)
);
}
/**
* @notice Unbond an amount of the delegator's bonded stake
* @param _amount Amount of tokens to unbond
*/
function unbond(uint256 _amount) external {
unbondWithHint(_amount, address(0), address(0));
}
/**
* @notice Rebond tokens for an unbonding lock to a delegator's current delegate while a delegator is in the Bonded or Pending status
* @param _unbondingLockId ID of unbonding lock to rebond with
*/
function rebond(uint256 _unbondingLockId) external {
rebondWithHint(_unbondingLockId, address(0), address(0));
}
/**
* @notice Rebond tokens for an unbonding lock to a delegate while a delegator is in the Unbonded status
* @param _to Address of delegate
* @param _unbondingLockId ID of unbonding lock to rebond with
*/
function rebondFromUnbonded(address _to, uint256 _unbondingLockId) external {
rebondFromUnbondedWithHint(_to, _unbondingLockId, address(0), address(0));
}
/**
* @notice Withdraws tokens for an unbonding lock that has existed through an unbonding period
* @param _unbondingLockId ID of unbonding lock to withdraw with
*/
function withdrawStake(uint256 _unbondingLockId)
external
whenSystemNotPaused
currentRoundInitialized
{
Delegator storage del = delegators[msg.sender];
UnbondingLock storage lock = del.unbondingLocks[_unbondingLockId];
require(isValidUnbondingLock(msg.sender, _unbondingLockId), "invalid unbonding lock ID");
require(lock.withdrawRound <= roundsManager().currentRound(), "withdraw round must be before or equal to the current round");
uint256 amount = lock.amount;
uint256 withdrawRound = lock.withdrawRound;
// Delete unbonding lock
delete del.unbondingLocks[_unbondingLockId];
// Tell Minter to transfer stake (LPT) to the delegator
minter().trustedTransferTokens(msg.sender, amount);
emit WithdrawStake(msg.sender, _unbondingLockId, amount, withdrawRound);
}
/**
* @notice Withdraws fees to the caller
*/
function withdrawFees()
external
whenSystemNotPaused
currentRoundInitialized
autoClaimEarnings
{
uint256 fees = delegators[msg.sender].fees;
require(fees > 0, "no fees to withdraw");
delegators[msg.sender].fees = 0;
// Tell Minter to transfer fees (ETH) to the delegator
minter().trustedWithdrawETH(msg.sender, fees);
emit WithdrawFees(msg.sender);
}
/**
* @notice Mint token rewards for an active transcoder and its delegators
*/
function reward() external {
rewardWithHint(address(0), address(0));
}
/**
* @notice Update transcoder's fee pool. Only callable by the TicketBroker
* @param _transcoder Transcoder address
* @param _fees Fees to be added to the fee pool
*/
function updateTranscoderWithFees(
address _transcoder,
uint256 _fees,
uint256 _round
)
external
whenSystemNotPaused
onlyTicketBroker
{
// Silence unused param compiler warning
_round;
require(isRegisteredTranscoder(_transcoder), "transcoder must be registered");
uint256 currentRound = roundsManager().currentRound();
Transcoder storage t = transcoders[_transcoder];
uint256 lastRewardRound = t.lastRewardRound;
uint256 activeCumulativeRewards = t.activeCumulativeRewards;
// LIP-36: Add fees for the current round instead of '_round'
// https://github.com/livepeer/LIPs/issues/35#issuecomment-673659199
EarningsPool.Data storage earningsPool = t.earningsPoolPerRound[currentRound];
EarningsPool.Data memory prevEarningsPool = latestCumulativeFactorsPool(t, currentRound.sub(1));
// if transcoder hasn't called 'reward()' for '_round' its 'transcoderFeeShare', 'transcoderRewardCut' and 'totalStake'
// on the 'EarningsPool' for '_round' would not be initialized and the fee distribution wouldn't happen as expected
// for cumulative fee calculation this would result in division by zero.
if (currentRound > lastRewardRound) {
earningsPool.setCommission(
t.rewardCut,
t.feeShare
);
uint256 lastUpdateRound = t.lastActiveStakeUpdateRound;
if (lastUpdateRound < currentRound) {
earningsPool.setStake(t.earningsPoolPerRound[lastUpdateRound].totalStake);
}
// If reward() has not been called yet in the current round, then the transcoder's activeCumulativeRewards has not
// yet been set in for the round. When the transcoder calls reward() its activeCumulativeRewards will be set to its
// current cumulativeRewards. So, we can just use the transcoder's cumulativeRewards here because this will become
// the transcoder's activeCumulativeRewards if it calls reward() later on in the current round
activeCumulativeRewards = t.cumulativeRewards;
}
uint256 totalStake = earningsPool.totalStake;
if (prevEarningsPool.cumulativeRewardFactor == 0 && lastRewardRound == currentRound) {
// if transcoder called reward for 'currentRound' but not for 'currentRound - 1' (missed reward call)
// retroactively calculate what its cumulativeRewardFactor would have been for 'currentRound - 1' (cfr. previous lastRewardRound for transcoder)
// based on rewards for currentRound
IMinter mtr = minter();
uint256 rewards = PreciseMathUtils.percOf(mtr.currentMintableTokens().add(mtr.currentMintedTokens()), totalStake, currentRoundTotalActiveStake);
uint256 transcoderCommissionRewards = MathUtils.percOf(rewards, earningsPool.transcoderRewardCut);
uint256 delegatorsRewards = rewards.sub(transcoderCommissionRewards);
prevEarningsPool.cumulativeRewardFactor = PreciseMathUtils.percOf(
earningsPool.cumulativeRewardFactor,
totalStake,
delegatorsRewards.add(totalStake)
);
}
// If the previous cumulativeRewardFactor is 0 and the current round is before the LIP-71 round, set the default value to
// MathUtils.percPoints(1, 1) because we only set the default value to PreciseMathUtils.percPoints(1, 1) when storing for
// the LIP-71 round and onwards (see updateCumulativeFeeFactor() in EarningsPoolLIP36.sol)
if (prevEarningsPool.cumulativeRewardFactor == 0 && currentRound < roundsManager().lipUpgradeRound(71)) {
prevEarningsPool.cumulativeRewardFactor = MathUtils.percPoints(1, 1);
}
uint256 delegatorsFees = MathUtils.percOf(_fees, earningsPool.transcoderFeeShare);
uint256 transcoderCommissionFees = _fees.sub(delegatorsFees);
// Calculate the fees earned by the transcoder's earned rewards
uint256 transcoderRewardStakeFees = PreciseMathUtils.percOf(delegatorsFees, activeCumulativeRewards, totalStake);
// Track fees earned by the transcoder based on its earned rewards and feeShare
t.cumulativeFees = t.cumulativeFees.add(transcoderRewardStakeFees).add(transcoderCommissionFees);
// Update cumulative fee factor with new fees
// The cumulativeFeeFactor is used to calculate fees for all delegators including the transcoder (self-delegated)
// Note that delegatorsFees includes transcoderRewardStakeFees, but no delegator will claim that amount using
// the earnings claiming algorithm and instead that amount is accounted for in the transcoder's cumulativeFees field
earningsPool.updateCumulativeFeeFactor(prevEarningsPool, delegatorsFees);
t.lastFeeRound = currentRound;
}
/**
* @notice Slash a transcoder. Only callable by the Verifier
* @param _transcoder Transcoder address
* @param _finder Finder that proved a transcoder violated a slashing condition. Null address if there is no finder
* @param _slashAmount Percentage of transcoder bond to be slashed
* @param _finderFee Percentage of penalty awarded to finder. Zero if there is no finder
*/
function slashTranscoder(
address _transcoder,
address _finder,
uint256 _slashAmount,
uint256 _finderFee
)
external
whenSystemNotPaused
onlyVerifier
{
Delegator storage del = delegators[_transcoder];
if (del.bondedAmount > 0) {
uint256 penalty = MathUtils.percOf(delegators[_transcoder].bondedAmount, _slashAmount);
// If active transcoder, resign it
if (transcoderPoolV2.contains(_transcoder)) {
resignTranscoder(_transcoder);
}
// Decrease bonded stake
del.bondedAmount = del.bondedAmount.sub(penalty);
// If still bonded decrease delegate's delegated amount
if (delegatorStatus(_transcoder) == DelegatorStatus.Bonded) {
delegators[del.delegateAddress].delegatedAmount = delegators[del.delegateAddress].delegatedAmount.sub(penalty);
}
// Account for penalty
uint256 burnAmount = penalty;
// Award finder fee if there is a finder address
if (_finder != address(0)) {
uint256 finderAmount = MathUtils.percOf(penalty, _finderFee);
minter().trustedTransferTokens(_finder, finderAmount);
// Minter burns the slashed funds - finder reward
minter().trustedBurnTokens(burnAmount.sub(finderAmount));
emit TranscoderSlashed(_transcoder, _finder, penalty, finderAmount);
} else {
// Minter burns the slashed funds
minter().trustedBurnTokens(burnAmount);
emit TranscoderSlashed(_transcoder, address(0), penalty, 0);
}
} else {
emit TranscoderSlashed(_transcoder, _finder, 0, 0);
}
}
/**
* @notice Claim token pools shares for a delegator from its lastClaimRound through the end round
* @param _endRound The last round for which to claim token pools shares for a delegator
*/
function claimEarnings(uint256 _endRound) external whenSystemNotPaused currentRoundInitialized {
uint256 lastClaimRound = delegators[msg.sender].lastClaimRound;
require(lastClaimRound < _endRound, "end round must be after last claim round");
// _endRound should be equal to the current round because after LIP-36 using a past _endRound can result
// in incorrect cumulative factor values used/stored for the _endRound in updateDelegatorWithEarnings().
// The exception is when claiming through an _endRound before the LIP-36 upgrade round because cumulative factor
// values will not be used/stored in updateDelegatorWithEarnings() before the LIP-36 upgrade round.
require(
_endRound == roundsManager().currentRound() || _endRound < roundsManager().lipUpgradeRound(36),
"end round must be equal to the current round or before the LIP-36 upgrade round"
);
updateDelegatorWithEarnings(msg.sender, _endRound, lastClaimRound);
}
/**
* @notice Claim earnings for a delegator based on the snapshot taken in LIP-52
* @dev https://github.com/livepeer/LIPs/blob/master/LIPs/LIP-52.md
* @param _pendingStake the amount of pending stake for the delegator (current stake + pending rewards)
* @param _pendingFees the amount of pending fees for the delegator (current fees + pending fees)
* @param _earningsProof array of keccak256 sibling hashes on the branch of the leaf for the delegator up to the root
* @param _data (optional) raw transaction data to be executed on behalf of msg.sender after claiming snapshot earnings
*/
function claimSnapshotEarnings(
uint256 _pendingStake,
uint256 _pendingFees,
bytes32[] calldata _earningsProof,
bytes calldata _data
)
external
whenSystemNotPaused
currentRoundInitialized
{
Delegator storage del = delegators[msg.sender];
uint256 lip52Round = roundsManager().lipUpgradeRound(52);
uint256 lastClaimRound = del.lastClaimRound;
require(lastClaimRound < lip52Round, "Already claimed for LIP-52");
bytes32 leaf = keccak256(abi.encode(msg.sender, _pendingStake, _pendingFees));
require(
IMerkleSnapshot(controller.getContract(keccak256("MerkleSnapshot"))).verify(keccak256("LIP-52"), _earningsProof, leaf),
"Merkle proof is invalid"
);
emit EarningsClaimed(
del.delegateAddress,
msg.sender,
_pendingStake.sub(del.bondedAmount),
_pendingFees.sub(del.fees),
lastClaimRound.add(1),
lip52Round
);
del.lastClaimRound = lip52Round;
del.bondedAmount = _pendingStake;
del.fees = _pendingFees;
// allow for execution of subsequent claiming or staking operations
if (_data.length > 0) {
(bool success, bytes memory returnData) = address(this).delegatecall(_data);
require(success, string(returnData));
}
}
/**
* @notice Called during round initialization to set the total active stake for the round. Only callable by the RoundsManager
*/
function setCurrentRoundTotalActiveStake() external onlyRoundsManager {
currentRoundTotalActiveStake = nextRoundTotalActiveStake;
}
/**
* @notice Sets commission rates as a transcoder and if the caller is not in the transcoder pool tries to add it using an optional list hint
* @dev Percentages are represented as numerators of fractions over MathUtils.PERC_DIVISOR. If the caller is going to be added to the pool, the
* caller can provide an optional hint for the insertion position in the pool via the `_newPosPrev` and `_newPosNext` params. A linear search will
* be executed starting at the hint to find the correct position - in the best case, the hint is the correct position so no search is executed.
* See SortedDoublyLL.sol for details on list hints
* @param _rewardCut % of reward paid to transcoder by a delegator
* @param _feeShare % of fees paid to delegators by a transcoder
* @param _newPosPrev Address of previous transcoder in pool if the caller joins the pool
* @param _newPosNext Address of next transcoder in pool if the caller joins the pool
*/
function transcoderWithHint(uint256 _rewardCut, uint256 _feeShare, address _newPosPrev, address _newPosNext)
public
whenSystemNotPaused
currentRoundInitialized
{
require(
!roundsManager().currentRoundLocked(),
"can't update transcoder params, current round is locked"
);
require(MathUtils.validPerc(_rewardCut), "invalid rewardCut percentage");
require(MathUtils.validPerc(_feeShare), "invalid feeShare percentage");
require(isRegisteredTranscoder(msg.sender), "transcoder must be registered");
Transcoder storage t = transcoders[msg.sender];
uint256 currentRound = roundsManager().currentRound();
require(
!isActiveTranscoder(msg.sender) || t.lastRewardRound == currentRound,
"caller can't be active or must have already called reward for the current round"
);
t.rewardCut = _rewardCut;
t.feeShare = _feeShare;
if (!transcoderPoolV2.contains(msg.sender)) {
tryToJoinActiveSet(msg.sender, delegators[msg.sender].delegatedAmount, currentRound.add(1), _newPosPrev, _newPosNext);
}
emit TranscoderUpdate(msg.sender, _rewardCut, _feeShare);
}
/**
* @notice Delegate stake towards a specific address and updates the transcoder pool using optional list hints if needed
* @dev If the caller is decreasing the stake of its old delegate in the transcoder pool, the caller can provide an optional hint
* for the insertion position of the old delegate via the `_oldDelegateNewPosPrev` and `_oldDelegateNewPosNext` params.
* If the caller is delegating to a delegate that is in the transcoder pool, the caller can provide an optional hint for the
* insertion position of the delegate via the `_currDelegateNewPosPrev` and `_currDelegateNewPosNext` params.
* In both cases, a linear search will be executed starting at the hint to find the correct position. In the best case, the hint
* is the correct position so no search is executed. See SortedDoublyLL.sol for details on list hints
* @param _amount The amount of tokens to stake.
* @param _to The address of the transcoder to stake towards
* @param _oldDelegateNewPosPrev The address of the previous transcoder in the pool for the old delegate
* @param _oldDelegateNewPosNext The address of the next transcoder in the pool for the old delegate
* @param _currDelegateNewPosPrev The address of the previous transcoder in the pool for the current delegate
* @param _currDelegateNewPosNext The address of the next transcoder in the pool for the current delegate
*/
function bondWithHint(
uint256 _amount,
address _to,
address _oldDelegateNewPosPrev,
address _oldDelegateNewPosNext,
address _currDelegateNewPosPrev,
address _currDelegateNewPosNext
)
public
whenSystemNotPaused
currentRoundInitialized
autoClaimEarnings
{
Delegator storage del = delegators[msg.sender];
uint256 currentRound = roundsManager().currentRound();
// Amount to delegate
uint256 delegationAmount = _amount;
// Current delegate
address currentDelegate = del.delegateAddress;
if (delegatorStatus(msg.sender) == DelegatorStatus.Unbonded) {
// New delegate
// Set start round
// Don't set start round if delegator is in pending state because the start round would not change
del.startRound = currentRound.add(1);
// Unbonded state = no existing delegate and no bonded stake
// Thus, delegation amount = provided amount
} else if (currentDelegate != address(0) && currentDelegate != _to) {
// A registered transcoder cannot delegate its bonded stake toward another address
// because it can only be delegated toward itself
// In the future, if delegation towards another registered transcoder as an already
// registered transcoder becomes useful (i.e. for transitive delegation), this restriction
// could be removed
require(!isRegisteredTranscoder(msg.sender), "registered transcoders can't delegate towards other addresses");
// Changing delegate
// Set start round
del.startRound = currentRound.add(1);
// Update amount to delegate with previous delegation amount
delegationAmount = delegationAmount.add(del.bondedAmount);
decreaseTotalStake(currentDelegate, del.bondedAmount, _oldDelegateNewPosPrev, _oldDelegateNewPosNext);
}
Transcoder storage newDelegate = transcoders[_to];
EarningsPool.Data storage currPool = newDelegate.earningsPoolPerRound[currentRound];
if (currPool.cumulativeRewardFactor == 0) {
currPool.cumulativeRewardFactor = cumulativeFactorsPool(newDelegate, newDelegate.lastRewardRound).cumulativeRewardFactor;
}
if (currPool.cumulativeFeeFactor == 0) {
currPool.cumulativeFeeFactor = cumulativeFactorsPool(newDelegate, newDelegate.lastFeeRound).cumulativeFeeFactor;
}
// cannot delegate to someone without having bonded stake
require(delegationAmount > 0, "delegation amount must be greater than 0");
// Update delegate
del.delegateAddress = _to;
// Update bonded amount
del.bondedAmount = del.bondedAmount.add(_amount);
increaseTotalStake(_to, delegationAmount, _currDelegateNewPosPrev, _currDelegateNewPosNext);
if (_amount > 0) {
// Transfer the LPT to the Minter
livepeerToken().transferFrom(msg.sender, address(minter()), _amount);
}
emit Bond(_to, currentDelegate, msg.sender, _amount, del.bondedAmount);
}
/**
* @notice Unbond an amount of the delegator's bonded stake and updates the transcoder pool using an optional list hint if needed
* @dev If the caller remains in the transcoder pool, the caller can provide an optional hint for its insertion position in the
* pool via the `_newPosPrev` and `_newPosNext` params. A linear search will be executed starting at the hint to find the correct position.
* In the best case, the hint is the correct position so no search is executed. See SortedDoublyLL.sol details on list hints
* @param _amount Amount of tokens to unbond
* @param _newPosPrev Address of previous transcoder in pool if the caller remains in the pool
* @param _newPosNext Address of next transcoder in pool if the caller remains in the pool
*/
function unbondWithHint(uint256 _amount, address _newPosPrev, address _newPosNext)
public
whenSystemNotPaused
currentRoundInitialized
autoClaimEarnings
{
require(delegatorStatus(msg.sender) == DelegatorStatus.Bonded, "caller must be bonded");
Delegator storage del = delegators[msg.sender];
require(_amount > 0, "unbond amount must be greater than 0");
require(_amount <= del.bondedAmount, "amount is greater than bonded amount");
address currentDelegate = del.delegateAddress;
uint256 currentRound = roundsManager().currentRound();
uint256 withdrawRound = currentRound.add(unbondingPeriod);
uint256 unbondingLockId = del.nextUnbondingLockId;
// Create new unbonding lock
del.unbondingLocks[unbondingLockId] = UnbondingLock({
amount: _amount,
withdrawRound: withdrawRound
});
// Increment ID for next unbonding lock
del.nextUnbondingLockId = unbondingLockId.add(1);
// Decrease delegator's bonded amount
del.bondedAmount = del.bondedAmount.sub(_amount);
if (del.bondedAmount == 0) {
// Delegator no longer delegated to anyone if it does not have a bonded amount
del.delegateAddress = address(0);
// Delegator does not have a start round if it is no longer delegated to anyone
del.startRound = 0;
if (transcoderPoolV2.contains(msg.sender)) {
resignTranscoder(msg.sender);
}
}
// If msg.sender was resigned this statement will only decrease delegators[currentDelegate].delegatedAmount
decreaseTotalStake(currentDelegate, _amount, _newPosPrev, _newPosNext);
emit Unbond(currentDelegate, msg.sender, unbondingLockId, _amount, withdrawRound);
}
/**
* @notice Rebond tokens for an unbonding lock to a delegator's current delegate while a delegator is in the Bonded or Pending status and updates
* the transcoder pool using an optional list hint if needed
* @dev If the delegate is in the transcoder pool, the caller can provide an optional hint for the delegate's insertion position in the
* pool via the `_newPosPrev` and `_newPosNext` params. A linear search will be executed starting at the hint to find the correct position.
* In the best case, the hint is the correct position so no search is executed. See SortedDoublyLL.sol details on list hints
* @param _unbondingLockId ID of unbonding lock to rebond with
* @param _newPosPrev Address of previous transcoder in pool if the delegate is in the pool
* @param _newPosNext Address of next transcoder in pool if the delegate is in the pool
*/
function rebondWithHint(
uint256 _unbondingLockId,
address _newPosPrev,
address _newPosNext
)
public
whenSystemNotPaused
currentRoundInitialized
autoClaimEarnings
{
require(delegatorStatus(msg.sender) != DelegatorStatus.Unbonded, "caller must be bonded");
// Process rebond using unbonding lock
processRebond(msg.sender, _unbondingLockId, _newPosPrev, _newPosNext);
}
/**
* @notice Rebond tokens for an unbonding lock to a delegate while a delegator is in the Unbonded status and updates the transcoder pool using
* an optional list hint if needed
* @dev If the delegate joins the transcoder pool, the caller can provide an optional hint for the delegate's insertion position in the
* pool via the `_newPosPrev` and `_newPosNext` params. A linear search will be executed starting at the hint to find the correct position.
* In the best case, the hint is the correct position so no search is executed. See SortedDoublyLL.sol for details on list hints
* @param _to Address of delegate
* @param _unbondingLockId ID of unbonding lock to rebond with
* @param _newPosPrev Address of previous transcoder in pool if the delegate joins the pool
* @param _newPosNext Address of next transcoder in pool if the delegate joins the pool
*/
function rebondFromUnbondedWithHint(
address _to,
uint256 _unbondingLockId,
address _newPosPrev,
address _newPosNext
)
public
whenSystemNotPaused
currentRoundInitialized
autoClaimEarnings
{
require(delegatorStatus(msg.sender) == DelegatorStatus.Unbonded, "caller must be unbonded");
// Set delegator's start round and transition into Pending state
delegators[msg.sender].startRound = roundsManager().currentRound().add(1);
// Set delegator's delegate
delegators[msg.sender].delegateAddress = _to;
// Process rebond using unbonding lock
processRebond(msg.sender, _unbondingLockId, _newPosPrev, _newPosNext);
}
/**
* @notice Mint token rewards for an active transcoder and its delegators and update the transcoder pool using an optional list hint if needed
* @dev If the caller is in the transcoder pool, the caller can provide an optional hint for its insertion position in the
* pool via the `_newPosPrev` and `_newPosNext` params. A linear search will be executed starting at the hint to find the correct position.
* In the best case, the hint is the correct position so no search is executed. See SortedDoublyLL.sol for details on list hints
* @param _newPosPrev Address of previous transcoder in pool if the caller is in the pool
* @param _newPosNext Address of next transcoder in pool if the caller is in the pool
*/
function rewardWithHint(address _newPosPrev, address _newPosNext) public whenSystemNotPaused currentRoundInitialized {
uint256 currentRound = roundsManager().currentRound();
require(isActiveTranscoder(msg.sender), "caller must be an active transcoder");
require(transcoders[msg.sender].lastRewardRound != currentRound, "caller has already called reward for the current round");
Transcoder storage t = transcoders[msg.sender];
EarningsPool.Data storage earningsPool = t.earningsPoolPerRound[currentRound];
// Set last round that transcoder called reward
earningsPool.setCommission(t.rewardCut, t.feeShare);
// If transcoder didn't receive stake updates during the previous round and hasn't called reward for > 1 round
// the 'totalStake' on its 'EarningsPool' for the current round wouldn't be initialized
// Thus we sync the the transcoder's stake to when it was last updated
// 'updateTrancoderWithRewards()' will set the update round to 'currentRound +1' so this synchronization shouldn't occur frequently
uint256 lastUpdateRound = t.lastActiveStakeUpdateRound;
if (lastUpdateRound < currentRound) {
earningsPool.setStake(t.earningsPoolPerRound[lastUpdateRound].totalStake);
}
// Create reward based on active transcoder's stake relative to the total active stake
// rewardTokens = (current mintable tokens for the round * active transcoder stake) / total active stake
uint256 rewardTokens = minter().createReward(earningsPool.totalStake, currentRoundTotalActiveStake);
updateTranscoderWithRewards(msg.sender, rewardTokens, currentRound, _newPosPrev, _newPosNext);
// Set last round that transcoder called reward
t.lastRewardRound = currentRound;
emit Reward(msg.sender, rewardTokens);
}
/**
* @notice Returns pending bonded stake for a delegator from its lastClaimRound through an end round
* @param _delegator Address of delegator
* @param _endRound The last round to compute pending stake from
* @return Pending bonded stake for '_delegator' since last claiming rewards
*/
function pendingStake(address _delegator, uint256 _endRound) public view returns (uint256) {
// _endRound should be equal to the current round because after LIP-36 using a past _endRound can result
// in incorrect cumulative factor values used for the _endRound in pendingStakeAndFees().
// The exception is when calculating stake through an _endRound before the LIP-36 upgrade round because cumulative factor
// values will not be used in pendingStakeAndFees() before the LIP-36 upgrade round.
uint256 endRound = _endRound;
if (endRound >= roundsManager().lipUpgradeRound(36)) {
endRound = roundsManager().currentRound();
}
(
uint256 stake,
) = pendingStakeAndFees(_delegator, endRound);
return stake;
}
/**
* @notice Returns pending fees for a delegator from its lastClaimRound through an end round
* @param _delegator Address of delegator
* @param _endRound The last round to compute pending fees from
* @return Pending fees for '_delegator' since last claiming fees
*/
function pendingFees(address _delegator, uint256 _endRound) public view returns (uint256) {
// _endRound should be equal to the current round because after LIP-36 using a past _endRound can result
// in incorrect cumulative factor values used for the _endRound in pendingStakeAndFees().
// The exception is when calculating fees through an _endRound before the LIP-36 upgrade round because cumulative factor
// values will not be used in pendingStakeAndFees() before the LIP-36 upgrade round.
uint256 endRound = _endRound;
if (endRound >= roundsManager().lipUpgradeRound(36)) {
endRound = roundsManager().currentRound();
}
(
,
uint256 fees
) = pendingStakeAndFees(_delegator, endRound);
return fees;
}
/**
* @notice Returns total bonded stake for a transcoder
* @param _transcoder Address of transcoder
* @return total bonded stake for a delegator
*/
function transcoderTotalStake(address _transcoder) public view returns (uint256) {
return delegators[_transcoder].delegatedAmount;
}
/**
* @notice Computes transcoder status
* @param _transcoder Address of transcoder
* @return registered or not registered transcoder status
*/
function transcoderStatus(address _transcoder) public view returns (TranscoderStatus) {
if (isRegisteredTranscoder(_transcoder)) return TranscoderStatus.Registered;
return TranscoderStatus.NotRegistered;
}
/**
* @notice Computes delegator status
* @param _delegator Address of delegator
* @return bonded, unbonded or pending delegator status
*/
function delegatorStatus(address _delegator) public view returns (DelegatorStatus) {
Delegator storage del = delegators[_delegator];
if (del.bondedAmount == 0) {
// Delegator unbonded all its tokens
return DelegatorStatus.Unbonded;
} else if (del.startRound > roundsManager().currentRound()) {
// Delegator round start is in the future
return DelegatorStatus.Pending;
} else {
// Delegator round start is now or in the past
// del.startRound != 0 here because if del.startRound = 0 then del.bondedAmount = 0 which
// would trigger the first if clause
return DelegatorStatus.Bonded;
}
}
/**
* @notice Return transcoder information
* @param _transcoder Address of transcoder
* @return lastRewardRound Trancoder's last reward round
* @return rewardCut Transcoder's reward cut
* @return feeShare Transcoder's fee share
* @return lastActiveStakeUpdateRound Round in which transcoder's stake was last updated while active
* @return activationRound Round in which transcoder became active
* @return deactivationRound Round in which transcoder will no longer be active
* @return activeCumulativeRewards Transcoder's cumulative rewards that are currently active
* @return cumulativeRewards Transcoder's cumulative rewards (earned via its active staked rewards and its reward cut)
* @return cumulativeFees Transcoder's cumulative fees (earned via its active staked rewards and its fee share)
* @return lastFeeRound Latest round that the transcoder received fees
*/
function getTranscoder(
address _transcoder
)
public
view
returns (uint256 lastRewardRound, uint256 rewardCut, uint256 feeShare, uint256 lastActiveStakeUpdateRound, uint256 activationRound, uint256 deactivationRound, uint256 activeCumulativeRewards, uint256 cumulativeRewards, uint256 cumulativeFees, uint256 lastFeeRound)
{
Transcoder storage t = transcoders[_transcoder];
lastRewardRound = t.lastRewardRound;
rewardCut = t.rewardCut;
feeShare = t.feeShare;
lastActiveStakeUpdateRound = t.lastActiveStakeUpdateRound;
activationRound = t.activationRound;
deactivationRound = t.deactivationRound;
activeCumulativeRewards = t.activeCumulativeRewards;
cumulativeRewards = t.cumulativeRewards;
cumulativeFees = t.cumulativeFees;
lastFeeRound = t.lastFeeRound;
}
/**
* @notice Return transcoder's earnings pool for a given round
* @param _transcoder Address of transcoder
* @param _round Round number
* @return rewardPool Reward pool for delegators (only used before LIP-36)
* @return feePool Fee pool for delegators (only used before LIP-36)
* @return totalStake Transcoder's total stake in '_round'
* @return claimableStake Remaining stake that can be used to claim from the pool (only used before LIP-36)
* @return transcoderRewardCut Transcoder's reward cut for '_round'
* @return transcoderFeeShare Transcoder's fee share for '_round'
* @return transcoderRewardPool Transcoder's rewards for '_round' (only used before LIP-36)
* @return transcoderFeePool Transcoder's fees for '_round' (only used before LIP-36)
* @return hasTranscoderRewardFeePool True if there is a split reward/fee pool for the transcoder (only used before LIP-36)
* @return cumulativeRewardFactor The cumulative reward factor for delegator rewards calculation (only used after LIP-36)
* @return cumulativeFeeFactor The cumulative fee factor for delegator fees calculation (only used after LIP-36)
*/
function getTranscoderEarningsPoolForRound(
address _transcoder,
uint256 _round
)
public
view
returns (uint256 rewardPool, uint256 feePool, uint256 totalStake, uint256 claimableStake, uint256 transcoderRewardCut, uint256 transcoderFeeShare, uint256 transcoderRewardPool, uint256 transcoderFeePool, bool hasTranscoderRewardFeePool, uint256 cumulativeRewardFactor, uint256 cumulativeFeeFactor)
{
EarningsPool.Data storage earningsPool = transcoders[_transcoder].earningsPoolPerRound[_round];
rewardPool = earningsPool.rewardPool;
feePool = earningsPool.feePool;
totalStake = earningsPool.totalStake;
claimableStake = earningsPool.claimableStake;
transcoderRewardCut = earningsPool.transcoderRewardCut;
transcoderFeeShare = earningsPool.transcoderFeeShare;
transcoderRewardPool = earningsPool.transcoderRewardPool;
transcoderFeePool = earningsPool.transcoderFeePool;
hasTranscoderRewardFeePool = earningsPool.hasTranscoderRewardFeePool;
cumulativeRewardFactor = earningsPool.cumulativeRewardFactor;
cumulativeFeeFactor = earningsPool.cumulativeFeeFactor;
}
/**
* @notice Return delegator info
* @param _delegator Address of delegator
* @return total amount bonded by '_delegator'
* @return amount of fees collected by '_delegator'
* @return address '_delegator' has bonded to
* @return total amount delegated to '_delegator'
* @return round in which bond for '_delegator' became effective
* @return round for which '_delegator' has last claimed earnings
* @return ID for the next unbonding lock created for '_delegator'
*/
function getDelegator(
address _delegator
)
public
view
returns (uint256 bondedAmount, uint256 fees, address delegateAddress, uint256 delegatedAmount, uint256 startRound, uint256 lastClaimRound, uint256 nextUnbondingLockId)
{
Delegator storage del = delegators[_delegator];
bondedAmount = del.bondedAmount;
fees = del.fees;
delegateAddress = del.delegateAddress;
delegatedAmount = del.delegatedAmount;
startRound = del.startRound;
lastClaimRound = del.lastClaimRound;
nextUnbondingLockId = del.nextUnbondingLockId;
}
/**
* @notice Return delegator's unbonding lock info
* @param _delegator Address of delegator
* @param _unbondingLockId ID of unbonding lock
* @return amount of stake locked up by unbonding lock
* @return round in which 'amount' becomes available for withdrawal
*/
function getDelegatorUnbondingLock(
address _delegator,
uint256 _unbondingLockId
)
public
view
returns (uint256 amount, uint256 withdrawRound)
{
UnbondingLock storage lock = delegators[_delegator].unbondingLocks[_unbondingLockId];
return (lock.amount, lock.withdrawRound);
}
/**
* @notice Returns max size of transcoder pool
* @return transcoder pool max size
*/
function getTranscoderPoolMaxSize() public view returns (uint256) {
return transcoderPoolV2.getMaxSize();
}
/**
* @notice Returns size of transcoder pool
* @return transcoder pool current size
*/
function getTranscoderPoolSize() public view returns (uint256) {
return transcoderPoolV2.getSize();
}
/**
* @notice Returns transcoder with most stake in pool
* @return address for transcoder with highest stake in transcoder pool
*/
function getFirstTranscoderInPool() public view returns (address) {
return transcoderPoolV2.getFirst();
}
/**
* @notice Returns next transcoder in pool for a given transcoder
* @param _transcoder Address of a transcoder in the pool
* @return address for the transcoder after '_transcoder' in transcoder pool
*/
function getNextTranscoderInPool(address _transcoder) public view returns (address) {
return transcoderPoolV2.getNext(_transcoder);
}
/**
* @notice Return total bonded tokens
* @return total active stake for the current round
*/
function getTotalBonded() public view returns (uint256) {
return currentRoundTotalActiveStake;
}
/**
* @notice Return whether a transcoder is active for the current round
* @param _transcoder Transcoder address
* @return true if transcoder is active
*/
function isActiveTranscoder(address _transcoder) public view returns (bool) {
Transcoder storage t = transcoders[_transcoder];
uint256 currentRound = roundsManager().currentRound();
return t.activationRound <= currentRound && currentRound < t.deactivationRound;
}
/**
* @notice Return whether a transcoder is registered
* @param _transcoder Transcoder address
* @return true if transcoder is self-bonded
*/
function isRegisteredTranscoder(address _transcoder) public view returns (bool) {
Delegator storage d = delegators[_transcoder];
return d.delegateAddress == _transcoder && d.bondedAmount > 0;
}
/**
* @notice Return whether an unbonding lock for a delegator is valid
* @param _delegator Address of delegator
* @param _unbondingLockId ID of unbonding lock
* @return true if unbondingLock for ID has a non-zero withdraw round
*/
function isValidUnbondingLock(address _delegator, uint256 _unbondingLockId) public view returns (bool) {
// A unbonding lock is only valid if it has a non-zero withdraw round (the default value is zero)
return delegators[_delegator].unbondingLocks[_unbondingLockId].withdrawRound > 0;
}
/**
* @notice Return an EarningsPool.Data struct with cumulative factors for a given round that are rescaled if needed
* @param _transcoder Storage pointer to a transcoder struct
* @param _round The round to fetch the cumulative factors for
*/
function cumulativeFactorsPool(Transcoder storage _transcoder, uint256 _round) internal view returns (EarningsPool.Data memory pool) {
pool.cumulativeRewardFactor = _transcoder.earningsPoolPerRound[_round].cumulativeRewardFactor;
pool.cumulativeFeeFactor = _transcoder.earningsPoolPerRound[_round].cumulativeFeeFactor;
uint256 lip71Round = roundsManager().lipUpgradeRound(71);
// If we are at or after the LIP-71 round then all cumulative factor values should be scaled using PreciseMathUtils.percPoints(1, 1)
// If a cumulative factor was stored before the LIP-71 round it will still be scaled using MathUtils.percPoints(1, 1)
// So, once we are at or after the LIP-71 round, if we read a cumulative factor for a round before the LIP-71 round, we rescale
// the value by RESCALE_FACTOR so that the end value is scaled by PreciseMathUtils.percPoints(1, 1)
if (roundsManager().currentRound() >= lip71Round) {
if (_round < lip71Round) {
pool.cumulativeRewardFactor = pool.cumulativeRewardFactor.mul(RESCALE_FACTOR);
pool.cumulativeFeeFactor = pool.cumulativeFeeFactor.mul(RESCALE_FACTOR);
} else {
// There was a bug in bondWithHint() that allowed cumulative factors to be stored after LIP-71 round to still be scaled using MathUtils.percPoints(1, 1)
// If we read a cumulativeRewardFactor for a round after the LIP-71 round and it is less than PreciseMathUtils.percPoints(1, 1), it was
// affected by this bug so we rescale it by RESCALE_FACTOR
if (pool.cumulativeRewardFactor < PreciseMathUtils.percPoints(1, 1)) {
pool.cumulativeRewardFactor = pool.cumulativeRewardFactor.mul(RESCALE_FACTOR);
}
// If cumulativeFeeFactor was previously rescaled, then its minimum value non-zero value is RESCALE_FACTOR
// If prior to rescaling:
// - cumulativeFeeFactor = 0, then after rescaling it would be 0
// - cumulativeFeeFactor >= 1, then after rescaling it would be >= RESCALE_FACTOR
// So, if we read a cumulativeFeeFactor for a round after the LIP-71 round and it is less than RESCALE_FACTOR its value is either 0, in which case
// it is still safe to rescale, or > 0, in which case it needs to be rescaled
if (pool.cumulativeFeeFactor < RESCALE_FACTOR) {
pool.cumulativeFeeFactor = pool.cumulativeFeeFactor.mul(RESCALE_FACTOR);
}
}
}
return pool;
}
/**
* @notice Return an EarningsPool.Data struct with the latest cumulative factors for a given round
* @param _transcoder Storage pointer to a transcoder struct
* @param _round The round to fetch the latest cumulative factors for
* @return pool An EarningsPool.Data populated with the latest cumulative factors for _round
*/
function latestCumulativeFactorsPool(Transcoder storage _transcoder, uint256 _round) internal view returns (EarningsPool.Data memory pool) {
pool = cumulativeFactorsPool(_transcoder, _round);
uint256 lastRewardRound = _transcoder.lastRewardRound;
// Only use the cumulativeRewardFactor for lastRewardRound if lastRewardRound is before _round
if (pool.cumulativeRewardFactor == 0 && lastRewardRound < _round) {
pool.cumulativeRewardFactor = cumulativeFactorsPool(_transcoder, lastRewardRound).cumulativeRewardFactor;
}
uint256 lastFeeRound = _transcoder.lastFeeRound;
// Only use the cumulativeFeeFactor for lastFeeRound if lastFeeRound is before _round
if (pool.cumulativeFeeFactor == 0 && lastFeeRound < _round) {
pool.cumulativeFeeFactor = cumulativeFactorsPool(_transcoder, lastFeeRound).cumulativeFeeFactor;
}
return pool;
}
/**
* @notice Return a delegator's cumulative stake and fees using the LIP-36 earnings claiming algorithm
* @param _transcoder Storage pointer to a transcoder struct for a delegator's delegate
* @param _startRound The round for the start cumulative factors
* @param _endRound The round for the end cumulative factors
* @param _stake The delegator's initial stake before including earned rewards
* @param _fees The delegator's initial fees before including earned fees
* @return (cStake, cFees) where cStake is the delegator's cumulative stake including earned rewards and cFees is the delegator's cumulative fees including earned fees
*/
function delegatorCumulativeStakeAndFees(
Transcoder storage _transcoder,
uint256 _startRound,
uint256 _endRound,
uint256 _stake,
uint256 _fees
)
internal
view
returns (uint256 cStake, uint256 cFees)
{
// Fetch start cumulative factors
EarningsPool.Data memory startPool = cumulativeFactorsPool(_transcoder, _startRound);
// We can lookback for a cumulativeRewardFactor if the start cumulativeRewardFactor is 0
// Do not lookback if the latest cumulativeRewardFactor is 0 because that indicates that the factor was never > 0 for the transcoder in the past
bool lookbackCumulativeRewardFactor = _transcoder.earningsPoolPerRound[_transcoder.lastRewardRound].cumulativeRewardFactor > 0 && startPool.cumulativeRewardFactor == 0;
// We can lookback for a cumulativeFeeFactor if the start cumulativeFeeFactor is 0
// Do not lookback if the latest cumulativeFeeFactor is 0 because that indicates that the factor was never > 0 for the transcoder in the past
bool lookbackCumulativeFeeFactor = _transcoder.earningsPoolPerRound[_transcoder.lastFeeRound].cumulativeFeeFactor > 0 && startPool.cumulativeFeeFactor == 0;
// The lookback loop will only be needed for a few accounts delegated to transcoders before the update that ensures start factors are always initialized
// If we need a cumulativeRewardFactor OR cumulativeFeeFactor lookback up to min(MAX_LOOKBACK_ROUNDS, _startRound) # of rounds
uint256 lip36Round = roundsManager().lipUpgradeRound(36);
for (uint256 lookback = 1; lookback <= MAX_LOOKBACK_ROUNDS && lookback <= _startRound && (lookbackCumulativeRewardFactor || lookbackCumulativeFeeFactor); lookback++) {
uint256 lookbackRound = _startRound.sub(lookback);
// Cannot lookback past the LIP-36 upgrade round
if (lookbackRound < lip36Round) {
break;
}
EarningsPool.Data storage pool = _transcoder.earningsPoolPerRound[lookbackRound];
// Short-circuit in the following conditionals by running the boolean check before the storage check
if (lookbackCumulativeRewardFactor && pool.cumulativeRewardFactor > 0) {
startPool.cumulativeRewardFactor = cumulativeFactorsPool(_transcoder, lookbackRound).cumulativeRewardFactor;
lookbackCumulativeRewardFactor = false;
}
if (lookbackCumulativeFeeFactor && pool.cumulativeFeeFactor > 0) {
startPool.cumulativeFeeFactor = cumulativeFactorsPool(_transcoder, lookbackRound).cumulativeFeeFactor;
lookbackCumulativeFeeFactor = false;
}
}
// If the start cumulativeRewardFactor is 0 and we are before the LIP-71 round, set the default value to
// MathUtils.percPoints(1, 1) because we only set the default value to PreciseMathUtils.percPoints(1, 1) from LIP-71 round
// and onward
if (startPool.cumulativeRewardFactor == 0) {
startPool.cumulativeRewardFactor = roundsManager().currentRound() < roundsManager().lipUpgradeRound(71) ?
MathUtils.percPoints(1, 1) : PreciseMathUtils.percPoints(1, 1);
}
// Fetch end cumulative factors
EarningsPool.Data memory endPool = latestCumulativeFactorsPool(_transcoder, _endRound);
// If the end cumulativeRewardFactor is 0 and we are before the LIP-71 round, set the default value to
// MathUtils.percPoints(1, 1) because we only set the default value to PreciseMathUtils.percPoints(1, 1) from LIP-71 round
// and onward
if (endPool.cumulativeRewardFactor == 0) {
endPool.cumulativeRewardFactor = roundsManager().currentRound() < roundsManager().lipUpgradeRound(71) ?
MathUtils.percPoints(1, 1) : PreciseMathUtils.percPoints(1, 1);
}
cFees = _fees.add(
PreciseMathUtils.percOf(
_stake,
endPool.cumulativeFeeFactor.sub(startPool.cumulativeFeeFactor),
startPool.cumulativeRewardFactor
)
);
cStake = PreciseMathUtils.percOf(
_stake,
endPool.cumulativeRewardFactor,
startPool.cumulativeRewardFactor
);
return (cStake, cFees);
}
/**
* @notice Return the pending stake and fees for a delegator
* @param _delegator Address of a delegator
* @param _endRound The last round to claim earnings for when calculating the pending stake and fees
* @return (stake, fees) where stake is the delegator's pending stake and fees is the delegator's pending fees
*/
function pendingStakeAndFees(address _delegator, uint256 _endRound) internal view returns (uint256 stake, uint256 fees) {
Delegator storage del = delegators[_delegator];
Transcoder storage t = transcoders[del.delegateAddress];
fees = del.fees;
stake = del.bondedAmount;
uint256 startRound = del.lastClaimRound.add(1);
address delegateAddr = del.delegateAddress;
bool isTranscoder = _delegator == delegateAddr;
uint256 lip36Round = roundsManager().lipUpgradeRound(36);
while (startRound <= _endRound && startRound <= lip36Round) {
EarningsPool.Data storage earningsPool = t.earningsPoolPerRound[startRound];
// If earningsPool.hasTranscoderRewardFeePool is not set during lip36Round then the transcoder did not call
// reward during lip36Round before the upgrade. In this case, if the transcoder calls reward in lip36Round
// the delegator can use the LIP-36 earnings claiming algorithm to claim for lip36Round
if (startRound == lip36Round && !earningsPool.hasTranscoderRewardFeePool) {
break;
}
if (earningsPool.hasClaimableShares()) {
// Calculate and add fee pool share from this round
fees = fees.add(earningsPool.feePoolShare(stake, isTranscoder));
// Calculate new bonded amount with rewards from this round. Updated bonded amount used
// to calculate fee pool share in next round
stake = stake.add(earningsPool.rewardPoolShare(stake, isTranscoder));
}
startRound = startRound.add(1);
}
// If the transcoder called reward during lip36Round the upgrade, then startRound = lip36Round
// Otherwise, startRound = lip36Round + 1
// If the start round is greater than the end round, we've already claimed for the end round so we do not
// need to execute the LIP-36 earnings claiming algorithm. This could be the case if:
// - _endRound < lip36Round i.e. we are not claiming through the lip36Round
// - _endRound == lip36Round AND startRound = lip36Round + 1 i.e we already claimed through the lip36Round
// The LIP-36 earnings claiming algorithm uses the cumulative factors from the delegator's lastClaimRound i.e. startRound - 1
// and from the specified _endRound
// We only need to execute this algorithm if the end round >= lip36Round
if (_endRound >= lip36Round) {
// Make sure there is a round to claim i.e. end round - (start round - 1) > 0
if (startRound <= _endRound) {
(
stake,
fees
) = delegatorCumulativeStakeAndFees(t, startRound.sub(1), _endRound, stake, fees);
}
// cumulativeRewards and cumulativeFees will track *all* rewards/fees earned by the transcoder
// so it is important that this is only executed with the end round as the current round or else
// the returned stake and fees will reflect rewards/fees earned in the future relative to the end round
if (isTranscoder) {
stake = stake.add(t.cumulativeRewards);
fees = fees.add(t.cumulativeFees);
}
}
return (stake, fees);
}
/**
* @dev Increase the total stake for a delegate and updates its 'lastActiveStakeUpdateRound'
* @param _delegate The delegate to increase the stake for
* @param _amount The amount to increase the stake for '_delegate' by
*/
function increaseTotalStake(address _delegate, uint256 _amount, address _newPosPrev, address _newPosNext) internal {
if (isRegisteredTranscoder(_delegate)) {
uint256 currStake = transcoderTotalStake(_delegate);
uint256 newStake = currStake.add(_amount);
uint256 currRound = roundsManager().currentRound();
uint256 nextRound = currRound.add(1);
// If the transcoder is already in the active set update its stake and return
if (transcoderPoolV2.contains(_delegate)) {
transcoderPoolV2.updateKey(_delegate, newStake, _newPosPrev, _newPosNext);
nextRoundTotalActiveStake = nextRoundTotalActiveStake.add(_amount);
Transcoder storage t = transcoders[_delegate];
// currStake (the transcoder's delegatedAmount field) will reflect the transcoder's stake from lastActiveStakeUpdateRound
// because it is updated every time lastActiveStakeUpdateRound is updated
// The current active total stake is set to currStake to ensure that the value can be used in updateTranscoderWithRewards()
// and updateTranscoderWithFees() when lastActiveStakeUpdateRound > currentRound
if (t.lastActiveStakeUpdateRound < currRound) {
t.earningsPoolPerRound[currRound].setStake(currStake);
}
t.earningsPoolPerRound[nextRound].setStake(newStake);
t.lastActiveStakeUpdateRound = nextRound;
} else {
// Check if the transcoder is eligible to join the active set in the update round
tryToJoinActiveSet(_delegate, newStake, nextRound, _newPosPrev, _newPosNext);
}
}
// Increase delegate's delegated amount
delegators[_delegate].delegatedAmount = delegators[_delegate].delegatedAmount.add(_amount);
}
/**
* @dev Decrease the total stake for a delegate and updates its 'lastActiveStakeUpdateRound'
* @param _delegate The transcoder to decrease the stake for
* @param _amount The amount to decrease the stake for '_delegate' by
*/
function decreaseTotalStake(address _delegate, uint256 _amount, address _newPosPrev, address _newPosNext) internal {
if (transcoderPoolV2.contains(_delegate)) {
uint256 currStake = transcoderTotalStake(_delegate);
uint256 newStake = currStake.sub(_amount);
uint256 currRound = roundsManager().currentRound();
uint256 nextRound = currRound.add(1);
transcoderPoolV2.updateKey(_delegate, newStake, _newPosPrev, _newPosNext);
nextRoundTotalActiveStake = nextRoundTotalActiveStake.sub(_amount);
Transcoder storage t = transcoders[_delegate];
// currStake (the transcoder's delegatedAmount field) will reflect the transcoder's stake from lastActiveStakeUpdateRound
// because it is updated every time lastActiveStakeUpdateRound is updated
// The current active total stake is set to currStake to ensure that the value can be used in updateTranscoderWithRewards()
// and updateTranscoderWithFees() when lastActiveStakeUpdateRound > currentRound
if (t.lastActiveStakeUpdateRound < currRound) {
t.earningsPoolPerRound[currRound].setStake(currStake);
}
t.lastActiveStakeUpdateRound = nextRound;
t.earningsPoolPerRound[nextRound].setStake(newStake);
}
// Decrease old delegate's delegated amount
delegators[_delegate].delegatedAmount = delegators[_delegate].delegatedAmount.sub(_amount);
}
/**
* @dev Tries to add a transcoder to active transcoder pool, evicts the active transcoder with the lowest stake if the pool is full
* @param _transcoder The transcoder to insert into the transcoder pool
* @param _totalStake The total stake for '_transcoder'
* @param _activationRound The round in which the transcoder should become active
*/
function tryToJoinActiveSet(
address _transcoder,
uint256 _totalStake,
uint256 _activationRound,
address _newPosPrev,
address _newPosNext
)
internal
{
uint256 pendingNextRoundTotalActiveStake = nextRoundTotalActiveStake;
if (transcoderPoolV2.isFull()) {
address lastTranscoder = transcoderPoolV2.getLast();
uint256 lastStake = transcoderTotalStake(lastTranscoder);
// If the pool is full and the transcoder has less stake than the least stake transcoder in the pool
// then the transcoder is unable to join the active set for the next round
if (_totalStake <= lastStake) {
return;
}
// Evict the least stake transcoder from the active set for the next round
// Not zeroing 'Transcoder.lastActiveStakeUpdateRound' saves gas (5k when transcoder is evicted and 20k when transcoder is reinserted)
// There should be no side-effects as long as the value is properly updated on stake updates
// Not zeroing the stake on the current round's 'EarningsPool' saves gas and should have no side effects as long as
// 'EarningsPool.setStake()' is called whenever a transcoder becomes active again.
transcoderPoolV2.remove(lastTranscoder);
transcoders[lastTranscoder].deactivationRound = _activationRound;
pendingNextRoundTotalActiveStake = pendingNextRoundTotalActiveStake.sub(lastStake);
emit TranscoderDeactivated(lastTranscoder, _activationRound);
}
transcoderPoolV2.insert(_transcoder, _totalStake, _newPosPrev, _newPosNext);
pendingNextRoundTotalActiveStake = pendingNextRoundTotalActiveStake.add(_totalStake);
Transcoder storage t = transcoders[_transcoder];
t.lastActiveStakeUpdateRound = _activationRound;
t.activationRound = _activationRound;
t.deactivationRound = MAX_FUTURE_ROUND;
t.earningsPoolPerRound[_activationRound].setStake(_totalStake);
nextRoundTotalActiveStake = pendingNextRoundTotalActiveStake;
emit TranscoderActivated(_transcoder, _activationRound);
}
/**
* @dev Remove a transcoder from the pool and deactivate it
*/
function resignTranscoder(address _transcoder) internal {
// Not zeroing 'Transcoder.lastActiveStakeUpdateRound' saves gas (5k when transcoder is evicted and 20k when transcoder is reinserted)
// There should be no side-effects as long as the value is properly updated on stake updates
// Not zeroing the stake on the current round's 'EarningsPool' saves gas and should have no side effects as long as
// 'EarningsPool.setStake()' is called whenever a transcoder becomes active again.
transcoderPoolV2.remove(_transcoder);
nextRoundTotalActiveStake = nextRoundTotalActiveStake.sub(transcoderTotalStake(_transcoder));
uint256 deactivationRound = roundsManager().currentRound().add(1);
transcoders[_transcoder].deactivationRound = deactivationRound;
emit TranscoderDeactivated(_transcoder, deactivationRound);
}
/**
* @dev Update a transcoder with rewards and update the transcoder pool with an optional list hint if needed.
* See SortedDoublyLL.sol for details on list hints
* @param _transcoder Address of transcoder
* @param _rewards Amount of rewards
* @param _round Round that transcoder is updated
* @param _newPosPrev Address of previous transcoder in pool if the transcoder is in the pool
* @param _newPosNext Address of next transcoder in pool if the transcoder is in the pool
*/
function updateTranscoderWithRewards(
address _transcoder,
uint256 _rewards,
uint256 _round,
address _newPosPrev,
address _newPosNext
)
internal
{
Transcoder storage t = transcoders[_transcoder];
EarningsPool.Data storage earningsPool = t.earningsPoolPerRound[_round];
EarningsPool.Data memory prevEarningsPool = cumulativeFactorsPool(t, t.lastRewardRound);
// If the previous cumulativeRewardFactor is 0 and we are before the LIP-71 round, set the default value to
// MathUtils.percPoints(1, 1) because we only set the default value to PreciseMathUtils.percPoints(1, 1) when storing for
// the LIP-71 round and onwards (see updateCumulativeRewardFactor() in EarningsPoolLIP36.sol)
if (prevEarningsPool.cumulativeRewardFactor == 0 && _round < roundsManager().lipUpgradeRound(71)) {
prevEarningsPool.cumulativeRewardFactor = MathUtils.percPoints(1, 1);
}
t.activeCumulativeRewards = t.cumulativeRewards;
uint256 transcoderCommissionRewards = MathUtils.percOf(_rewards, earningsPool.transcoderRewardCut);
uint256 delegatorsRewards = _rewards.sub(transcoderCommissionRewards);
// Calculate the rewards earned by the transcoder's earned rewards
uint256 transcoderRewardStakeRewards = PreciseMathUtils.percOf(delegatorsRewards, t.activeCumulativeRewards, earningsPool.totalStake);
// Track rewards earned by the transcoder based on its earned rewards and rewardCut
t.cumulativeRewards = t.cumulativeRewards.add(transcoderRewardStakeRewards).add(transcoderCommissionRewards);
// Update cumulative reward factor with new rewards
// The cumulativeRewardFactor is used to calculate rewards for all delegators including the transcoder (self-delegated)
// Note that delegatorsRewards includes transcoderRewardStakeRewards, but no delegator will claim that amount using
// the earnings claiming algorithm and instead that amount is accounted for in the transcoder's cumulativeRewards field
earningsPool.updateCumulativeRewardFactor(prevEarningsPool, delegatorsRewards);
// Update transcoder's total stake with rewards
increaseTotalStake(_transcoder, _rewards, _newPosPrev, _newPosNext);
}
/**
* @dev Update a delegator with token pools shares from its lastClaimRound through a given round
* @param _delegator Delegator address
* @param _endRound The last round for which to update a delegator's stake with earnings pool shares
* @param _lastClaimRound The round for which a delegator has last claimed earnings
*/
function updateDelegatorWithEarnings(address _delegator, uint256 _endRound, uint256 _lastClaimRound) internal {
Delegator storage del = delegators[_delegator];
uint256 startRound = _lastClaimRound.add(1);
uint256 currentBondedAmount = del.bondedAmount;
uint256 currentFees = del.fees;
uint256 lip36Round = roundsManager().lipUpgradeRound(36);
// Only will have earnings to claim if you have a delegate
// If not delegated, skip the earnings claim process
if (del.delegateAddress != address(0)) {
if (startRound <= lip36Round) {
// Cannot claim earnings for more than maxEarningsClaimsRounds before LIP-36
// This is a number to cause transactions to fail early if
// we know they will require too much gas to loop through all the necessary rounds to claim earnings
// The user should instead manually invoke `claimEarnings` to split up the claiming process
// across multiple transactions
uint256 endLoopRound = _endRound <= lip36Round ? _endRound : lip36Round;
require(endLoopRound.sub(_lastClaimRound) <= maxEarningsClaimsRounds, "too many rounds to claim through");
}
(
currentBondedAmount,
currentFees
) = pendingStakeAndFees(_delegator, _endRound);
// Only execute cumulative factor logic after LIP-36 upgrade round
// After LIP-36 upgrade round the following code block should only be executed if _endRound is the current round
// See claimEarnings() and autoClaimEarnings()
if (_endRound >= lip36Round) {
// Check whether the endEarningsPool is initialised
// If it is not initialised set it's cumulative factors so that they can be used when a delegator
// next claims earnings as the start cumulative factors (see delegatorCumulativeStakeAndFees())
Transcoder storage t = transcoders[del.delegateAddress];
EarningsPool.Data storage endEarningsPool = t.earningsPoolPerRound[_endRound];
if (endEarningsPool.cumulativeRewardFactor == 0) {
uint256 lastRewardRound = t.lastRewardRound;
if (lastRewardRound < _endRound) {
endEarningsPool.cumulativeRewardFactor = cumulativeFactorsPool(t, lastRewardRound).cumulativeRewardFactor;
}
}
if (endEarningsPool.cumulativeFeeFactor == 0) {
uint256 lastFeeRound = t.lastFeeRound;
if (lastFeeRound < _endRound) {
endEarningsPool.cumulativeFeeFactor = cumulativeFactorsPool(t, lastFeeRound).cumulativeFeeFactor;
}
}
if (del.delegateAddress == _delegator) {
t.cumulativeFees = 0;
t.cumulativeRewards = 0;
// activeCumulativeRewards is not cleared here because the next reward() call will set it to cumulativeRewards
}
}
}
emit EarningsClaimed(
del.delegateAddress,
_delegator,
currentBondedAmount.sub(del.bondedAmount),
currentFees.sub(del.fees),
startRound,
_endRound
);
del.lastClaimRound = _endRound;
// Rewards are bonded by default
del.bondedAmount = currentBondedAmount;
del.fees = currentFees;
}
/**
* @dev Update the state of a delegator and its delegate by processing a rebond using an unbonding lock and update the transcoder pool with an optional
* list hint if needed. See SortedDoublyLL.sol for details on list hints
* @param _delegator Address of delegator
* @param _unbondingLockId ID of unbonding lock to rebond with
* @param _newPosPrev Address of previous transcoder in pool if the delegate is already in or joins the pool
* @param _newPosNext Address of next transcoder in pool if the delegate is already in or joins the pool
*/
function processRebond(address _delegator, uint256 _unbondingLockId, address _newPosPrev, address _newPosNext) internal {
Delegator storage del = delegators[_delegator];
UnbondingLock storage lock = del.unbondingLocks[_unbondingLockId];
require(isValidUnbondingLock(_delegator, _unbondingLockId), "invalid unbonding lock ID");
uint256 amount = lock.amount;
// Increase delegator's bonded amount
del.bondedAmount = del.bondedAmount.add(amount);
// Delete lock
delete del.unbondingLocks[_unbondingLockId];
increaseTotalStake(del.delegateAddress, amount, _newPosPrev, _newPosNext);
emit Rebond(del.delegateAddress, _delegator, _unbondingLockId, amount);
}
/**
* @dev Return LivepeerToken interface
* @return Livepeer token contract registered with Controller
*/
function livepeerToken() internal view returns (ILivepeerToken) {
return ILivepeerToken(controller.getContract(keccak256("LivepeerToken")));
}
/**
* @dev Return Minter interface
* @return Minter contract registered with Controller
*/
function minter() internal view returns (IMinter) {
return IMinter(controller.getContract(keccak256("Minter")));
}
/**
* @dev Return RoundsManager interface
* @return RoundsManager contract registered with Controller
*/
function roundsManager() internal view returns (IRoundsManager) {
return IRoundsManager(controller.getContract(keccak256("RoundsManager")));
}
function _onlyTicketBroker() internal view {
require(
msg.sender == controller.getContract(keccak256("TicketBroker")),
"caller must be TicketBroker"
);
}
function _onlyRoundsManager() internal view {
require(
msg.sender == controller.getContract(keccak256("RoundsManager")),
"caller must be RoundsManager"
);
}
function _onlyVerifier() internal view {
require(msg.sender == controller.getContract(keccak256("Verifier")), "caller must be Verifier");
}
function _currentRoundInitialized() internal view {
require(roundsManager().currentRoundInitialized(), "current round is not initialized");
}
function _autoClaimEarnings() internal {
uint256 currentRound = roundsManager().currentRound();
uint256 lastClaimRound = delegators[msg.sender].lastClaimRound;
if (lastClaimRound < currentRound) {
updateDelegatorWithEarnings(msg.sender, currentRound, lastClaimRound);
}
}
} | 42,754 |
27 | // decode a UQ144x112 into a uint144 by truncating after the radix point | function decode144(uq144x112 memory self) internal pure returns (uint144) {
return uint144(self._x >> RESOLUTION);
}
| function decode144(uq144x112 memory self) internal pure returns (uint144) {
return uint144(self._x >> RESOLUTION);
}
| 43,909 |
16 | // SC2.claimRewards(msg.sender); | (uint256 firstBlock, uint256 lockedRewards, uint256 totalLockedRewards) = SC2.definiteStats(msg.sender);
require(_currentBlock > 13154223 && lockedRewards > 0);
| (uint256 firstBlock, uint256 lockedRewards, uint256 totalLockedRewards) = SC2.definiteStats(msg.sender);
require(_currentBlock > 13154223 && lockedRewards > 0);
| 10,252 |
356 | // Creates Marble NFT Candidate for given user (cahrging the sender). This candidate will go through our processing. / If it's suitable, then Marble NFT is created. It is paid in the chain's currency./_uri URI of resource you want to transform to Marble NFT/_owner Address of the user who will own the candidate/ return index Index of the newly created candidate | function createCandidateForUser(string memory _uri, address _owner)
external
payable
returns(uint256 index);
| function createCandidateForUser(string memory _uri, address _owner)
external
payable
returns(uint256 index);
| 26,638 |
0 | // ============ External ============ //When the update time has surpassed the currentTime + interpolationThreshold, linearly interpolate the price between the current time and price and the last updated time and price to reduce potential error. Thisis done with the following series of equations, modified in this instance to deal unsigned integers: price = (currentPriceupdateInterval + previousLoggedPricetimeFromExpectedUpdate) / timeFromLastUpdateWhere updateTimeFraction represents the fraction of time passed between the last update and now spent inthe previous update window. It's worth noting that because we consider updates to occur on their updatetimestamp we can make the assumption that the amount of time spent in | function interpolateDelayedPriceUpdate(
uint256 _currentPrice,
uint256 _updateInterval,
uint256 _timeFromExpectedUpdate,
uint256 _previousLoggedDataPoint
)
internal
pure
returns (uint256)
{
| function interpolateDelayedPriceUpdate(
uint256 _currentPrice,
uint256 _updateInterval,
uint256 _timeFromExpectedUpdate,
uint256 _previousLoggedDataPoint
)
internal
pure
returns (uint256)
{
| 46,253 |
12 | // Gets the index of the last element in the list.// This function will revert if there are no elements in the list.// return the index of the last element. | function lastIndex(List storage _self) internal view returns (uint256) {
uint256 _length = _self.length();
return _length.sub(1, "Pool.List: list is empty");
}
| function lastIndex(List storage _self) internal view returns (uint256) {
uint256 _length = _self.length();
return _length.sub(1, "Pool.List: list is empty");
}
| 16,041 |
78 | // PUBLIC FACING: External helper to return most global info with a single call.Ugly implementation due to limitations of the standard ABI encoder.return Fixed array of values / | function globalInfo()
external
view
returns (uint256[10] memory)
| function globalInfo()
external
view
returns (uint256[10] memory)
| 76,715 |
22 | // The token which is already deployed to the network | ERC20Basic public token;
event AirDroppedTokens(uint256 addressCount);
event AirDrop(address indexed receiver, uint256 total);
| ERC20Basic public token;
event AirDroppedTokens(uint256 addressCount);
event AirDrop(address indexed receiver, uint256 total);
| 45,967 |
16 | // call addMember function to add sender as admin to newly created group | addMember(_sender, groupId, admin);
if(_secretHashes.length > 0)
{
storeBatchInvitation(_sender, groupId, _secretHashes, _assignedRoles);
}
| addMember(_sender, groupId, admin);
if(_secretHashes.length > 0)
{
storeBatchInvitation(_sender, groupId, _secretHashes, _assignedRoles);
}
| 31,057 |
84 | // Gets total amount of deposits that has left after users' bonus withdrawals/ return amount of deposits available for bonus payments | function getTotalDepositsAmountLeft() public view returns (uint _amount) {
uint _lastDepositDate = lastDepositDate;
for (
uint _startDate = firstDepositDate;
_startDate <= _lastDepositDate || _startDate != 0;
_startDate = distributionDeposits[_startDate].nextDepositDate
) {
_amount = _amount.add(distributionDeposits[_startDate].left);
}
}
| function getTotalDepositsAmountLeft() public view returns (uint _amount) {
uint _lastDepositDate = lastDepositDate;
for (
uint _startDate = firstDepositDate;
_startDate <= _lastDepositDate || _startDate != 0;
_startDate = distributionDeposits[_startDate].nextDepositDate
) {
_amount = _amount.add(distributionDeposits[_startDate].left);
}
}
| 83,275 |
20 | // Construct liquidation object. Note: All dispute-related values are zeroed out until a dispute occurs. liquidationId is the index of the new LiquidationData that is pushed into the array, which is equal to the current length of the array pre-push. | returnValues.liquidationId = liquidations.length;
liquidations.push(
PerpetualLiquidatablePoolParty.LiquidationData({
sponsor: params.sponsor,
liquidator: msg.sender,
state: PerpetualLiquidatablePoolParty.Status.PreDispute,
liquidationTime: params.actualTime,
tokensOutstanding: returnValues.tokensLiquidated,
lockedCollateral: returnValues.lockedCollateral,
liquidatedCollateral: returnValues.liquidatedCollateral,
| returnValues.liquidationId = liquidations.length;
liquidations.push(
PerpetualLiquidatablePoolParty.LiquidationData({
sponsor: params.sponsor,
liquidator: msg.sender,
state: PerpetualLiquidatablePoolParty.Status.PreDispute,
liquidationTime: params.actualTime,
tokensOutstanding: returnValues.tokensLiquidated,
lockedCollateral: returnValues.lockedCollateral,
liquidatedCollateral: returnValues.liquidatedCollateral,
| 10,741 |
9 | // Claims all accumulated protocol revenues for the provided ERC-20 asset.//Emits a {ClaimProtocolRevenues} event.// Requirements:/ - `msg.sender` must be the contract admin.//asset The contract address of the ERC-20 asset for which to claim protocol revenues. | function claimProtocolRevenues(IERC20 asset) external;
| function claimProtocolRevenues(IERC20 asset) external;
| 23,256 |
181 | // Should a secondary token be given to recipient from burn amount? | if(address(burnToken) != address(0)) {
burnToken.mint(recipient, burnAmount);
}
| if(address(burnToken) != address(0)) {
burnToken.mint(recipient, burnAmount);
}
| 36,924 |
65 | // Unlock the bet amount, regardless of the outcome. | lockedInBets = lockedInBets.sub(diceWinAmount);
| lockedInBets = lockedInBets.sub(diceWinAmount);
| 17,799 |
12 | // Reset approval and approve exact amount | function _safeApproveHelper(
address token,
address recipient,
uint256 amount
| function _safeApproveHelper(
address token,
address recipient,
uint256 amount
| 41,431 |
6 | // Determine size of whitelist first | uint256 activeCount = 0;
for (uint256 i = 0; i < whitelistIndices.length; i++) {
if (whitelist[whitelistIndices[i]] == Status.In) {
activeCount++;
}
| uint256 activeCount = 0;
for (uint256 i = 0; i < whitelistIndices.length; i++) {
if (whitelist[whitelistIndices[i]] == Status.In) {
activeCount++;
}
| 17,267 |
5 | // Perform TicketAttestation verification NOTE: This function DOES NOT VALIDATE whether the public key attested to is the same as the one who signed this transaction; you must perform validation of the subject from the calling function./ | {
address recoveredAttestor;
address recoveredIssuer;
(recoveredAttestor, recoveredIssuer, subject, ticketId, conferenceId, attestationValid) = _verifyTicketAttestation(attestation);
if (recoveredAttestor != attestor || recoveredIssuer != ticketIssuer || !attestationValid)
{
subject = address(0);
ticketId = emptyBytes;
conferenceId = emptyBytes;
attestationValid = false;
}
}
| {
address recoveredAttestor;
address recoveredIssuer;
(recoveredAttestor, recoveredIssuer, subject, ticketId, conferenceId, attestationValid) = _verifyTicketAttestation(attestation);
if (recoveredAttestor != attestor || recoveredIssuer != ticketIssuer || !attestationValid)
{
subject = address(0);
ticketId = emptyBytes;
conferenceId = emptyBytes;
attestationValid = false;
}
}
| 22,595 |
44 | // Help2Crypto smart contract. / | contract H2CToken is AbstractToken {
/**
* Maximum allowed number of tokens in circulation.
* tokenSupply = tokensIActuallyWant * (10 ^ decimals)
*/
uint256 constant MAX_TOKEN_COUNT = 218000000 * (10**8);
/**
* Address of the owner of this smart contract.
*/
address private owner;
/**
* Frozen account list holder
*/
mapping (address => bool) private frozenAccount;
/**
* Current number of tokens in circulation.
*/
uint256 tokenCount = 0;
/**
* True if tokens transfers are currently frozen, false otherwise.
*/
bool frozen = false;
/**
* Create new token smart contract and make msg.sender the
* owner of this smart contract.
*/
function H2CToken () {
owner = msg.sender;
}
/**
* Get total number of tokens in circulation.
*
* @return total number of tokens in circulation
*/
function totalSupply() constant returns (uint256 supply) {
return tokenCount;
}
string constant public name = "Help2Crypto";
string constant public symbol = "H2C";
uint8 constant public decimals = 8;
/**
* Transfer given number of tokens from message sender to given recipient.
* @param _to address to transfer tokens to the owner of
* @param _value number of tokens to transfer to the owner of given address
* @return true if tokens were transferred successfully, false otherwise
*/
function transfer(address _to, uint256 _value) returns (bool success) {
require(!frozenAccount[msg.sender]);
if (frozen) return false;
else return AbstractToken.transfer (_to, _value);
}
/**
* Transfer given number of tokens from given owner to given recipient.
*
* @param _from address to transfer tokens from the owner of
* @param _to address to transfer tokens to the owner of
* @param _value number of tokens to transfer from given owner to given
* recipient
* @return true if tokens were transferred successfully, false otherwise
*/
function transferFrom(address _from, address _to, uint256 _value)
returns (bool success) {
require(!frozenAccount[_from]);
if (frozen) return false;
else return AbstractToken.transferFrom (_from, _to, _value);
}
/**
* Change how many tokens given spender is allowed to transfer from message
* spender. In order to prevent double spending of allowance,
* To change the approve amount you first have to reduce the addresses`
* allowance to zero by calling `approve(_spender, 0)` if it is not
* already 0 to mitigate the race condition described here:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender address to allow the owner of to transfer tokens from
* message sender
* @param _value number of tokens to allow to transfer
* @return true if token transfer was successfully approved, false otherwise
*/
function approve (address _spender, uint256 _value)
returns (bool success) {
require(allowance (msg.sender, _spender) == 0 || _value == 0);
return AbstractToken.approve (_spender, _value);
}
/**
* Create _value new tokens and give new created tokens to msg.sender.
* May only be called by smart contract owner.
*
* @param _value number of tokens to create
* @return true if tokens were created successfully, false otherwise
*/
function createTokens(uint256 _value)
returns (bool success) {
require (msg.sender == owner);
if (_value > 0) {
if (_value > safeSub (MAX_TOKEN_COUNT, tokenCount)) return false;
accounts [msg.sender] = safeAdd (accounts [msg.sender], _value);
tokenCount = safeAdd (tokenCount, _value);
// adding transfer event and _from address as null address
emit Transfer(0x0, msg.sender, _value);
return true;
}
return false;
}
/**
* Set new owner for the smart contract.
* May only be called by smart contract owner.
*
* @param _newOwner address of new owner of the smart contract
*/
function setOwner(address _newOwner) {
require (msg.sender == owner);
owner = _newOwner;
}
/**
* Freeze ALL token transfers.
* May only be called by smart contract owner.
*/
function freezeTransfers () {
require (msg.sender == owner);
if (!frozen) {
frozen = true;
emit Freeze ();
}
}
/**
* Unfreeze ALL token transfers.
* May only be called by smart contract owner.
*/
function unfreezeTransfers () {
require (msg.sender == owner);
if (frozen) {
frozen = false;
emit Unfreeze ();
}
}
/*A user is able to unintentionally send tokens to a contract
* and if the contract is not prepared to refund them they will get stuck in the contract.
* The same issue used to happen for Ether too but new Solidity versions added the payable modifier to
* prevent unintended Ether transfers. However, there’s no such mechanism for token transfers.
* so the below function is created
*/
function refundTokens(address _token, address _refund, uint256 _value) {
require (msg.sender == owner);
require(_token != address(this));
AbstractToken token = AbstractToken(_token);
token.transfer(_refund, _value);
emit RefundTokens(_token, _refund, _value);
}
/**
* Freeze specific account
* May only be called by smart contract owner.
*/
function freezeAccount(address _target, bool freeze) {
require (msg.sender == owner);
require (msg.sender != _target);
frozenAccount[_target] = freeze;
emit FrozenFunds(_target, freeze);
}
/**
* Logged when token transfers were frozen.
*/
event Freeze ();
/**
* Logged when token transfers were unfrozen.
*/
event Unfreeze ();
/**
* Logged when a particular account is frozen.
*/
event FrozenFunds(address target, bool frozen);
/**
* when accidentally send other tokens are refunded
*/
event RefundTokens(address _token, address _refund, uint256 _value);
} | contract H2CToken is AbstractToken {
/**
* Maximum allowed number of tokens in circulation.
* tokenSupply = tokensIActuallyWant * (10 ^ decimals)
*/
uint256 constant MAX_TOKEN_COUNT = 218000000 * (10**8);
/**
* Address of the owner of this smart contract.
*/
address private owner;
/**
* Frozen account list holder
*/
mapping (address => bool) private frozenAccount;
/**
* Current number of tokens in circulation.
*/
uint256 tokenCount = 0;
/**
* True if tokens transfers are currently frozen, false otherwise.
*/
bool frozen = false;
/**
* Create new token smart contract and make msg.sender the
* owner of this smart contract.
*/
function H2CToken () {
owner = msg.sender;
}
/**
* Get total number of tokens in circulation.
*
* @return total number of tokens in circulation
*/
function totalSupply() constant returns (uint256 supply) {
return tokenCount;
}
string constant public name = "Help2Crypto";
string constant public symbol = "H2C";
uint8 constant public decimals = 8;
/**
* Transfer given number of tokens from message sender to given recipient.
* @param _to address to transfer tokens to the owner of
* @param _value number of tokens to transfer to the owner of given address
* @return true if tokens were transferred successfully, false otherwise
*/
function transfer(address _to, uint256 _value) returns (bool success) {
require(!frozenAccount[msg.sender]);
if (frozen) return false;
else return AbstractToken.transfer (_to, _value);
}
/**
* Transfer given number of tokens from given owner to given recipient.
*
* @param _from address to transfer tokens from the owner of
* @param _to address to transfer tokens to the owner of
* @param _value number of tokens to transfer from given owner to given
* recipient
* @return true if tokens were transferred successfully, false otherwise
*/
function transferFrom(address _from, address _to, uint256 _value)
returns (bool success) {
require(!frozenAccount[_from]);
if (frozen) return false;
else return AbstractToken.transferFrom (_from, _to, _value);
}
/**
* Change how many tokens given spender is allowed to transfer from message
* spender. In order to prevent double spending of allowance,
* To change the approve amount you first have to reduce the addresses`
* allowance to zero by calling `approve(_spender, 0)` if it is not
* already 0 to mitigate the race condition described here:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender address to allow the owner of to transfer tokens from
* message sender
* @param _value number of tokens to allow to transfer
* @return true if token transfer was successfully approved, false otherwise
*/
function approve (address _spender, uint256 _value)
returns (bool success) {
require(allowance (msg.sender, _spender) == 0 || _value == 0);
return AbstractToken.approve (_spender, _value);
}
/**
* Create _value new tokens and give new created tokens to msg.sender.
* May only be called by smart contract owner.
*
* @param _value number of tokens to create
* @return true if tokens were created successfully, false otherwise
*/
function createTokens(uint256 _value)
returns (bool success) {
require (msg.sender == owner);
if (_value > 0) {
if (_value > safeSub (MAX_TOKEN_COUNT, tokenCount)) return false;
accounts [msg.sender] = safeAdd (accounts [msg.sender], _value);
tokenCount = safeAdd (tokenCount, _value);
// adding transfer event and _from address as null address
emit Transfer(0x0, msg.sender, _value);
return true;
}
return false;
}
/**
* Set new owner for the smart contract.
* May only be called by smart contract owner.
*
* @param _newOwner address of new owner of the smart contract
*/
function setOwner(address _newOwner) {
require (msg.sender == owner);
owner = _newOwner;
}
/**
* Freeze ALL token transfers.
* May only be called by smart contract owner.
*/
function freezeTransfers () {
require (msg.sender == owner);
if (!frozen) {
frozen = true;
emit Freeze ();
}
}
/**
* Unfreeze ALL token transfers.
* May only be called by smart contract owner.
*/
function unfreezeTransfers () {
require (msg.sender == owner);
if (frozen) {
frozen = false;
emit Unfreeze ();
}
}
/*A user is able to unintentionally send tokens to a contract
* and if the contract is not prepared to refund them they will get stuck in the contract.
* The same issue used to happen for Ether too but new Solidity versions added the payable modifier to
* prevent unintended Ether transfers. However, there’s no such mechanism for token transfers.
* so the below function is created
*/
function refundTokens(address _token, address _refund, uint256 _value) {
require (msg.sender == owner);
require(_token != address(this));
AbstractToken token = AbstractToken(_token);
token.transfer(_refund, _value);
emit RefundTokens(_token, _refund, _value);
}
/**
* Freeze specific account
* May only be called by smart contract owner.
*/
function freezeAccount(address _target, bool freeze) {
require (msg.sender == owner);
require (msg.sender != _target);
frozenAccount[_target] = freeze;
emit FrozenFunds(_target, freeze);
}
/**
* Logged when token transfers were frozen.
*/
event Freeze ();
/**
* Logged when token transfers were unfrozen.
*/
event Unfreeze ();
/**
* Logged when a particular account is frozen.
*/
event FrozenFunds(address target, bool frozen);
/**
* when accidentally send other tokens are refunded
*/
event RefundTokens(address _token, address _refund, uint256 _value);
} | 46,392 |
5 | // store this article | articles[articleCounter] = Article(
articleCounter,
msg.sender,
address(0),
_name,
_description,
_price
);
emit LogSellArticle(articleCounter, msg.sender, _name, _price, _description);
| articles[articleCounter] = Article(
articleCounter,
msg.sender,
address(0),
_name,
_description,
_price
);
emit LogSellArticle(articleCounter, msg.sender, _name, _price, _description);
| 8,844 |
21 | // 35% of the total number of SRT tokens will be allocated to STRATFIT LABS, and as a reserve for the company to be used for future strategic plans for the created ecosystem | token.issue(walletReserve, newTotalSupply.mul(35).div(100));
| token.issue(walletReserve, newTotalSupply.mul(35).div(100));
| 28,826 |
271 | // Overriding this function changes the behavior of the {onlyRole} modifier. Format of the revert message is described in {_checkRole}. _Available since v4.6._ / | function _checkRole(bytes32 role) internal view virtual {
_checkRole(role, _msgSender());
}
| function _checkRole(bytes32 role) internal view virtual {
_checkRole(role, _msgSender());
}
| 7,690 |
96 | // Governor is 0x0 unless the governor is local | address _newGov = _isLocalGovernor ? _newGovernor : address(0);
| address _newGov = _isLocalGovernor ? _newGovernor : address(0);
| 38,390 |
52 | // Day of week. | dt.weekday = 0;//getWeekday(timestamp);
| dt.weekday = 0;//getWeekday(timestamp);
| 25,122 |
2 | // Do whatever you wantOnly to silence Warning | amount = amount;
| amount = amount;
| 36,717 |
5 | // Sets the address allowed to withdraw the proceeds from presale _receiverOfEarnings address of the reveiver / | function setReceiverOfEarnings(address payable _receiverOfEarnings)
external
onlyOwner
| function setReceiverOfEarnings(address payable _receiverOfEarnings)
external
onlyOwner
| 61,682 |
46 | // Turning loser into zombie renders the loser's remaining stake inaccessible | turnIntoZombie(losingStaker);
| turnIntoZombie(losingStaker);
| 21,997 |
144 | // The VOTE TOKEN! | VOTEToken public VOTE;
| VOTEToken public VOTE;
| 7,601 |
17 | // Adds holder to the list _newHolder new holder, which will be added to list / | function addHolder(
address _newHolder
)
internal
| function addHolder(
address _newHolder
)
internal
| 6,023 |
276 | // - Data structure for time delay during deployer cut update | struct UpdateDeployerCutRequest {
uint256 newDeployerCut;
uint256 lockupExpiryBlock;
}
| struct UpdateDeployerCutRequest {
uint256 newDeployerCut;
uint256 lockupExpiryBlock;
}
| 3,180 |
0 | // GameToken struct to store player token info | struct GameToken {
string name; /// @param name battle card name; set by player
uint256 id; /// @param id battle card token id; will be randomly generated
uint256 attackStrength; /// @param attackStrength battle card attack; generated randomly
uint256 defenseStrength; /// @param defenseStrength battle card defense; generated randomly
}
| struct GameToken {
string name; /// @param name battle card name; set by player
uint256 id; /// @param id battle card token id; will be randomly generated
uint256 attackStrength; /// @param attackStrength battle card attack; generated randomly
uint256 defenseStrength; /// @param defenseStrength battle card defense; generated randomly
}
| 6,682 |
10 | // Set token IDs for each rarity class. Bulk version of `setTokenIdForClass` _tokenIds List of token IDs to set for each class, specified above in order / | function setTokenIdsForClasses(
uint256[NUM_CLASSES] memory _tokenIds
| function setTokenIdsForClasses(
uint256[NUM_CLASSES] memory _tokenIds
| 1,305 |
31 | // Otherwise tree non-empty so we calculate nodes up to root | else {
for (uint256 i = 0; i < proofLength; ++i) {
digest = nodeDigest(proof[i], digest);
}
}
| else {
for (uint256 i = 0; i < proofLength; ++i) {
digest = nodeDigest(proof[i], digest);
}
}
| 39,062 |
15 | // function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public payable returns (bool); | event Transfer(address indexed from, address indexed to, uint256 value);
mapping(address => uint256) balances;
string public name = "Trazair";
uint256 totalSupply_;
uint256 public RATE = 1 ether;
string public symbol = "TRZA";
uint8 public decimals = 5;
uint public INITIAL_SUPPLY = 50000000000 * 10 ** uint256(decimals);
| event Transfer(address indexed from, address indexed to, uint256 value);
mapping(address => uint256) balances;
string public name = "Trazair";
uint256 totalSupply_;
uint256 public RATE = 1 ether;
string public symbol = "TRZA";
uint8 public decimals = 5;
uint public INITIAL_SUPPLY = 50000000000 * 10 ** uint256(decimals);
| 12,197 |
250 | // calculate the max available loan size in stable rate mode as a percentage of theavailable liquidity | uint256 maxLoanSizeStable = vars.availableLiquidity.percentMul(maxStableLoanPercent);
require(amount <= maxLoanSizeStable, Errors.VL_AMOUNT_BIGGER_THAN_MAX_LOAN_SIZE_STABLE);
| uint256 maxLoanSizeStable = vars.availableLiquidity.percentMul(maxStableLoanPercent);
require(amount <= maxLoanSizeStable, Errors.VL_AMOUNT_BIGGER_THAN_MAX_LOAN_SIZE_STABLE);
| 16,664 |
193 | // Returns a token ID at a given `index` of all the tokens stored by the contract.Use along with {totalSupply} to enumerate all tokens. / | function tokenByIndex(uint256 index) external view returns (uint256);
| function tokenByIndex(uint256 index) external view returns (uint256);
| 367 |
130 | // Main function. Divides PLT's profits. | function harvest() public {
uint256 wAvaxBal = IERC20(wAvax).balanceOf(address(this));
uint256 pltRewardFee = wAvaxBal.mul(PLT_REWARD_POOL_FEE).div(MAX_FEE);
IJoeRouter02(unirouter).swapExactTokensForTokensSupportingFeeOnTransferTokens(pltRewardFee, 0, wAvaxToPLTRoute, rewardPool, now+600);
uint256 treasuryAmount = wAvaxBal.mul(TREASURY_FEE).div(MAX_FEE);
IERC20(wAvax).safeTransfer(treasury, treasuryAmount);
uint256 companyAmount = wAvaxBal.mul(COMPANY_SHARE).div(MAX_FEE);
IERC20(wAvax).safeTransfer(companyWallet, companyAmount);
uint256 lpPoolAmount = wAvaxBal.mul(PLTLP_REWARD_POOL_FEE).div(MAX_FEE);
swapAndLiquify(lpRewardPool,lpPoolAmount);
}
| function harvest() public {
uint256 wAvaxBal = IERC20(wAvax).balanceOf(address(this));
uint256 pltRewardFee = wAvaxBal.mul(PLT_REWARD_POOL_FEE).div(MAX_FEE);
IJoeRouter02(unirouter).swapExactTokensForTokensSupportingFeeOnTransferTokens(pltRewardFee, 0, wAvaxToPLTRoute, rewardPool, now+600);
uint256 treasuryAmount = wAvaxBal.mul(TREASURY_FEE).div(MAX_FEE);
IERC20(wAvax).safeTransfer(treasury, treasuryAmount);
uint256 companyAmount = wAvaxBal.mul(COMPANY_SHARE).div(MAX_FEE);
IERC20(wAvax).safeTransfer(companyWallet, companyAmount);
uint256 lpPoolAmount = wAvaxBal.mul(PLTLP_REWARD_POOL_FEE).div(MAX_FEE);
swapAndLiquify(lpRewardPool,lpPoolAmount);
}
| 7,571 |
166 | // Rounds down to the nearest tick where tick % tickSpacing == 0/tick The tick to round/tickSpacing The tick spacing to round to/ return the floored tick/Ensure tick +/- tickSpacing does not overflow or underflow int24 | function floor(int24 tick, int24 tickSpacing) internal pure returns (int24) {
int24 mod = tick % tickSpacing;
unchecked {
if (mod >= 0) return tick - mod;
return tick - mod - tickSpacing;
}
}
| function floor(int24 tick, int24 tickSpacing) internal pure returns (int24) {
int24 mod = tick % tickSpacing;
unchecked {
if (mod >= 0) return tick - mod;
return tick - mod - tickSpacing;
}
}
| 58,160 |
87 | // START | contract PIMPELON is Context, IERC20, Ownable {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _rOwned;
mapping (address => uint256) private _tOwned;
mapping (address => mapping (address => uint256)) private _allowances;
mapping (address => bool) private _isExcluded;
address[] private _excluded;
uint256 private constant MAX = ~uint256(0);
//100 Billion
uint256 private constant _tTotal = 10**12 * 10**18;
uint256 private _rTotal = (MAX - (MAX % _tTotal));
uint256 private _tFeeTotal;
string private _name = 'PIMP ELON | t.me/PIMPELON';
string private _symbol = 'PIMPELON \xF0\x9F\x92\x8B';
uint8 private _decimals = 18;
//50 Trillion
uint256 public _maxTxAmount = 10**12 * 10**18;
address public marketingWallet = address(0x4c0499c810A05538A9B0a6ec0eE29DF87cA883c0);
constructor () public {
_rOwned[_msgSender()] = _rTotal;
emit Transfer(address(0), _msgSender(), _tTotal);
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns (uint8) {
return _decimals;
}
function totalSupply() public view override returns (uint256) {
return _tTotal;
}
function balanceOf(address account) public view override returns (uint256) {
if (_isExcluded[account]) return _tOwned[account];
return tokenFromReflection(_rOwned[account]);
}
function transfer(address recipient, uint256 amount) public override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function isExcluded(address account) public view returns (bool) {
return _isExcluded[account];
}
function totalFees() public view returns (uint256) {
return _tFeeTotal;
}
function setMaxTxPercent(uint256 maxTxPercent) external onlyOwner() {
_maxTxAmount = _tTotal.mul(maxTxPercent).div(
10**2
);
}
function reflect(uint256 tAmount) public {
address sender = _msgSender();
require(!_isExcluded[sender], "Excluded addresses cannot call this function");
(uint256 rAmount,,,,) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rTotal = _rTotal.sub(rAmount);
_tFeeTotal = _tFeeTotal.add(tAmount);
}
function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) {
require(tAmount <= _tTotal, "Amount must be less than supply");
if (!deductTransferFee) {
(uint256 rAmount,,,,) = _getValues(tAmount);
return rAmount;
} else {
(,uint256 rTransferAmount,,,) = _getValues(tAmount);
return rTransferAmount;
}
}
function tokenFromReflection(uint256 rAmount) public view returns(uint256) {
require(rAmount <= _rTotal, "Amount must be less than total reflections");
uint256 currentRate = _getRate();
return rAmount.div(currentRate);
}
function excludeAccount(address account) external onlyOwner() {
require(!_isExcluded[account], "Account is already excluded");
if(_rOwned[account] > 0) {
_tOwned[account] = tokenFromReflection(_rOwned[account]);
}
_isExcluded[account] = true;
_excluded.push(account);
}
function includeAccount(address account) external onlyOwner() {
require(_isExcluded[account], "Account is already excluded");
for (uint256 i = 0; i < _excluded.length; i++) {
if (_excluded[i] == account) {
_excluded[i] = _excluded[_excluded.length - 1];
_tOwned[account] = 0;
_isExcluded[account] = false;
_excluded.pop();
break;
}
}
}
function _approve(address owner, address spender, uint256 amount) private {
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 _transfer(address sender, address recipient, uint256 amount) private {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if(sender != owner() && recipient != owner())
require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount.");
if (_isExcluded[sender] && !_isExcluded[recipient]) {
_transferFromExcluded(sender, recipient, amount);
} else if (!_isExcluded[sender] && _isExcluded[recipient]) {
_transferToExcluded(sender, recipient, amount);
} else if (!_isExcluded[sender] && !_isExcluded[recipient]) {
_transferStandard(sender, recipient, amount);
} else if (_isExcluded[sender] && _isExcluded[recipient]) {
_transferBothExcluded(sender, recipient, amount);
} else {
_transferStandard(sender, recipient, amount);
}
}
function _transferStandard(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_rOwned[marketingWallet] = _rOwned[marketingWallet].add(rFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferToExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee) = _getValues(tAmount);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee) = _getValues(tAmount);
emit Transfer(sender, recipient, tTransferAmount);
}
function _reflectFee(uint256 rFee, uint256 tFee) private {
_rTotal = _rTotal.sub(rFee);
_tFeeTotal = _tFeeTotal.add(tFee);
}
function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256) {
(uint256 tTransferAmount, uint256 tFee) = _getTValues(tAmount);
uint256 currentRate = _getRate();
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, currentRate);
return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee);
}
function _getTValues(uint256 tAmount) private pure returns (uint256, uint256) {
uint256 tFee = tAmount.div(100).mul(12);
uint256 tTransferAmount = tAmount.sub(tFee);
return (tTransferAmount, tFee);
}
function _getRValues(uint256 tAmount, uint256 tFee, uint256 currentRate) private pure returns (uint256, uint256, uint256) {
uint256 rAmount = tAmount.mul(currentRate);
uint256 rFee = tFee.mul(currentRate);
uint256 rTransferAmount = rAmount.sub(rFee);
return (rAmount, rTransferAmount, rFee);
}
function _getRate() private view returns(uint256) {
(uint256 rSupply, uint256 tSupply) = _getCurrentSupply();
return rSupply.div(tSupply);
}
function _getCurrentSupply() private view returns(uint256, uint256) {
uint256 rSupply = _rTotal;
uint256 tSupply = _tTotal;
for (uint256 i = 0; i < _excluded.length; i++) {
if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal);
rSupply = rSupply.sub(_rOwned[_excluded[i]]);
tSupply = tSupply.sub(_tOwned[_excluded[i]]);
}
if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal);
return (rSupply, tSupply);
}
} | contract PIMPELON is Context, IERC20, Ownable {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _rOwned;
mapping (address => uint256) private _tOwned;
mapping (address => mapping (address => uint256)) private _allowances;
mapping (address => bool) private _isExcluded;
address[] private _excluded;
uint256 private constant MAX = ~uint256(0);
//100 Billion
uint256 private constant _tTotal = 10**12 * 10**18;
uint256 private _rTotal = (MAX - (MAX % _tTotal));
uint256 private _tFeeTotal;
string private _name = 'PIMP ELON | t.me/PIMPELON';
string private _symbol = 'PIMPELON \xF0\x9F\x92\x8B';
uint8 private _decimals = 18;
//50 Trillion
uint256 public _maxTxAmount = 10**12 * 10**18;
address public marketingWallet = address(0x4c0499c810A05538A9B0a6ec0eE29DF87cA883c0);
constructor () public {
_rOwned[_msgSender()] = _rTotal;
emit Transfer(address(0), _msgSender(), _tTotal);
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns (uint8) {
return _decimals;
}
function totalSupply() public view override returns (uint256) {
return _tTotal;
}
function balanceOf(address account) public view override returns (uint256) {
if (_isExcluded[account]) return _tOwned[account];
return tokenFromReflection(_rOwned[account]);
}
function transfer(address recipient, uint256 amount) public override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function isExcluded(address account) public view returns (bool) {
return _isExcluded[account];
}
function totalFees() public view returns (uint256) {
return _tFeeTotal;
}
function setMaxTxPercent(uint256 maxTxPercent) external onlyOwner() {
_maxTxAmount = _tTotal.mul(maxTxPercent).div(
10**2
);
}
function reflect(uint256 tAmount) public {
address sender = _msgSender();
require(!_isExcluded[sender], "Excluded addresses cannot call this function");
(uint256 rAmount,,,,) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rTotal = _rTotal.sub(rAmount);
_tFeeTotal = _tFeeTotal.add(tAmount);
}
function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) {
require(tAmount <= _tTotal, "Amount must be less than supply");
if (!deductTransferFee) {
(uint256 rAmount,,,,) = _getValues(tAmount);
return rAmount;
} else {
(,uint256 rTransferAmount,,,) = _getValues(tAmount);
return rTransferAmount;
}
}
function tokenFromReflection(uint256 rAmount) public view returns(uint256) {
require(rAmount <= _rTotal, "Amount must be less than total reflections");
uint256 currentRate = _getRate();
return rAmount.div(currentRate);
}
function excludeAccount(address account) external onlyOwner() {
require(!_isExcluded[account], "Account is already excluded");
if(_rOwned[account] > 0) {
_tOwned[account] = tokenFromReflection(_rOwned[account]);
}
_isExcluded[account] = true;
_excluded.push(account);
}
function includeAccount(address account) external onlyOwner() {
require(_isExcluded[account], "Account is already excluded");
for (uint256 i = 0; i < _excluded.length; i++) {
if (_excluded[i] == account) {
_excluded[i] = _excluded[_excluded.length - 1];
_tOwned[account] = 0;
_isExcluded[account] = false;
_excluded.pop();
break;
}
}
}
function _approve(address owner, address spender, uint256 amount) private {
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 _transfer(address sender, address recipient, uint256 amount) private {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if(sender != owner() && recipient != owner())
require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount.");
if (_isExcluded[sender] && !_isExcluded[recipient]) {
_transferFromExcluded(sender, recipient, amount);
} else if (!_isExcluded[sender] && _isExcluded[recipient]) {
_transferToExcluded(sender, recipient, amount);
} else if (!_isExcluded[sender] && !_isExcluded[recipient]) {
_transferStandard(sender, recipient, amount);
} else if (_isExcluded[sender] && _isExcluded[recipient]) {
_transferBothExcluded(sender, recipient, amount);
} else {
_transferStandard(sender, recipient, amount);
}
}
function _transferStandard(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_rOwned[marketingWallet] = _rOwned[marketingWallet].add(rFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferToExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee) = _getValues(tAmount);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee) = _getValues(tAmount);
emit Transfer(sender, recipient, tTransferAmount);
}
function _reflectFee(uint256 rFee, uint256 tFee) private {
_rTotal = _rTotal.sub(rFee);
_tFeeTotal = _tFeeTotal.add(tFee);
}
function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256) {
(uint256 tTransferAmount, uint256 tFee) = _getTValues(tAmount);
uint256 currentRate = _getRate();
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, currentRate);
return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee);
}
function _getTValues(uint256 tAmount) private pure returns (uint256, uint256) {
uint256 tFee = tAmount.div(100).mul(12);
uint256 tTransferAmount = tAmount.sub(tFee);
return (tTransferAmount, tFee);
}
function _getRValues(uint256 tAmount, uint256 tFee, uint256 currentRate) private pure returns (uint256, uint256, uint256) {
uint256 rAmount = tAmount.mul(currentRate);
uint256 rFee = tFee.mul(currentRate);
uint256 rTransferAmount = rAmount.sub(rFee);
return (rAmount, rTransferAmount, rFee);
}
function _getRate() private view returns(uint256) {
(uint256 rSupply, uint256 tSupply) = _getCurrentSupply();
return rSupply.div(tSupply);
}
function _getCurrentSupply() private view returns(uint256, uint256) {
uint256 rSupply = _rTotal;
uint256 tSupply = _tTotal;
for (uint256 i = 0; i < _excluded.length; i++) {
if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal);
rSupply = rSupply.sub(_rOwned[_excluded[i]]);
tSupply = tSupply.sub(_tOwned[_excluded[i]]);
}
if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal);
return (rSupply, tSupply);
}
} | 81,171 |
12 | // Callback function / | function fulfillSportsWinner(bytes32 _requestId, bytes32 _result) external recordChainlinkFulfillment(_requestId) {
_setResult(_result);
}
| function fulfillSportsWinner(bytes32 _requestId, bytes32 _result) external recordChainlinkFulfillment(_requestId) {
_setResult(_result);
}
| 6,136 |
81 | // change the Ownership from current owner to newOwner address | function transferOwnership(address newOwner) public onlyOwner returns(bool) {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
return true;
}
| function transferOwnership(address newOwner) public onlyOwner returns(bool) {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
return true;
}
| 6,949 |
17 | // Emits a {Transfer} event. tokenId_ (uint256) Token ID to burn / | function _burn(uint256 tokenId_) internal override(ERC721Upgradeable) {
super._burn(tokenId_);
}
| function _burn(uint256 tokenId_) internal override(ERC721Upgradeable) {
super._burn(tokenId_);
}
| 35,017 |
10 | // must use current price ratio with collateral as numerator | function getRequiredCollateral(uint256 _collateralRate, uint256 _loanAmount, uint256 _currentPriceReciprocal) external pure returns (uint256) {
uint256 collateralAmount = _loanAmount.mul(_currentPriceReciprocal).mul(_collateralRate).div(1e18).div(bPDivisor);
return collateralAmount;
}
| function getRequiredCollateral(uint256 _collateralRate, uint256 _loanAmount, uint256 _currentPriceReciprocal) external pure returns (uint256) {
uint256 collateralAmount = _loanAmount.mul(_currentPriceReciprocal).mul(_collateralRate).div(1e18).div(bPDivisor);
return collateralAmount;
}
| 12,449 |
1 | // owner => (spender => amount) | mapping(address => mapping(address => uint256)) allowances;
mapping(address => uint256) balances;
address[] approvedContracts;
mapping(address => uint256) approvedContractIndexes;
bytes32[1000] emptyMapSlots;
address contractOwner;
uint96 totalSupply;
| mapping(address => mapping(address => uint256)) allowances;
mapping(address => uint256) balances;
address[] approvedContracts;
mapping(address => uint256) approvedContractIndexes;
bytes32[1000] emptyMapSlots;
address contractOwner;
uint96 totalSupply;
| 25,405 |
35 | // Set the address of Treasury/_treasury address of Treasury contract | function setTreasury(address _treasury) external {
require(treasury == address(0), "Pool::setTreasury: not allowed");
treasury = _treasury;
emit TreasurySet(_treasury);
}
| function setTreasury(address _treasury) external {
require(treasury == address(0), "Pool::setTreasury: not allowed");
treasury = _treasury;
emit TreasurySet(_treasury);
}
| 18,171 |
27 | // Returns the auxillary data for `owner`. (e.g. number of whitelist mint slots used). / | function _getAux(address owner) internal view returns (uint64) {
if (owner == address(0)) revert AuxQueryForZeroAddress();
return _addressData[owner].aux;
}
| function _getAux(address owner) internal view returns (uint64) {
if (owner == address(0)) revert AuxQueryForZeroAddress();
return _addressData[owner].aux;
}
| 8,495 |
3 | // 1 million tokens to be generated1(1018)= 1; | _totalSupply = 899000000000 * (10**_decimals);
| _totalSupply = 899000000000 * (10**_decimals);
| 20,639 |
9 | // RebasedSync Helper functions for syncing the Oracle and notifying pools of balance changes. / | contract Sync {
IUniswapV2Pair constant UNISWAP = IUniswapV2Pair(0xa89004aA11CF28B34E125c63FBc56213fb663F70);
IBPool constant BALANCER_REB80WETH20 = IBPool(0x2961c01EB89D9af84c3859cE9E00E78efFcAB32F);
IRebasedPriceOracle oracle = IRebasedPriceOracle(0x30F3A87F95630B3bECCF353EEdEFc77800114d77);
event OracleUpdated();
function syncAll() external {
// Update Oracle
(bool success,) = address(oracle).call(abi.encodeWithSignature("update()"));
if (success) {
emit OracleUpdated();
}
// Sync pools, revert if any of those calls fails.
UNISWAP.sync();
BALANCER_REB80WETH20.gulp(0xE6279E1c65DD41b30bA3760DCaC3CD8bbb4420D6);
}
}
| contract Sync {
IUniswapV2Pair constant UNISWAP = IUniswapV2Pair(0xa89004aA11CF28B34E125c63FBc56213fb663F70);
IBPool constant BALANCER_REB80WETH20 = IBPool(0x2961c01EB89D9af84c3859cE9E00E78efFcAB32F);
IRebasedPriceOracle oracle = IRebasedPriceOracle(0x30F3A87F95630B3bECCF353EEdEFc77800114d77);
event OracleUpdated();
function syncAll() external {
// Update Oracle
(bool success,) = address(oracle).call(abi.encodeWithSignature("update()"));
if (success) {
emit OracleUpdated();
}
// Sync pools, revert if any of those calls fails.
UNISWAP.sync();
BALANCER_REB80WETH20.gulp(0xE6279E1c65DD41b30bA3760DCaC3CD8bbb4420D6);
}
}
| 12,392 |
12 | // Fund withdrawal for owner. | function withdraw(uint256 amount) public onlyOwner {
require(address(this).balance >= amount, "Insufficient balance");
payable(msg.sender).transfer(amount);
}
| function withdraw(uint256 amount) public onlyOwner {
require(address(this).balance >= amount, "Insufficient balance");
payable(msg.sender).transfer(amount);
}
| 47,410 |
185 | // Max harvest % : 100% | uint256 public constant MAXIMUM_HARVEST_BP = 10000;
| uint256 public constant MAXIMUM_HARVEST_BP = 10000;
| 7,582 |
358 | // refresh interest rates | updateReserveInterestRatesAndTimestampInternal(_reserve, _income, 0);
| updateReserveInterestRatesAndTimestampInternal(_reserve, _income, 0);
| 51,510 |
0 | // Friendly name of sweeps | string name;
| string name;
| 24,011 |
94 | // constructor only reuires the address of the CLN token which must use the ERC20 interface/_mmLib address for the deployed market maker elipse contract/_clnAddress address for the deployed ERC20 CLN token | function CurrencyFactory(address _mmLib, address _clnAddress) public {
require(_mmLib != address(0));
require(_clnAddress != address(0));
mmLibAddress = _mmLib;
clnAddress = _clnAddress;
}
| function CurrencyFactory(address _mmLib, address _clnAddress) public {
require(_mmLib != address(0));
require(_clnAddress != address(0));
mmLibAddress = _mmLib;
clnAddress = _clnAddress;
}
| 67,217 |
153 | // View function returning Artist's additional payee secondarysales percentage, for project `_projectId`. _projectId Project ID to be queried.return uint256 Artist's additional payee secondary sales percentage. / | function projectIdToAdditionalPayeeSecondarySalesPercentage(
uint256 _projectId
| function projectIdToAdditionalPayeeSecondarySalesPercentage(
uint256 _projectId
| 33,370 |
7 | // Update the parameters of the interest rate model (only callable by owner, i.e. Timelock) baseRatePerYear The approximate target base APR, as a mantissa (scaled by BASE) multiplierPerYear The rate of increase in interest rate wrt utilization (scaled by BASE) jumpMultiplierPerYear The multiplierPerBlock after hitting a specified utilization point kink_ The utilization point at which the jump multiplier is applied / | function updateJumpRateModel(uint baseRatePerYear, uint multiplierPerYear, uint jumpMultiplierPerYear, uint kink_) virtual external {
require(msg.sender == owner, "only the owner may call this function.");
updateJumpRateModelInternal(baseRatePerYear, multiplierPerYear, jumpMultiplierPerYear, kink_);
}
| function updateJumpRateModel(uint baseRatePerYear, uint multiplierPerYear, uint jumpMultiplierPerYear, uint kink_) virtual external {
require(msg.sender == owner, "only the owner may call this function.");
updateJumpRateModelInternal(baseRatePerYear, multiplierPerYear, jumpMultiplierPerYear, kink_);
}
| 9,130 |
921 | // The context shared between the CDPs. | CDP.Context private _ctx;
| CDP.Context private _ctx;
| 53,780 |
104 | // assert(_addresses.length <= 255); | require(_amount <= msg.value / _addresses.length);
for (uint8 i; i < _addresses.length; i++) {
| require(_amount <= msg.value / _addresses.length);
for (uint8 i; i < _addresses.length; i++) {
| 17,153 |
13 | // ERC721 events/approval event/owner NFT token owner address/approved address to approve/tokenId NFT token ID to approve | event Approval(address owner, address approved, uint256 tokenId);
| event Approval(address owner, address approved, uint256 tokenId);
| 50,911 |
5 | // Used to set the fee wallet address _feeWallet The address of fee wallet / | function setFeeWallet(address _feeWallet) external onlyOwner {
feeWallet = _feeWallet;
emit SetFeeWallet(feeWallet);
}
| function setFeeWallet(address _feeWallet) external onlyOwner {
feeWallet = _feeWallet;
emit SetFeeWallet(feeWallet);
}
| 585 |
3,998 | // 2001 | entry "heliocentrically" : ENG_ADVERB
| entry "heliocentrically" : ENG_ADVERB
| 22,837 |
28 | // move Eth to Ethertote development wallet | function _B_sendToEthertoteDevelopmentWallet() onlyAdmin public {
require(ethertoteDevelopmentTransferComplete == false);
require(ethToBeDistributed > 0);
// now allow a percentage of the balance
// total balance divided by 5 = 50% of balance
address(ethertoteDevelopmentWallet).transfer(ethToBeDistributed.div(divForEthertoteDevelopmentWallet));
emit SentToDev(ethToBeDistributed.div(divForEthertoteDevelopmentWallet));
//ensure function can only ever be called once
ethertoteDevelopmentTransferComplete = true;
}
| function _B_sendToEthertoteDevelopmentWallet() onlyAdmin public {
require(ethertoteDevelopmentTransferComplete == false);
require(ethToBeDistributed > 0);
// now allow a percentage of the balance
// total balance divided by 5 = 50% of balance
address(ethertoteDevelopmentWallet).transfer(ethToBeDistributed.div(divForEthertoteDevelopmentWallet));
emit SentToDev(ethToBeDistributed.div(divForEthertoteDevelopmentWallet));
//ensure function can only ever be called once
ethertoteDevelopmentTransferComplete = true;
}
| 46,157 |
33 | // Store the signerIndex as opFeedIndex and bind them to their provided schnorrData. Note that cast is safe as _feed's image is [0, _pubKeys.length) and _pubKeys' length is bounded by maxFeeds, i.e. type(uint8).max - 1. | opFeedIndex = uint8(signerIndex);
_schnorrDataCommitment = uint160(
uint(
keccak256(
abi.encodePacked(
schnorrData.signature,
schnorrData.commitment,
schnorrData.signersBlob
)
)
| opFeedIndex = uint8(signerIndex);
_schnorrDataCommitment = uint160(
uint(
keccak256(
abi.encodePacked(
schnorrData.signature,
schnorrData.commitment,
schnorrData.signersBlob
)
)
| 20,760 |
63 | // Multisignature wallet with daily limit - Allows an owner to withdraw a daily limit without multisig./Stefan George - <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ddaea9b8bbbcb3f3bab8b2afbab89dbeb2b3aeb8b3aea4aef3b3b8a9">[email&160;protected]</a>> | contract MultiSigWalletWithDailyLimit is MultiSigWallet {
/*
* Events
*/
event DailyLimitChange(uint dailyLimit);
/*
* Storage
*/
uint public dailyLimit;
uint public lastDay;
uint public spentToday;
/*
* Public functions
*/
/// @dev Contract constructor sets initial owners, required number of confirmations and daily withdraw limit.
/// @param _owners List of initial owners.
/// @param _required Number of required confirmations.
/// @param _dailyLimit Amount in wei, which can be withdrawn without confirmations on a daily basis.
function MultiSigWalletWithDailyLimit(address[] _owners, uint _required, uint _dailyLimit)
public
MultiSigWallet(_owners, _required)
{
dailyLimit = _dailyLimit;
}
/// @dev Allows to change the daily limit. Transaction has to be sent by wallet.
/// @param _dailyLimit Amount in wei.
function changeDailyLimit(uint _dailyLimit)
public
onlyWallet
{
dailyLimit = _dailyLimit;
DailyLimitChange(_dailyLimit);
}
/// @dev Allows anyone to execute a confirmed transaction or ether withdraws until daily limit is reached.
/// @param transactionId Transaction ID.
function executeTransaction(uint transactionId)
public
ownerExists(msg.sender)
confirmed(transactionId, msg.sender)
notExecuted(transactionId)
{
Transaction storage txn = transactions[transactionId];
bool _confirmed = isConfirmed(transactionId);
if (_confirmed || txn.data.length == 0 && isUnderLimit(txn.value)) {
txn.executed = true;
if (!_confirmed)
spentToday += txn.value;
if (txn.destination.call.value(txn.value)(txn.data))
Execution(transactionId);
else {
ExecutionFailure(transactionId);
txn.executed = false;
if (!_confirmed)
spentToday -= txn.value;
}
}
}
/*
* Internal functions
*/
/// @dev Returns if amount is within daily limit and resets spentToday after one day.
/// @param amount Amount to withdraw.
/// @return Returns if amount is under daily limit.
function isUnderLimit(uint amount)
internal
returns (bool)
{
if (now > lastDay + 24 hours) {
lastDay = now;
spentToday = 0;
}
if (spentToday + amount > dailyLimit || spentToday + amount < spentToday)
return false;
return true;
}
/*
* Web3 call functions
*/
/// @dev Returns maximum withdraw amount.
/// @return Returns amount.
function calcMaxWithdraw()
public
constant
returns (uint)
{
if (now > lastDay + 24 hours)
return dailyLimit;
if (dailyLimit < spentToday)
return 0;
return dailyLimit - spentToday;
}
} | contract MultiSigWalletWithDailyLimit is MultiSigWallet {
/*
* Events
*/
event DailyLimitChange(uint dailyLimit);
/*
* Storage
*/
uint public dailyLimit;
uint public lastDay;
uint public spentToday;
/*
* Public functions
*/
/// @dev Contract constructor sets initial owners, required number of confirmations and daily withdraw limit.
/// @param _owners List of initial owners.
/// @param _required Number of required confirmations.
/// @param _dailyLimit Amount in wei, which can be withdrawn without confirmations on a daily basis.
function MultiSigWalletWithDailyLimit(address[] _owners, uint _required, uint _dailyLimit)
public
MultiSigWallet(_owners, _required)
{
dailyLimit = _dailyLimit;
}
/// @dev Allows to change the daily limit. Transaction has to be sent by wallet.
/// @param _dailyLimit Amount in wei.
function changeDailyLimit(uint _dailyLimit)
public
onlyWallet
{
dailyLimit = _dailyLimit;
DailyLimitChange(_dailyLimit);
}
/// @dev Allows anyone to execute a confirmed transaction or ether withdraws until daily limit is reached.
/// @param transactionId Transaction ID.
function executeTransaction(uint transactionId)
public
ownerExists(msg.sender)
confirmed(transactionId, msg.sender)
notExecuted(transactionId)
{
Transaction storage txn = transactions[transactionId];
bool _confirmed = isConfirmed(transactionId);
if (_confirmed || txn.data.length == 0 && isUnderLimit(txn.value)) {
txn.executed = true;
if (!_confirmed)
spentToday += txn.value;
if (txn.destination.call.value(txn.value)(txn.data))
Execution(transactionId);
else {
ExecutionFailure(transactionId);
txn.executed = false;
if (!_confirmed)
spentToday -= txn.value;
}
}
}
/*
* Internal functions
*/
/// @dev Returns if amount is within daily limit and resets spentToday after one day.
/// @param amount Amount to withdraw.
/// @return Returns if amount is under daily limit.
function isUnderLimit(uint amount)
internal
returns (bool)
{
if (now > lastDay + 24 hours) {
lastDay = now;
spentToday = 0;
}
if (spentToday + amount > dailyLimit || spentToday + amount < spentToday)
return false;
return true;
}
/*
* Web3 call functions
*/
/// @dev Returns maximum withdraw amount.
/// @return Returns amount.
function calcMaxWithdraw()
public
constant
returns (uint)
{
if (now > lastDay + 24 hours)
return dailyLimit;
if (dailyLimit < spentToday)
return 0;
return dailyLimit - spentToday;
}
} | 9,826 |
62 | // If bid is in shortfall, mark for unlocking if not a rollover | if (
_isInMaintenanceCollateralShortFall(
revealedBid.amount,
revealedBid.bidPriceRevealed,
revealedBid.collateralTokens,
revealedBid.collateralAmounts
)
) {
emitter.emitBidInShortfall(termAuctionId, revealedBid.id);
| if (
_isInMaintenanceCollateralShortFall(
revealedBid.amount,
revealedBid.bidPriceRevealed,
revealedBid.collateralTokens,
revealedBid.collateralAmounts
)
) {
emitter.emitBidInShortfall(termAuctionId, revealedBid.id);
| 27,811 |
10 | // Adds an identifier to the whitelist. newIdentifier the new identifier to add. / | function addToWhitelist(bytes32 newIdentifier)
external
override
onlyMaintainer
| function addToWhitelist(bytes32 newIdentifier)
external
override
onlyMaintainer
| 21,668 |
268 | // column8_row0/ mload(0x2e60), pedersen/hash1/ec_subset_sum/bit_neg_0 = 1 - pedersen__hash1__ec_subset_sum__bit_0. |
let val := addmod(
1,
sub(PRIME, /*intermediate_value/pedersen/hash1/ec_subset_sum/bit_0*/ mload(0x41c0)),
PRIME)
mstore(0x41e0, val)
|
let val := addmod(
1,
sub(PRIME, /*intermediate_value/pedersen/hash1/ec_subset_sum/bit_0*/ mload(0x41c0)),
PRIME)
mstore(0x41e0, val)
| 4,358 |
123 | // Non-zero shares | require(_shares > 0, "No shares");
| require(_shares > 0, "No shares");
| 37,874 |
98 | // Transfer DELTA/this address is already mature as in it has 100% of DELTA in its balance | uint256 deltaForPoolAndReserve = balanceOfDELTA.div(2);
| uint256 deltaForPoolAndReserve = balanceOfDELTA.div(2);
| 17,589 |
248 | // List of supporters for each active bid proposal | mapping (uint256 => mapping (address => bool)) BidProposalSupporters;
| mapping (uint256 => mapping (address => bool)) BidProposalSupporters;
| 23,214 |
8 | // erc223: Retrieve the size of the code on target address, this needs assembly . | uint256 codeLength;
assembly {
codeLength := extcodesize(_to)
}
| uint256 codeLength;
assembly {
codeLength := extcodesize(_to)
}
| 34,572 |
250 | // maps tokenId to stake | mapping(uint256 => Stake) public vault;
| mapping(uint256 => Stake) public vault;
| 6,477 |
194 | // Gets the time remaining until the governable parameter update/ can be committed./changeTimestamp Timestamp indicating the beginning of the change./delay Governance delay./ return Remaining time in seconds. | function getRemainingChangeTime(uint256 changeTimestamp, uint256 delay)
internal
view
returns (uint256)
| function getRemainingChangeTime(uint256 changeTimestamp, uint256 delay)
internal
view
returns (uint256)
| 61,567 |
252 | // Change loan overdue duration, based on the number of blocks Accept claims only from the adminoverdueBlocks_ Maximum late repayment block. The number of arrivals is a default / | function setOverdueBlocks(uint256 overdueBlocks_) external;
| function setOverdueBlocks(uint256 overdueBlocks_) external;
| 71,527 |
31 | // raise (1+R) to the power of 4 | F_ += (LPamount << 120) / totalLPs; // (1+R) (2.120 bits)
F_ = F_ * F_ >> 120; // (1+R)**2 (4.120 bits)
F_ = F_ * F_ >> 120; // (1+R)**4 (8.120 bits)
| F_ += (LPamount << 120) / totalLPs; // (1+R) (2.120 bits)
F_ = F_ * F_ >> 120; // (1+R)**2 (4.120 bits)
F_ = F_ * F_ >> 120; // (1+R)**4 (8.120 bits)
| 19,651 |
44 | // Event emitted when the contract is initialized | event InitializeHermezEvent(
uint8 forgeL1L2BatchTimeout,
uint256 feeAddToken,
uint64 withdrawalDelay
);
| event InitializeHermezEvent(
uint8 forgeL1L2BatchTimeout,
uint256 feeAddToken,
uint64 withdrawalDelay
);
| 60,997 |
86 | // mint drop and move into vault | uint priceDROP = assessor.calcSeniorTokenPrice();
uint collateralDROP = rdiv(amountDAI, priceDROP);
tranche.mint(address(this), collateralDROP);
collateral.approve(address(mgr), collateralDROP);
mgr.join(collateralDROP);
| uint priceDROP = assessor.calcSeniorTokenPrice();
uint collateralDROP = rdiv(amountDAI, priceDROP);
tranche.mint(address(this), collateralDROP);
collateral.approve(address(mgr), collateralDROP);
mgr.join(collateralDROP);
| 30,525 |
26 | // DSMath.wpow | function bpowi(uint a, uint n)
internal pure
returns (uint)
| function bpowi(uint a, uint n)
internal pure
returns (uint)
| 37,997 |
55 | // add a new stake | UserStake memory userStake;
userStake.startBlock = block.number.safe32();
userStake.lockedAmount = _amount;
userStakes[user].push(userStake);
stakeId = userStakes[user].length - 1;
_updateVotes(address(0), user, _amount);
emit Deposit(user, stakeId, _amount);
| UserStake memory userStake;
userStake.startBlock = block.number.safe32();
userStake.lockedAmount = _amount;
userStakes[user].push(userStake);
stakeId = userStakes[user].length - 1;
_updateVotes(address(0), user, _amount);
emit Deposit(user, stakeId, _amount);
| 80,368 |
16 | // Mapping of address allowed to hold multiple tokens. | mapping (address => bool) private _whitelistAddress;
| mapping (address => bool) private _whitelistAddress;
| 7,327 |
18 | // Priced in WEI. This is just incase ETH goes TO DAMN HIGH, and we need to lower the mint price | function updateMintPrice(uint256 _newPrice) external onlyOwner() {
price = _newPrice;
}
| function updateMintPrice(uint256 _newPrice) external onlyOwner() {
price = _newPrice;
}
| 21,132 |
24 | // Tries to returns the value associated with `key`.O(1).Does not revert if `key` is not in the map. / | function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) {
bytes32 value = map._values[key];
if (value == bytes32(0)) {
return (_contains(map, key), bytes32(0));
} else {
return (true, value);
}
}
| function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) {
bytes32 value = map._values[key];
if (value == bytes32(0)) {
return (_contains(map, key), bytes32(0));
} else {
return (true, value);
}
}
| 1,350 |
25 | // internal function _addressToRefund the address being refundedaccessed via public functions emergencyWithdraw and safeWithdrawcalculates refund amount available for an address/ | function calcRefund(address _addressToRefund) internal
| function calcRefund(address _addressToRefund) internal
| 31,478 |
10 | // Set the address of the Chainlink price feed for ETH/USD on Sepolia (please verify the correct address) | priceFeed = AggregatorV3Interface(0x649a2C205BE7A3d5e99206CEEFF30c794f0E31EC);
| priceFeed = AggregatorV3Interface(0x649a2C205BE7A3d5e99206CEEFF30c794f0E31EC);
| 31,189 |
31 | // Tokens to 1 eth | uint256 public rate;
event WithDraw(address indexed _from, address indexed _to,uint256 _value);
event BuyToken(address indexed _from, address indexed _to, uint256 _value);
| uint256 public rate;
event WithDraw(address indexed _from, address indexed _to,uint256 _value);
event BuyToken(address indexed _from, address indexed _to, uint256 _value);
| 16,684 |
17 | // Transfer tokens from one address to another. Note that while this function emits an Approval event, this is not required as per the specification, and other compliant implementations may not emit the event.from address The address which you want to send tokens fromto address The address which you want to transfer tovalue uint256 the amount of tokens to be transferred/ | function transferFrom(address from, address to, uint256 value) public returns (bool) {
if (from != msg.sender && _allowed[from][msg.sender] != uint256(-1))
_allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value);
_transfer(from, to, value);
return true;
}
| function transferFrom(address from, address to, uint256 value) public returns (bool) {
if (from != msg.sender && _allowed[from][msg.sender] != uint256(-1))
_allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value);
_transfer(from, to, value);
return true;
}
| 24,059 |
39 | // Provides EIP-2612 signed approval for this contract to spend user tokens./token Address of ERC-20 token./amount Token amount to grant spending right over./deadline Termination for signed approval in Unix time./v The recovery byte of the signature./r Half of the ECDSA signature pair./s Half of the ECDSA signature pair. | function permitThis(
address token,
uint256 amount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
| function permitThis(
address token,
uint256 amount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
| 29,681 |
7 | // Amount of token already released / | function released(address token_) public view virtual returns (uint256) {
return unlocks[token_].released;
}
| function released(address token_) public view virtual returns (uint256) {
return unlocks[token_].released;
}
| 32,539 |
54 | // approve CrowdSale to spend 100 000 000 tokens on behalf of moderator | require(tokenContract.transferFrom(moderator,_purchaser,_tokens));
| require(tokenContract.transferFrom(moderator,_purchaser,_tokens));
| 8,446 |
174 | // negative ledger | uint256 negative = insNegative[token];
| uint256 negative = insNegative[token];
| 41,120 |
104 | // 再加些其他的代币todo |
function calculate(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags
|
function calculate(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags
| 87 |
10 | // For each of the LBCRs in Byzantic, if the round has elapsed, users will be curated into layers according to their score | function curateLBCRs() public {
for(uint i = 0; i < lbcrs.length; i++) {
lbcrs[i].curateIfRoundEnded();
}
}
| function curateLBCRs() public {
for(uint i = 0; i < lbcrs.length; i++) {
lbcrs[i].curateIfRoundEnded();
}
}
| 23,362 |
4 | // function _beforeClaim( uint256 _tokenId, address _receiver, uint256 _quantity, address _currency, uint256 _pricePerToken, AllowlistProof calldata _allowlistProof, bytes memory _data | // ) internal virtual override {
// uint256 _maxTotalSupply = getErc20Balance();
// require(_quantity <= _maxTotalSupply, "exceeds max total supply.");
// }
| // ) internal virtual override {
// uint256 _maxTotalSupply = getErc20Balance();
// require(_quantity <= _maxTotalSupply, "exceeds max total supply.");
// }
| 26,151 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.