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
|
---|---|---|---|---|
10 | // Governance message is invalid (e.g., deserialization error). Signature: 0x97363b35 | error InvalidGovernanceMessage();
| error InvalidGovernanceMessage();
| 25,519 |
9 | // checks for requested epoch | require (_getEpochId() > epochId, "This epoch is in the future");
require(epochId <= numberOfEpochs, "Maximum number of epochs is 12");
require (lastEpochIdHarvested[msg.sender].add(1) == epochId, "Harvest in order");
uint userReward = _harvest(epochId);
if (userReward > 0) {
_rewardToken.transferFrom(_communityVault, msg.sender, userReward);
}
| require (_getEpochId() > epochId, "This epoch is in the future");
require(epochId <= numberOfEpochs, "Maximum number of epochs is 12");
require (lastEpochIdHarvested[msg.sender].add(1) == epochId, "Harvest in order");
uint userReward = _harvest(epochId);
if (userReward > 0) {
_rewardToken.transferFrom(_communityVault, msg.sender, userReward);
}
| 35,241 |
54 | // Investing all underlying. / | function investedUnderlyingBalance() public view returns (uint256) {
return
Gauge(pool).balanceOf(address(this)).add(
IERC20(underlying).balanceOf(address(this))
);
}
| function investedUnderlyingBalance() public view returns (uint256) {
return
Gauge(pool).balanceOf(address(this)).add(
IERC20(underlying).balanceOf(address(this))
);
}
| 35,662 |
26 | // Reveal a previously committed bug. bugId The ID of the bug commitment bugDescription The description of the bug / | function revealBug(uint256 bugId, string bugDescription, uint256 nonce) public returns (bool) {
address hunter = msg.sender;
uint256 bountyId = bountyData.getBugCommitBountyId(bugId);
// the bug commit exists, and the committer is the hunter
require(bountyData.getBugCommitCommitter(bugId) == hunter);
// the current timestamp is within the reveal period
require(bountyData.isRevealPeriod(bountyId));
// the bounty is active. Otherwise, it's too late to reveal, and funds should
// be rescued using rescueHunterDeposit below (that function does not reveal
// the bug)
require(bountyData.bountyActive(bountyId));
// the hash of the bug description matches the hash and was sent from the hunter
// the hunter address will be converted to lower case after abi.encodePacked
// so be sure to use the lower-case version during bug hash generation.
require(keccak256(abi.encodePacked(bugDescription, hunter, nonce)) == bountyData.getBugCommitBugDescriptionHash(bugId));
// create a poll for the TCR to vote on the bug
uint256 pollId = bountyData.voting().startPoll(
bountyData.parameterizer().get("voteQuorum"),
bountyData.getBountyJudgeCommitPhaseEndTimestamp(bountyId).sub(block.timestamp),
bountyData.getBountyJudgeRevealDuration(bountyId)
);
// the minimum votes for a vote to succeed
uint256 minVotes = bountyData.getBountyMinVotes(bountyId);
// the judge must stake a deposit to incentivize vote reveal
uint256 judgeDeposit = bountyData.getBountyJudgeDeposit(bountyId);
bountyData.voting().restrictPoll(pollId, minVotes, judgeDeposit);
// add the bug to the list of revealed bugs
bountyData.addBug(bugId, bugDescription, pollId);
bountyData.addBugToHunter(hunter, bugId);
// delete the bug commit
bountyData.removeBugCommitment(bugId);
emit LogBugRevealed(bountyId, bugId, hunter);
emit LogBugVoteInitiated(bountyId, bugId, pollId);
return true;
}
| function revealBug(uint256 bugId, string bugDescription, uint256 nonce) public returns (bool) {
address hunter = msg.sender;
uint256 bountyId = bountyData.getBugCommitBountyId(bugId);
// the bug commit exists, and the committer is the hunter
require(bountyData.getBugCommitCommitter(bugId) == hunter);
// the current timestamp is within the reveal period
require(bountyData.isRevealPeriod(bountyId));
// the bounty is active. Otherwise, it's too late to reveal, and funds should
// be rescued using rescueHunterDeposit below (that function does not reveal
// the bug)
require(bountyData.bountyActive(bountyId));
// the hash of the bug description matches the hash and was sent from the hunter
// the hunter address will be converted to lower case after abi.encodePacked
// so be sure to use the lower-case version during bug hash generation.
require(keccak256(abi.encodePacked(bugDescription, hunter, nonce)) == bountyData.getBugCommitBugDescriptionHash(bugId));
// create a poll for the TCR to vote on the bug
uint256 pollId = bountyData.voting().startPoll(
bountyData.parameterizer().get("voteQuorum"),
bountyData.getBountyJudgeCommitPhaseEndTimestamp(bountyId).sub(block.timestamp),
bountyData.getBountyJudgeRevealDuration(bountyId)
);
// the minimum votes for a vote to succeed
uint256 minVotes = bountyData.getBountyMinVotes(bountyId);
// the judge must stake a deposit to incentivize vote reveal
uint256 judgeDeposit = bountyData.getBountyJudgeDeposit(bountyId);
bountyData.voting().restrictPoll(pollId, minVotes, judgeDeposit);
// add the bug to the list of revealed bugs
bountyData.addBug(bugId, bugDescription, pollId);
bountyData.addBugToHunter(hunter, bugId);
// delete the bug commit
bountyData.removeBugCommitment(bugId);
emit LogBugRevealed(bountyId, bugId, hunter);
emit LogBugVoteInitiated(bountyId, bugId, pollId);
return true;
}
| 53,089 |
382 | // Ensure assetData length is valid | require(
assetData.length > 3,
"LENGTH_GREATER_THAN_3_REQUIRED"
);
| require(
assetData.length > 3,
"LENGTH_GREATER_THAN_3_REQUIRED"
);
| 42,274 |
35 | // just in case | function recoverEth() external onlyOwner {
payable(owner).transfer(address(this).balance);
}
| function recoverEth() external onlyOwner {
payable(owner).transfer(address(this).balance);
}
| 43,261 |
9 | // Address to number of mints | mapping(address => uint256) public mintsPerAddress;
| mapping(address => uint256) public mintsPerAddress;
| 29,950 |
144 | // Modifier to make a function callable only when the contract is paused. / | modifier whenPaused() {
require(_paused, "Pausable: not paused");
_;
}
| modifier whenPaused() {
require(_paused, "Pausable: not paused");
_;
}
| 7,034 |
55 | // No distribnution | IMintableERC20(udt).mint(_referrer, tokensToDistribute - devReward);
IMintableERC20(udt).mint(owner(), devReward);
| IMintableERC20(udt).mint(_referrer, tokensToDistribute - devReward);
IMintableERC20(udt).mint(owner(), devReward);
| 35,631 |
666 | // discount to pay fully in erc20 token (Mona), assumed to always be to 1 decimal place i.e. 20 = 2.0% | uint256 public discountToPayERC20 = 20;
| uint256 public discountToPayERC20 = 20;
| 13,705 |
187 | // Dolphin referral contract address. | IDolphinReferral public DolphinReferral;
| IDolphinReferral public DolphinReferral;
| 8,420 |
65 | // Lets a contract admin update the platform fee recipient and bps | function setPlatformFeeInfo(address _platformFeeRecipient, uint256 _platformFeeBps)
external
onlyRole(DEFAULT_ADMIN_ROLE)
| function setPlatformFeeInfo(address _platformFeeRecipient, uint256 _platformFeeBps)
external
onlyRole(DEFAULT_ADMIN_ROLE)
| 6,397 |
23 | // ----------------- total counts ----------------- / | function countTotalStake() public view returns (uint _totalStake) {
_totalStake = totalStake + totalStakingAmount.mul((block.timestamp).sub(lastUpdateTime));
}
| function countTotalStake() public view returns (uint _totalStake) {
_totalStake = totalStake + totalStakingAmount.mul((block.timestamp).sub(lastUpdateTime));
}
| 27,933 |
37 | // Update CID | tokenIdListToCID[_tokenId] = _newCID;
| tokenIdListToCID[_tokenId] = _newCID;
| 51,590 |
187 | // Adds a given asset to the list of collateral markets. This operation is impossible to reverse. Note: this will not add the asset if it already exists. / | function addCollateralMarket(address asset) internal {
for (uint256 i = 0; i < collateralMarkets.length; i++) {
if (collateralMarkets[i] == asset) {
return;
}
}
collateralMarkets.push(asset);
}
| function addCollateralMarket(address asset) internal {
for (uint256 i = 0; i < collateralMarkets.length; i++) {
if (collateralMarkets[i] == asset) {
return;
}
}
collateralMarkets.push(asset);
}
| 26,048 |
260 | // check tokens left | uint256 tokenAmount = tokensLeft();
| uint256 tokenAmount = tokensLeft();
| 25,985 |
14 | // by convention, we assume that all growth before a tick was initialized happened _below_ the tick | if (tick <= tickCurrent) {
info.feeGrowthOutside0X128 = feeGrowthGlobal0X128;
info.feeGrowthOutside1X128 = feeGrowthGlobal1X128;
info.secondsPerLiquidityOutsideX128 = secondsPerLiquidityCumulativeX128;
info.tickCumulativeOutside = tickCumulative;
info.secondsOutside = time;
}
| if (tick <= tickCurrent) {
info.feeGrowthOutside0X128 = feeGrowthGlobal0X128;
info.feeGrowthOutside1X128 = feeGrowthGlobal1X128;
info.secondsPerLiquidityOutsideX128 = secondsPerLiquidityCumulativeX128;
info.tickCumulativeOutside = tickCumulative;
info.secondsOutside = time;
}
| 35,693 |
1 | // Subtracts two integers, returns 0 on underflow. / | function subCap(uint _a, uint _b) internal pure returns (uint) {
if (_b > _a)
return 0;
else
return _a - _b;
}
| function subCap(uint _a, uint _b) internal pure returns (uint) {
if (_b > _a)
return 0;
else
return _a - _b;
}
| 40,612 |
28 | // Give an account access to this role. / | function add(Role storage role, address account) internal {
require(!has(role, account), "Roles: account already has role");
role.bearer[account] = true;
}
| function add(Role storage role, address account) internal {
require(!has(role, account), "Roles: account already has role");
role.bearer[account] = true;
}
| 2,552 |
95 | // / | abstract contract ERC20Allowlistable is ERC20Flaggable, Ownable {
uint8 private constant TYPE_DEFAULT = 0x0;
uint8 private constant TYPE_ALLOWLISTED = 0x1;
uint8 private constant TYPE_FORBIDDEN = 0x2;
uint8 private constant TYPE_POWERLISTED = 0x4;
uint8 private constant FLAG_INDEX_ALLOWLIST = 20;
uint8 private constant FLAG_INDEX_FORBIDDEN = 21;
uint8 private constant FLAG_INDEX_POWERLIST = 22;
event AddressTypeUpdate(address indexed account, uint8 addressType);
bool public restrictTransfers;
constructor(){
setApplicableInternal(true);
}
/**
* Configures whether the allowlisting is applied.
* Also sets the powerlist and allowlist flags on the null address accordingly.
* It is recommended to also deactivate the powerlist flag on other addresses.
*/
function setApplicable(bool transferRestrictionsApplicable) external onlyOwner {
setApplicableInternal(transferRestrictionsApplicable);
}
function setApplicableInternal(bool transferRestrictionsApplicable) internal {
restrictTransfers = true;
// if transfer restrictions are applied, we guess that should also be the case for newly minted tokens
// if the admin disagrees, it is still possible to change the type of the null address
if (transferRestrictionsApplicable){
setTypeInternal(address(0x0), TYPE_POWERLISTED);
} else {
setTypeInternal(address(0x0), TYPE_DEFAULT);
}
}
function setType(address account, uint8 typeNumber) public onlyOwner {
setTypeInternal(account, typeNumber);
}
function setTypeInternal(address account, uint8 typeNumber) internal {
setFlag(account, FLAG_INDEX_ALLOWLIST, typeNumber == TYPE_ALLOWLISTED);
setFlag(account, FLAG_INDEX_FORBIDDEN, typeNumber == TYPE_FORBIDDEN);
setFlag(account, FLAG_INDEX_POWERLIST, typeNumber == TYPE_POWERLISTED);
emit AddressTypeUpdate(account, typeNumber);
}
function setType(address[] calldata addressesToAdd, uint8 value) public onlyOwner {
for (uint i=0; i<addressesToAdd.length; i++){
setType(addressesToAdd, value);
}
}
/**
* If true, this address is allowlisted and can only transfer tokens to other allowlisted addresses.
*/
function canReceiveFromAnyone(address account) public view returns (bool) {
return hasFlagInternal(account, FLAG_INDEX_ALLOWLIST) || hasFlagInternal(account, FLAG_INDEX_POWERLIST);
}
/**
* If true, this address can only transfer tokens to allowlisted addresses and not receive from anyone.
*/
function isForbidden(address account) public view returns (bool){
return hasFlagInternal(account, FLAG_INDEX_FORBIDDEN);
}
/**
* If true, this address can automatically allowlist target addresses if necessary.
*/
function isPowerlisted(address account) public view returns (bool) {
return hasFlagInternal(account, FLAG_INDEX_POWERLIST);
}
/**
* Cleans the allowlist and disallowlist flag under the assumption that the
* allowlisting is not applicable any more.
*/
function failOrCleanup(address account) internal {
require(!restrictTransfers, "not allowed");
setType(account, TYPE_DEFAULT);
}
function _beforeTokenTransfer(address from, address to, uint256 amount) override virtual internal {
super._beforeTokenTransfer(from, to, amount);
if (canReceiveFromAnyone(to)){
// ok, transfers to allowlisted addresses are always allowed
} else if (isForbidden(to)){
// Target is forbidden, but maybe restrictions have been removed and we can clean the flag
failOrCleanup(to);
} else {
if (isPowerlisted(from)){
// it is not allowlisted, but we can make it so
setType(to, TYPE_ALLOWLISTED);
}
// if we made it to here, the target must be a free address and we are not powerlisted
else if (hasFlagInternal(from, FLAG_INDEX_ALLOWLIST) || isForbidden(from)){
// We cannot send to free addresses, but maybe the restrictions have been removed and we can clean the flag?
failOrCleanup(from);
}
}
}
}
| abstract contract ERC20Allowlistable is ERC20Flaggable, Ownable {
uint8 private constant TYPE_DEFAULT = 0x0;
uint8 private constant TYPE_ALLOWLISTED = 0x1;
uint8 private constant TYPE_FORBIDDEN = 0x2;
uint8 private constant TYPE_POWERLISTED = 0x4;
uint8 private constant FLAG_INDEX_ALLOWLIST = 20;
uint8 private constant FLAG_INDEX_FORBIDDEN = 21;
uint8 private constant FLAG_INDEX_POWERLIST = 22;
event AddressTypeUpdate(address indexed account, uint8 addressType);
bool public restrictTransfers;
constructor(){
setApplicableInternal(true);
}
/**
* Configures whether the allowlisting is applied.
* Also sets the powerlist and allowlist flags on the null address accordingly.
* It is recommended to also deactivate the powerlist flag on other addresses.
*/
function setApplicable(bool transferRestrictionsApplicable) external onlyOwner {
setApplicableInternal(transferRestrictionsApplicable);
}
function setApplicableInternal(bool transferRestrictionsApplicable) internal {
restrictTransfers = true;
// if transfer restrictions are applied, we guess that should also be the case for newly minted tokens
// if the admin disagrees, it is still possible to change the type of the null address
if (transferRestrictionsApplicable){
setTypeInternal(address(0x0), TYPE_POWERLISTED);
} else {
setTypeInternal(address(0x0), TYPE_DEFAULT);
}
}
function setType(address account, uint8 typeNumber) public onlyOwner {
setTypeInternal(account, typeNumber);
}
function setTypeInternal(address account, uint8 typeNumber) internal {
setFlag(account, FLAG_INDEX_ALLOWLIST, typeNumber == TYPE_ALLOWLISTED);
setFlag(account, FLAG_INDEX_FORBIDDEN, typeNumber == TYPE_FORBIDDEN);
setFlag(account, FLAG_INDEX_POWERLIST, typeNumber == TYPE_POWERLISTED);
emit AddressTypeUpdate(account, typeNumber);
}
function setType(address[] calldata addressesToAdd, uint8 value) public onlyOwner {
for (uint i=0; i<addressesToAdd.length; i++){
setType(addressesToAdd, value);
}
}
/**
* If true, this address is allowlisted and can only transfer tokens to other allowlisted addresses.
*/
function canReceiveFromAnyone(address account) public view returns (bool) {
return hasFlagInternal(account, FLAG_INDEX_ALLOWLIST) || hasFlagInternal(account, FLAG_INDEX_POWERLIST);
}
/**
* If true, this address can only transfer tokens to allowlisted addresses and not receive from anyone.
*/
function isForbidden(address account) public view returns (bool){
return hasFlagInternal(account, FLAG_INDEX_FORBIDDEN);
}
/**
* If true, this address can automatically allowlist target addresses if necessary.
*/
function isPowerlisted(address account) public view returns (bool) {
return hasFlagInternal(account, FLAG_INDEX_POWERLIST);
}
/**
* Cleans the allowlist and disallowlist flag under the assumption that the
* allowlisting is not applicable any more.
*/
function failOrCleanup(address account) internal {
require(!restrictTransfers, "not allowed");
setType(account, TYPE_DEFAULT);
}
function _beforeTokenTransfer(address from, address to, uint256 amount) override virtual internal {
super._beforeTokenTransfer(from, to, amount);
if (canReceiveFromAnyone(to)){
// ok, transfers to allowlisted addresses are always allowed
} else if (isForbidden(to)){
// Target is forbidden, but maybe restrictions have been removed and we can clean the flag
failOrCleanup(to);
} else {
if (isPowerlisted(from)){
// it is not allowlisted, but we can make it so
setType(to, TYPE_ALLOWLISTED);
}
// if we made it to here, the target must be a free address and we are not powerlisted
else if (hasFlagInternal(from, FLAG_INDEX_ALLOWLIST) || isForbidden(from)){
// We cannot send to free addresses, but maybe the restrictions have been removed and we can clean the flag?
failOrCleanup(from);
}
}
}
}
| 67,571 |
62 | // Bird's BDelegate Interface/ | contract BDelegateInterface is BDelegationStorage {
/**
* @notice Called by the delegator on a delegate to initialize it for duty
* @dev Should revert if any issues arise which make it unfit for delegation
* @param data The encoded bytes data for any initialization
*/
function _becomeImplementation(bytes memory data) public;
/**
* @notice Called by the delegator on a delegate to forfeit its responsibility
*/
function _resignImplementation() public;
}
| contract BDelegateInterface is BDelegationStorage {
/**
* @notice Called by the delegator on a delegate to initialize it for duty
* @dev Should revert if any issues arise which make it unfit for delegation
* @param data The encoded bytes data for any initialization
*/
function _becomeImplementation(bytes memory data) public;
/**
* @notice Called by the delegator on a delegate to forfeit its responsibility
*/
function _resignImplementation() public;
}
| 17,284 |
184 | // Check cash balance | IERC20 tokenContract=IERC20(token);
uint256 cashBal = tokenContract.balanceOf(address(this));
if (cashBal < tokenAmount) {
uint256 diff = tokenAmount.sub(cashBal);
IController(getController()).harvest(diff);
tokenAmount=tokenContract.balanceOf(address(this));
}
| IERC20 tokenContract=IERC20(token);
uint256 cashBal = tokenContract.balanceOf(address(this));
if (cashBal < tokenAmount) {
uint256 diff = tokenAmount.sub(cashBal);
IController(getController()).harvest(diff);
tokenAmount=tokenContract.balanceOf(address(this));
}
| 4,884 |
24 | // call super method | treasuryCoreContract.transferRewardAmount(
to,
recordId,
contributionId,
rewardGovernance,
rewardCommunity
);
| treasuryCoreContract.transferRewardAmount(
to,
recordId,
contributionId,
rewardGovernance,
rewardCommunity
);
| 23,479 |
84 | // Called by operator to pause child contract. The contractmust already be paused. / | function unpause() public onlyOperatorOrTraderOrSystem whenPaused {
_paused = false;
emit Unpaused(msg.sender);
}
| function unpause() public onlyOperatorOrTraderOrSystem whenPaused {
_paused = false;
emit Unpaused(msg.sender);
}
| 76,000 |
268 | // If not burning to target, then burning requires that the minimum stake time has elapsed. | require(_canBurnSynths(from), "Minimum stake time not reached");
| require(_canBurnSynths(from), "Minimum stake time not reached");
| 7,289 |
15 | // Add the applicant | applicants[msg.sender] = Applicant(name, age, resumeHash, msg.sender);
| applicants[msg.sender] = Applicant(name, age, resumeHash, msg.sender);
| 20,420 |
0 | // Throws if called by any account other than a minter/ | modifier onlyMinters() {
require(minters[msg.sender] == true, "minters only");
_;
}
| modifier onlyMinters() {
require(minters[msg.sender] == true, "minters only");
_;
}
| 36,480 |
357 | // Credit line terms | address public override borrower;
uint256 public currentLimit;
uint256 public override maxLimit;
uint256 public override interestApr;
uint256 public override paymentPeriodInDays;
uint256 public override termInDays;
uint256 public override principalGracePeriodInDays;
uint256 public override lateFeeApr;
| address public override borrower;
uint256 public currentLimit;
uint256 public override maxLimit;
uint256 public override interestApr;
uint256 public override paymentPeriodInDays;
uint256 public override termInDays;
uint256 public override principalGracePeriodInDays;
uint256 public override lateFeeApr;
| 53,851 |
431 | // Checks if the account should be allowed to transfer tokens in the given market gToken The market to verify the transfer against src The account which sources the tokens dst The account which receives the tokens transferTokens The number of gTokens to transferreturn 0 if the transfer is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) / | function transferAllowed(address gToken, address src, address dst, uint transferTokens) external returns (uint) {
// Pausing is a very serious situation - we revert to sound the alarms
require(!transferGuardianPaused, "transfer is paused");
// Currently the only consideration is whether or not
// the src is allowed to redeem this many tokens
uint allowed = redeemAllowedInternal(gToken, src, transferTokens);
if (allowed != uint(Error.NO_ERROR)) {
return allowed;
}
return uint(Error.NO_ERROR);
}
| function transferAllowed(address gToken, address src, address dst, uint transferTokens) external returns (uint) {
// Pausing is a very serious situation - we revert to sound the alarms
require(!transferGuardianPaused, "transfer is paused");
// Currently the only consideration is whether or not
// the src is allowed to redeem this many tokens
uint allowed = redeemAllowedInternal(gToken, src, transferTokens);
if (allowed != uint(Error.NO_ERROR)) {
return allowed;
}
return uint(Error.NO_ERROR);
}
| 45,396 |
16 | // Verify the other signer | bytes32 operationHash = keccak256(
abi.encodePacked(
getNetworkId(),
toAddress,
value,
data,
expireTime,
sequenceId
)
);
| bytes32 operationHash = keccak256(
abi.encodePacked(
getNetworkId(),
toAddress,
value,
data,
expireTime,
sequenceId
)
);
| 48,397 |
12 | // A mapping of all beneficiaries | mapping(address => Beneficiary) beneficiaries;
| mapping(address => Beneficiary) beneficiaries;
| 54,855 |
34 | // Note: can be made external into a utility contract (used for deployment) | function getResolverAddressesRequired()
external
view
returns (bytes32[MAX_ADDRESSES_FROM_RESOLVER] memory addressesRequired)
| function getResolverAddressesRequired()
external
view
returns (bytes32[MAX_ADDRESSES_FROM_RESOLVER] memory addressesRequired)
| 30,325 |
8 | // See {ERC20-_mint}. //Creates `_amount` token to `_to`. Must only be called by the owner (MasterChef). | function _mint(address _to, uint256 _amount) internal virtual onlyOwner override {
require(ERC20.totalSupply() + _amount <= cap(), "ERC20Capped: cap exceeded");
super._mint(_to, _amount);
}
| function _mint(address _to, uint256 _amount) internal virtual onlyOwner override {
require(ERC20.totalSupply() + _amount <= cap(), "ERC20Capped: cap exceeded");
super._mint(_to, _amount);
}
| 18,123 |
175 | // The SUSHI TOKEN! | SushiToken public sushi;
| SushiToken public sushi;
| 11,189 |
47 | // Returns Minted TokenID / | function readMintedTokenID(uint ArtistID, uint TicketID) external view returns (uint)
| function readMintedTokenID(uint ArtistID, uint TicketID) external view returns (uint)
| 21,342 |
12 | // this safely mints an NFT to the _holder address at the current counter index newItemID./_safeMint ensures that the receiver address can receive and handle ERC721s - which is either a normal wallet, or a smart contract that has implemented ERC721 receiver | _safeMint(_holder, newItemId);
| _safeMint(_holder, newItemId);
| 19,477 |
65 | // 3 | ReserveManagerQueue[_address] = block.number.add(
blocksNeededForQueue.mul(2)
);
| ReserveManagerQueue[_address] = block.number.add(
blocksNeededForQueue.mul(2)
);
| 37,192 |
11 | // EIP-20 token decimals for this token / | uint8 public decimals;
| uint8 public decimals;
| 4,736 |
15 | // require approved minter |
_mintBatch(_to, _tokenIds, _values, _data);
|
_mintBatch(_to, _tokenIds, _values, _data);
| 30,537 |
68 | // The cut contract takes from the share sales of an approved company. price is in wei | function _computeSalesCut(uint _price)
pure
internal
| function _computeSalesCut(uint _price)
pure
internal
| 44,351 |
142 | // solium-disable-next-line security/no-tx-origin | require(tx.origin == msg.sender, "Must be EOA");
Liquidation memory liquidation = liquidations[_integration];
address bAsset = liquidation.bAsset;
require(bAsset != address(0), "Liquidation does not exist");
require(block.timestamp > liquidation.lastTriggered.add(interval), "Must wait for interval");
liquidations[_integration].lastTriggered = block.timestamp;
| require(tx.origin == msg.sender, "Must be EOA");
Liquidation memory liquidation = liquidations[_integration];
address bAsset = liquidation.bAsset;
require(bAsset != address(0), "Liquidation does not exist");
require(block.timestamp > liquidation.lastTriggered.add(interval), "Must wait for interval");
liquidations[_integration].lastTriggered = block.timestamp;
| 53,554 |
202 | // ^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/ / | function _checkRole(bytes32 role, address account) internal view {
if(!hasRole(role, account)) {
revert(string(abi.encodePacked(
"AccessControl: account ",
Strings.toHexString(uint160(account), 20),
" is missing role ",
Strings.toHexString(uint256(role), 32)
)));
}
| function _checkRole(bytes32 role, address account) internal view {
if(!hasRole(role, account)) {
revert(string(abi.encodePacked(
"AccessControl: account ",
Strings.toHexString(uint160(account), 20),
" is missing role ",
Strings.toHexString(uint256(role), 32)
)));
}
| 9,922 |
94 | // update globalHarvestLastUpdateTime | info.globalHarvestLastUpdateTime = block.timestamp;
| info.globalHarvestLastUpdateTime = block.timestamp;
| 25,224 |
35 | // 4. Update user's stat 4.1 update purchase per window per user 4.2 update purchase per address | _updatePurchasePerUser(msg.sender, _purchaseableAmount);
_updateUserPurchaseWindow(msg.sender, _purchaseableAmount);
| _updatePurchasePerUser(msg.sender, _purchaseableAmount);
_updateUserPurchaseWindow(msg.sender, _purchaseableAmount);
| 39,988 |
174 | // Establish direct path between tokens. | (address[] memory path, uint256[] memory amounts) = _createPathAndAmounts(
address(tokenProvided), tokenReceived, false
);
| (address[] memory path, uint256[] memory amounts) = _createPathAndAmounts(
address(tokenProvided), tokenReceived, false
);
| 42,007 |
118 | // Rebalance collateral and debt in Maker.Based on defined risk parameter either borrow more DAI from Maker orpayback some DAI in Maker. It will try to mitigate risk of liquidation.Anyone can call it except when paused. / | function rebalanceCollateral() external onlyKeeper {
_rebalanceCollateral();
}
| function rebalanceCollateral() external onlyKeeper {
_rebalanceCollateral();
}
| 21,962 |
64 | // When token.balanceOf(this) < fork.allAmount, get token from LP | if (IERC20(tokenAddress).balanceOf(address(this)) < forkAllAmount) {
uint256 diffAmount = forkAllAmount -
IERC20(tokenAddress).balanceOf(address(this));
| if (IERC20(tokenAddress).balanceOf(address(this)) < forkAllAmount) {
uint256 diffAmount = forkAllAmount -
IERC20(tokenAddress).balanceOf(address(this));
| 47,707 |
31 | // Wrapper around OpenZeppelin's UpgradeabilityProxy contract.Permissions proxy upgrade logic to Audius Governance contract. Any logic contract that has a signature clash with this proxy contract will be unable to call those functions Please ensure logic contract functions do not share a signature with any functions defined in this file / | contract AudiusAdminUpgradeabilityProxy is UpgradeabilityProxy {
address private proxyAdmin;
string private constant ERROR_ONLY_ADMIN = (
"AudiusAdminUpgradeabilityProxy: Caller must be current proxy admin"
);
/**
* @notice Sets admin address for future upgrades
* @param _logic - address of underlying logic contract.
* Passed to UpgradeabilityProxy constructor.
* @param _proxyAdmin - address of proxy admin
* Set to governance contract address for all non-governance contracts
* Governance is deployed and upgraded to have own address as admin
* @param _data - data of function to be called on logic contract.
* Passed to UpgradeabilityProxy constructor.
*/
constructor(
address _logic,
address _proxyAdmin,
bytes memory _data
)
UpgradeabilityProxy(_logic, _data) public payable
{
proxyAdmin = _proxyAdmin;
}
/**
* @notice Upgrade the address of the logic contract for this proxy
* @dev Recreation of AdminUpgradeabilityProxy._upgradeTo.
* Adds a check to ensure msg.sender is the Audius Proxy Admin
* @param _newImplementation - new address of logic contract that the proxy will point to
*/
function upgradeTo(address _newImplementation) external {
require(msg.sender == proxyAdmin, ERROR_ONLY_ADMIN);
_upgradeTo(_newImplementation);
}
/**
* @return Current proxy admin address
*/
function getAudiusProxyAdminAddress() external view returns (address) {
return proxyAdmin;
}
/**
* @return The address of the implementation.
*/
function implementation() external view returns (address) {
return _implementation();
}
/**
* @notice Set the Audius Proxy Admin
* @dev Only callable by current proxy admin address
* @param _adminAddress - new admin address
*/
function setAudiusProxyAdminAddress(address _adminAddress) external {
require(msg.sender == proxyAdmin, ERROR_ONLY_ADMIN);
proxyAdmin = _adminAddress;
}
} | contract AudiusAdminUpgradeabilityProxy is UpgradeabilityProxy {
address private proxyAdmin;
string private constant ERROR_ONLY_ADMIN = (
"AudiusAdminUpgradeabilityProxy: Caller must be current proxy admin"
);
/**
* @notice Sets admin address for future upgrades
* @param _logic - address of underlying logic contract.
* Passed to UpgradeabilityProxy constructor.
* @param _proxyAdmin - address of proxy admin
* Set to governance contract address for all non-governance contracts
* Governance is deployed and upgraded to have own address as admin
* @param _data - data of function to be called on logic contract.
* Passed to UpgradeabilityProxy constructor.
*/
constructor(
address _logic,
address _proxyAdmin,
bytes memory _data
)
UpgradeabilityProxy(_logic, _data) public payable
{
proxyAdmin = _proxyAdmin;
}
/**
* @notice Upgrade the address of the logic contract for this proxy
* @dev Recreation of AdminUpgradeabilityProxy._upgradeTo.
* Adds a check to ensure msg.sender is the Audius Proxy Admin
* @param _newImplementation - new address of logic contract that the proxy will point to
*/
function upgradeTo(address _newImplementation) external {
require(msg.sender == proxyAdmin, ERROR_ONLY_ADMIN);
_upgradeTo(_newImplementation);
}
/**
* @return Current proxy admin address
*/
function getAudiusProxyAdminAddress() external view returns (address) {
return proxyAdmin;
}
/**
* @return The address of the implementation.
*/
function implementation() external view returns (address) {
return _implementation();
}
/**
* @notice Set the Audius Proxy Admin
* @dev Only callable by current proxy admin address
* @param _adminAddress - new admin address
*/
function setAudiusProxyAdminAddress(address _adminAddress) external {
require(msg.sender == proxyAdmin, ERROR_ONLY_ADMIN);
proxyAdmin = _adminAddress;
}
} | 43,727 |
53 | // we can't give people infinite ethereum | if (tokenSupply_ > 0) {
| if (tokenSupply_ > 0) {
| 70,761 |
304 | // Determine the prior number of votes for an account as of a block number Block number must be a finalized block or else this function will revert to prevent misinformation. account The address of the account to check blockNumber The block number to get the vote balance atreturn The number of votes the account had as of the given block / | function getPriorVotes(address account, uint blockNumber) external view returns (uint96) {
require(blockNumber < block.number, "HAT::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
| function getPriorVotes(address account, uint blockNumber) external view returns (uint96) {
require(blockNumber < block.number, "HAT::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
| 1,047 |
20 | // | struct Device {
bytes32 secondaryPublicKeyHash;
bytes32 tertiaryPublicKeyHash;
address contractAddress;
bytes32 hardwareManufacturer;
bytes32 hardwareModel;
bytes32 hardwareSerial;
bytes32 hardwareConfig;
uint256 kongAmount;
bool mintable;
}
| struct Device {
bytes32 secondaryPublicKeyHash;
bytes32 tertiaryPublicKeyHash;
address contractAddress;
bytes32 hardwareManufacturer;
bytes32 hardwareModel;
bytes32 hardwareSerial;
bytes32 hardwareConfig;
uint256 kongAmount;
bool mintable;
}
| 27,710 |
12 | // Returns an account's deposits. These can be either a contract's funds, or a relay manager's revenue. | function balanceOf(address target) external view returns (uint256);
| function balanceOf(address target) external view returns (uint256);
| 40,937 |
26 | // Upgradable by the owner./ | function _authorizeUpgrade(address /*newImplementation*/ ) internal view override {
_onlyOwner();
}
| function _authorizeUpgrade(address /*newImplementation*/ ) internal view override {
_onlyOwner();
}
| 16,861 |
45 | // Remove a funded function functionPosition The position of the funded function in fundedFunctions / | function removeFundedFunction(uint256 functionPosition) internal {
require(both(functionPosition <= latestFundedFunction, functionPosition > 0), "RewardAdjusterBundler/invalid-position");
FundedFunction memory fundedFunction = fundedFunctions[functionPosition];
require(addedFunction[fundedFunction.receiverContract][fundedFunction.functionName] == 1, "RewardAdjusterBundler/function-not-added");
delete(addedFunction[fundedFunction.receiverContract][fundedFunction.functionName]);
if (functionPosition == latestFundedFunction) {
(, uint256 prevReceiver) = fundedFunctionsList.prev(latestFundedFunction);
latestFundedFunction = prevReceiver;
}
fundedFunctionsList.del(functionPosition);
delete(fundedFunctions[functionPosition]);
emit RemoveFundedFunction(functionPosition);
}
| function removeFundedFunction(uint256 functionPosition) internal {
require(both(functionPosition <= latestFundedFunction, functionPosition > 0), "RewardAdjusterBundler/invalid-position");
FundedFunction memory fundedFunction = fundedFunctions[functionPosition];
require(addedFunction[fundedFunction.receiverContract][fundedFunction.functionName] == 1, "RewardAdjusterBundler/function-not-added");
delete(addedFunction[fundedFunction.receiverContract][fundedFunction.functionName]);
if (functionPosition == latestFundedFunction) {
(, uint256 prevReceiver) = fundedFunctionsList.prev(latestFundedFunction);
latestFundedFunction = prevReceiver;
}
fundedFunctionsList.del(functionPosition);
delete(fundedFunctions[functionPosition]);
emit RemoveFundedFunction(functionPosition);
}
| 23,141 |
142 | // | //function symbol() public view virtual returns (string memory) {
// return "UP";
//}
| //function symbol() public view virtual returns (string memory) {
// return "UP";
//}
| 23,326 |
44 | // In dst chain order will start from 0-NotSet | if (orderState.status != OrderTakeStatus.NotSet) revert IncorrectOrderStatus();
orderState.status = OrderTakeStatus.SentCancel;
| if (orderState.status != OrderTakeStatus.NotSet) revert IncorrectOrderStatus();
orderState.status = OrderTakeStatus.SentCancel;
| 13,473 |
128 | // Calculates the next value of an specific distribution index, with validations currentIndex Current index of the distribution emissionPerSecond Representing the total rewards distributed per second per asset unit, on the distribution lastUpdateTimestamp Last moment this distribution was updated totalBalance of tokens considered for the distributionreturn The new index. / | ) internal view returns (uint256) {
if (
emissionPerSecond == 0 ||
totalBalance == 0 ||
lastUpdateTimestamp == block.timestamp ||
lastUpdateTimestamp >= DISTRIBUTION_END
) {
return currentIndex;
}
uint256 currentTimestamp =
block.timestamp > DISTRIBUTION_END ? DISTRIBUTION_END : block.timestamp;
uint256 timeDelta = currentTimestamp.sub(lastUpdateTimestamp);
return
emissionPerSecond.mul(timeDelta).mul(10**uint256(PRECISION)).div(totalBalance).add(
currentIndex
);
}
| ) internal view returns (uint256) {
if (
emissionPerSecond == 0 ||
totalBalance == 0 ||
lastUpdateTimestamp == block.timestamp ||
lastUpdateTimestamp >= DISTRIBUTION_END
) {
return currentIndex;
}
uint256 currentTimestamp =
block.timestamp > DISTRIBUTION_END ? DISTRIBUTION_END : block.timestamp;
uint256 timeDelta = currentTimestamp.sub(lastUpdateTimestamp);
return
emissionPerSecond.mul(timeDelta).mul(10**uint256(PRECISION)).div(totalBalance).add(
currentIndex
);
}
| 31,383 |
9 | // Modifier throws if called by any account other than the pendingOwner. | modifier onlyPendingOwner() {
require(msg.sender == pendingOwner, "UNAUTHORIZED");
_;
}
| modifier onlyPendingOwner() {
require(msg.sender == pendingOwner, "UNAUTHORIZED");
_;
}
| 3,435 |
24 | // return list of addresses permitted to transmit reports to this contract The list will match the order used to specify the transmitter during setConfig / | function transmitters() external view returns (address[] memory) {
return s_transmitters;
}
| function transmitters() external view returns (address[] memory) {
return s_transmitters;
}
| 5,249 |
84 | // Only one plan will be active at the time of a hack--return cover amount from then. | if (_hackTime >= plan.startTime && _hackTime < plan.endTime) {
for(uint256 j = 0; j< plan.length; j++){
bytes32 key = _hashKey(_user, uint256(i), j);
if(IStakeManager(getModule("STAKE")).protocolAddress(protocolPlan[key].protocolId) == _protocol){
return (uint256(i), _amount <= uint256(protocolPlan[key].amount));
}
| if (_hackTime >= plan.startTime && _hackTime < plan.endTime) {
for(uint256 j = 0; j< plan.length; j++){
bytes32 key = _hashKey(_user, uint256(i), j);
if(IStakeManager(getModule("STAKE")).protocolAddress(protocolPlan[key].protocolId) == _protocol){
return (uint256(i), _amount <= uint256(protocolPlan[key].amount));
}
| 84,715 |
13 | // TRANSFER LOGIC / |
function transfer(address recipient, uint256 amount)
public
override
returns (bool)
|
function transfer(address recipient, uint256 amount)
public
override
returns (bool)
| 952 |
2 | // Views |
function getMostPremium()
public
override
view
returns (address, uint256)
{
|
function getMostPremium()
public
override
view
returns (address, uint256)
{
| 1,675 |
4 | // log the event | logger.Log(address(this), msg.sender, "ExchangeSell", abi.encode(wrapper, exData.srcAddr, exData.destAddr, exData.srcAmount, destAmount));
| logger.Log(address(this), msg.sender, "ExchangeSell", abi.encode(wrapper, exData.srcAddr, exData.destAddr, exData.srcAmount, destAmount));
| 46,929 |
6 | // Get the amount of unsold tokens allocated to this contract; / | function getTokensLeft() public view returns (uint) {
return token.allowance(owner, address(this));
}
| function getTokensLeft() public view returns (uint) {
return token.allowance(owner, address(this));
}
| 32,570 |
35 | // https:github.com/provable-things/ethereum-api/blob/master/provableAPI_0.6.sol | function _uint2str(uint _i) internal pure returns (string memory) {
if (_i == 0) {
return "0";
}
uint j = _i;
uint len;
while (j != 0) {
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint k = len;
while (_i != 0) {
k = k-1;
uint8 temp = (48 + uint8(_i - _i / 10 * 10));
bytes1 b1 = bytes1(temp);
bstr[k] = b1;
_i /= 10;
}
return string(bstr);
}
| function _uint2str(uint _i) internal pure returns (string memory) {
if (_i == 0) {
return "0";
}
uint j = _i;
uint len;
while (j != 0) {
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint k = len;
while (_i != 0) {
k = k-1;
uint8 temp = (48 + uint8(_i - _i / 10 * 10));
bytes1 b1 = bytes1(temp);
bstr[k] = b1;
_i /= 10;
}
return string(bstr);
}
| 79,099 |
77 | // This internal function is equivalent to {transfer}, and can be used toe.g. implement automatic token fees, slashing mechanisms, etc. Emits a {Transfer} event. Requirements: - `sender` cannot be the zero address.- `recipient` cannot be the zero address.- `sender` must have a balance of at least `amount`. / | function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
| function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
| 11,715 |
194 | // wait 3 blocks to avoid flash loans | require((_lastCall[msg.sender] + MIN_DELAY) <= block.number, "action too soon - please wait a few more blocks");
| require((_lastCall[msg.sender] + MIN_DELAY) <= block.number, "action too soon - please wait a few more blocks");
| 16,624 |
405 | // SPDX-License-Identifier: MIT/ Token Geyser A smart-contract based mechanism to distribute tokens over time, inspired loosely by Compound and Uniswap.Distribution tokens are added to a locked pool in the contract and become unlocked over time according to a once-configurable unlock schedule. Once unlocked, they are available to be claimed by users.A user may deposit tokens to accrue ownership share over the unlocked pool. This owner share is a function of the number of tokens deposited as well as the length of time deposited. Specifically, a user's share of the currently-unlocked pool equals their "deposit-seconds" divided by the global "deposit-seconds". This aligns | contract TokenGeyser is IStaking, IStakeWithNFT, Ownable {
using SafeMath for uint256;
event Staked(
address indexed user,
uint256 amount,
uint256 total,
bytes data
);
event Unstaked(
address indexed user,
uint256 amount,
uint256 total,
bytes data
);
event TokensClaimed(address indexed user, uint256 amount);
event TokensLocked(uint256 amount, uint256 durationSec, uint256 total);
// amount: Unlocked tokens, total: Total locked tokens
event TokensUnlocked(uint256 amount, uint256 total);
TokenPool private _stakingPool;
TokenPool private _unlockedPool;
TokenPool private _lockedPool;
//
// Time-bonus params
//
uint256 public bonusDecimals = 2;
uint256 public startBonus = 0;
uint256 public bonusPeriodSec = 0;
//
// Global accounting state
//
uint256 public totalLockedShares = 0;
uint256 public totalStakingShares = 0;
uint256 private _totalStakingShareSeconds = 0;
uint256 private _lastAccountingTimestampSec = now;
uint256 private _maxUnlockSchedules = 0;
uint256 private _initialSharesPerToken = 0;
//
// User accounting state
//
// Represents a single stake for a user. A user may have multiple.
struct Stake {
uint256 stakingShares;
uint256 timestampSec;
}
// Caches aggregated values from the User->Stake[] map to save computation.
// If lastAccountingTimestampSec is 0, there's no entry for that user.
struct UserTotals {
uint256 stakingShares;
uint256 stakingShareSeconds;
uint256 lastAccountingTimestampSec;
}
// Aggregated staking values per user
mapping(address => UserTotals) private _userTotals;
// The collection of stakes for each user. Ordered by timestamp, earliest to latest.
mapping(address => Stake[]) private _userStakes;
//
// Locked/Unlocked Accounting state
//
struct UnlockSchedule {
uint256 initialLockedShares;
uint256 unlockedShares;
uint256 lastUnlockTimestampSec;
uint256 endAtSec;
uint256 durationSec;
}
UnlockSchedule[] public unlockSchedules;
WarpNFT public _warpNFT;
address public geyserManager;
mapping(address => uint256) public originalAmounts;
mapping(address => uint256) public extraAmounts;
uint256 public totalExtra;
mapping(address => uint256) userEarnings;
/**
* @param stakingToken The token users deposit as stake.
* @param distributionToken The token users receive as they unstake.
* @param maxUnlockSchedules Max number of unlock stages, to guard against hitting gas limit.
* @param startBonus_ Starting time bonus
* e.g. 25% means user gets 25% of max distribution tokens.
* @param bonusPeriodSec_ Length of time for bonus to increase linearly to max.
* @param initialSharesPerToken Number of shares to mint per staking token on first stake.
* @param bonusDecimals_ The number of decimals for shares
*/
constructor(
IERC20 stakingToken,
IERC20 distributionToken,
uint256 maxUnlockSchedules,
uint256 startBonus_,
uint256 bonusPeriodSec_,
uint256 initialSharesPerToken,
uint256 bonusDecimals_,
address warpNFT,
address managerAddress
) public {
// The start bonus must be some fraction of the max. (i.e. <= 100%)
require(
startBonus_ <= 10**bonusDecimals_,
"TokenGeyser: start bonus too high"
);
// If no period is desired, instead set startBonus = 100%
// and bonusPeriod to a small value like 1sec.
require(bonusPeriodSec_ != 0, "TokenGeyser: bonus period is zero");
require(
initialSharesPerToken > 0,
"TokenGeyser: initialSharesPerToken is zero"
);
require(bonusDecimals_ > 0, "TokenGeyser: bonusDecimals_ is zero");
_stakingPool = new TokenPool(stakingToken);
_unlockedPool = new TokenPool(distributionToken);
_lockedPool = new TokenPool(distributionToken);
_unlockedPool.setRescuable(true);
geyserManager = managerAddress;
startBonus = startBonus_;
bonusDecimals = bonusDecimals_;
bonusPeriodSec = bonusPeriodSec_;
_maxUnlockSchedules = maxUnlockSchedules;
_initialSharesPerToken = initialSharesPerToken;
_warpNFT = WarpNFT(warpNFT);
}
/**
* @return Total earnings for a user
*/
function getEarnings(address user) public view returns (uint256) {
return userEarnings[user];
}
/**
* @dev Rescue rewards
*/
function rescueRewards(address user) external onlyOwner {
require(totalUnlocked() > 0, "TokenGeyser: Nothing to rescue");
require(
_unlockedPool.transfer(user, _unlockedPool.balance()),
"TokenGeyser: rescue rewards from rewards pool failed"
);
}
/**
* @return The token users deposit as stake.
*/
function getStakingToken() public view returns (IERC20) {
return _stakingPool.token();
}
/**
* @return The token users receive as they unstake.
*/
function getDistributionToken() public view returns (IERC20) {
assert(_unlockedPool.token() == _lockedPool.token());
return _unlockedPool.token();
}
/**
* @dev Transfers amount of deposit tokens from the user.
* @param amount Number of deposit tokens to stake.
* @param data Not used.
*/
function stake(
address staker,
uint256 amount,
bytes calldata data,
int256 nftId
) external override {
require(
geyserManager == msg.sender,
"This method can be called by the geyser manager only"
);
_stakeFor(staker, staker, amount, nftId);
}
/**
* @dev Transfers amount of deposit tokens from the caller on behalf of user.
* @param user User address who gains credit for this stake operation.
* @param amount Number of deposit tokens to stake.
* @param data Not used.
*/
function stakeFor(
address staker,
address user,
uint256 amount,
bytes calldata data,
int256 nftId
) external override onlyOwner {
require(
geyserManager == msg.sender,
"This method can be called by the geyser manager only"
);
_stakeFor(staker, user, amount, nftId);
}
/**
* @dev Retrieves the boost you get for a specific NFT
* @param beneficiary The address who receives the bonus
* @param amount The amount for which the bonus is calculated
* @param nftId The NFT identifier
*/
function getNftBoost(
address beneficiary,
uint256 amount,
int256 nftId
) public view returns (uint256) {
if (nftId < 0) return 0;
if (_warpNFT.ownerOf(uint256(nftId)) != beneficiary) return 0;
uint256 nftType = _warpNFT.tokenType(uint256(nftId));
if (nftType == uint256(1)) return 0;
// 1 | Social - no boost
// 2 | Rare - 15% boost
// 4 | Epic - 75% boost
// 8 | Legendary - 150% boost
uint256 bonus = 1;
if (nftType == uint256(2)) {
bonus = 15;
}
if (nftType == uint256(4)) {
bonus = 75;
}
if (nftType == uint256(8)) {
bonus = 150;
}
uint256 result = (amount * bonus) / 100;
return result;
}
/**
* @dev Private implementation of staking methods.
* @param staker User address who deposits tokens to stake.
* @param beneficiary User address who gains credit for this stake operation.
* @param amount Number of deposit tokens to stake.
*/
function _stakeFor(
address staker,
address beneficiary,
uint256 amount,
int256 nftId
) private {
require(amount > 0, "TokenGeyser: stake amount is zero");
require(
beneficiary != address(0),
"TokenGeyser: beneficiary is zero address"
);
require(
totalStakingShares == 0 || totalStaked() > 0,
"TokenGeyser: Invalid state. Staking shares exist, but no staking tokens do"
);
uint256 sentAmount = 0;
sentAmount += amount;
uint256 extra = getNftBoost(beneficiary, amount, nftId);
originalAmounts[beneficiary] += amount;
extraAmounts[beneficiary] += extra;
amount += extra;
uint256 mintedStakingShares =
(totalStakingShares > 0)
? totalStakingShares.mul(amount).div(totalStaked())
: amount.mul(_initialSharesPerToken);
totalExtra += extra;
require(
mintedStakingShares > 0,
"TokenGeyser: Stake amount is too small"
);
updateAccounting(beneficiary);
// 1. User Accounting
UserTotals storage totals = _userTotals[beneficiary];
totals.stakingShares = totals.stakingShares.add(mintedStakingShares);
totals.lastAccountingTimestampSec = now;
Stake memory newStake = Stake(mintedStakingShares, now);
_userStakes[beneficiary].push(newStake);
// 2. Global Accounting
totalStakingShares = totalStakingShares.add(mintedStakingShares);
// Already set in updateAccounting()
// _lastAccountingTimestampSec = now;
// interactions
require(
_stakingPool.token().transferFrom(
staker,
address(_stakingPool),
sentAmount
),
"TokenGeyser: transfer into staking pool failed"
);
emit Staked(beneficiary, sentAmount, totalStakedFor(beneficiary), "");
}
/**
* @dev Unstakes a certain amount of previously deposited tokens. User also receives their
* alotted number of distribution tokens.
* @param amount Number of deposit tokens to unstake / withdraw.
* @param data Not used.
*/
function unstake(address staker, uint256 amount, bytes calldata data) external override {
require(
geyserManager == msg.sender,
"This method can be called by the geyser manager only"
);
_unstake(staker, amount);
}
/**
* @param amount Number of deposit tokens to unstake / withdraw.
* @return The total number of distribution tokens that would be rewarded.
*/
function unstakeQuery(address staker, uint256 amount) public returns (uint256) {
require(
geyserManager == msg.sender,
"This method can be called by the geyser manager only"
);
return _unstake(staker, amount);
}
/**
* @dev Unstakes a certain amount of previously deposited tokens. User also receives their
* alotted number of distribution tokens.
* @param amount Number of deposit tokens to unstake / withdraw.
* @return The total number of distribution tokens rewarded.
*/
function _unstake(address user, uint256 amount) private returns (uint256) {
updateAccounting(user);
// checks
require(amount == 0, "TokenGeyser: only full unstake is allowed");
amount = originalAmounts[user] + extraAmounts[user];
uint256 stakingSharesToBurn =
totalStakingShares.mul(amount).div(totalStaked());
require(
stakingSharesToBurn > 0,
"TokenGeyser: Unable to unstake amount this small"
);
// 1. User Accounting
UserTotals storage totals = _userTotals[user];
Stake[] storage accountStakes = _userStakes[user];
// Redeem from most recent stake and go backwards in time.
uint256 stakingShareSecondsToBurn = 0;
uint256 sharesLeftToBurn = stakingSharesToBurn;
uint256 rewardAmount = 0;
while (sharesLeftToBurn > 0) {
Stake storage lastStake = accountStakes[accountStakes.length - 1];
uint256 stakeTimeSec = now.sub(lastStake.timestampSec);
uint256 newStakingShareSecondsToBurn = 0;
if (lastStake.stakingShares <= sharesLeftToBurn) {
newStakingShareSecondsToBurn = lastStake.stakingShares.mul(
stakeTimeSec
);
rewardAmount = computeNewReward(
rewardAmount,
newStakingShareSecondsToBurn,
stakeTimeSec
);
stakingShareSecondsToBurn = stakingShareSecondsToBurn.add(
newStakingShareSecondsToBurn
);
sharesLeftToBurn = sharesLeftToBurn.sub(
lastStake.stakingShares
);
accountStakes.pop();
} else {
newStakingShareSecondsToBurn = sharesLeftToBurn.mul(
stakeTimeSec
);
rewardAmount = computeNewReward(
rewardAmount,
newStakingShareSecondsToBurn,
stakeTimeSec
);
stakingShareSecondsToBurn = stakingShareSecondsToBurn.add(
newStakingShareSecondsToBurn
);
lastStake.stakingShares = lastStake.stakingShares.sub(
sharesLeftToBurn
);
sharesLeftToBurn = 0;
}
}
totals.stakingShareSeconds = totals.stakingShareSeconds.sub(
stakingShareSecondsToBurn
);
totals.stakingShares = totals.stakingShares.sub(stakingSharesToBurn);
// Already set in updateAccounting
// totals.lastAccountingTimestampSec = now;
// 2. Global Accounting
_totalStakingShareSeconds = _totalStakingShareSeconds.sub(
stakingShareSecondsToBurn
);
totalStakingShares = totalStakingShares.sub(stakingSharesToBurn);
// Already set in updateAccounting
// _lastAccountingTimestampSec = now;
// interactions
require(
_stakingPool.transfer(user, originalAmounts[user]),
"TokenGeyser: transfer out of staking pool failed"
);
//in case rescueRewards was called, there are no rewards to be transfered
if (totalUnlocked() >= rewardAmount) {
require(
_unlockedPool.transfer(user, rewardAmount),
"TokenGeyser: transfer out of unlocked pool failed"
);
emit TokensClaimed(user, rewardAmount);
userEarnings[user] += rewardAmount;
}
emit Unstaked(user, amount, totalStakedFor(user), "");
require(
totalStakingShares == 0 || totalStaked() > 0,
"TokenGeyser: Error unstaking. Staking shares exist, but no staking tokens do"
);
totalExtra -= extraAmounts[user];
originalAmounts[user] = 0;
extraAmounts[user] = 0;
return rewardAmount;
}
/**
* @dev Applies an additional time-bonus to a distribution amount. This is necessary to
* encourage long-term deposits instead of constant unstake/restakes.
* The bonus-multiplier is the result of a linear function that starts at startBonus and
* ends at 100% over bonusPeriodSec, then stays at 100% thereafter.
* @param currentRewardTokens The current number of distribution tokens already alotted for this
* unstake op. Any bonuses are already applied.
* @param stakingShareSeconds The stakingShare-seconds that are being burned for new
* distribution tokens.
* @param stakeTimeSec Length of time for which the tokens were staked. Needed to calculate
* the time-bonus.
* @return Updated amount of distribution tokens to award, with any bonus included on the
* newly added tokens.
*/
function computeNewReward(
uint256 currentRewardTokens,
uint256 stakingShareSeconds,
uint256 stakeTimeSec
) private view returns (uint256) {
uint256 newRewardTokens =
totalUnlocked().mul(stakingShareSeconds).div(
_totalStakingShareSeconds
);
if (stakeTimeSec >= bonusPeriodSec) {
return currentRewardTokens.add(newRewardTokens);
}
uint256 oneHundredPct = 10**bonusDecimals;
uint256 bonusedReward =
startBonus
.add(
oneHundredPct.sub(startBonus).mul(stakeTimeSec).div(
bonusPeriodSec
)
)
.mul(newRewardTokens)
.div(oneHundredPct);
return currentRewardTokens.add(bonusedReward);
}
/**
* @param addr The user to look up staking information for.
* @return The number of staking tokens deposited for addr.
*/
function totalStakedFor(address addr)
public
view
override
returns (uint256)
{
uint256 amountWithExtra =
totalStakingShares > 0
? totalStaked().mul(_userTotals[addr].stakingShares).div(
totalStakingShares
)
: 0;
if (amountWithExtra == 0) return amountWithExtra;
return amountWithExtra - extraAmounts[addr];
}
/**
* @return The total number of deposit tokens staked globally, by all users.
*/
function totalStaked() public view override returns (uint256) {
return _stakingPool.balance() + totalExtra;
}
/**
* @dev Note that this application has a staking token as well as a distribution token, which
* may be different. This function is required by EIP-900.
* @return The deposit token used for staking.
*/
function token() external view override returns (address) {
return address(getStakingToken());
}
/**
* @dev A globally callable function to update the accounting state of the system.
* Global state and state for the caller are updated.
* @return [0] balance of the locked pool
* @return [1] balance of the unlocked pool
* @return [2] caller's staking share seconds
* @return [3] global staking share seconds
* @return [4] Rewards caller has accumulated, optimistically assumes max time-bonus.
* @return [5] block timestamp
*/
function updateAccounting(address user)
public
returns (
uint256,
uint256,
uint256,
uint256,
uint256,
uint256
)
{
_unlockTokens();
// Global accounting
uint256 newStakingShareSeconds =
now.sub(_lastAccountingTimestampSec).mul(totalStakingShares);
_totalStakingShareSeconds = _totalStakingShareSeconds.add(
newStakingShareSeconds
);
_lastAccountingTimestampSec = now;
// User Accounting
UserTotals storage totals = _userTotals[user];
uint256 newUserStakingShareSeconds =
now.sub(totals.lastAccountingTimestampSec).mul(
totals.stakingShares
);
totals.stakingShareSeconds = totals.stakingShareSeconds.add(
newUserStakingShareSeconds
);
totals.lastAccountingTimestampSec = now;
uint256 totalUserRewards =
(_totalStakingShareSeconds > 0)
? totalUnlocked().mul(totals.stakingShareSeconds).div(
_totalStakingShareSeconds
)
: 0;
return (
totalLocked(),
totalUnlocked(),
totals.stakingShareSeconds,
_totalStakingShareSeconds,
totalUserRewards,
now
);
}
/**
* @return Total number of locked distribution tokens.
*/
function totalLocked() public view returns (uint256) {
return _lockedPool.balance();
}
/**
* @return Total number of unlocked distribution tokens.
*/
function totalUnlocked() public view returns (uint256) {
return _unlockedPool.balance();
}
/**
* @return Number of unlock schedules.
*/
function unlockScheduleCount() public view returns (uint256) {
return unlockSchedules.length;
}
/**
* @dev This funcion allows the contract owner to add more locked distribution tokens, along
* with the associated "unlock schedule". These locked tokens immediately begin unlocking
* linearly over the duraction of durationSec timeframe.
* @param amount Number of distribution tokens to lock. These are transferred from the caller.
* @param durationSec Length of time to linear unlock the tokens.
*/
function lockTokens(uint256 amount, uint256 durationSec)
external
onlyOwner
{
require(
unlockSchedules.length < _maxUnlockSchedules,
"TokenGeyser: reached maximum unlock schedules"
);
// Update lockedTokens amount before using it in computations after.
updateAccounting(msg.sender);
uint256 lockedTokens = totalLocked();
uint256 mintedLockedShares =
(lockedTokens > 0)
? totalLockedShares.mul(amount).div(lockedTokens)
: amount.mul(_initialSharesPerToken);
UnlockSchedule memory schedule;
schedule.initialLockedShares = mintedLockedShares;
schedule.lastUnlockTimestampSec = now;
schedule.endAtSec = now.add(durationSec);
schedule.durationSec = durationSec;
unlockSchedules.push(schedule);
totalLockedShares = totalLockedShares.add(mintedLockedShares);
require(
_lockedPool.token().transferFrom(
msg.sender,
address(_lockedPool),
amount
),
"TokenGeyser: transfer into locked pool failed"
);
emit TokensLocked(amount, durationSec, totalLocked());
}
/**
* @dev Moves distribution tokens from the locked pool to the unlocked pool, according to the
* previously defined unlock schedules. Publicly callable.
* @return Number of newly unlocked distribution tokens.
*/
function unlockTokens() public onlyOwner returns (uint256) {
_unlockTokens();
}
function _unlockTokens() private returns (uint256) {
uint256 unlockedTokens = 0;
uint256 lockedTokens = totalLocked();
if (totalLockedShares == 0) {
unlockedTokens = lockedTokens;
} else {
uint256 unlockedShares = 0;
for (uint256 s = 0; s < unlockSchedules.length; s++) {
unlockedShares = unlockedShares.add(unlockScheduleShares(s));
}
unlockedTokens = unlockedShares.mul(lockedTokens).div(
totalLockedShares
);
totalLockedShares = totalLockedShares.sub(unlockedShares);
}
if (unlockedTokens > 0) {
require(
_lockedPool.transfer(address(_unlockedPool), unlockedTokens),
"TokenGeyser: transfer out of locked pool failed"
);
emit TokensUnlocked(unlockedTokens, totalLocked());
}
return unlockedTokens;
}
/**
* @dev Returns the number of unlockable shares from a given schedule. The returned value
* depends on the time since the last unlock. This function updates schedule accounting,
* but does not actually transfer any tokens.
* @param s Index of the unlock schedule.
* @return The number of unlocked shares.
*/
function unlockScheduleShares(uint256 s) private returns (uint256) {
UnlockSchedule storage schedule = unlockSchedules[s];
if (schedule.unlockedShares >= schedule.initialLockedShares) {
return 0;
}
uint256 sharesToUnlock = 0;
// Special case to handle any leftover dust from integer division
if (now >= schedule.endAtSec) {
sharesToUnlock = (
schedule.initialLockedShares.sub(schedule.unlockedShares)
);
schedule.lastUnlockTimestampSec = schedule.endAtSec;
} else {
sharesToUnlock = now
.sub(schedule.lastUnlockTimestampSec)
.mul(schedule.initialLockedShares)
.div(schedule.durationSec);
schedule.lastUnlockTimestampSec = now;
}
schedule.unlockedShares = schedule.unlockedShares.add(sharesToUnlock);
return sharesToUnlock;
}
/**
* @dev Lets the owner rescue funds air-dropped to the staking pool.
* @param tokenToRescue Address of the token to be rescued.
* @param to Address to which the rescued funds are to be sent.
* @param amount Amount of tokens to be rescued.
* @return Transfer success.
*/
function rescueFundsFromStakingPool(
address tokenToRescue,
address to,
uint256 amount
) public onlyOwner returns (bool) {
return _stakingPool.rescueFunds(tokenToRescue, to, amount);
}
function supportsHistory() external pure override returns (bool) {
return false;
}
}
| contract TokenGeyser is IStaking, IStakeWithNFT, Ownable {
using SafeMath for uint256;
event Staked(
address indexed user,
uint256 amount,
uint256 total,
bytes data
);
event Unstaked(
address indexed user,
uint256 amount,
uint256 total,
bytes data
);
event TokensClaimed(address indexed user, uint256 amount);
event TokensLocked(uint256 amount, uint256 durationSec, uint256 total);
// amount: Unlocked tokens, total: Total locked tokens
event TokensUnlocked(uint256 amount, uint256 total);
TokenPool private _stakingPool;
TokenPool private _unlockedPool;
TokenPool private _lockedPool;
//
// Time-bonus params
//
uint256 public bonusDecimals = 2;
uint256 public startBonus = 0;
uint256 public bonusPeriodSec = 0;
//
// Global accounting state
//
uint256 public totalLockedShares = 0;
uint256 public totalStakingShares = 0;
uint256 private _totalStakingShareSeconds = 0;
uint256 private _lastAccountingTimestampSec = now;
uint256 private _maxUnlockSchedules = 0;
uint256 private _initialSharesPerToken = 0;
//
// User accounting state
//
// Represents a single stake for a user. A user may have multiple.
struct Stake {
uint256 stakingShares;
uint256 timestampSec;
}
// Caches aggregated values from the User->Stake[] map to save computation.
// If lastAccountingTimestampSec is 0, there's no entry for that user.
struct UserTotals {
uint256 stakingShares;
uint256 stakingShareSeconds;
uint256 lastAccountingTimestampSec;
}
// Aggregated staking values per user
mapping(address => UserTotals) private _userTotals;
// The collection of stakes for each user. Ordered by timestamp, earliest to latest.
mapping(address => Stake[]) private _userStakes;
//
// Locked/Unlocked Accounting state
//
struct UnlockSchedule {
uint256 initialLockedShares;
uint256 unlockedShares;
uint256 lastUnlockTimestampSec;
uint256 endAtSec;
uint256 durationSec;
}
UnlockSchedule[] public unlockSchedules;
WarpNFT public _warpNFT;
address public geyserManager;
mapping(address => uint256) public originalAmounts;
mapping(address => uint256) public extraAmounts;
uint256 public totalExtra;
mapping(address => uint256) userEarnings;
/**
* @param stakingToken The token users deposit as stake.
* @param distributionToken The token users receive as they unstake.
* @param maxUnlockSchedules Max number of unlock stages, to guard against hitting gas limit.
* @param startBonus_ Starting time bonus
* e.g. 25% means user gets 25% of max distribution tokens.
* @param bonusPeriodSec_ Length of time for bonus to increase linearly to max.
* @param initialSharesPerToken Number of shares to mint per staking token on first stake.
* @param bonusDecimals_ The number of decimals for shares
*/
constructor(
IERC20 stakingToken,
IERC20 distributionToken,
uint256 maxUnlockSchedules,
uint256 startBonus_,
uint256 bonusPeriodSec_,
uint256 initialSharesPerToken,
uint256 bonusDecimals_,
address warpNFT,
address managerAddress
) public {
// The start bonus must be some fraction of the max. (i.e. <= 100%)
require(
startBonus_ <= 10**bonusDecimals_,
"TokenGeyser: start bonus too high"
);
// If no period is desired, instead set startBonus = 100%
// and bonusPeriod to a small value like 1sec.
require(bonusPeriodSec_ != 0, "TokenGeyser: bonus period is zero");
require(
initialSharesPerToken > 0,
"TokenGeyser: initialSharesPerToken is zero"
);
require(bonusDecimals_ > 0, "TokenGeyser: bonusDecimals_ is zero");
_stakingPool = new TokenPool(stakingToken);
_unlockedPool = new TokenPool(distributionToken);
_lockedPool = new TokenPool(distributionToken);
_unlockedPool.setRescuable(true);
geyserManager = managerAddress;
startBonus = startBonus_;
bonusDecimals = bonusDecimals_;
bonusPeriodSec = bonusPeriodSec_;
_maxUnlockSchedules = maxUnlockSchedules;
_initialSharesPerToken = initialSharesPerToken;
_warpNFT = WarpNFT(warpNFT);
}
/**
* @return Total earnings for a user
*/
function getEarnings(address user) public view returns (uint256) {
return userEarnings[user];
}
/**
* @dev Rescue rewards
*/
function rescueRewards(address user) external onlyOwner {
require(totalUnlocked() > 0, "TokenGeyser: Nothing to rescue");
require(
_unlockedPool.transfer(user, _unlockedPool.balance()),
"TokenGeyser: rescue rewards from rewards pool failed"
);
}
/**
* @return The token users deposit as stake.
*/
function getStakingToken() public view returns (IERC20) {
return _stakingPool.token();
}
/**
* @return The token users receive as they unstake.
*/
function getDistributionToken() public view returns (IERC20) {
assert(_unlockedPool.token() == _lockedPool.token());
return _unlockedPool.token();
}
/**
* @dev Transfers amount of deposit tokens from the user.
* @param amount Number of deposit tokens to stake.
* @param data Not used.
*/
function stake(
address staker,
uint256 amount,
bytes calldata data,
int256 nftId
) external override {
require(
geyserManager == msg.sender,
"This method can be called by the geyser manager only"
);
_stakeFor(staker, staker, amount, nftId);
}
/**
* @dev Transfers amount of deposit tokens from the caller on behalf of user.
* @param user User address who gains credit for this stake operation.
* @param amount Number of deposit tokens to stake.
* @param data Not used.
*/
function stakeFor(
address staker,
address user,
uint256 amount,
bytes calldata data,
int256 nftId
) external override onlyOwner {
require(
geyserManager == msg.sender,
"This method can be called by the geyser manager only"
);
_stakeFor(staker, user, amount, nftId);
}
/**
* @dev Retrieves the boost you get for a specific NFT
* @param beneficiary The address who receives the bonus
* @param amount The amount for which the bonus is calculated
* @param nftId The NFT identifier
*/
function getNftBoost(
address beneficiary,
uint256 amount,
int256 nftId
) public view returns (uint256) {
if (nftId < 0) return 0;
if (_warpNFT.ownerOf(uint256(nftId)) != beneficiary) return 0;
uint256 nftType = _warpNFT.tokenType(uint256(nftId));
if (nftType == uint256(1)) return 0;
// 1 | Social - no boost
// 2 | Rare - 15% boost
// 4 | Epic - 75% boost
// 8 | Legendary - 150% boost
uint256 bonus = 1;
if (nftType == uint256(2)) {
bonus = 15;
}
if (nftType == uint256(4)) {
bonus = 75;
}
if (nftType == uint256(8)) {
bonus = 150;
}
uint256 result = (amount * bonus) / 100;
return result;
}
/**
* @dev Private implementation of staking methods.
* @param staker User address who deposits tokens to stake.
* @param beneficiary User address who gains credit for this stake operation.
* @param amount Number of deposit tokens to stake.
*/
function _stakeFor(
address staker,
address beneficiary,
uint256 amount,
int256 nftId
) private {
require(amount > 0, "TokenGeyser: stake amount is zero");
require(
beneficiary != address(0),
"TokenGeyser: beneficiary is zero address"
);
require(
totalStakingShares == 0 || totalStaked() > 0,
"TokenGeyser: Invalid state. Staking shares exist, but no staking tokens do"
);
uint256 sentAmount = 0;
sentAmount += amount;
uint256 extra = getNftBoost(beneficiary, amount, nftId);
originalAmounts[beneficiary] += amount;
extraAmounts[beneficiary] += extra;
amount += extra;
uint256 mintedStakingShares =
(totalStakingShares > 0)
? totalStakingShares.mul(amount).div(totalStaked())
: amount.mul(_initialSharesPerToken);
totalExtra += extra;
require(
mintedStakingShares > 0,
"TokenGeyser: Stake amount is too small"
);
updateAccounting(beneficiary);
// 1. User Accounting
UserTotals storage totals = _userTotals[beneficiary];
totals.stakingShares = totals.stakingShares.add(mintedStakingShares);
totals.lastAccountingTimestampSec = now;
Stake memory newStake = Stake(mintedStakingShares, now);
_userStakes[beneficiary].push(newStake);
// 2. Global Accounting
totalStakingShares = totalStakingShares.add(mintedStakingShares);
// Already set in updateAccounting()
// _lastAccountingTimestampSec = now;
// interactions
require(
_stakingPool.token().transferFrom(
staker,
address(_stakingPool),
sentAmount
),
"TokenGeyser: transfer into staking pool failed"
);
emit Staked(beneficiary, sentAmount, totalStakedFor(beneficiary), "");
}
/**
* @dev Unstakes a certain amount of previously deposited tokens. User also receives their
* alotted number of distribution tokens.
* @param amount Number of deposit tokens to unstake / withdraw.
* @param data Not used.
*/
function unstake(address staker, uint256 amount, bytes calldata data) external override {
require(
geyserManager == msg.sender,
"This method can be called by the geyser manager only"
);
_unstake(staker, amount);
}
/**
* @param amount Number of deposit tokens to unstake / withdraw.
* @return The total number of distribution tokens that would be rewarded.
*/
function unstakeQuery(address staker, uint256 amount) public returns (uint256) {
require(
geyserManager == msg.sender,
"This method can be called by the geyser manager only"
);
return _unstake(staker, amount);
}
/**
* @dev Unstakes a certain amount of previously deposited tokens. User also receives their
* alotted number of distribution tokens.
* @param amount Number of deposit tokens to unstake / withdraw.
* @return The total number of distribution tokens rewarded.
*/
function _unstake(address user, uint256 amount) private returns (uint256) {
updateAccounting(user);
// checks
require(amount == 0, "TokenGeyser: only full unstake is allowed");
amount = originalAmounts[user] + extraAmounts[user];
uint256 stakingSharesToBurn =
totalStakingShares.mul(amount).div(totalStaked());
require(
stakingSharesToBurn > 0,
"TokenGeyser: Unable to unstake amount this small"
);
// 1. User Accounting
UserTotals storage totals = _userTotals[user];
Stake[] storage accountStakes = _userStakes[user];
// Redeem from most recent stake and go backwards in time.
uint256 stakingShareSecondsToBurn = 0;
uint256 sharesLeftToBurn = stakingSharesToBurn;
uint256 rewardAmount = 0;
while (sharesLeftToBurn > 0) {
Stake storage lastStake = accountStakes[accountStakes.length - 1];
uint256 stakeTimeSec = now.sub(lastStake.timestampSec);
uint256 newStakingShareSecondsToBurn = 0;
if (lastStake.stakingShares <= sharesLeftToBurn) {
newStakingShareSecondsToBurn = lastStake.stakingShares.mul(
stakeTimeSec
);
rewardAmount = computeNewReward(
rewardAmount,
newStakingShareSecondsToBurn,
stakeTimeSec
);
stakingShareSecondsToBurn = stakingShareSecondsToBurn.add(
newStakingShareSecondsToBurn
);
sharesLeftToBurn = sharesLeftToBurn.sub(
lastStake.stakingShares
);
accountStakes.pop();
} else {
newStakingShareSecondsToBurn = sharesLeftToBurn.mul(
stakeTimeSec
);
rewardAmount = computeNewReward(
rewardAmount,
newStakingShareSecondsToBurn,
stakeTimeSec
);
stakingShareSecondsToBurn = stakingShareSecondsToBurn.add(
newStakingShareSecondsToBurn
);
lastStake.stakingShares = lastStake.stakingShares.sub(
sharesLeftToBurn
);
sharesLeftToBurn = 0;
}
}
totals.stakingShareSeconds = totals.stakingShareSeconds.sub(
stakingShareSecondsToBurn
);
totals.stakingShares = totals.stakingShares.sub(stakingSharesToBurn);
// Already set in updateAccounting
// totals.lastAccountingTimestampSec = now;
// 2. Global Accounting
_totalStakingShareSeconds = _totalStakingShareSeconds.sub(
stakingShareSecondsToBurn
);
totalStakingShares = totalStakingShares.sub(stakingSharesToBurn);
// Already set in updateAccounting
// _lastAccountingTimestampSec = now;
// interactions
require(
_stakingPool.transfer(user, originalAmounts[user]),
"TokenGeyser: transfer out of staking pool failed"
);
//in case rescueRewards was called, there are no rewards to be transfered
if (totalUnlocked() >= rewardAmount) {
require(
_unlockedPool.transfer(user, rewardAmount),
"TokenGeyser: transfer out of unlocked pool failed"
);
emit TokensClaimed(user, rewardAmount);
userEarnings[user] += rewardAmount;
}
emit Unstaked(user, amount, totalStakedFor(user), "");
require(
totalStakingShares == 0 || totalStaked() > 0,
"TokenGeyser: Error unstaking. Staking shares exist, but no staking tokens do"
);
totalExtra -= extraAmounts[user];
originalAmounts[user] = 0;
extraAmounts[user] = 0;
return rewardAmount;
}
/**
* @dev Applies an additional time-bonus to a distribution amount. This is necessary to
* encourage long-term deposits instead of constant unstake/restakes.
* The bonus-multiplier is the result of a linear function that starts at startBonus and
* ends at 100% over bonusPeriodSec, then stays at 100% thereafter.
* @param currentRewardTokens The current number of distribution tokens already alotted for this
* unstake op. Any bonuses are already applied.
* @param stakingShareSeconds The stakingShare-seconds that are being burned for new
* distribution tokens.
* @param stakeTimeSec Length of time for which the tokens were staked. Needed to calculate
* the time-bonus.
* @return Updated amount of distribution tokens to award, with any bonus included on the
* newly added tokens.
*/
function computeNewReward(
uint256 currentRewardTokens,
uint256 stakingShareSeconds,
uint256 stakeTimeSec
) private view returns (uint256) {
uint256 newRewardTokens =
totalUnlocked().mul(stakingShareSeconds).div(
_totalStakingShareSeconds
);
if (stakeTimeSec >= bonusPeriodSec) {
return currentRewardTokens.add(newRewardTokens);
}
uint256 oneHundredPct = 10**bonusDecimals;
uint256 bonusedReward =
startBonus
.add(
oneHundredPct.sub(startBonus).mul(stakeTimeSec).div(
bonusPeriodSec
)
)
.mul(newRewardTokens)
.div(oneHundredPct);
return currentRewardTokens.add(bonusedReward);
}
/**
* @param addr The user to look up staking information for.
* @return The number of staking tokens deposited for addr.
*/
function totalStakedFor(address addr)
public
view
override
returns (uint256)
{
uint256 amountWithExtra =
totalStakingShares > 0
? totalStaked().mul(_userTotals[addr].stakingShares).div(
totalStakingShares
)
: 0;
if (amountWithExtra == 0) return amountWithExtra;
return amountWithExtra - extraAmounts[addr];
}
/**
* @return The total number of deposit tokens staked globally, by all users.
*/
function totalStaked() public view override returns (uint256) {
return _stakingPool.balance() + totalExtra;
}
/**
* @dev Note that this application has a staking token as well as a distribution token, which
* may be different. This function is required by EIP-900.
* @return The deposit token used for staking.
*/
function token() external view override returns (address) {
return address(getStakingToken());
}
/**
* @dev A globally callable function to update the accounting state of the system.
* Global state and state for the caller are updated.
* @return [0] balance of the locked pool
* @return [1] balance of the unlocked pool
* @return [2] caller's staking share seconds
* @return [3] global staking share seconds
* @return [4] Rewards caller has accumulated, optimistically assumes max time-bonus.
* @return [5] block timestamp
*/
function updateAccounting(address user)
public
returns (
uint256,
uint256,
uint256,
uint256,
uint256,
uint256
)
{
_unlockTokens();
// Global accounting
uint256 newStakingShareSeconds =
now.sub(_lastAccountingTimestampSec).mul(totalStakingShares);
_totalStakingShareSeconds = _totalStakingShareSeconds.add(
newStakingShareSeconds
);
_lastAccountingTimestampSec = now;
// User Accounting
UserTotals storage totals = _userTotals[user];
uint256 newUserStakingShareSeconds =
now.sub(totals.lastAccountingTimestampSec).mul(
totals.stakingShares
);
totals.stakingShareSeconds = totals.stakingShareSeconds.add(
newUserStakingShareSeconds
);
totals.lastAccountingTimestampSec = now;
uint256 totalUserRewards =
(_totalStakingShareSeconds > 0)
? totalUnlocked().mul(totals.stakingShareSeconds).div(
_totalStakingShareSeconds
)
: 0;
return (
totalLocked(),
totalUnlocked(),
totals.stakingShareSeconds,
_totalStakingShareSeconds,
totalUserRewards,
now
);
}
/**
* @return Total number of locked distribution tokens.
*/
function totalLocked() public view returns (uint256) {
return _lockedPool.balance();
}
/**
* @return Total number of unlocked distribution tokens.
*/
function totalUnlocked() public view returns (uint256) {
return _unlockedPool.balance();
}
/**
* @return Number of unlock schedules.
*/
function unlockScheduleCount() public view returns (uint256) {
return unlockSchedules.length;
}
/**
* @dev This funcion allows the contract owner to add more locked distribution tokens, along
* with the associated "unlock schedule". These locked tokens immediately begin unlocking
* linearly over the duraction of durationSec timeframe.
* @param amount Number of distribution tokens to lock. These are transferred from the caller.
* @param durationSec Length of time to linear unlock the tokens.
*/
function lockTokens(uint256 amount, uint256 durationSec)
external
onlyOwner
{
require(
unlockSchedules.length < _maxUnlockSchedules,
"TokenGeyser: reached maximum unlock schedules"
);
// Update lockedTokens amount before using it in computations after.
updateAccounting(msg.sender);
uint256 lockedTokens = totalLocked();
uint256 mintedLockedShares =
(lockedTokens > 0)
? totalLockedShares.mul(amount).div(lockedTokens)
: amount.mul(_initialSharesPerToken);
UnlockSchedule memory schedule;
schedule.initialLockedShares = mintedLockedShares;
schedule.lastUnlockTimestampSec = now;
schedule.endAtSec = now.add(durationSec);
schedule.durationSec = durationSec;
unlockSchedules.push(schedule);
totalLockedShares = totalLockedShares.add(mintedLockedShares);
require(
_lockedPool.token().transferFrom(
msg.sender,
address(_lockedPool),
amount
),
"TokenGeyser: transfer into locked pool failed"
);
emit TokensLocked(amount, durationSec, totalLocked());
}
/**
* @dev Moves distribution tokens from the locked pool to the unlocked pool, according to the
* previously defined unlock schedules. Publicly callable.
* @return Number of newly unlocked distribution tokens.
*/
function unlockTokens() public onlyOwner returns (uint256) {
_unlockTokens();
}
function _unlockTokens() private returns (uint256) {
uint256 unlockedTokens = 0;
uint256 lockedTokens = totalLocked();
if (totalLockedShares == 0) {
unlockedTokens = lockedTokens;
} else {
uint256 unlockedShares = 0;
for (uint256 s = 0; s < unlockSchedules.length; s++) {
unlockedShares = unlockedShares.add(unlockScheduleShares(s));
}
unlockedTokens = unlockedShares.mul(lockedTokens).div(
totalLockedShares
);
totalLockedShares = totalLockedShares.sub(unlockedShares);
}
if (unlockedTokens > 0) {
require(
_lockedPool.transfer(address(_unlockedPool), unlockedTokens),
"TokenGeyser: transfer out of locked pool failed"
);
emit TokensUnlocked(unlockedTokens, totalLocked());
}
return unlockedTokens;
}
/**
* @dev Returns the number of unlockable shares from a given schedule. The returned value
* depends on the time since the last unlock. This function updates schedule accounting,
* but does not actually transfer any tokens.
* @param s Index of the unlock schedule.
* @return The number of unlocked shares.
*/
function unlockScheduleShares(uint256 s) private returns (uint256) {
UnlockSchedule storage schedule = unlockSchedules[s];
if (schedule.unlockedShares >= schedule.initialLockedShares) {
return 0;
}
uint256 sharesToUnlock = 0;
// Special case to handle any leftover dust from integer division
if (now >= schedule.endAtSec) {
sharesToUnlock = (
schedule.initialLockedShares.sub(schedule.unlockedShares)
);
schedule.lastUnlockTimestampSec = schedule.endAtSec;
} else {
sharesToUnlock = now
.sub(schedule.lastUnlockTimestampSec)
.mul(schedule.initialLockedShares)
.div(schedule.durationSec);
schedule.lastUnlockTimestampSec = now;
}
schedule.unlockedShares = schedule.unlockedShares.add(sharesToUnlock);
return sharesToUnlock;
}
/**
* @dev Lets the owner rescue funds air-dropped to the staking pool.
* @param tokenToRescue Address of the token to be rescued.
* @param to Address to which the rescued funds are to be sent.
* @param amount Amount of tokens to be rescued.
* @return Transfer success.
*/
function rescueFundsFromStakingPool(
address tokenToRescue,
address to,
uint256 amount
) public onlyOwner returns (bool) {
return _stakingPool.rescueFunds(tokenToRescue, to, amount);
}
function supportsHistory() external pure override returns (bool) {
return false;
}
}
| 9,592 |
24 | // Returns the maximum number of nfts supported to be listed in this LendPool / | function getMaxNumberOfNfts() external view returns (uint256);
| function getMaxNumberOfNfts() external view returns (uint256);
| 24,251 |
9 | // Randomly set secretNumber with a value between 1 and 10 | secretNumber = uint8(keccak256(abi.encodePacked(block.timestamp, msg.sender))) % 10 + 1;
| secretNumber = uint8(keccak256(abi.encodePacked(block.timestamp, msg.sender))) % 10 + 1;
| 11,789 |
125 | // Return the withdrawal fee for a given amount of TokenA and TokenBfeeA := amountAfeeRatefeeB := amountBfeeRate / | function feeAFeeBForTokenATokenB(
uint256 amountA,
uint256 amountB,
uint256 feeRate
| function feeAFeeBForTokenATokenB(
uint256 amountA,
uint256 amountB,
uint256 feeRate
| 24,819 |
54 | // solhint-disable-next-line no-inline-assembly | assembly { size := extcodesize(account) }
| assembly { size := extcodesize(account) }
| 295 |
122 | // fallback function to receives ETH. | receive() external payable {
// calls `buyTokens()`
buyTokens();
}
| receive() external payable {
// calls `buyTokens()`
buyTokens();
}
| 22,048 |
107 | // Transfer tokens to this contract | IERC20(token).safeTransferFrom(msg.sender, address(locker), _amount);
| IERC20(token).safeTransferFrom(msg.sender, address(locker), _amount);
| 21,283 |
85 | // After iterating through all the nOutcomes bit positions, we should be left with 0. Otherwise, it means that other higher bits were set. | if (!(winningOutcomeIndexFlagsCopy == 0)) revert OutcomeIndexOutOfRange();
| if (!(winningOutcomeIndexFlagsCopy == 0)) revert OutcomeIndexOutOfRange();
| 22,404 |
78 | // check to see if this repo exists | if(orgsById[orgId].servicesById[serviceId].serviceId == bytes32(0x0)) {
found = false;
return;
}
| if(orgsById[orgId].servicesById[serviceId].serviceId == bytes32(0x0)) {
found = false;
return;
}
| 45,700 |
95 | // set's marketing address / | function setMarketingFeeAddress(address payable wallet) external onlyOwner {
marketingAddress = wallet;
}
| function setMarketingFeeAddress(address payable wallet) external onlyOwner {
marketingAddress = wallet;
}
| 21,468 |
155 | // Convert boolean value into bytes b The boolean valuereturnConverted bytes array/ | function WriteBool(bool b) internal pure returns (bytes memory) {
bytes memory buff;
assembly{
buff := mload(0x40)
mstore(buff, 1)
switch iszero(b)
case 1 {
mstore(add(buff, 0x20), shl(248, 0x00))
| function WriteBool(bool b) internal pure returns (bytes memory) {
bytes memory buff;
assembly{
buff := mload(0x40)
mstore(buff, 1)
switch iszero(b)
case 1 {
mstore(add(buff, 0x20), shl(248, 0x00))
| 29,021 |
148 | // The total number of burned FAIR tokens, excluding tokens burned from a `Sell` action in the DAT. | uint public burnedSupply;
| uint public burnedSupply;
| 7,788 |
613 | // delete token from previous owner | _deleteOwnershipRecord(_tokenId);
| _deleteOwnershipRecord(_tokenId);
| 18,417 |
478 | // Fills the input ExchangeV2 order. The `makerFeeAssetData` must be equal to EXCHANGE_V2_ORDER_ID (0x770501f8)./Returns false if the transaction would otherwise revert./order Order struct containing order specifications./takerAssetFillAmount Desired amount of takerAsset to sell./signature Proof that order has been created by maker./ return Amounts filled and fees paid by maker and taker. | function _fillV2OrderNoThrow(
LibOrder.Order memory order,
uint256 takerAssetFillAmount,
bytes memory signature
)
internal
returns (LibFillResults.FillResults memory fillResults)
| function _fillV2OrderNoThrow(
LibOrder.Order memory order,
uint256 takerAssetFillAmount,
bytes memory signature
)
internal
returns (LibFillResults.FillResults memory fillResults)
| 37,163 |
93 | // Safely transfers the ownership of a given token ID to another address If the target address is a contract, it must implement `onERC721Received`, which is called upon a safe transfer, and return the magic value `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`; otherwise, the transfer is reverted. Requires the msg sender to be the owner, approved, or operator _from current owner of the token _to address to receive the ownership of the given token ID _tokenId uint256 ID of the token to be transferred _data bytes data to send along with a safe transfer check / | function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId,
bytes _data
)
public
canTransfer(_tokenId)
| function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId,
bytes _data
)
public
canTransfer(_tokenId)
| 6,595 |
141 | // Reserved for future expansion | int256[98] private _reserved;
| int256[98] private _reserved;
| 83,527 |
24 | // checks that Node has correct data | require(params.ip != 0x0 && !nodesIPCheck[params.ip], "IP address is zero or is not available");
require(!nodesNameCheck[keccak256(abi.encodePacked(params.name))], "Name is already registered");
require(params.port > 0, "Port is zero");
require(from == _publicKeyToAddress(params.publicKey), "Public Key is incorrect");
uint validatorId = ValidatorService(
contractManager.getContract("ValidatorService")).getValidatorIdByNodeAddress(from);
| require(params.ip != 0x0 && !nodesIPCheck[params.ip], "IP address is zero or is not available");
require(!nodesNameCheck[keccak256(abi.encodePacked(params.name))], "Name is already registered");
require(params.port > 0, "Port is zero");
require(from == _publicKeyToAddress(params.publicKey), "Public Key is incorrect");
uint validatorId = ValidatorService(
contractManager.getContract("ValidatorService")).getValidatorIdByNodeAddress(from);
| 26,983 |
109 | // Full ERC721 TokenThis implementation includes all the required and some optional functionality of the ERC721 standardMoreover, it includes approve all functionality using operator terminology / | contract ERC721Token is SupportsInterfaceWithLookup, ERC721BasicToken, ERC721 {
bytes4 private constant InterfaceId_ERC721Enumerable = 0x780e9d63;
/**
* 0x780e9d63 ===
* bytes4(keccak256('totalSupply()')) ^
* bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) ^
* bytes4(keccak256('tokenByIndex(uint256)'))
*/
bytes4 private constant InterfaceId_ERC721Metadata = 0x5b5e139f;
/**
* 0x5b5e139f ===
* bytes4(keccak256('name()')) ^
* bytes4(keccak256('symbol()')) ^
* bytes4(keccak256('tokenURI(uint256)'))
*/
// Token name
string internal name_;
// Token symbol
string internal symbol_;
// Mapping from owner to list of owned token IDs
mapping(address => uint256[]) internal ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) internal ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] internal allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) internal allTokensIndex;
// Optional mapping for token URIs
mapping(uint256 => string) internal tokenURIs;
/**
* @dev Constructor function
*/
constructor(string _name, string _symbol) public {
name_ = _name;
symbol_ = _symbol;
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(InterfaceId_ERC721Enumerable);
_registerInterface(InterfaceId_ERC721Metadata);
}
/**
* @dev Gets the token name
* @return string representing the token name
*/
function name() external view returns (string) {
return name_;
}
/**
* @dev Gets the token symbol
* @return string representing the token symbol
*/
function symbol() external view returns (string) {
return symbol_;
}
/**
* @dev Returns an URI for a given token ID
* Throws if the token ID does not exist. May return an empty string.
* @param _tokenId uint256 ID of the token to query
*/
function tokenURI(uint256 _tokenId) public view returns (string) {
require(exists(_tokenId));
return tokenURIs[_tokenId];
}
/**
* @dev Gets the token ID at a given index of the tokens list of the requested owner
* @param _owner address owning the tokens list to be accessed
* @param _index uint256 representing the index to be accessed of the requested tokens list
* @return uint256 token ID at the given index of the tokens list owned by the requested address
*/
function tokenOfOwnerByIndex(
address _owner,
uint256 _index
)
public
view
returns (uint256)
{
require(_index < balanceOf(_owner));
return ownedTokens[_owner][_index];
}
/**
* @dev Gets the total amount of tokens stored by the contract
* @return uint256 representing the total amount of tokens
*/
function totalSupply() public view returns (uint256) {
return allTokens.length;
}
/**
* @dev Gets the token ID at a given index of all the tokens in this contract
* Reverts if the index is greater or equal to the total number of tokens
* @param _index uint256 representing the index to be accessed of the tokens list
* @return uint256 token ID at the given index of the tokens list
*/
function tokenByIndex(uint256 _index) public view returns (uint256) {
require(_index < totalSupply());
return allTokens[_index];
}
/**
* @dev Internal function to set the token URI for a given token
* Reverts if the token ID does not exist
* @param _tokenId uint256 ID of the token to set its URI
* @param _uri string URI to assign
*/
function _setTokenURI(uint256 _tokenId, string _uri) internal {
require(exists(_tokenId));
tokenURIs[_tokenId] = _uri;
}
/**
* @dev Internal function to add a token ID to the list of a given address
* @param _to address representing the new owner of the given token ID
* @param _tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function addTokenTo(address _to, uint256 _tokenId) internal {
super.addTokenTo(_to, _tokenId);
uint256 length = ownedTokens[_to].length;
ownedTokens[_to].push(_tokenId);
ownedTokensIndex[_tokenId] = length;
}
/**
* @dev Internal function to remove a token ID from the list of a given address
* @param _from address representing the previous owner of the given token ID
* @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function removeTokenFrom(address _from, uint256 _tokenId) internal {
super.removeTokenFrom(_from, _tokenId);
uint256 tokenIndex = ownedTokensIndex[_tokenId];
uint256 lastTokenIndex = ownedTokens[_from].length.sub(1);
uint256 lastToken = ownedTokens[_from][lastTokenIndex];
ownedTokens[_from][tokenIndex] = lastToken;
ownedTokens[_from][lastTokenIndex] = 0;
// Note that this will handle single-element arrays. In that case, both tokenIndex and lastTokenIndex are going to
// be zero. Then we can make sure that we will remove _tokenId from the ownedTokens list since we are first swapping
// the lastToken to the first position, and then dropping the element placed in the last position of the list
ownedTokens[_from].length--;
ownedTokensIndex[_tokenId] = 0;
ownedTokensIndex[lastToken] = tokenIndex;
}
/**
* @dev Internal function to mint a new token
* Reverts if the given token ID already exists
* @param _to address the beneficiary that will own the minted token
* @param _tokenId uint256 ID of the token to be minted by the msg.sender
*/
function _mint(address _to, uint256 _tokenId) internal {
super._mint(_to, _tokenId);
allTokensIndex[_tokenId] = allTokens.length;
allTokens.push(_tokenId);
}
/**
* @dev Internal function to burn a specific token
* Reverts if the token does not exist
* @param _owner owner of the token to burn
* @param _tokenId uint256 ID of the token being burned by the msg.sender
*/
function _burn(address _owner, uint256 _tokenId) internal {
super._burn(_owner, _tokenId);
// Clear metadata (if any)
if (bytes(tokenURIs[_tokenId]).length != 0) {
delete tokenURIs[_tokenId];
}
// Reorg all tokens array
uint256 tokenIndex = allTokensIndex[_tokenId];
uint256 lastTokenIndex = allTokens.length.sub(1);
uint256 lastToken = allTokens[lastTokenIndex];
allTokens[tokenIndex] = lastToken;
allTokens[lastTokenIndex] = 0;
allTokens.length--;
allTokensIndex[_tokenId] = 0;
allTokensIndex[lastToken] = tokenIndex;
}
}
| contract ERC721Token is SupportsInterfaceWithLookup, ERC721BasicToken, ERC721 {
bytes4 private constant InterfaceId_ERC721Enumerable = 0x780e9d63;
/**
* 0x780e9d63 ===
* bytes4(keccak256('totalSupply()')) ^
* bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) ^
* bytes4(keccak256('tokenByIndex(uint256)'))
*/
bytes4 private constant InterfaceId_ERC721Metadata = 0x5b5e139f;
/**
* 0x5b5e139f ===
* bytes4(keccak256('name()')) ^
* bytes4(keccak256('symbol()')) ^
* bytes4(keccak256('tokenURI(uint256)'))
*/
// Token name
string internal name_;
// Token symbol
string internal symbol_;
// Mapping from owner to list of owned token IDs
mapping(address => uint256[]) internal ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) internal ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] internal allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) internal allTokensIndex;
// Optional mapping for token URIs
mapping(uint256 => string) internal tokenURIs;
/**
* @dev Constructor function
*/
constructor(string _name, string _symbol) public {
name_ = _name;
symbol_ = _symbol;
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(InterfaceId_ERC721Enumerable);
_registerInterface(InterfaceId_ERC721Metadata);
}
/**
* @dev Gets the token name
* @return string representing the token name
*/
function name() external view returns (string) {
return name_;
}
/**
* @dev Gets the token symbol
* @return string representing the token symbol
*/
function symbol() external view returns (string) {
return symbol_;
}
/**
* @dev Returns an URI for a given token ID
* Throws if the token ID does not exist. May return an empty string.
* @param _tokenId uint256 ID of the token to query
*/
function tokenURI(uint256 _tokenId) public view returns (string) {
require(exists(_tokenId));
return tokenURIs[_tokenId];
}
/**
* @dev Gets the token ID at a given index of the tokens list of the requested owner
* @param _owner address owning the tokens list to be accessed
* @param _index uint256 representing the index to be accessed of the requested tokens list
* @return uint256 token ID at the given index of the tokens list owned by the requested address
*/
function tokenOfOwnerByIndex(
address _owner,
uint256 _index
)
public
view
returns (uint256)
{
require(_index < balanceOf(_owner));
return ownedTokens[_owner][_index];
}
/**
* @dev Gets the total amount of tokens stored by the contract
* @return uint256 representing the total amount of tokens
*/
function totalSupply() public view returns (uint256) {
return allTokens.length;
}
/**
* @dev Gets the token ID at a given index of all the tokens in this contract
* Reverts if the index is greater or equal to the total number of tokens
* @param _index uint256 representing the index to be accessed of the tokens list
* @return uint256 token ID at the given index of the tokens list
*/
function tokenByIndex(uint256 _index) public view returns (uint256) {
require(_index < totalSupply());
return allTokens[_index];
}
/**
* @dev Internal function to set the token URI for a given token
* Reverts if the token ID does not exist
* @param _tokenId uint256 ID of the token to set its URI
* @param _uri string URI to assign
*/
function _setTokenURI(uint256 _tokenId, string _uri) internal {
require(exists(_tokenId));
tokenURIs[_tokenId] = _uri;
}
/**
* @dev Internal function to add a token ID to the list of a given address
* @param _to address representing the new owner of the given token ID
* @param _tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function addTokenTo(address _to, uint256 _tokenId) internal {
super.addTokenTo(_to, _tokenId);
uint256 length = ownedTokens[_to].length;
ownedTokens[_to].push(_tokenId);
ownedTokensIndex[_tokenId] = length;
}
/**
* @dev Internal function to remove a token ID from the list of a given address
* @param _from address representing the previous owner of the given token ID
* @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function removeTokenFrom(address _from, uint256 _tokenId) internal {
super.removeTokenFrom(_from, _tokenId);
uint256 tokenIndex = ownedTokensIndex[_tokenId];
uint256 lastTokenIndex = ownedTokens[_from].length.sub(1);
uint256 lastToken = ownedTokens[_from][lastTokenIndex];
ownedTokens[_from][tokenIndex] = lastToken;
ownedTokens[_from][lastTokenIndex] = 0;
// Note that this will handle single-element arrays. In that case, both tokenIndex and lastTokenIndex are going to
// be zero. Then we can make sure that we will remove _tokenId from the ownedTokens list since we are first swapping
// the lastToken to the first position, and then dropping the element placed in the last position of the list
ownedTokens[_from].length--;
ownedTokensIndex[_tokenId] = 0;
ownedTokensIndex[lastToken] = tokenIndex;
}
/**
* @dev Internal function to mint a new token
* Reverts if the given token ID already exists
* @param _to address the beneficiary that will own the minted token
* @param _tokenId uint256 ID of the token to be minted by the msg.sender
*/
function _mint(address _to, uint256 _tokenId) internal {
super._mint(_to, _tokenId);
allTokensIndex[_tokenId] = allTokens.length;
allTokens.push(_tokenId);
}
/**
* @dev Internal function to burn a specific token
* Reverts if the token does not exist
* @param _owner owner of the token to burn
* @param _tokenId uint256 ID of the token being burned by the msg.sender
*/
function _burn(address _owner, uint256 _tokenId) internal {
super._burn(_owner, _tokenId);
// Clear metadata (if any)
if (bytes(tokenURIs[_tokenId]).length != 0) {
delete tokenURIs[_tokenId];
}
// Reorg all tokens array
uint256 tokenIndex = allTokensIndex[_tokenId];
uint256 lastTokenIndex = allTokens.length.sub(1);
uint256 lastToken = allTokens[lastTokenIndex];
allTokens[tokenIndex] = lastToken;
allTokens[lastTokenIndex] = 0;
allTokens.length--;
allTokensIndex[_tokenId] = 0;
allTokensIndex[lastToken] = tokenIndex;
}
}
| 65,424 |
44 | // Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. Beware that changing an allowance with this method brings the risk that someone may use both the oldand the new allowance by unfortunate transaction ordering. One possible solution to mitigate thisrace condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: _spender The address which will spend the funds. _value The amount of tokens to be spent. / | function approve(address _spender, uint256 _value) onlyPayloadSize(2) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
| function approve(address _spender, uint256 _value) onlyPayloadSize(2) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
| 13,623 |
32 | // require(capitalRequirement <= initialMint, "Insufficient capital"); |
BinaryOptionMarket market =
BinaryOptionMarketFactory(binaryOptionMarketFactory).createMarket(
msg.sender,
resolver,
oracleKey,
strikePrice,
[maturity, expiry],
initialMint,
[fees.poolFee, fees.creatorFee],
|
BinaryOptionMarket market =
BinaryOptionMarketFactory(binaryOptionMarketFactory).createMarket(
msg.sender,
resolver,
oracleKey,
strikePrice,
[maturity, expiry],
initialMint,
[fees.poolFee, fees.creatorFee],
| 16,591 |
13 | // Load the 32 bytes word from memory with the address on the lower 20 bytes, and mask those. | sender := and(mload(add(array, index)), 0xffffffffffffffffffffffffffffffffffffffff)
| sender := and(mload(add(array, index)), 0xffffffffffffffffffffffffffffffffffffffff)
| 11,254 |
119 | // Protocols that staking is allowed for. We may not allow all NFTs. | mapping (address => bool) public allowedProtocol;
mapping (address => uint64) public override protocolId;
mapping (uint64 => address) public override protocolAddress;
uint64 protocolCount;
| mapping (address => bool) public allowedProtocol;
mapping (address => uint64) public override protocolId;
mapping (uint64 => address) public override protocolAddress;
uint64 protocolCount;
| 51,007 |
8 | // Modifiers | modifier onlyTokenManager() { if(msg.sender != tokenManager) throw; _; }
modifier onlyCrowdsaleManager() { if(msg.sender != crowdsaleManager) throw; _; }
/*/
* Events
/*/
event LogBuy(address indexed owner, uint etherWeiIncoming, uint tokensSold);
event LogBurn(address indexed owner, uint value);
event LogPhaseSwitch(Phase newPhase);
event LogEscrowWei(uint balanceWei);
event LogEscrowWeiReq(uint balanceWei);
event LogEscrowEth(uint balanceEth);
event LogEscrowEthReq(uint balanceEth);
event LogStartDate(uint newdate, uint oldDate);
/**
* When somebody tries to buy tokens for X eth, calculate how many tokens they get.
*
* @param valueWei - What is the value of the transaction send in as wei
* @return Amount of tokens the investor receives
*/
function calculatePrice(uint valueWei) private constant returns (uint tokenAmount) {
uint res = valueWei * MAPT_IN_ETH;
return res;
}
| modifier onlyTokenManager() { if(msg.sender != tokenManager) throw; _; }
modifier onlyCrowdsaleManager() { if(msg.sender != crowdsaleManager) throw; _; }
/*/
* Events
/*/
event LogBuy(address indexed owner, uint etherWeiIncoming, uint tokensSold);
event LogBurn(address indexed owner, uint value);
event LogPhaseSwitch(Phase newPhase);
event LogEscrowWei(uint balanceWei);
event LogEscrowWeiReq(uint balanceWei);
event LogEscrowEth(uint balanceEth);
event LogEscrowEthReq(uint balanceEth);
event LogStartDate(uint newdate, uint oldDate);
/**
* When somebody tries to buy tokens for X eth, calculate how many tokens they get.
*
* @param valueWei - What is the value of the transaction send in as wei
* @return Amount of tokens the investor receives
*/
function calculatePrice(uint valueWei) private constant returns (uint tokenAmount) {
uint res = valueWei * MAPT_IN_ETH;
return res;
}
| 3,177 |
5 | // calculate the maximum quantity of base assets which may be deposited on behalf of given receiver receiver recipient of shares resulting from depositreturn maxAssets maximum asset deposit amount / | function maxDeposit(address receiver)
| function maxDeposit(address receiver)
| 37,707 |
101 | // Randomly select training indexes | while(t_index < training_partition.length) {
uint random_index = uint(sha256(block.blockhash(block.number-block_i))) % array_length;
training_partition[t_index] = array[random_index];
array[random_index] = array[array_length-1];
array_length--;
block_i++;
t_index++;
}
| while(t_index < training_partition.length) {
uint random_index = uint(sha256(block.blockhash(block.number-block_i))) % array_length;
training_partition[t_index] = array[random_index];
array[random_index] = array[array_length-1];
array_length--;
block_i++;
t_index++;
}
| 17,488 |
58 | // after the claiming operation succeeds | userToNonce[_user] += 1;
| userToNonce[_user] += 1;
| 20,452 |
17 | // Thrown if the deposit amount is zero. | error ZeroAmount();
| error ZeroAmount();
| 8,241 |
14 | // Returns the scaling factor for one of the Pool's tokens. Reverts if `token` is not a token registered by thePool. / | function _scalingFactor(IERC20 token) internal view virtual override returns (uint256) {
// prettier-ignore
if (token == _token0) { return _scalingFactor0; }
else if (token == _token1) { return _scalingFactor1; }
else if (token == _token2) { return _scalingFactor2; }
else if (token == _token3) { return _scalingFactor3; }
else if (token == _token4) { return _scalingFactor4; }
else if (token == _token5) { return _scalingFactor5; }
else if (token == _token6) { return _scalingFactor6; }
else if (token == _token7) { return _scalingFactor7; }
else if (token == _token8) { return _scalingFactor8; }
else if (token == _token9) { return _scalingFactor9; }
else if (token == _token10) { return _scalingFactor10; }
else if (token == _token11) { return _scalingFactor11; }
else if (token == _token12) { return _scalingFactor12; }
else if (token == _token13) { return _scalingFactor13; }
else if (token == _token14) { return _scalingFactor14; }
else if (token == _token15) { return _scalingFactor15; }
else if (token == _token16) { return _scalingFactor16; }
else if (token == _token17) { return _scalingFactor17; }
else if (token == _token18) { return _scalingFactor18; }
else if (token == _token19) { return _scalingFactor19; }
else {
_revert(Errors.INVALID_TOKEN);
}
}
| function _scalingFactor(IERC20 token) internal view virtual override returns (uint256) {
// prettier-ignore
if (token == _token0) { return _scalingFactor0; }
else if (token == _token1) { return _scalingFactor1; }
else if (token == _token2) { return _scalingFactor2; }
else if (token == _token3) { return _scalingFactor3; }
else if (token == _token4) { return _scalingFactor4; }
else if (token == _token5) { return _scalingFactor5; }
else if (token == _token6) { return _scalingFactor6; }
else if (token == _token7) { return _scalingFactor7; }
else if (token == _token8) { return _scalingFactor8; }
else if (token == _token9) { return _scalingFactor9; }
else if (token == _token10) { return _scalingFactor10; }
else if (token == _token11) { return _scalingFactor11; }
else if (token == _token12) { return _scalingFactor12; }
else if (token == _token13) { return _scalingFactor13; }
else if (token == _token14) { return _scalingFactor14; }
else if (token == _token15) { return _scalingFactor15; }
else if (token == _token16) { return _scalingFactor16; }
else if (token == _token17) { return _scalingFactor17; }
else if (token == _token18) { return _scalingFactor18; }
else if (token == _token19) { return _scalingFactor19; }
else {
_revert(Errors.INVALID_TOKEN);
}
}
| 21,841 |
1 | // is every thing okay..? | require(campaign.deadline <block.timestamp, "The deadline should be a date in future.");
campaign.owner = _owner;
campaign.title = _title;
campaign.description = _description;
campaign.target = _target;
campaign.deadline = _deadline;
campaign.amountCollected = 0;
campaign.image = _image;
| require(campaign.deadline <block.timestamp, "The deadline should be a date in future.");
campaign.owner = _owner;
campaign.title = _title;
campaign.description = _description;
campaign.target = _target;
campaign.deadline = _deadline;
campaign.amountCollected = 0;
campaign.image = _image;
| 25,650 |
32 | // Emitted when someone cancels a signature | event SignatureCancelled(address indexed signer, bytes sig);
| event SignatureCancelled(address indexed signer, bytes sig);
| 4,862 |
24 | // Since this is a UUPS Upgradable contract, use deployUUPSProxy | deployUUPSProxy(
"ProjectToken",
abi.encodeWithSelector(
ProjectToken.initialize.selector,
this,
name_,
description_,
symbol_,
maxSupply_,
isFixedSupply_,
| deployUUPSProxy(
"ProjectToken",
abi.encodeWithSelector(
ProjectToken.initialize.selector,
this,
name_,
description_,
symbol_,
maxSupply_,
isFixedSupply_,
| 16,331 |
8 | // Amount of votes that holder has./sender_ address of the holder./ return number of votes. | function votesOf(address sender_) external view returns (uint256);
| function votesOf(address sender_) external view returns (uint256);
| 10,700 |
256 | // Retrieves the value of a storage slot. _contract Address of the contract to query. _key 32 byte key of the storage slot.return _value 32 byte storage slot value. / | function _getContractStorage(
address _contract,
bytes32 _key
)
internal
returns (
bytes32 _value
)
| function _getContractStorage(
address _contract,
bytes32 _key
)
internal
returns (
bytes32 _value
)
| 28,045 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.