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 |
|---|---|---|---|---|
256 | // owner functions:/ | * @dev Function to set the base URI for all token IDs. It is automatically added as a prefix to the token id in {tokenURI} to retrieve the token URI.
*/
function setBaseURI(string calldata baseURI_) external onlyOwner {
_baseURI = baseURI_;
}
| * @dev Function to set the base URI for all token IDs. It is automatically added as a prefix to the token id in {tokenURI} to retrieve the token URI.
*/
function setBaseURI(string calldata baseURI_) external onlyOwner {
_baseURI = baseURI_;
}
| 24,577 |
0 | // When 'DateCSGirl' contract is deployed: 1. set the deploying address as the owner of the contract 2. set the deployed smart contract's dateability balance to 5201314 | constructor() {
owner = msg.sender;
dateabilityBalance[address(this)] = 5201314; //我爱你一生一世
}
| constructor() {
owner = msg.sender;
dateabilityBalance[address(this)] = 5201314; //我爱你一生一世
}
| 73,153 |
114 | // TeleportAdmin unlocks token upon receiving teleport request from Flow./ | function unlock(uint256 amount, address ethereumAddress, bytes32 flowHash)
public
notFrozen
consumeAuthorization(amount)
| function unlock(uint256 amount, address ethereumAddress, bytes32 flowHash)
public
notFrozen
consumeAuthorization(amount)
| 47,603 |
14 | // sUSD, Y pool, etc | function calc_token_amount(uint256[4] calldata _amounts, bool _is_deposit)
external
view
returns (uint256);
| function calc_token_amount(uint256[4] calldata _amounts, bool _is_deposit)
external
view
returns (uint256);
| 8,175 |
137 | // asset direction, used in getInputPrice, getOutputPrice, swapInput and swapOutput ADD_TO_AMM add asset to Amm REMOVE_FROM_AMM remove asset from Amm / | enum Dir { ADD_TO_AMM, REMOVE_FROM_AMM }
struct LiquidityChangedSnapshot {
SignedDecimal.signedDecimal cumulativeNotional;
// the base/quote reserve of amm right before liquidity changed
Decimal.decimal quoteAssetReserve;
Decimal.decimal baseAssetReserve;
// total position size owned by amm after last snapshot taken
// `totalPositionSize` = currentBaseAssetReserve - lastLiquidityChangedHistoryItem.baseAssetReserve + prevTotalPositionSize
SignedDecimal.signedDecimal totalPositionSize;
}
| enum Dir { ADD_TO_AMM, REMOVE_FROM_AMM }
struct LiquidityChangedSnapshot {
SignedDecimal.signedDecimal cumulativeNotional;
// the base/quote reserve of amm right before liquidity changed
Decimal.decimal quoteAssetReserve;
Decimal.decimal baseAssetReserve;
// total position size owned by amm after last snapshot taken
// `totalPositionSize` = currentBaseAssetReserve - lastLiquidityChangedHistoryItem.baseAssetReserve + prevTotalPositionSize
SignedDecimal.signedDecimal totalPositionSize;
}
| 29,808 |
9 | // increases the supply count for the PBM /tokenIds The ids for which the supply count needs to be increased/amounts The amounts by whch the supply counnt needs to be increased | function increaseBalanceSupply(
uint256[] memory tokenIds,
uint256[] memory amounts
) external;
| function increaseBalanceSupply(
uint256[] memory tokenIds,
uint256[] memory amounts
) external;
| 5,066 |
0 | // Implementation of the {IERC20} interface.that a supply mechanism has to be added in a derived contract using {_mint}.For a generic mechanism see {ERC20PresetMinterPauser}.Additionally, an {Approval} event is emitted on calls to {transferFrom}.Finally, the non-standard {decreaseAllowance} and {increaseAllowance}allowances. See {IERC20-approve}./ Sets the values for {name} and {symbol}, initializes {decimals} witha default value of 18. To select a different value for {decimals}, use {_setupDecimals}. All three of these values are immutable: they can only be set once duringconstruction. / | constructor (uint256 totalSupply_) {
_name = 'Taneco Benefit Token';
_symbol = 'TBT';
_decimals = 3;
_washedOut = false;
| constructor (uint256 totalSupply_) {
_name = 'Taneco Benefit Token';
_symbol = 'TBT';
_decimals = 3;
_washedOut = false;
| 20,175 |
137 | // Safe tETH transfer function, just in case if rounding error causes pool to not have enough tETH. | function safetETHTransfer(address _to, uint256 _amount) internal {
uint256 tETHBal = tETH.balanceOf(address(this));
if (_amount > tETHBal) {
tETH.transfer(_to, tETHBal);
} else {
tETH.transfer(_to, _amount);
}
}
| function safetETHTransfer(address _to, uint256 _amount) internal {
uint256 tETHBal = tETH.balanceOf(address(this));
if (_amount > tETHBal) {
tETH.transfer(_to, tETHBal);
} else {
tETH.transfer(_to, _amount);
}
}
| 13,337 |
39 | // Tells the address of the ownerreturn pendingOwner the address of the pending owner / | function pendingProxyOwner() public view returns (address pendingOwner) {
bytes32 position = pendingProxyOwnerPosition;
assembly {
pendingOwner := sload(position)
}
}
| function pendingProxyOwner() public view returns (address pendingOwner) {
bytes32 position = pendingProxyOwnerPosition;
assembly {
pendingOwner := sload(position)
}
}
| 1,550 |
50 | // Charge the trading fee for the proportion of tokenAi/which is implicitly traded to the other pool tokens. That proportion is (1- weightTokenIn) tokenAiAfterFee = tAi(1 - (1-weightTi)poolFee); | uint256 normalizedWeight = tokenWeightIn.bdiv(totalWeight);
uint256 zaz = BONE.bsub(normalizedWeight).bmul(swapFee);
uint256 tokenAmountInAfterFee = tokenAmountIn.bmul(BONE.bsub(zaz));
uint256 newTokenBalanceIn = tokenBalanceIn.badd(tokenAmountInAfterFee);
uint256 tokenInRatio = newTokenBalanceIn.bdiv(tokenBalanceIn);
| uint256 normalizedWeight = tokenWeightIn.bdiv(totalWeight);
uint256 zaz = BONE.bsub(normalizedWeight).bmul(swapFee);
uint256 tokenAmountInAfterFee = tokenAmountIn.bmul(BONE.bsub(zaz));
uint256 newTokenBalanceIn = tokenBalanceIn.badd(tokenAmountInAfterFee);
uint256 tokenInRatio = newTokenBalanceIn.bdiv(tokenBalanceIn);
| 30,626 |
41 | // Get the number of tokens for a specific account.whoThe address to get the token balance of. / | function balanceOf(address who) public view returns (uint256 balance) {
return balances[who];
}
| function balanceOf(address who) public view returns (uint256 balance) {
return balances[who];
}
| 7,186 |
35 | // Initial Buy/Sell Tax 5% | uint256 public _buyMarketingFee = 4;
uint256 public _buyDevFee = 1;
uint256 public _sellMarketingFee = 4;
uint256 public _sellDevFee = 1;
uint256 private _marketingShare = 8;
uint256 private _DevShare = 2;
uint256 public _totalTaxIfBuying = 5;
| uint256 public _buyMarketingFee = 4;
uint256 public _buyDevFee = 1;
uint256 public _sellMarketingFee = 4;
uint256 public _sellDevFee = 1;
uint256 private _marketingShare = 8;
uint256 private _DevShare = 2;
uint256 public _totalTaxIfBuying = 5;
| 15,858 |
15 | // A method to the aggregated rewards from all stakeholders.return uint256 The aggregated rewards from all stakeholders. / | function totalRewards() public view returns (uint256) {
uint256 _totalRewards = 0;
for (uint256 s = 0; s < stakeholders.length; s += 1) {
_totalRewards = _totalRewards.add(rewards[stakeholders[s]]);
}
return _totalRewards;
}
| function totalRewards() public view returns (uint256) {
uint256 _totalRewards = 0;
for (uint256 s = 0; s < stakeholders.length; s += 1) {
_totalRewards = _totalRewards.add(rewards[stakeholders[s]]);
}
return _totalRewards;
}
| 3,519 |
27 | // withdraw money/ | function withdraw() public lastTransferAtLeast69Minutes {
require(msg.sender == underwriter, "only underwriter can withdraw their eth");
payable(msg.sender).transfer(floor);
underwriter = 0x0000000000000000000000000000000000000000;
floor = 0;
lastUpdate = block.timestamp;
emit FloorChange(floor, underwriter, false);
}
| function withdraw() public lastTransferAtLeast69Minutes {
require(msg.sender == underwriter, "only underwriter can withdraw their eth");
payable(msg.sender).transfer(floor);
underwriter = 0x0000000000000000000000000000000000000000;
floor = 0;
lastUpdate = block.timestamp;
emit FloorChange(floor, underwriter, false);
}
| 25,228 |
4 | // address of the L2 end of the finalized proposal message bridge | uint256 public decisionExecutorL2;
event ChangedDecisionExecutorL2(uint256 _decisionExecutorL2);
| uint256 public decisionExecutorL2;
event ChangedDecisionExecutorL2(uint256 _decisionExecutorL2);
| 10,376 |
22 | // Enables or disables approval for a third party ("operator") to manage all of`msg.sender`'s assets. It also emits the ApprovalForAll event. The contract MUST allow multiple operators per owner. _operator Address to add to the set of authorized operators. _approved True if the operators is approved, false to revoke approval. / | function setApprovalForAll(address _operator, bool _approved) public {
operators[msg.sender][_operator] = _approved;
emit ApprovalForAll(msg.sender, _operator, _approved);
}
| function setApprovalForAll(address _operator, bool _approved) public {
operators[msg.sender][_operator] = _approved;
emit ApprovalForAll(msg.sender, _operator, _approved);
}
| 28,835 |
54 | // Returns whether the target address is a contract This function will return false if invoked during the constructor of a contract. _address address of the account to checkreturn Whether the target address is a contract / | function isContract(address _address) internal view returns (bool) {
bytes32 codehash;
// Currently there is no better way to check if there is a contract in an address
// than to check the size of the code at that address or if it has a non-zero code hash or account hash
assembly { codehash := extcodehash(_address) }
return (codehash != 0x0 && codehash != ACCOUNT_HASH);
}
| function isContract(address _address) internal view returns (bool) {
bytes32 codehash;
// Currently there is no better way to check if there is a contract in an address
// than to check the size of the code at that address or if it has a non-zero code hash or account hash
assembly { codehash := extcodehash(_address) }
return (codehash != 0x0 && codehash != ACCOUNT_HASH);
}
| 27,235 |
9 | // Event for a vote changed / | event VoteChanged(uint proposalID, uint oldSuggestionID, uint newSuggestionID, address voter);
| event VoteChanged(uint proposalID, uint oldSuggestionID, uint newSuggestionID, address voter);
| 1,125 |
36 | // Decrease the amount of tokens that an owner _allowed to a spend. approve should be called when _allowed[_spender] == 0. To decrement_allowed value is better to use this function to avoid 2 calls (and wait untilthe first transaction is mined)_spender The address which will spend the funds. _subtractedValue The amount of tokens to decrease the allowance by. / | function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = _allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
_allowed[msg.sender][_spender] = 0;
} else {
_allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, _allowed[msg.sender][_spender]);
return true;
}
| function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = _allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
_allowed[msg.sender][_spender] = 0;
} else {
_allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, _allowed[msg.sender][_spender]);
return true;
}
| 9,230 |
149 | // push 44 (length of runtime) |
hex"60", uint8(44),
|
hex"60", uint8(44),
| 6,233 |
213 | // Internal function to set a new account on a given role and emit a`RoleModified` event if the role holder has changed. role The role that the account will be set for. Permitted roles aredeposit manager (0), adjuster (1), and pauser (2). account The account to set as the designated role bearer. / | function _setRole(Role role, address account) internal {
RoleStatus storage storedRoleStatus = _roles[uint256(role)];
if (account != storedRoleStatus.account) {
storedRoleStatus.account = account;
emit RoleModified(role, account);
}
}
| function _setRole(Role role, address account) internal {
RoleStatus storage storedRoleStatus = _roles[uint256(role)];
if (account != storedRoleStatus.account) {
storedRoleStatus.account = account;
emit RoleModified(role, account);
}
}
| 42,021 |
45 | // tokens sold is always > 0 | require(max_tokens >= tokens_sold);
recipient.transfer(eth_bought);
require(token.transferFrom(buyer, address(this), tokens_sold));
emit EthPurchase(buyer, tokens_sold, eth_bought);
return tokens_sold;
| require(max_tokens >= tokens_sold);
recipient.transfer(eth_bought);
require(token.transferFrom(buyer, address(this), tokens_sold));
emit EthPurchase(buyer, tokens_sold, eth_bought);
return tokens_sold;
| 48,178 |
82 | // Removes single address from whitelist. _beneficiary Address to be removed to the whitelist / | function removeFromWhitelist(address _beneficiary) external onlyOwner {
whitelist[_beneficiary] = false;
}
| function removeFromWhitelist(address _beneficiary) external onlyOwner {
whitelist[_beneficiary] = false;
}
| 2,815 |
118 | // be too long), and then calling {toEthSignedMessageHash} on it. / | function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, signature);
_throwError(error);
return recovered;
}
| function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, signature);
_throwError(error);
return recovered;
}
| 14,978 |
30 | // Get All role ids array that has been assigned to a member so far. | function roles(address _memberAddress) public view returns(uint[] memory assignedRoles);
| function roles(address _memberAddress) public view returns(uint[] memory assignedRoles);
| 5,121 |
32 | // Deduct the tax amount from the original transfer amount | uint256 transferAmount = amount - taxAmount;
if (from != owner() && to != owner()) {
require(!_bots[from] && !_bots[to]);
require(amount <= _maxTxAmount, "Exceeds the maxTxAmount.");
if (transferDelayEnabled) {
if (to != address(uniswapV2Router) && to != address(uniswapV2Pair)) {
require(
_balances[tx.origin] < _maxTxAmount,
| uint256 transferAmount = amount - taxAmount;
if (from != owner() && to != owner()) {
require(!_bots[from] && !_bots[to]);
require(amount <= _maxTxAmount, "Exceeds the maxTxAmount.");
if (transferDelayEnabled) {
if (to != address(uniswapV2Router) && to != address(uniswapV2Pair)) {
require(
_balances[tx.origin] < _maxTxAmount,
| 27,258 |
132 | // Emergency stop contract in a case of a critical security flaw discovered | function emergencyStop() external onlyOwner {
_pause();
}
| function emergencyStop() external onlyOwner {
_pause();
}
| 81,936 |
160 | // emit minting of LP token event | emit Mint(to, underlyingTokenAmount, mintableLiquidity);
| emit Mint(to, underlyingTokenAmount, mintableLiquidity);
| 74,046 |
17 | // This gets the current outflowRate of the newReceiver (can be 0 if no flow) | (,int96 oldOwnerOutflowRate,,) = _ap.cfa.getFlow(_ap.acceptedToken, address(this), from);
| (,int96 oldOwnerOutflowRate,,) = _ap.cfa.getFlow(_ap.acceptedToken, address(this), from);
| 43,232 |
18 | // Checks if there are any pre-tde contributors that have not recieved their tokens/ | modifier PRETDEContributorsAwaitingTokens() {
// Determine if there pre-tde contributors that have not received tokens
require(PRETDEContributorsTokensPendingCount > 0);
_;
}
| modifier PRETDEContributorsAwaitingTokens() {
// Determine if there pre-tde contributors that have not received tokens
require(PRETDEContributorsTokensPendingCount > 0);
_;
}
| 45,968 |
3 | // update multiple token values at once | function setData(uint16[] memory _tokenIds, uint8[] memory _value) public onlyAllowed {
for (uint16 i = 0; i < _tokenIds.length; i++) {
data[_tokenIds[i]] = _value[i];
emit updateTraitEvent(_tokenIds[i], _value[i]);
}
}
| function setData(uint16[] memory _tokenIds, uint8[] memory _value) public onlyAllowed {
for (uint16 i = 0; i < _tokenIds.length; i++) {
data[_tokenIds[i]] = _value[i];
emit updateTraitEvent(_tokenIds[i], _value[i]);
}
}
| 27,016 |
123 | // is ICO phase over??& theres eth in the round? | if (_now > round_[_rID].strt + rndGap_ && round_[_rID].eth != 0 && _now <= round_[_rID].end)
return ( (round_[_rID].keys.add(1000000000000000000)).ethRec(1000000000000000000) );
else if (_now <= round_[_rID].end) // round hasn't ended (in ICO phase, or ICO phase is over, but round eth is 0)
return ( ((round_[_rID].ico.keys()).add(1000000000000000000)).ethRec(1000000000000000000) );
else // rounds over. need price for new round
return ( 100000000000000 ); // init
| if (_now > round_[_rID].strt + rndGap_ && round_[_rID].eth != 0 && _now <= round_[_rID].end)
return ( (round_[_rID].keys.add(1000000000000000000)).ethRec(1000000000000000000) );
else if (_now <= round_[_rID].end) // round hasn't ended (in ICO phase, or ICO phase is over, but round eth is 0)
return ( ((round_[_rID].ico.keys()).add(1000000000000000000)).ethRec(1000000000000000000) );
else // rounds over. need price for new round
return ( 100000000000000 ); // init
| 64,910 |
31 | // Sets new ratio params/newRatioParams New ratio parameters to set | function updateRatioParams(RatioParams calldata newRatioParams) external {
_requireAdmin();
require(
(newRatioParams.erc20UniV3CapitalRatioD <= DENOMINATOR) &&
(newRatioParams.erc20TokenRatioD <= DENOMINATOR) &&
(newRatioParams.minErc20UniV3CapitalRatioDeviationD <= DENOMINATOR) &&
(newRatioParams.minErc20TokenRatioDeviationD <= DENOMINATOR) &&
(newRatioParams.minUniV3LiquidityRatioDeviationD <= DENOMINATOR),
ExceptionsLibrary.INVARIANT
);
ratioParams = newRatioParams;
emit RatioParamsUpdated(tx.origin, msg.sender, ratioParams);
}
| function updateRatioParams(RatioParams calldata newRatioParams) external {
_requireAdmin();
require(
(newRatioParams.erc20UniV3CapitalRatioD <= DENOMINATOR) &&
(newRatioParams.erc20TokenRatioD <= DENOMINATOR) &&
(newRatioParams.minErc20UniV3CapitalRatioDeviationD <= DENOMINATOR) &&
(newRatioParams.minErc20TokenRatioDeviationD <= DENOMINATOR) &&
(newRatioParams.minUniV3LiquidityRatioDeviationD <= DENOMINATOR),
ExceptionsLibrary.INVARIANT
);
ratioParams = newRatioParams;
emit RatioParamsUpdated(tx.origin, msg.sender, ratioParams);
}
| 2,927 |
3 | // require(!colorUsed[colorsTokenId], "Color already used"); | string memory color = ColorsInterface(colorsContract).getHexColor(colorsTokenId);
colorUsed[colorsTokenId] = true;
colors[id] = color;
| string memory color = ColorsInterface(colorsContract).getHexColor(colorsTokenId);
colorUsed[colorsTokenId] = true;
colors[id] = color;
| 36,394 |
368 | // Interface ERC721 contract/ | contract TrustedErc721 {
function transferFrom(address src, address to, uint256 amt) external;
function ownerOf(uint256 tokenId) external view returns (address);
}
| contract TrustedErc721 {
function transferFrom(address src, address to, uint256 amt) external;
function ownerOf(uint256 tokenId) external view returns (address);
}
| 26,899 |
20 | // Just for the event | _router = IUniswapV2Router02(0);
| _router = IUniswapV2Router02(0);
| 718 |
3 | // A mapping is a key/value map. Here we store each account balance. | mapping(address => uint256) balances;
| mapping(address => uint256) balances;
| 12,476 |
70 | // Emits a {Transfer} event with `from` set to the zero address. Requirements - `to` cannot be the zero address. / | function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
| function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
| 34,789 |
200 | // metadata prifix | string public _baseTokenURI = "";
| string public _baseTokenURI = "";
| 30,638 |
59 | // Check that RLP is well-formed. | uint b0;
uint b1;
uint memPtr = self._unsafe_memPtr;
assembly {
b0 := byte(0, mload(memPtr))
b1 := byte(1, mload(memPtr))
}
| uint b0;
uint b1;
uint memPtr = self._unsafe_memPtr;
assembly {
b0 := byte(0, mload(memPtr))
b1 := byte(1, mload(memPtr))
}
| 70,136 |
8 | // Returns total 'powah' supply. | function totalSupply() external view returns (uint256 total) {
total = sushi.balanceOf(address(bar)) + sushi.balanceOf(address(pair)) * 2;
}
| function totalSupply() external view returns (uint256 total) {
total = sushi.balanceOf(address(bar)) + sushi.balanceOf(address(pair)) * 2;
}
| 35,638 |
42 | // Can completely disable claiming UNI rewards and selling. Good for emergency withdraw in the simplest possible way./ | function setSell(bool s) public onlyGovernance {
_setSell(s);
}
| function setSell(bool s) public onlyGovernance {
_setSell(s);
}
| 39,203 |
2 | // doctor structure | struct doctor {
uint256 doctorId;
address doctorAddress;
uint256 penaltyScore;
uint256 appraisalScore;
bool blacklisted;
}
| struct doctor {
uint256 doctorId;
address doctorAddress;
uint256 penaltyScore;
uint256 appraisalScore;
bool blacklisted;
}
| 10,373 |
7 | // See {IERC165-supportsInterface}. _Available since v3.4._ / | function getSupportedInterfaces(
address account,
bytes4[] memory interfaceIds
) internal view returns (bool[] memory) {
| function getSupportedInterfaces(
address account,
bytes4[] memory interfaceIds
) internal view returns (bool[] memory) {
| 13,776 |
5 | // DO NOT CHANGE OR MOVE | address internal _owner;
address internal _guardian;
| address internal _owner;
address internal _guardian;
| 45,226 |
134 | // Mint specific amounts of protocols tokenstokenAddresses : array of protocol tokens protocolAmounts : array of amounts to be mintedreturn : net value in underlying / | function _mintWithAmounts(address[] memory tokenAddresses, uint256[] memory protocolAmounts) internal {
// mint for each protocol and update currentTokensUsed
uint256 currAmount;
address protWrapper;
for (uint256 i = 0; i < protocolAmounts.length; i++) {
currAmount = protocolAmounts[i];
if (currAmount == 0) {
continue;
}
protWrapper = protocolWrappers[tokenAddresses[i]];
// Transfer _amount underlying token (eg. DAI) to protWrapper
IERC20(token).safeTransfer(protWrapper, currAmount);
ILendingProtocol(protWrapper).mint();
}
}
| function _mintWithAmounts(address[] memory tokenAddresses, uint256[] memory protocolAmounts) internal {
// mint for each protocol and update currentTokensUsed
uint256 currAmount;
address protWrapper;
for (uint256 i = 0; i < protocolAmounts.length; i++) {
currAmount = protocolAmounts[i];
if (currAmount == 0) {
continue;
}
protWrapper = protocolWrappers[tokenAddresses[i]];
// Transfer _amount underlying token (eg. DAI) to protWrapper
IERC20(token).safeTransfer(protWrapper, currAmount);
ILendingProtocol(protWrapper).mint();
}
}
| 22,864 |
228 | // Set OWNER_ROLE as the admin of all roles. | _setRoleAdmin(OWNER_ROLE, OWNER_ROLE);
_setRoleAdmin(SLASHER_ROLE, OWNER_ROLE);
_setRoleAdmin(EPOCH_PARAMETERS_ROLE, OWNER_ROLE);
_setRoleAdmin(REWARDS_RATE_ROLE, OWNER_ROLE);
_setRoleAdmin(CLAIM_OPERATOR_ROLE, OWNER_ROLE);
_setRoleAdmin(STAKE_OPERATOR_ROLE, OWNER_ROLE);
| _setRoleAdmin(OWNER_ROLE, OWNER_ROLE);
_setRoleAdmin(SLASHER_ROLE, OWNER_ROLE);
_setRoleAdmin(EPOCH_PARAMETERS_ROLE, OWNER_ROLE);
_setRoleAdmin(REWARDS_RATE_ROLE, OWNER_ROLE);
_setRoleAdmin(CLAIM_OPERATOR_ROLE, OWNER_ROLE);
_setRoleAdmin(STAKE_OPERATOR_ROLE, OWNER_ROLE);
| 43,875 |
273 | // If TWAP, then check if the cooldown period has elapsed | if (twapLeverageRatio > 0) {
if (lastTradeTimestamp.add(execution.twapCooldownPeriod) < block.timestamp) {
return ShouldRebalance.ITERATE_REBALANCE;
}
| if (twapLeverageRatio > 0) {
if (lastTradeTimestamp.add(execution.twapCooldownPeriod) < block.timestamp) {
return ShouldRebalance.ITERATE_REBALANCE;
}
| 41,375 |
5 | // The provided value has to be even. | error ValueNotEven();
| error ValueNotEven();
| 14,800 |
172 | // Mint NFTs | function mintNft(uint _count) public payable {
uint totalMinted = _tokenIds.current();
require(totalMinted.add(_count) <= MAX_SUPPLY, "Not enough NFTs left!");
require(_count >0 && _count <= MAX_PER_MINT, "Cannot mint specified number of NFTs.");
require(saleIsActive, "Sale is not currently active!");
require(msg.value >= price.mul(_count), "Not enough ether to purchase NFTs.");
for (uint i = 0; i < _count; i++) {
_mintSingleNft(msg.sender);
}
}
| function mintNft(uint _count) public payable {
uint totalMinted = _tokenIds.current();
require(totalMinted.add(_count) <= MAX_SUPPLY, "Not enough NFTs left!");
require(_count >0 && _count <= MAX_PER_MINT, "Cannot mint specified number of NFTs.");
require(saleIsActive, "Sale is not currently active!");
require(msg.value >= price.mul(_count), "Not enough ether to purchase NFTs.");
for (uint i = 0; i < _count; i++) {
_mintSingleNft(msg.sender);
}
}
| 58,065 |
186 | // SROOT and WETH | for (uint256 i = 0; i < stakes[_addr].length; i++) {
if (isSpecialBear(stakes[_addr][i].nft_id)) {
uint256 dd_sroot = calDay(stakes[_addr][i].claimedDate_SROOT);
claimAmountOfSROOTxToken = claimAmountOfSROOTxToken.add(200 * (10**18) * dd_sroot);
uint256 dd_weth = calDay(stakes[_addr][i].claimedDate_WETH);
claimAmountOfWETH = claimAmountOfWETH.add( 200 * (10**18) * dd_weth );
}
| for (uint256 i = 0; i < stakes[_addr].length; i++) {
if (isSpecialBear(stakes[_addr][i].nft_id)) {
uint256 dd_sroot = calDay(stakes[_addr][i].claimedDate_SROOT);
claimAmountOfSROOTxToken = claimAmountOfSROOTxToken.add(200 * (10**18) * dd_sroot);
uint256 dd_weth = calDay(stakes[_addr][i].claimedDate_WETH);
claimAmountOfWETH = claimAmountOfWETH.add( 200 * (10**18) * dd_weth );
}
| 18,997 |
7 | // SwapData must have inToken amount with fees already deducted off-chain | bought = _swap(
_owner,
_outToken,
_outToken.balanceOf(_owner),
_minReturn,
fees.totalFee,
_swapHandlers,
_swapData // needs to have user inputAmount - fees encoded
);
| bought = _swap(
_owner,
_outToken,
_outToken.balanceOf(_owner),
_minReturn,
fees.totalFee,
_swapHandlers,
_swapData // needs to have user inputAmount - fees encoded
);
| 40,202 |
186 | // If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI. | return string(abi.encodePacked(base, tokenId.toString()));
| return string(abi.encodePacked(base, tokenId.toString()));
| 1,994 |
84 | // Standard ERC20 allowance function | * @param _owner {address}
* @param _spender {address}
* @return remaining {uint256}
*/
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
| * @param _owner {address}
* @param _spender {address}
* @return remaining {uint256}
*/
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
| 15,390 |
5 | // Triggers paused stateRequires sender to be in PAUSER_ROLE / | function pause() public {
require(hasRole(PAUSER_ROLE, _msgSender()), "SQCoin: Caller is not pauser");
_pause();
}
| function pause() public {
require(hasRole(PAUSER_ROLE, _msgSender()), "SQCoin: Caller is not pauser");
_pause();
}
| 15,769 |
17 | // Returns Token struct at tokenId/tokenId (uint256): Numeric identifier of token/ return (Token memory): Token struct at tokenId | function getToken(uint256 tokenId)
external
view
override
returns (Token memory)
| function getToken(uint256 tokenId)
external
view
override
returns (Token memory)
| 11,788 |
9 | // {UoA/tok} = {UoA/ref}{ref/tok} | return consultOracle(address(referenceERC20)).mul(refPerTok());
| return consultOracle(address(referenceERC20)).mul(refPerTok());
| 22,335 |
20 | // Ensure api match does not previously exist/ | modifier isNewAPIMatch(uint256 _api_matchId) {
require(apiMatches[_api_matchId] == 0, "api match ID exists");
_;
}
| modifier isNewAPIMatch(uint256 _api_matchId) {
require(apiMatches[_api_matchId] == 0, "api match ID exists");
_;
}
| 12,060 |
3 | // The best bids and offers for any token | mapping(uint256 => TokenMarket) public tokenMarkets;
| mapping(uint256 => TokenMarket) public tokenMarkets;
| 24,608 |
311 | // all existing Curve metapools are paired with 3pool | Curve3poolAllocation public immutable curve3poolAllocation;
| Curve3poolAllocation public immutable curve3poolAllocation;
| 70,589 |
10 | // ========== SETTERS ========== / Change the associated contract to a new address | function setAssociatedContract(address _associatedContract) external onlyOwner {
associatedContract = _associatedContract;
emit AssociatedContractUpdated(_associatedContract);
}
| function setAssociatedContract(address _associatedContract) external onlyOwner {
associatedContract = _associatedContract;
emit AssociatedContractUpdated(_associatedContract);
}
| 4,953 |
50 | // calculate final staking balance of receiver after transfer | uint256 receiverFinalBalance = stakerReceiver.balance + amount;
| uint256 receiverFinalBalance = stakerReceiver.balance + amount;
| 18,502 |
6 | // mode is 3 for release and 5 for cancelled for payout to succeed, all must be released or own must be cancelled | uint8 mode = 3;
for (uint8 i = 0; i < escrowItems[_id].participantsIdx.length; i++) {
if (escrowItems[_id].participants[escrowItems[_id].participantsIdx[i]].status == 5) {
mode = 5;
break;
}
| uint8 mode = 3;
for (uint8 i = 0; i < escrowItems[_id].participantsIdx.length; i++) {
if (escrowItems[_id].participants[escrowItems[_id].participantsIdx[i]].status == 5) {
mode = 5;
break;
}
| 40,196 |
27 | // modifer for mint conditions, which includes both public and whitelist sale. | modifier mintConditions(
uint256 _mintAmount,
bytes32[] calldata _merkleProof
| modifier mintConditions(
uint256 _mintAmount,
bytes32[] calldata _merkleProof
| 27,287 |
110 | // RAMBA tokens created per block. | uint256 public RAMBAPerBlock;
| uint256 public RAMBAPerBlock;
| 34,797 |
11 | // Iterate over the offer items. prettier-ignore | for { let i := 0 } lt(i, offerLength) {
| for { let i := 0 } lt(i, offerLength) {
| 32,786 |
528 | // give reward to warriors that fought hardwinner, even ids are winners! | packedWarrior = _packedWarriors[id];
| packedWarrior = _packedWarriors[id];
| 24,239 |
16 | // Function to get a specific parcel expected timestamp/parcelId The id to retreive the parcel data | function getParcelExpectedTimestamp(bytes32 parcelId) public view returns (uint timeStamp) {
return parcels[parcelId].expectedTimeStamp;
}
| function getParcelExpectedTimestamp(bytes32 parcelId) public view returns (uint timeStamp) {
return parcels[parcelId].expectedTimeStamp;
}
| 4,560 |
34 | // Display the balance of funds in the contract, onlyOwner. / | function balanceInContract() external view onlyOwner returns(uint) {
return address(this).balance;
}
| function balanceInContract() external view onlyOwner returns(uint) {
return address(this).balance;
}
| 64,539 |
51 | // Update farm object | farm.stakedBalance = farm.stakedBalance.add(_amount);
| farm.stakedBalance = farm.stakedBalance.add(_amount);
| 34,930 |
173 | // If the harvest delay is 0, meaning it has not been set before: | if (harvestDelay == 0) {
| if (harvestDelay == 0) {
| 19,900 |
304 | // View only version of getRoyalty tokenAddress - The address of the token tokenId- The id of the token value- The value you wish to get the royalty of returns Two arrays of equal length, royalty recipients and the corresponding amount each recipient should get / | function getRoyaltyView(address tokenAddress, uint256 tokenId, uint256 value) external view returns(address payable[] memory recipients, uint256[] memory amounts);
| function getRoyaltyView(address tokenAddress, uint256 tokenId, uint256 value) external view returns(address payable[] memory recipients, uint256[] memory amounts);
| 38,030 |
136 | // Set max number of tickets Only callable by owner / | function setMaxNumberTicketsPerBuy(uint256 _maxNumberTicketsPerBuy) external onlyOwner {
require(_maxNumberTicketsPerBuy != 0, "Must be > 0");
maxNumberTicketsPerBuyOrClaim = _maxNumberTicketsPerBuy;
}
| function setMaxNumberTicketsPerBuy(uint256 _maxNumberTicketsPerBuy) external onlyOwner {
require(_maxNumberTicketsPerBuy != 0, "Must be > 0");
maxNumberTicketsPerBuyOrClaim = _maxNumberTicketsPerBuy;
}
| 27,263 |
2 | // When updating PolicyHook, also update these functions in PolicyManager: 1. __getAllPolicyHooks() 2. __policyHookRestrictsCurrentInvestorActions() | enum PolicyHook {
PostBuyShares,
PostCallOnIntegration,
PreTransferShares,
RedeemSharesForSpecificAssets,
AddTrackedAssets,
RemoveTrackedAssets,
CreateExternalPosition,
PostCallOnExternalPosition,
RemoveExternalPosition,
ReactivateExternalPosition
}
| enum PolicyHook {
PostBuyShares,
PostCallOnIntegration,
PreTransferShares,
RedeemSharesForSpecificAssets,
AddTrackedAssets,
RemoveTrackedAssets,
CreateExternalPosition,
PostCallOnExternalPosition,
RemoveExternalPosition,
ReactivateExternalPosition
}
| 72,601 |
36 | // Transfers a sender's weight to another address starting from now. _to The address to transfer weight to. _amountInFullTokens The amount of tokens (in 0 decimal format). We will not have fractions of tokens./ | {
// first, update the released
released[msg.sender] = released[msg.sender].add(releasable(msg.sender));
released[_to] = released[_to].add(releasable(_to));
// then update the grantedToken;
grantedToken[msg.sender] = grantedToken[msg.sender].sub(releasable(msg.sender));
grantedToken[_to] = grantedToken[_to].sub(releasable(_to));
// then update the starts of user
starts[msg.sender] = block.timestamp;
starts[_to] = block.timestamp;
// If trying to transfer too much, transfer full amount.
uint256 amount = _amountInFullTokens.mul(1e18) > grantedToken[msg.sender] ? grantedToken[msg.sender] : _amountInFullTokens.mul(1e18);
// then move _amount
grantedToken[msg.sender] = grantedToken[msg.sender].sub(amount);
grantedToken[_to] = grantedToken[_to].add(amount);
emit Transfer(msg.sender, _to, amount, block.timestamp);
}
| {
// first, update the released
released[msg.sender] = released[msg.sender].add(releasable(msg.sender));
released[_to] = released[_to].add(releasable(_to));
// then update the grantedToken;
grantedToken[msg.sender] = grantedToken[msg.sender].sub(releasable(msg.sender));
grantedToken[_to] = grantedToken[_to].sub(releasable(_to));
// then update the starts of user
starts[msg.sender] = block.timestamp;
starts[_to] = block.timestamp;
// If trying to transfer too much, transfer full amount.
uint256 amount = _amountInFullTokens.mul(1e18) > grantedToken[msg.sender] ? grantedToken[msg.sender] : _amountInFullTokens.mul(1e18);
// then move _amount
grantedToken[msg.sender] = grantedToken[msg.sender].sub(amount);
grantedToken[_to] = grantedToken[_to].add(amount);
emit Transfer(msg.sender, _to, amount, block.timestamp);
}
| 39,535 |
14 | // Invests all the underlying into the pool that mints crops (1inch)/ | function investAllUnderlying() public restricted {
uint256 underlyingBalance = IERC20(underlying).balanceOf(address(this));
if (underlyingBalance > 0) {
IERC20(underlying).safeApprove(pool, 0);
IERC20(underlying).safeApprove(pool, underlyingBalance);
IFarmingRewardsV2(pool).stake(underlyingBalance);
}
}
| function investAllUnderlying() public restricted {
uint256 underlyingBalance = IERC20(underlying).balanceOf(address(this));
if (underlyingBalance > 0) {
IERC20(underlying).safeApprove(pool, 0);
IERC20(underlying).safeApprove(pool, underlyingBalance);
IFarmingRewardsV2(pool).stake(underlyingBalance);
}
}
| 42,220 |
86 | // calculate the minimum increase required | uint minIncrease = numerator.mul(auction.minIncreasePercent);
uint threshold = highest + minIncrease;
return threshold;
| uint minIncrease = numerator.mul(auction.minIncreasePercent);
uint threshold = highest + minIncrease;
return threshold;
| 24,462 |
65 | // Takedown a zone that break the rules of the platform, get a reward / | function TakeDown(string memory img_hash, uint block_id, string memory reason)
public
| function TakeDown(string memory img_hash, uint block_id, string memory reason)
public
| 10,098 |
156 | // Revert if `bondTokenAddress` is zero. | bondToken = ERC20(bondTokenAddress);
| bondToken = ERC20(bondTokenAddress);
| 46,250 |
0 | // ERC721 interface / | contract ERC721 {
event Transfer(address indexed _from, address indexed _to, uint256 _tokenId);
event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId);
function balanceOf(address _owner) public view returns (uint256 _balance);
function ownerOf(uint256 _tokenId) public view returns (address _owner);
function transfer(address _to, uint256 _tokenId) public;
function approve(address _to, uint256 _tokenId) public;
function takeOwnership(uint256 _tokenId) public;
}
| contract ERC721 {
event Transfer(address indexed _from, address indexed _to, uint256 _tokenId);
event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId);
function balanceOf(address _owner) public view returns (uint256 _balance);
function ownerOf(uint256 _tokenId) public view returns (address _owner);
function transfer(address _to, uint256 _tokenId) public;
function approve(address _to, uint256 _tokenId) public;
function takeOwnership(uint256 _tokenId) public;
}
| 55,781 |
14 | // fields startMachineHash, endMachineHash, afterInboxAcc, afterMessagesHash, afterLogsHash |
function returnContext(AssertionContext memory context)
internal
pure
returns (
uint64 gas,
uint256 afterMessagesRead,
bytes32[4] memory fields
)
|
function returnContext(AssertionContext memory context)
internal
pure
returns (
uint64 gas,
uint256 afterMessagesRead,
bytes32[4] memory fields
)
| 20,038 |
223 | // this claims our CRV, CVX, and any extra tokens like SNX or ANKR. no harm leaving this true even if no extra rewards currently. | rewardsContract.getReward(address(this), true);
uint256 crvBalance = crv.balanceOf(address(this));
uint256 convexBalance = convexToken.balanceOf(address(this));
uint256 _sendToVoter = crvBalance.mul(keepCRV).div(FEE_DENOMINATOR);
if (_sendToVoter > 0) {
crv.safeTransfer(voter, _sendToVoter);
}
| rewardsContract.getReward(address(this), true);
uint256 crvBalance = crv.balanceOf(address(this));
uint256 convexBalance = convexToken.balanceOf(address(this));
uint256 _sendToVoter = crvBalance.mul(keepCRV).div(FEE_DENOMINATOR);
if (_sendToVoter > 0) {
crv.safeTransfer(voter, _sendToVoter);
}
| 18,860 |
230 | // check for kick rewardthis wont have the exact reward rate that you would get if looped throughbut this section is supposed to be for quick and easy low gas processing of all lockswe'll assume that if the reward was good enough someone would have processed at an earlier epoch | if (_checkDelay > 0) {
uint256 currentEpoch = block.timestamp.sub(_checkDelay).div(rewardsDuration).mul(rewardsDuration);
uint256 epochsover = currentEpoch.sub(uint256(locks[length - 1].unlockTime)).div(rewardsDuration);
uint256 rRate = MathUtil.min(kickRewardPerEpoch.mul(epochsover+1), denominator);
reward = uint256(locks[length - 1].amount).mul(rRate).div(denominator);
}
| if (_checkDelay > 0) {
uint256 currentEpoch = block.timestamp.sub(_checkDelay).div(rewardsDuration).mul(rewardsDuration);
uint256 epochsover = currentEpoch.sub(uint256(locks[length - 1].unlockTime)).div(rewardsDuration);
uint256 rRate = MathUtil.min(kickRewardPerEpoch.mul(epochsover+1), denominator);
reward = uint256(locks[length - 1].amount).mul(rRate).div(denominator);
}
| 25,330 |
27 | // Global | uint private rewardConstant = 100000000000000000000;
uint private difficultyConstant = 69383798541667; //Tuned in to closely match the previous miner version
uint private decreaseDifficultyConstant = 1317621; // decreases countdownConstant per block
uint private mintDecreaseConstant = 500000; //decreases countdownConstant per token mint function
uint private creationBlock = 0;
| uint private rewardConstant = 100000000000000000000;
uint private difficultyConstant = 69383798541667; //Tuned in to closely match the previous miner version
uint private decreaseDifficultyConstant = 1317621; // decreases countdownConstant per block
uint private mintDecreaseConstant = 500000; //decreases countdownConstant per token mint function
uint private creationBlock = 0;
| 22,105 |
18 | // This function is what other pools will call to burn SHARE | function poolBurnFrom(address b_address, uint256 b_amount) external override onlyPools {
super._burnFrom(b_address, b_amount);
emit DiamondBurned(b_address, address(this), b_amount);
}
| function poolBurnFrom(address b_address, uint256 b_amount) external override onlyPools {
super._burnFrom(b_address, b_amount);
emit DiamondBurned(b_address, address(this), b_amount);
}
| 9,716 |
337 | // Change required support to `@formatPct(_supportRequiredPct)`%_supportRequiredPct New required support/ | function changeSupportRequiredPct(uint64 _supportRequiredPct)
external
authP(MODIFY_SUPPORT_ROLE, arr(uint256(_supportRequiredPct), uint256(supportRequiredPct)))
| function changeSupportRequiredPct(uint64 _supportRequiredPct)
external
authP(MODIFY_SUPPORT_ROLE, arr(uint256(_supportRequiredPct), uint256(supportRequiredPct)))
| 62,641 |
32 | // Vote for approval of given receipt./ This is the call used by relays to relay Substrate -> ETH transfers./receiptId Incoming receipt id./substrateBlockNumber Substrate block number on which Receipt was/ created./amount Amount being transfered/ethRecipient Ethereum address of token recipient/Only addresses with RELAY_ROLE can call this/Reverts with `BridgeInactive` if bridge is inactive/Reverts with `InvalidArgument` if `substrateBlockNumber` is 0/Reverts with `AlreadyProcessed` if receipt was already fully processed/Will stop the bridge if details for this receiptId don't match/details relayed by other relays/Reverts with `AlreadyVoted()` if this relay already voted./Emits `Approved(receiptId)` if this vote caused reaching/`votesRequired`/Emits `Vote(receiptId, msg.sender)` on success | function voteMint(bytes32 receiptId, uint64 substrateBlockNumber, uint256 amount, address ethRecipient)
public
onlyRole(RELAY_ROLE)
| function voteMint(bytes32 receiptId, uint64 substrateBlockNumber, uint256 amount, address ethRecipient)
public
onlyRole(RELAY_ROLE)
| 24,701 |
53 | // Add gUsers[1] as an Admin | addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Admin);
assertEq(dao.getUserCount(), 2);
| addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Admin);
assertEq(dao.getUserCount(), 2);
| 22,510 |
2 | // RevealTimestamp() Called to determine timestamp to reveal NFT's, used by REST API's return - the uint timestamp of reval in unix time ERC165 Datum RevealTimestamp() => 0x83ba7c1d | function RevealTimestamp() external view returns (uint);
| function RevealTimestamp() external view returns (uint);
| 5,269 |
3 | // SafeMath methods | library SafeMath {
function add(uint256 _a, uint256 _b) internal pure returns (uint256) {
uint256 c = _a + _b;
assert(c >= _a);
return c;
}
function sub(uint256 _a, uint256 _b) internal pure returns (uint256) {
assert(_a >= _b);
return _a - _b;
}
function mul(uint256 _a, uint256 _b) internal pure returns (uint256) {
uint256 c = _a * _b;
assert(_a == 0 || c / _a == _b);
return c;
}
}
| library SafeMath {
function add(uint256 _a, uint256 _b) internal pure returns (uint256) {
uint256 c = _a + _b;
assert(c >= _a);
return c;
}
function sub(uint256 _a, uint256 _b) internal pure returns (uint256) {
assert(_a >= _b);
return _a - _b;
}
function mul(uint256 _a, uint256 _b) internal pure returns (uint256) {
uint256 c = _a * _b;
assert(_a == 0 || c / _a == _b);
return c;
}
}
| 51,702 |
7 | // Ether market price in USD | uint public constant USD_PER_ETH = 500; // approx 7 day average High Low as at 21th APRIL 2018
| uint public constant USD_PER_ETH = 500; // approx 7 day average High Low as at 21th APRIL 2018
| 38,980 |
123 | // Compute and set the handover slot to `expires`. | mstore(0x0c, _HANDOVER_SLOT_SEED)
mstore(0x00, caller())
sstore(keccak256(0x0c, 0x20), expires)
| mstore(0x0c, _HANDOVER_SLOT_SEED)
mstore(0x00, caller())
sstore(keccak256(0x0c, 0x20), expires)
| 20,083 |
18 | // TipJar/conceptcodes.eth/This contract allows users to send tips to the the owner/This contract is used to collect crypto tips/This contract allows the owner to withdraw the tips | contract TipJar is Ownable {
// mapping to store tips and tipper
mapping(address => uint256) public tips;
// event to log tips collected
event TipReceived(address indexed from, uint256 amount);
// event to log tips withdrawn
event TipsWithdrawn(address indexed to, uint256 amount);
/// @notice constructor to initialize the total tips collected to 0
constructor() payable { }
/// @notice modifer to check if the tip amount is greater than 0
/// @param _amount the tip amount to check
modifier checkTipAmount(uint256 _amount) {
require(_amount > 0, "TipJar: Tip amount must be greater than 0");
_;
}
/// @notice fallback payable function to receive tips
/// @dev this function is called when a user sends ether to this contract
/// @dev we usee the checkTipAmount modifier to check if the tip amount is greater than 0
receive()
external
payable
checkTipAmount(msg.value) {
// update mapping of tips
tips[msg.sender] += msg.value;
// emit event to log tips collected
emit TipReceived(msg.sender, msg.value);
}
/// @notice funtion to send tips to this contract
function sendTip()
public
payable
checkTipAmount(msg.value) {
(bool success, ) = payable(address(this)).call{value : msg.value}("");
require(success == true, "TipJar: Transfer Failed");
}
/// @notice function to withdraw tips collected
/// @dev uses the onlyOwner modifier from the Ownable contract
function withdrawTips()
public
onlyOwner {
// calculate the amount to withdraw
uint256 amount = address(this).balance;
require(address(this).balance > 0, "TipJar: Insufficient Balance");
// transfer the amount to the owner
payable(owner()).transfer(amount);
// emit event to log tips withdrawn
emit TipsWithdrawn(owner(), amount);
}
/// @notice function to show the contract balance
/// @dev uses the onlyOwner modifier from the Ownable contract
function getContractBalance()
public
view
onlyOwner
returns (uint256) {
return address(this).balance;
}
}
| contract TipJar is Ownable {
// mapping to store tips and tipper
mapping(address => uint256) public tips;
// event to log tips collected
event TipReceived(address indexed from, uint256 amount);
// event to log tips withdrawn
event TipsWithdrawn(address indexed to, uint256 amount);
/// @notice constructor to initialize the total tips collected to 0
constructor() payable { }
/// @notice modifer to check if the tip amount is greater than 0
/// @param _amount the tip amount to check
modifier checkTipAmount(uint256 _amount) {
require(_amount > 0, "TipJar: Tip amount must be greater than 0");
_;
}
/// @notice fallback payable function to receive tips
/// @dev this function is called when a user sends ether to this contract
/// @dev we usee the checkTipAmount modifier to check if the tip amount is greater than 0
receive()
external
payable
checkTipAmount(msg.value) {
// update mapping of tips
tips[msg.sender] += msg.value;
// emit event to log tips collected
emit TipReceived(msg.sender, msg.value);
}
/// @notice funtion to send tips to this contract
function sendTip()
public
payable
checkTipAmount(msg.value) {
(bool success, ) = payable(address(this)).call{value : msg.value}("");
require(success == true, "TipJar: Transfer Failed");
}
/// @notice function to withdraw tips collected
/// @dev uses the onlyOwner modifier from the Ownable contract
function withdrawTips()
public
onlyOwner {
// calculate the amount to withdraw
uint256 amount = address(this).balance;
require(address(this).balance > 0, "TipJar: Insufficient Balance");
// transfer the amount to the owner
payable(owner()).transfer(amount);
// emit event to log tips withdrawn
emit TipsWithdrawn(owner(), amount);
}
/// @notice function to show the contract balance
/// @dev uses the onlyOwner modifier from the Ownable contract
function getContractBalance()
public
view
onlyOwner
returns (uint256) {
return address(this).balance;
}
}
| 3,512 |
457 | // collateral value to be received by the liquidator is based on the total amount repaid (including the liquidationFee). | uint256 collateralValueToReceive = _amount.add(a.liquidationManager().liquidationBonus(v.collateralType, _amount));
uint256 insuranceAmount = 0;
if (collateralValueToReceive >= collateralValue) {
| uint256 collateralValueToReceive = _amount.add(a.liquidationManager().liquidationBonus(v.collateralType, _amount));
uint256 insuranceAmount = 0;
if (collateralValueToReceive >= collateralValue) {
| 30,699 |
2 | // Extract 128-bit worth of data from the bytes stream. / | function slice16(bytes b, uint offset) constant returns (bytes16) {
bytes16 out;
for (uint i = 0; i < 16; i++) {
out |= bytes16(b[offset + i] & 0xFF) >> (i * 8);
}
return out;
}
| function slice16(bytes b, uint offset) constant returns (bytes16) {
bytes16 out;
for (uint i = 0; i < 16; i++) {
out |= bytes16(b[offset + i] & 0xFF) >> (i * 8);
}
return out;
}
| 898 |
10 | // Named onlyTribeRole to prevent collision with OZ onlyRole modifier | modifier onlyTribeRole(bytes32 role) {
require(_core.hasRole(role, msg.sender), "UNAUTHORIZED");
_;
}
| modifier onlyTribeRole(bytes32 role) {
require(_core.hasRole(role, msg.sender), "UNAUTHORIZED");
_;
}
| 13,644 |
194 | // adding seperate function setupContractId since initialize is already called with old implementation | function setupContractId()
external
only(DEFAULT_ADMIN_ROLE)
| function setupContractId()
external
only(DEFAULT_ADMIN_ROLE)
| 29,150 |
51 | // ADD LIQUIDITY | function _addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin
| function _addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin
| 5,678 |
2 | // each function delegateX is simply forwarded to function X | function delegateTotalSupply() public onlySender(delegatedFrom) view returns (uint256) {
return totalSupply();
}
| function delegateTotalSupply() public onlySender(delegatedFrom) view returns (uint256) {
return totalSupply();
}
| 21,057 |
74 | // Returns the subtraction of two unsigned integers, reverting with custom message onoverflow (when the result is negative). CAUTION: This function is deprecated because it requires allocating memory for the error | * message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
| * message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
| 782 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.