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 |
|---|---|---|---|---|
11 | // adds liquidity to the cherry pool to offer swaps against _amount amount of deposited DAIreturn cherryDaiToMint amount of minted CherryDai / | function mint(uint256 _amount) external returns (uint256) {
require(_amount > 0, "Cherrypool::amount provided must be higher");
// collect liquidity from provider
require(token.transferFrom(msg.sender, address(this), _amount), "Cherrypool::deposit liquidity failed");
// deposit liqudity into compound
token.approve(address(cToken), _amount);
// On compound this function's parameter is defined as the amount of the
// asset to be supplied, in units of the underlying asset. this is the dai amount.
assert(cToken.mint(_amount) == 0);
// Get the pools amount in cTokens.
uint256 cTokensMinted = cToken.balanceOf(address(this));
uint256 _cherryRate;
_cherryRate = exchangeRate();
// mint CherryDai to liquidity provider
uint256 cherryDaiToMint = _amount.mul(1e18).div(_cherryRate);
cherryDai.mint(msg.sender, cherryDaiToMint);
// internal accounting to store pool balances
poolBalance = poolBalance.add(_amount);
poolcBalance = cTokensMinted;
longPoolBalance = longPoolBalance.add(_amount.div(2));
shortPoolBalance = shortPoolBalance.add(_amount.div(2));
emit DepositLiquidity(msg.sender, _amount);
emit MintCherry(msg.sender, _amount, cTokensMinted, cherryDaiToMint);
return cherryDaiToMint;
}
| function mint(uint256 _amount) external returns (uint256) {
require(_amount > 0, "Cherrypool::amount provided must be higher");
// collect liquidity from provider
require(token.transferFrom(msg.sender, address(this), _amount), "Cherrypool::deposit liquidity failed");
// deposit liqudity into compound
token.approve(address(cToken), _amount);
// On compound this function's parameter is defined as the amount of the
// asset to be supplied, in units of the underlying asset. this is the dai amount.
assert(cToken.mint(_amount) == 0);
// Get the pools amount in cTokens.
uint256 cTokensMinted = cToken.balanceOf(address(this));
uint256 _cherryRate;
_cherryRate = exchangeRate();
// mint CherryDai to liquidity provider
uint256 cherryDaiToMint = _amount.mul(1e18).div(_cherryRate);
cherryDai.mint(msg.sender, cherryDaiToMint);
// internal accounting to store pool balances
poolBalance = poolBalance.add(_amount);
poolcBalance = cTokensMinted;
longPoolBalance = longPoolBalance.add(_amount.div(2));
shortPoolBalance = shortPoolBalance.add(_amount.div(2));
emit DepositLiquidity(msg.sender, _amount);
emit MintCherry(msg.sender, _amount, cTokensMinted, cherryDaiToMint);
return cherryDaiToMint;
}
| 34,011 |
18 | // total RFV deployed into lending pool | uint256 public totalValueDeployed;
| uint256 public totalValueDeployed;
| 38,879 |
3 | // The number of function selectors in selectorSlots | uint16 selectorCount;
| uint16 selectorCount;
| 20,220 |
54 | // Buddy | if (hasBuddy) {
for (uint256 i = renderPathIndex["buddy"].startIndex; i <= renderPathIndex["buddy"].endIndex; i++) {
output = string.concat(output, makePath(i, tokenId));
}
| if (hasBuddy) {
for (uint256 i = renderPathIndex["buddy"].startIndex; i <= renderPathIndex["buddy"].endIndex; i++) {
output = string.concat(output, makePath(i, tokenId));
}
| 24,350 |
64 | // both sides safe | require(srcTotalDebtIssued <= multiply(srcSAFE.lockedCollateral, collateralType_.safetyPrice), "SAFEEngine/not-safe-src");
require(dstTotalDebtIssued <= multiply(dstSAFE.lockedCollateral, collateralType_.safetyPrice), "SAFEEngine/not-safe-dst");
| require(srcTotalDebtIssued <= multiply(srcSAFE.lockedCollateral, collateralType_.safetyPrice), "SAFEEngine/not-safe-src");
require(dstTotalDebtIssued <= multiply(dstSAFE.lockedCollateral, collateralType_.safetyPrice), "SAFEEngine/not-safe-dst");
| 36,935 |
19 | // get if msg.sender has claim in the current phase/ | function hasClaimed() external view returns (bool) {
return isClaimed[phaseForClaim][msg.sender];
}
| function hasClaimed() external view returns (bool) {
return isClaimed[phaseForClaim][msg.sender];
}
| 31,006 |
57 | // The new observation for each symbolHash | mapping(bytes32 => Observation) public newObservations;
| mapping(bytes32 => Observation) public newObservations;
| 54,760 |
165 | // relayCall()'s msg.data upper bound gas cost per byte | uint256 dataGasCostPerByte;
| uint256 dataGasCostPerByte;
| 11,212 |
21 | // APPROVE ARBITRATOR/ | function Approve(uint256 _bondnum) external returns(bool){
/*bond beneficiary approve*/
if(spec[_bondnum].BondBeneficiary == msg.sender){
agree[_bondnum].Beneficiary = true;
}
/*bond writer approve*/
if(spec[_bondnum].BondWriter == msg.sender){
agree[_bondnum].Writer = true;
}
return true;
}
| function Approve(uint256 _bondnum) external returns(bool){
/*bond beneficiary approve*/
if(spec[_bondnum].BondBeneficiary == msg.sender){
agree[_bondnum].Beneficiary = true;
}
/*bond writer approve*/
if(spec[_bondnum].BondWriter == msg.sender){
agree[_bondnum].Writer = true;
}
return true;
}
| 51,027 |
40 | // We've got some shared nibbles between the last node and our key remainder. We'll need to insert an extension node that covers these shared nibbles. | bytes memory nextNodeKey = Lib_BytesUtils.slice(lastNodeKey, 0, sharedNibbleLength);
newNodes[totalNewNodes] = _makeExtensionNode(nextNodeKey, _getNodeHash(_value));
totalNewNodes += 1;
| bytes memory nextNodeKey = Lib_BytesUtils.slice(lastNodeKey, 0, sharedNibbleLength);
newNodes[totalNewNodes] = _makeExtensionNode(nextNodeKey, _getNodeHash(_value));
totalNewNodes += 1;
| 12,478 |
18 | // To change the approve amount you first have to reduce the addresses`allowance to zero by calling `approve(_spender, 0)` if it is notalready 0 to mitigate the race condition described here:https:github.com/ethereum/EIPs/issues/20issuecomment-263524729 | require((_value == 0) || (allowed[msg.sender][_spender] == 0));
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
| require((_value == 0) || (allowed[msg.sender][_spender] == 0));
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
| 3,040 |
1 | // PUBLIC / | function initialize(address admin) public initializer {
__AccessControl_init();
_setupRole(DEFAULT_ADMIN_ROLE, admin);
_setupRole(UPDATER_ROLE, admin);
}
| function initialize(address admin) public initializer {
__AccessControl_init();
_setupRole(DEFAULT_ADMIN_ROLE, admin);
_setupRole(UPDATER_ROLE, admin);
}
| 34,257 |
5 | // adding voters in the list | function Add_voter (address _voter ,string memory _name,bool _elegiable) public{
bool new_voter = true;
require( msg.sender == chairperson, ' you are not authorized Persons' );
require(voting == false ,'during voting no new voter can be added' );
for (uint j = 1;j<=voter_count;j++){
if (voter_list[j] == _voter){
new_voter = false;
}
}
// adding voter is allowed once
require(new_voter == true,'voter allready added to the list');
voter_count += 1;
voter_list[voter_count] = _voter;
Voters[_voter].voter_name = _name;
Voters[_voter].voted = 0;
Voters[_voter].elegiable = _elegiable;
}
| function Add_voter (address _voter ,string memory _name,bool _elegiable) public{
bool new_voter = true;
require( msg.sender == chairperson, ' you are not authorized Persons' );
require(voting == false ,'during voting no new voter can be added' );
for (uint j = 1;j<=voter_count;j++){
if (voter_list[j] == _voter){
new_voter = false;
}
}
// adding voter is allowed once
require(new_voter == true,'voter allready added to the list');
voter_count += 1;
voter_list[voter_count] = _voter;
Voters[_voter].voter_name = _name;
Voters[_voter].voted = 0;
Voters[_voter].elegiable = _elegiable;
}
| 34,022 |
114 | // column6_row0/ mload(0x2e80), pedersen/hash0/ec_subset_sum/bit_neg_0 = 1 - pedersen__hash0__ec_subset_sum__bit_0. | let val := addmod(
1,
sub(PRIME, /*intermediate_value/pedersen/hash0/ec_subset_sum/bit_0*/ mload(0x41a0)),
PRIME)
mstore(0x41c0, val)
| let val := addmod(
1,
sub(PRIME, /*intermediate_value/pedersen/hash0/ec_subset_sum/bit_0*/ mload(0x41a0)),
PRIME)
mstore(0x41c0, val)
| 20,669 |
26 | // Sell `_amount` tokens to contract/_amount Amount of tokens to be sold | function sell(uint256 _amount) {
require(sellPrice > 0);
require(this.balance >= _amount * sellPrice); // checks if the contract has enough ether to buy
_transfer(msg.sender, this, _amount); // makes the transfers
msg.sender.transfer(_amount * sellPrice); // sends ether to the seller. It's important to do this last to avoid recursion attacks
}
| function sell(uint256 _amount) {
require(sellPrice > 0);
require(this.balance >= _amount * sellPrice); // checks if the contract has enough ether to buy
_transfer(msg.sender, this, _amount); // makes the transfers
msg.sender.transfer(_amount * sellPrice); // sends ether to the seller. It's important to do this last to avoid recursion attacks
}
| 2,658 |
22 | // Only allow deposits if the contract hasn't already purchased the tokens. | if (!bought_tokens) {
| if (!bought_tokens) {
| 7,462 |
14 | // Last timestamp when the funding receiver data was updated | uint256 lastUpdateTime; // [unix timestamp]
| uint256 lastUpdateTime; // [unix timestamp]
| 50,740 |
171 | // Withdraw stake from BaseRewardPool, remove liquidity and convert one asset to another. /minToken0AmountConverted The minimum amount of token0 received when removing liquidity /minToken1AmountConverted The minimum amount of token1 received when removing liquidity /amount Amount of stake to withdraw function withdrawWithNative( uint256 minToken0AmountConverted, uint256 minToken1AmountConverted, uint256 amount | // ) public nonReentrant updateReward(msg.sender) {
// revert("Not supported");
// }
| // ) public nonReentrant updateReward(msg.sender) {
// revert("Not supported");
// }
| 6,875 |
71 | // Removes discount for concrete buyer. _buyer the address for which the discount will be removed. / | function removeExistingDiscount(address _buyer) internal {
delete(discounts[_buyer]);
}
| function removeExistingDiscount(address _buyer) internal {
delete(discounts[_buyer]);
}
| 39,735 |
13 | // Function to send a batch of NFTs to a user account Batch is minted to recipient's account To be used for NFT giveaways and promotions | function sendPack(uint256[] memory packId, address[] memory recipient) public onlyOwner {
require(packId.length == recipient.length, "Mismatched ID and Address array sizes");
for(uint i = 0; i < packId.length; i++) {
require(batchesForSale[packId[i]].isSold == false, "Pack has already been sold.");
batchesForSale[packId[i]].isSold = true;
// Take pack off of marketplace
for(uint256 j = 0; i < batchesForSale[packId[i]].tokenIds.length; j++) {
isLocal[batchesForSale[packId[i]].tokenIds[j]][recipient[i]] = true;
itemsForSale[batchesForSale[packId[i]].tokenIds[j]].owner = payable(recipient[i]);
}
safeBatchTransferFrom(_msgSender(), recipient[i], batchesForSale[packId[i]].tokenIds, batchesForSale[packId[i]].amounts, data);
}
}
| function sendPack(uint256[] memory packId, address[] memory recipient) public onlyOwner {
require(packId.length == recipient.length, "Mismatched ID and Address array sizes");
for(uint i = 0; i < packId.length; i++) {
require(batchesForSale[packId[i]].isSold == false, "Pack has already been sold.");
batchesForSale[packId[i]].isSold = true;
// Take pack off of marketplace
for(uint256 j = 0; i < batchesForSale[packId[i]].tokenIds.length; j++) {
isLocal[batchesForSale[packId[i]].tokenIds[j]][recipient[i]] = true;
itemsForSale[batchesForSale[packId[i]].tokenIds[j]].owner = payable(recipient[i]);
}
safeBatchTransferFrom(_msgSender(), recipient[i], batchesForSale[packId[i]].tokenIds, batchesForSale[packId[i]].amounts, data);
}
}
| 22,203 |
139 | // Mapping from token ID to the creator's address. | mapping(uint256 => address) private tokenCreators;
| mapping(uint256 => address) private tokenCreators;
| 44,234 |
56 | // Returns the integer division of two unsigned integers, reverting with custom message ondivision by zero. The result is rounded towards zero. Counterpart to Solidity's `%` operator. This function uses a `revert`opcode (which leaves remaining gas untouched) while Solidity uses aninvalid opcode to revert (consuming all remaining gas). Counterpart to Solidity's `/` operator. Note: this function uses a`revert` opcode (which leaves remaining gas untouched) while Solidityuses an invalid opcode to revert (consuming all remaining gas). Requirements: - The divisor cannot be zero. / | function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
| function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
| 2,660 |
188 | // Updating Request | TellorStorage.Request storage _tblock = self.requestDetails[self.uintVars[_tBlock]];
_tblock.minersByValue[1][_slotProgress]= msg.sender;
| TellorStorage.Request storage _tblock = self.requestDetails[self.uintVars[_tBlock]];
_tblock.minersByValue[1][_slotProgress]= msg.sender;
| 41,773 |
231 | // CLRt+1 = max(MINLR, min(MAXLR, CLRt(1 - RS) + TLRRS)) a: TLRRS b: (1- RS)CLRt c: (1- RS)CLRt + TLRRS d: min(MAXLR, CLRt(1 - RS) + TLRRS) | uint256 a = methodology.targetLeverageRatio.preciseMul(methodology.recenteringSpeed);
uint256 b = PreciseUnitMath.preciseUnit().sub(methodology.recenteringSpeed).preciseMul(_currentLeverageRatio);
uint256 c = a.add(b);
uint256 d = Math.min(c, methodology.maxLeverageRatio);
return Math.max(methodology.minLeverageRatio, d);
| uint256 a = methodology.targetLeverageRatio.preciseMul(methodology.recenteringSpeed);
uint256 b = PreciseUnitMath.preciseUnit().sub(methodology.recenteringSpeed).preciseMul(_currentLeverageRatio);
uint256 c = a.add(b);
uint256 d = Math.min(c, methodology.maxLeverageRatio);
return Math.max(methodology.minLeverageRatio, d);
| 38,941 |
10 | // If Gas receipt is being passed | if (metaTag == METATRANSFER_FLAG) {
(bytes4 metaTag, GasReceipt memory gasTx, bytes memory _data) = abi.decode(_data, (bytes4, GasReceipt, bytes));
transferData = validateTransferSignature(_from, _to, _id, _value, _data);
} else {
| if (metaTag == METATRANSFER_FLAG) {
(bytes4 metaTag, GasReceipt memory gasTx, bytes memory _data) = abi.decode(_data, (bytes4, GasReceipt, bytes));
transferData = validateTransferSignature(_from, _to, _id, _value, _data);
} else {
| 13,699 |
7 | // First get the amount of tokens sold from the beginning of this generation and the amount left. | uint currentGeneration = amountSoldStart / tokensPerGeneration;
uint amountLeftInCurrentGeneration = tokensPerGeneration - (amountSoldStart % tokensPerGeneration);
| uint currentGeneration = amountSoldStart / tokensPerGeneration;
uint amountLeftInCurrentGeneration = tokensPerGeneration - (amountSoldStart % tokensPerGeneration);
| 17,133 |
299 | // Total currently in queue | uint256 Amount;
| uint256 Amount;
| 84,854 |
13 | // This is the whitelist of users who are registered to be able to own the tokens | mapping (address => bool) public isOnList;
| mapping (address => bool) public isOnList;
| 9,153 |
0 | // address when calling {latestResolver}. It takes the answer from {latestRoundData}mandatory to wrap its answer into a function mimicking {latestRoundData}(See {latestResolver} implementation)./ Returns USD values decimalsmeaning that 1.00 USD <=> 1E18. / | function decimalsUSD()
external
pure
returns (uint8)
{
return _decimalsUSD;
}
| function decimalsUSD()
external
pure
returns (uint8)
{
return _decimalsUSD;
}
| 37,684 |
71 | // Sets `adminRole` as ``role``'s admin role. / | function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
_roles[role].adminRole = adminRole;
}
| function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
_roles[role].adminRole = adminRole;
}
| 22,461 |
18 | // Give back the last bidders money | if (winning != address(0)) {
require(block.timestamp >= startTime, "Auction not started");
require(block.timestamp < endTime, "Auction ended");
uint8 base = 100;
uint256 multiplier = base.add(percentageIncreasePerBid);
require(msg.value >= lastBid.mul(multiplier).div(100), "Bid too small"); // % increase
winning.transfer(lastBid);
} else {
| if (winning != address(0)) {
require(block.timestamp >= startTime, "Auction not started");
require(block.timestamp < endTime, "Auction ended");
uint8 base = 100;
uint256 multiplier = base.add(percentageIncreasePerBid);
require(msg.value >= lastBid.mul(multiplier).div(100), "Bid too small"); // % increase
winning.transfer(lastBid);
} else {
| 9,915 |
30 | // creates the token to be sold. override this method to have crowdsale of a specific mintable token. | function createTokenContract() internal returns (MintableToken) {
return new MintableToken();
}
| function createTokenContract() internal returns (MintableToken) {
return new MintableToken();
}
| 854 |
87 | // Gets all the bid data related to a token/tokenId The id of the token/ return bid information | function getBidData(uint256 tokenId) view public returns (bool hasBid, address bidder, uint value) {
Bid memory bid = tokenBids[tokenId];
hasBid = bid.hasBid;
bidder = bid.bidder;
value = bid.value;
}
| function getBidData(uint256 tokenId) view public returns (bool hasBid, address bidder, uint value) {
Bid memory bid = tokenBids[tokenId];
hasBid = bid.hasBid;
bidder = bid.bidder;
value = bid.value;
}
| 6,899 |
13 | // NOTE: Whenever modifying the storage layout here it is important to update the validateStorageLayout function in its respective mock contract to ensure that it doesn't break anything or lead to unexpected behaviors/layout when upgrading |
uint256 internal _reserve22;
uint256 private _reserve23;
uint256 private _reserve24;
uint256 private _reserve25;
uint256 private _reserve26;
uint256 private _reserve27;
uint256 private _reserve28;
uint256 private _reserve29;
uint256 private _reserve30;
|
uint256 internal _reserve22;
uint256 private _reserve23;
uint256 private _reserve24;
uint256 private _reserve25;
uint256 private _reserve26;
uint256 private _reserve27;
uint256 private _reserve28;
uint256 private _reserve29;
uint256 private _reserve30;
| 23,347 |
17 | // Upgrade to the new target | _target = Proxyable(_owner.getTargetAddress());
| _target = Proxyable(_owner.getTargetAddress());
| 6,788 |
120 | // set instance type | bytes4 instanceType = bytes4(keccak256(bytes('Post')));
| bytes4 instanceType = bytes4(keccak256(bytes('Post')));
| 31,040 |
0 | // ===================================== proof of stake (defaults at 50 tokens) | uint public stakingRequirement = 50e18;
| uint public stakingRequirement = 50e18;
| 28,475 |
132 | // total fees | function totalFees() external view returns (uint256) {
return _tFeeTotal;
}
| function totalFees() external view returns (uint256) {
return _tFeeTotal;
}
| 38,854 |
178 | // ======================================= | {
bankrollAddress = _bankrollAddress;
divCardContract = ZethrDividendCards(_divCardAddress);
administrators[0x4F4eBF556CFDc21c3424F85ff6572C77c514Fcae] = true;
// Norsefire
administrators[0x11e52c75998fe2E7928B191bfc5B25937Ca16741] = true;
// klob
administrators[0x20C945800de43394F70D789874a4daC9cFA57451] = true;
// Etherguy
administrators[0xef764BAC8a438E7E498c2E5fcCf0f174c3E3F8dB] = true;
// blurr
administrators[0x8537aa2911b193e5B377938A723D805bb0865670] = true;
// oguzhanox
administrators[0x9D221b2100CbE5F05a0d2048E2556a6Df6f9a6C3] = true;
// Randall
administrators[0xDa83156106c4dba7A26E9bF2Ca91E273350aa551] = true;
// TropicalRogue
administrators[0x71009e9E4e5e68e77ECc7ef2f2E95cbD98c6E696] = true;
// cryptodude
administrators[msg.sender] = true;
// Helps with debugging!
validDividendRates_[2] = true;
validDividendRates_[5] = true;
validDividendRates_[10] = true;
validDividendRates_[15] = true;
validDividendRates_[20] = true;
validDividendRates_[25] = true;
validDividendRates_[33] = true;
userSelectedRate[bankrollAddress] = true;
userDividendRate[bankrollAddress] = 33;
}
| {
bankrollAddress = _bankrollAddress;
divCardContract = ZethrDividendCards(_divCardAddress);
administrators[0x4F4eBF556CFDc21c3424F85ff6572C77c514Fcae] = true;
// Norsefire
administrators[0x11e52c75998fe2E7928B191bfc5B25937Ca16741] = true;
// klob
administrators[0x20C945800de43394F70D789874a4daC9cFA57451] = true;
// Etherguy
administrators[0xef764BAC8a438E7E498c2E5fcCf0f174c3E3F8dB] = true;
// blurr
administrators[0x8537aa2911b193e5B377938A723D805bb0865670] = true;
// oguzhanox
administrators[0x9D221b2100CbE5F05a0d2048E2556a6Df6f9a6C3] = true;
// Randall
administrators[0xDa83156106c4dba7A26E9bF2Ca91E273350aa551] = true;
// TropicalRogue
administrators[0x71009e9E4e5e68e77ECc7ef2f2E95cbD98c6E696] = true;
// cryptodude
administrators[msg.sender] = true;
// Helps with debugging!
validDividendRates_[2] = true;
validDividendRates_[5] = true;
validDividendRates_[10] = true;
validDividendRates_[15] = true;
validDividendRates_[20] = true;
validDividendRates_[25] = true;
validDividendRates_[33] = true;
userSelectedRate[bankrollAddress] = true;
userDividendRate[bankrollAddress] = 33;
}
| 18,774 |
45 | // Applies accrued interest to total borrows and reserves. This calculates interest accrued from the last checkpointed block up to the current block and writes new checkpoint to storage. / | function accrueInterest() public returns (uint256) {
delegateAndReturn();
}
| function accrueInterest() public returns (uint256) {
delegateAndReturn();
}
| 5,259 |
216 | // isInList(left) and isInList(right) are checked in remove |
address previousRight = self.list[right].previous;
remove(self, right);
insertAfter(self, left, right);
remove(self, left);
insertAfter(self, previousRight, left);
|
address previousRight = self.list[right].previous;
remove(self, right);
insertAfter(self, left, right);
remove(self, left);
insertAfter(self, previousRight, left);
| 41,609 |
3 | // Deploy a new contract for the new vault. | function deploy(
Vault.Parameters calldata _vaultParameters,
bytes calldata _validatorParameters
) external returns (address);
| function deploy(
Vault.Parameters calldata _vaultParameters,
bytes calldata _validatorParameters
) external returns (address);
| 10,600 |
809 | // Unstaked | else {
require(EvoSnails.ownerOf(_id) == msg.sender, "not owner");
}
| else {
require(EvoSnails.ownerOf(_id) == msg.sender, "not owner");
}
| 28,814 |
150 | // Store date for lock-up calculation | WithdrawalRequest storage withdrawalReq = withdrawalRequest[_msgSender()];
withdrawalReq.lastStakedBlock = rewards._getBlock();
emit IncreasedServiceProviderBond(serviceProvider, rewardsProgrammeId, _amount, delegatedStake[serviceProvider]);
| WithdrawalRequest storage withdrawalReq = withdrawalRequest[_msgSender()];
withdrawalReq.lastStakedBlock = rewards._getBlock();
emit IncreasedServiceProviderBond(serviceProvider, rewardsProgrammeId, _amount, delegatedStake[serviceProvider]);
| 26,589 |
36 | // This function makes it easy to get the total number of tokens/ return The total number of tokens | function totalSupply() public constant returns (uint256) {
return totalSupplyAt(block.number);
}
| function totalSupply() public constant returns (uint256) {
return totalSupplyAt(block.number);
}
| 11,003 |
22 | // Set new price impact basis points value. newBasisPoints New price impact basis points value. / | function setPriceImpactBasisPoints(uint256 newBasisPoints) external onlyOwner {
require(
newBasisPoints < 1500,
"TreasuryHandlerAlpha:setPriceImpactBasisPoints:OUT_OF_BOUNDS: Cannot set price impact too high."
);
uint256 oldBasisPoints = priceImpactBasisPoints;
priceImpactBasisPoints = newBasisPoints;
emit PriceImpactBasisPointsUpdated(oldBasisPoints, newBasisPoints);
}
| function setPriceImpactBasisPoints(uint256 newBasisPoints) external onlyOwner {
require(
newBasisPoints < 1500,
"TreasuryHandlerAlpha:setPriceImpactBasisPoints:OUT_OF_BOUNDS: Cannot set price impact too high."
);
uint256 oldBasisPoints = priceImpactBasisPoints;
priceImpactBasisPoints = newBasisPoints;
emit PriceImpactBasisPointsUpdated(oldBasisPoints, newBasisPoints);
}
| 59,269 |
1,111 | // implementation from https:github.com/Uniswap/uniswap-lib/commit/99f3f28770640ba1bb1ff460ac7c5292fb8291a0 original implementation: https:github.com/abdk-consulting/abdk-libraries-solidity/blob/master/ABDKMath64x64.solL687 | function sqrt(uint x) internal pure returns (uint) {
if (x == 0) return 0;
uint xx = x;
uint r = 1;
if (xx >= 0x100000000000000000000000000000000) {
xx >>= 128;
r <<= 64;
}
if (xx >= 0x10000000000000000) {
xx >>= 64;
r <<= 32;
}
if (xx >= 0x100000000) {
xx >>= 32;
r <<= 16;
}
if (xx >= 0x10000) {
xx >>= 16;
r <<= 8;
}
if (xx >= 0x100) {
xx >>= 8;
r <<= 4;
}
if (xx >= 0x10) {
xx >>= 4;
r <<= 2;
}
if (xx >= 0x8) {
r <<= 1;
}
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1; // Seven iterations should be enough
uint r1 = x / r;
return (r < r1 ? r : r1);
}
| function sqrt(uint x) internal pure returns (uint) {
if (x == 0) return 0;
uint xx = x;
uint r = 1;
if (xx >= 0x100000000000000000000000000000000) {
xx >>= 128;
r <<= 64;
}
if (xx >= 0x10000000000000000) {
xx >>= 64;
r <<= 32;
}
if (xx >= 0x100000000) {
xx >>= 32;
r <<= 16;
}
if (xx >= 0x10000) {
xx >>= 16;
r <<= 8;
}
if (xx >= 0x100) {
xx >>= 8;
r <<= 4;
}
if (xx >= 0x10) {
xx >>= 4;
r <<= 2;
}
if (xx >= 0x8) {
r <<= 1;
}
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1; // Seven iterations should be enough
uint r1 = x / r;
return (r < r1 ? r : r1);
}
| 49,007 |
5 | // NFT => (borrower, due_date) | mapping(uint256 => borrowInfo) public borrow_status;
| mapping(uint256 => borrowInfo) public borrow_status;
| 17,020 |
26 | // Total amount of shares . / | function totalShares() external view virtual returns (uint256) {
return _totalShares;
}
| function totalShares() external view virtual returns (uint256) {
return _totalShares;
}
| 77,152 |
1 | // Public functions //Returns natural exponential function value of given x/x x/ return ex | function exp(int x)
public
constant
returns (uint)
| function exp(int x)
public
constant
returns (uint)
| 45,716 |
91 | // _TABLE FUNCTIONS | function getTableMetadata(bytes32 _tableKey)
view
public
returns (uint256 permission, address delegate)
| function getTableMetadata(bytes32 _tableKey)
view
public
returns (uint256 permission, address delegate)
| 11,740 |
70 | // List of agents that are allowed to create new tokens // inPercentageUnit is percents of tokens multiplied to 10 up to percents decimals. For example, for reserved tokens in percents 2.54% inPercentageUnit = 254 inPercentageDecimals = 2/ | struct ReservedTokensData {
uint inTokens;
uint inPercentageUnit;
uint inPercentageDecimals;
bool isReserved;
bool isDistributed;
}
| struct ReservedTokensData {
uint inTokens;
uint inPercentageUnit;
uint inPercentageDecimals;
bool isReserved;
bool isDistributed;
}
| 5,064 |
18 | // ERC Token Standard 20 - https:github.com/ethereum/EIPs/issues/20 | contract ERC20Token {
// ------------------------------------------------------------------------
// Balances for each account
// ------------------------------------------------------------------------
mapping(address => uint) balances;
// ------------------------------------------------------------------------
// Owner of account approves the transfer of an amount to another account
// ------------------------------------------------------------------------
mapping(address => mapping (address => uint)) allowed;
// ------------------------------------------------------------------------
// Total token supply
// ------------------------------------------------------------------------
uint public totalSupply;
// ------------------------------------------------------------------------
// Get the account balance of another account with address _owner
// ------------------------------------------------------------------------
function balanceOf(address _owner) constant returns (uint balance) {
return balances[_owner];
}
// ------------------------------------------------------------------------
// Transfer the balance from owner's account to another account
// ------------------------------------------------------------------------
function transfer(address _to, uint _amount) returns (bool success) {
if (balances[msg.sender] >= _amount
&& _amount > 0
&& balances[_to] + _amount > balances[_to]) {
balances[msg.sender] -= _amount;
balances[_to] += _amount;
Transfer(msg.sender, _to, _amount);
return true;
} else {
return false;
}
}
// ------------------------------------------------------------------------
// Allow _spender to withdraw from your account, multiple times, up to the
// _value amount. If this function is called again it overwrites the
// current allowance with _value.
// ------------------------------------------------------------------------
function approve(
address _spender,
uint _amount
) returns (bool success) {
allowed[msg.sender][_spender] = _amount;
Approval(msg.sender, _spender, _amount);
return true;
}
// ------------------------------------------------------------------------
// Spender of tokens transfer an amount of tokens from the token owner's
// balance to the spender's account. The owner of the tokens must already
// have approve(...)-d this transfer
// ------------------------------------------------------------------------
function transferFrom(
address _from,
address _to,
uint _amount
) returns (bool success) {
if (balances[_from] >= _amount
&& allowed[_from][msg.sender] >= _amount
&& _amount > 0
&& balances[_to] + _amount > balances[_to]) {
balances[_from] -= _amount;
allowed[_from][msg.sender] -= _amount;
balances[_to] += _amount;
Transfer(_from, _to, _amount);
return true;
} else {
return false;
}
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(
address _owner,
address _spender
) constant returns (uint remaining) {
return allowed[_owner][_spender];
}
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender,
uint _value);
}
| contract ERC20Token {
// ------------------------------------------------------------------------
// Balances for each account
// ------------------------------------------------------------------------
mapping(address => uint) balances;
// ------------------------------------------------------------------------
// Owner of account approves the transfer of an amount to another account
// ------------------------------------------------------------------------
mapping(address => mapping (address => uint)) allowed;
// ------------------------------------------------------------------------
// Total token supply
// ------------------------------------------------------------------------
uint public totalSupply;
// ------------------------------------------------------------------------
// Get the account balance of another account with address _owner
// ------------------------------------------------------------------------
function balanceOf(address _owner) constant returns (uint balance) {
return balances[_owner];
}
// ------------------------------------------------------------------------
// Transfer the balance from owner's account to another account
// ------------------------------------------------------------------------
function transfer(address _to, uint _amount) returns (bool success) {
if (balances[msg.sender] >= _amount
&& _amount > 0
&& balances[_to] + _amount > balances[_to]) {
balances[msg.sender] -= _amount;
balances[_to] += _amount;
Transfer(msg.sender, _to, _amount);
return true;
} else {
return false;
}
}
// ------------------------------------------------------------------------
// Allow _spender to withdraw from your account, multiple times, up to the
// _value amount. If this function is called again it overwrites the
// current allowance with _value.
// ------------------------------------------------------------------------
function approve(
address _spender,
uint _amount
) returns (bool success) {
allowed[msg.sender][_spender] = _amount;
Approval(msg.sender, _spender, _amount);
return true;
}
// ------------------------------------------------------------------------
// Spender of tokens transfer an amount of tokens from the token owner's
// balance to the spender's account. The owner of the tokens must already
// have approve(...)-d this transfer
// ------------------------------------------------------------------------
function transferFrom(
address _from,
address _to,
uint _amount
) returns (bool success) {
if (balances[_from] >= _amount
&& allowed[_from][msg.sender] >= _amount
&& _amount > 0
&& balances[_to] + _amount > balances[_to]) {
balances[_from] -= _amount;
allowed[_from][msg.sender] -= _amount;
balances[_to] += _amount;
Transfer(_from, _to, _amount);
return true;
} else {
return false;
}
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(
address _owner,
address _spender
) constant returns (uint remaining) {
return allowed[_owner][_spender];
}
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender,
uint _value);
}
| 10,980 |
9 | // If the hash is correct, finalize the state with provided transfers. / | return abi.encode(
AppState(
| return abi.encode(
AppState(
| 28,553 |
6 | // Ownable | uint internal constant OWNERSHIP_DURATION_TIME = 7; // 7 days
| uint internal constant OWNERSHIP_DURATION_TIME = 7; // 7 days
| 9,791 |
2 | // metadata renderer contract for each token | mapping(uint256 => address) public metadataRendererContract;
| mapping(uint256 => address) public metadataRendererContract;
| 24,001 |
177 | // emit an event regarding the nonce used | emit AuthorizationUsed(authorizer_, nonce_);
| emit AuthorizationUsed(authorizer_, nonce_);
| 37,342 |
21 | // Function to retrieve whether an address owns a token owner address the address to check the balance of / | function balanceOf(address owner) public view isValidAddress(owner) returns (uint256) {
return tokenOwned[owner] > 0 ? 1 : 0;
}
| function balanceOf(address owner) public view isValidAddress(owner) returns (uint256) {
return tokenOwned[owner] > 0 ? 1 : 0;
}
| 13,915 |
149 | // set maximum price (global)/ | function setMaxTicketPrice(uint64 _maxPriceFactor)
public
EventNotStarted
onlyOwner
| function setMaxTicketPrice(uint64 _maxPriceFactor)
public
EventNotStarted
onlyOwner
| 19,203 |
6 | // Constructor function / | constructor(address _nameTAOPositionAddress) public {
setNameTAOPositionAddress(_nameTAOPositionAddress);
}
| constructor(address _nameTAOPositionAddress) public {
setNameTAOPositionAddress(_nameTAOPositionAddress);
}
| 25,410 |
5 | // Set the minters and their corresponding allocations. Each mint gets 40000 Path Tokens with a vesting schedule_addresses The recipient of the allocation_totalAllocated The total number of minted NFT/ | function setAllocation (address[] memory _addresses, uint[] memory _totalAllocated, uint[] memory _initialPercentage) onlyOwner external {
//make sure that the length of address and total minted is the same
require(_addresses.length == _totalAllocated.length, "Input array length not match");
require(_addresses.length == _initialPercentage.length, "Input array length not match");
uint amountToTransfer;
for (uint i = 0; i < _addresses.length; i++ ) {
uint initialAllocation = _totalAllocated[i] * _initialPercentage[i] / 100;
allocations[_addresses[i]] = Allocation(initialAllocation, _totalAllocated[i], 0);
amountToTransfer += _totalAllocated[i];
totalAllocated += _totalAllocated[i];
}
require(token.transferFrom(msg.sender, address(this), amountToTransfer), "Token Transfer Failed");
}
| function setAllocation (address[] memory _addresses, uint[] memory _totalAllocated, uint[] memory _initialPercentage) onlyOwner external {
//make sure that the length of address and total minted is the same
require(_addresses.length == _totalAllocated.length, "Input array length not match");
require(_addresses.length == _initialPercentage.length, "Input array length not match");
uint amountToTransfer;
for (uint i = 0; i < _addresses.length; i++ ) {
uint initialAllocation = _totalAllocated[i] * _initialPercentage[i] / 100;
allocations[_addresses[i]] = Allocation(initialAllocation, _totalAllocated[i], 0);
amountToTransfer += _totalAllocated[i];
totalAllocated += _totalAllocated[i];
}
require(token.transferFrom(msg.sender, address(this), amountToTransfer), "Token Transfer Failed");
}
| 12,691 |
7 | // mint(tokenId, uri, owner): 발행 | function mintWithTokenURI(address to, uint256 tokenId, string memory tokenURI) public returns (bool) {
// to에게 tokenId(일련번호)를 발행하겠다.
tokenOwner[tokenId] = to;
// 적힐 글자는 tokenURI
tokenURIs[tokenId] = tokenURI;
// add token to the list
_ownedTokens[to].push(tokenId);
return true;
}
| function mintWithTokenURI(address to, uint256 tokenId, string memory tokenURI) public returns (bool) {
// to에게 tokenId(일련번호)를 발행하겠다.
tokenOwner[tokenId] = to;
// 적힐 글자는 tokenURI
tokenURIs[tokenId] = tokenURI;
// add token to the list
_ownedTokens[to].push(tokenId);
return true;
}
| 50,086 |
17 | // Function is used in the whenNotTaxed() modifier. | require(!taxed(), "Taxable: taxed"); // Throws the call if the tax is disabled.
| require(!taxed(), "Taxable: taxed"); // Throws the call if the tax is disabled.
| 12,351 |
56 | // === enumeration things === get unstaked ducks and hunters | function walletOfOwner(address _owner) public view humansOnly returns (uint256[] memory) {
return ownerTokens[_owner];
}
| function walletOfOwner(address _owner) public view humansOnly returns (uint256[] memory) {
return ownerTokens[_owner];
}
| 40,184 |
49 | // We simply add to the balance. | balances[insureeAddress] = SafeMath.add(balances[insureeAddress], amount);
| balances[insureeAddress] = SafeMath.add(balances[insureeAddress], amount);
| 10,952 |
49 | // convert period ID to period's finish timestamp.periodID period ID./ | function getPeriodFinishTime(uint256 /*periodID*/)public view returns (uint256) {
delegateToViewAndReturn();
}
| function getPeriodFinishTime(uint256 /*periodID*/)public view returns (uint256) {
delegateToViewAndReturn();
}
| 10,508 |
3 | // Price | uint256 public price = 50000000000000000; // 0.05 eth
| uint256 public price = 50000000000000000; // 0.05 eth
| 57,294 |
6 | // Sending to address `0` means that the token is getting burned. | if (to == address(0)) {
delete _contentHashes[tokenId];
delete _creatorFingerprints[tokenId];
}
| if (to == address(0)) {
delete _contentHashes[tokenId];
delete _creatorFingerprints[tokenId];
}
| 10,608 |
40 | // ---- | round_[1].strt = now ;
round_[1].end = round_[1].strt + rndMax_;
| round_[1].strt = now ;
round_[1].end = round_[1].strt + rndMax_;
| 50,621 |
40 | // Transfer tokens from ICO address to another address._to The address to transfer to._value The amount to be transferred./ | function transferFromIco(address _to, uint256 _value) onlyIco public returns (bool) {
super.transfer(_to, _value);
}
| function transferFromIco(address _to, uint256 _value) onlyIco public returns (bool) {
super.transfer(_to, _value);
}
| 19,031 |
185 | // parts[18] = '</text></svg>'; |
string memory output = string(abi.encodePacked(parts[0], parts[1], parts[2], parts[3], parts[4], parts[5], parts[6], parts[7], parts[8] ));
output = string(abi.encodePacked(output, parts[9], parts[10], parts[11], parts[12], parts[13], parts[14], parts[15], parts[16], parts[17], parts[18] ));
|
string memory output = string(abi.encodePacked(parts[0], parts[1], parts[2], parts[3], parts[4], parts[5], parts[6], parts[7], parts[8] ));
output = string(abi.encodePacked(output, parts[9], parts[10], parts[11], parts[12], parts[13], parts[14], parts[15], parts[16], parts[17], parts[18] ));
| 16,418 |
11 | // Gets the latest price of the trading bot's traded asset and uses it to update the bot's state based on entry/exit rules.Simulates an order if entry/exit rules are met.This function is meant to be called once per timeframe by a Keeper contract./ | function update() external returns (bool);
| function update() external returns (bool);
| 28,897 |
23 | // In ether | function SetHealingCost(uint _healingcost) external onlyOwner {
LEVEL_UP_COST_MULTIPLIER = _healingcost * 1e18;
}
| function SetHealingCost(uint _healingcost) external onlyOwner {
LEVEL_UP_COST_MULTIPLIER = _healingcost * 1e18;
}
| 33,212 |
93 | // 2. convert Uniswap WBTC-WETH to usdc | vars.token0 = wethAddress;
vars.token1 = wbtcAddress;
convertToUSDC(vars);
| vars.token0 = wethAddress;
vars.token1 = wbtcAddress;
convertToUSDC(vars);
| 57,563 |
24 | // Returns the element stored at position `index` in the set. O(1).Note that there are no guarantees on the ordering of values inside thearray, and it may change when more values are added or removed. Requirements: | * - `index` must be strictly less than {length}.
*/
function at(UintToUintMap storage map, uint256 index) internal view returns (uint256, uint256) {
(bytes32 key, bytes32 value) = at(map._inner, index);
return (uint256(key), uint256(value));
}
| * - `index` must be strictly less than {length}.
*/
function at(UintToUintMap storage map, uint256 index) internal view returns (uint256, uint256) {
(bytes32 key, bytes32 value) = at(map._inner, index);
return (uint256(key), uint256(value));
}
| 23,587 |
42 | // Return the approved address for the tokentokenId Id of the token return address : spender's address/ | function getApproved(uint256 tokenId) public view override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return approvals[tokenId];
}
| function getApproved(uint256 tokenId) public view override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return approvals[tokenId];
}
| 52,244 |
117 | // remove an address from the array finds the element, swaps it with the last element, and then deletes it; returns a boolean whether the element was found and deleted self Storage array containing address type variables element the element to remove from the array / | function remove(Addresses storage self, address payable element) internal returns (bool) {
int256 i = getIndex(self, element);
if (i >= 0) {
return removeByIndex(self, uint256(i));
}
return false;
}
| function remove(Addresses storage self, address payable element) internal returns (bool) {
int256 i = getIndex(self, element);
if (i >= 0) {
return removeByIndex(self, uint256(i));
}
return false;
}
| 49,022 |
13 | // Safety function / | function ownerBurn(
address wallet,
uint256 tokenId,
uint256 amount
| function ownerBurn(
address wallet,
uint256 tokenId,
uint256 amount
| 40,990 |
9 | // range: [0, 2144 - 1] resolution: 1 / 2112 | struct uq144x112 {
uint _x;
}
| struct uq144x112 {
uint _x;
}
| 3,213 |
801 | // User Events | event CollateralAdded(address indexed lp, address indexed account, uint lpAmount);
event CollateralRemoved(address indexed lp, address indexed account, uint lpAmount);
event UnpaidProfitClaimed(address indexed account, uint ethValue);
event LossRealized(address indexed lp, address indexed account, uint indexed eventId, uint soldLPAmount, uint ethValue);
| event CollateralAdded(address indexed lp, address indexed account, uint lpAmount);
event CollateralRemoved(address indexed lp, address indexed account, uint lpAmount);
event UnpaidProfitClaimed(address indexed account, uint ethValue);
event LossRealized(address indexed lp, address indexed account, uint indexed eventId, uint soldLPAmount, uint ethValue);
| 48,975 |
3 | // ============ Constructor ============ //Instantiate with ManagerCore address, TradeModule address, and allowed TradeModule integration strings._managerCoreAddress of ManagerCore contract _tradeModuleAddress of TradeModule contract / | constructor(
IManagerCore _managerCore,
ITradeModule _tradeModule,
ISignalSuscriptionModule _signalSuscriptionModule
| constructor(
IManagerCore _managerCore,
ITradeModule _tradeModule,
ISignalSuscriptionModule _signalSuscriptionModule
| 5,522 |
360 | // `ago` must not be before the epoch. | _require(block.timestamp >= ago, Errors.ORACLE_INVALID_SECONDS_QUERY);
uint256 lookUpTime = block.timestamp - ago;
bytes32 latestSample = _getSample(latestIndex);
uint256 latestTimestamp = latestSample.timestamp();
| _require(block.timestamp >= ago, Errors.ORACLE_INVALID_SECONDS_QUERY);
uint256 lookUpTime = block.timestamp - ago;
bytes32 latestSample = _getSample(latestIndex);
uint256 latestTimestamp = latestSample.timestamp();
| 14,986 |
55 | // Cost to mint a token | uint256 public constant PUBLIC_SALE_PRICE = 0.05 ether;
| uint256 public constant PUBLIC_SALE_PRICE = 0.05 ether;
| 48,799 |
41 | // ========== CONSTANT VARIABLES ========== // ========== CONSTRUCTOR ========== / | ) public {
factory = IJoeFactory(_factory);
bar = _bar;
joe = _joe;
wavax = _wavax;
}
| ) public {
factory = IJoeFactory(_factory);
bar = _bar;
joe = _joe;
wavax = _wavax;
}
| 9,145 |
343 | // build the EIP-712 contract domain separator | bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), block.chainid, address(this)));
| bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), block.chainid, address(this)));
| 49,912 |
247 | // Helper to self-destruct the contract./ There should never be ETH in the ComptrollerLib,/ so no need to waste gas to get the fund owner | function __selfDestruct() private {
| function __selfDestruct() private {
| 38,730 |
22 | // Calculate using this as the base | uint256 constant calcBase = 1 ether;
| uint256 constant calcBase = 1 ether;
| 7,935 |
559 | // Compute the LUSD and ETH rewards. Uses a "feedback" error correction, to keep the cumulative error in the P and S state variables low: 1) Form numerators which compensate for the floor division errors that occurred the last time thisfunction was called. 2) Calculate "per-unit-staked" ratios. 3) Multiply each ratio back by its denominator, to reveal the current floor division error. 4) Store these errors for use in the next correction when this function is called. 5) Note: static analysis tools complain about this "division before multiplication", however, it is intended./ | uint ETHNumerator = _collToAdd.mul(DECIMAL_PRECISION).add(lastETHError_Offset);
| uint ETHNumerator = _collToAdd.mul(DECIMAL_PRECISION).add(lastETHError_Offset);
| 10,412 |
0 | // the owner can assign someone to be an admin | bytes32 public constant OWNER_ROLE = keccak256("OWNER");
bytes32 public constant ADMIN_ROLE = keccak256("ADMIN");
event AdminAdded(address indexed account);
event AdminRemoved(address indexed account);
event RoleAdded(string indexed role, address indexed account);
event RoleRemoved(string indexed role, address indexed account);
address public owner;
| bytes32 public constant OWNER_ROLE = keccak256("OWNER");
bytes32 public constant ADMIN_ROLE = keccak256("ADMIN");
event AdminAdded(address indexed account);
event AdminRemoved(address indexed account);
event RoleAdded(string indexed role, address indexed account);
event RoleRemoved(string indexed role, address indexed account);
address public owner;
| 48,038 |
152 | // - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called for each safe transfer.- `quantity` must be greater than 0. Emits a {Transfer} event. / | function _safeMint(
address to,
uint256 quantity,
bytes memory _data
) internal {
_mint(to, quantity, _data, true);
}
| function _safeMint(
address to,
uint256 quantity,
bytes memory _data
) internal {
_mint(to, quantity, _data, true);
}
| 1,426 |
669 | // Adds `delta` to element of segment tree at `toPlace`and subtracts `delta` from element at `fromPlace`Requirements:- `fromPlace` must be in range [1, size]- `toPlace` must be in range [1, size]- initial value of element at `fromPlace` must be not less than `delta` / | function moveFromPlaceToPlace(
Tree storage self,
uint fromPlace,
uint toPlace,
uint delta
)
external
| function moveFromPlaceToPlace(
Tree storage self,
uint fromPlace,
uint toPlace,
uint delta
)
external
| 81,741 |
24 | // Approves an operator to manage a specific token./Overrides the equivalent function in the ERC721 standard to include a check for allowed operators./_operator The operator to approve./_tokenId The ID of the token to approve the operator for. | function approve(
address _operator,
uint256 _tokenId
| function approve(
address _operator,
uint256 _tokenId
| 1,273 |
194 | // A xref:ROOT:gsn-strategies.adocgsn-strategies[GSN strategy] that charges transaction fees in a special purpose ERC20token, which we refer to as the gas payment token. The amount charged is exactly the amount of Ether charged to therecipient. This means that the token is essentially pegged to the value of Ether. The distribution strategy of the gas payment token to users is not defined by this contract. It's a mintable tokenwhose only minter is the recipient, so the strategy must be implemented in a derived contract, making use of the | * internal {_mint} function.
*/
contract GSNRecipientERC20Fee is GSNRecipient {
using SafeERC20 for __unstable__ERC20Owned;
using SafeMath for uint256;
enum GSNRecipientERC20FeeErrorCodes {
INSUFFICIENT_BALANCE
}
__unstable__ERC20Owned private _token;
/**
* @dev The arguments to the constructor are the details that the gas payment token will have: `name` and `symbol`. `decimals` is hard-coded to 18.
*/
constructor(string memory name, string memory symbol) public {
_token = new __unstable__ERC20Owned(name, symbol);
}
/**
* @dev Returns the gas payment token.
*/
function token() public view returns (IERC20) {
return IERC20(_token);
}
/**
* @dev Internal function that mints the gas payment token. Derived contracts should expose this function in their public API, with proper access control mechanisms.
*/
function _mint(address account, uint256 amount) internal virtual {
_token.mint(account, amount);
}
/**
* @dev Ensures that only users with enough gas payment token balance can have transactions relayed through the GSN.
*/
function acceptRelayedCall(
address,
address from,
bytes memory,
uint256 transactionFee,
uint256 gasPrice,
uint256,
uint256,
bytes memory,
uint256 maxPossibleCharge
)
public
view
virtual
override
returns (uint256, bytes memory)
{
if (_token.balanceOf(from) < maxPossibleCharge) {
return _rejectRelayedCall(uint256(GSNRecipientERC20FeeErrorCodes.INSUFFICIENT_BALANCE));
}
return _approveRelayedCall(abi.encode(from, maxPossibleCharge, transactionFee, gasPrice));
}
/**
* @dev Implements the precharge to the user. The maximum possible charge (depending on gas limit, gas price, and
* fee) will be deducted from the user balance of gas payment token. Note that this is an overestimation of the
* actual charge, necessary because we cannot predict how much gas the execution will actually need. The remainder
* is returned to the user in {_postRelayedCall}.
*/
function _preRelayedCall(bytes memory context) internal virtual override returns (bytes32) {
(address from, uint256 maxPossibleCharge) = abi.decode(context, (address, uint256));
// The maximum token charge is pre-charged from the user
_token.safeTransferFrom(from, address(this), maxPossibleCharge);
return 0;
}
/**
* @dev Returns to the user the extra amount that was previously charged, once the actual execution cost is known.
*/
function _postRelayedCall(bytes memory context, bool, uint256 actualCharge, bytes32) internal virtual override {
(address from, uint256 maxPossibleCharge, uint256 transactionFee, uint256 gasPrice) =
abi.decode(context, (address, uint256, uint256, uint256));
// actualCharge is an _estimated_ charge, which assumes postRelayedCall will use all available gas.
// This implementation's gas cost can be roughly estimated as 10k gas, for the two SSTORE operations in an
// ERC20 transfer.
uint256 overestimation = _computeCharge(_POST_RELAYED_CALL_MAX_GAS.sub(10000), gasPrice, transactionFee);
actualCharge = actualCharge.sub(overestimation);
// After the relayed call has been executed and the actual charge estimated, the excess pre-charge is returned
_token.safeTransfer(from, maxPossibleCharge.sub(actualCharge));
}
}
| * internal {_mint} function.
*/
contract GSNRecipientERC20Fee is GSNRecipient {
using SafeERC20 for __unstable__ERC20Owned;
using SafeMath for uint256;
enum GSNRecipientERC20FeeErrorCodes {
INSUFFICIENT_BALANCE
}
__unstable__ERC20Owned private _token;
/**
* @dev The arguments to the constructor are the details that the gas payment token will have: `name` and `symbol`. `decimals` is hard-coded to 18.
*/
constructor(string memory name, string memory symbol) public {
_token = new __unstable__ERC20Owned(name, symbol);
}
/**
* @dev Returns the gas payment token.
*/
function token() public view returns (IERC20) {
return IERC20(_token);
}
/**
* @dev Internal function that mints the gas payment token. Derived contracts should expose this function in their public API, with proper access control mechanisms.
*/
function _mint(address account, uint256 amount) internal virtual {
_token.mint(account, amount);
}
/**
* @dev Ensures that only users with enough gas payment token balance can have transactions relayed through the GSN.
*/
function acceptRelayedCall(
address,
address from,
bytes memory,
uint256 transactionFee,
uint256 gasPrice,
uint256,
uint256,
bytes memory,
uint256 maxPossibleCharge
)
public
view
virtual
override
returns (uint256, bytes memory)
{
if (_token.balanceOf(from) < maxPossibleCharge) {
return _rejectRelayedCall(uint256(GSNRecipientERC20FeeErrorCodes.INSUFFICIENT_BALANCE));
}
return _approveRelayedCall(abi.encode(from, maxPossibleCharge, transactionFee, gasPrice));
}
/**
* @dev Implements the precharge to the user. The maximum possible charge (depending on gas limit, gas price, and
* fee) will be deducted from the user balance of gas payment token. Note that this is an overestimation of the
* actual charge, necessary because we cannot predict how much gas the execution will actually need. The remainder
* is returned to the user in {_postRelayedCall}.
*/
function _preRelayedCall(bytes memory context) internal virtual override returns (bytes32) {
(address from, uint256 maxPossibleCharge) = abi.decode(context, (address, uint256));
// The maximum token charge is pre-charged from the user
_token.safeTransferFrom(from, address(this), maxPossibleCharge);
return 0;
}
/**
* @dev Returns to the user the extra amount that was previously charged, once the actual execution cost is known.
*/
function _postRelayedCall(bytes memory context, bool, uint256 actualCharge, bytes32) internal virtual override {
(address from, uint256 maxPossibleCharge, uint256 transactionFee, uint256 gasPrice) =
abi.decode(context, (address, uint256, uint256, uint256));
// actualCharge is an _estimated_ charge, which assumes postRelayedCall will use all available gas.
// This implementation's gas cost can be roughly estimated as 10k gas, for the two SSTORE operations in an
// ERC20 transfer.
uint256 overestimation = _computeCharge(_POST_RELAYED_CALL_MAX_GAS.sub(10000), gasPrice, transactionFee);
actualCharge = actualCharge.sub(overestimation);
// After the relayed call has been executed and the actual charge estimated, the excess pre-charge is returned
_token.safeTransfer(from, maxPossibleCharge.sub(actualCharge));
}
}
| 25,230 |
5 | // Give $(toVoter) the right to vote on this ballot./ May only be called by $(chairperson). | function register(address toVoter) public onlyOwner{
if(voters[toVoter].weight != 0) revert();
voters[toVoter].weight = 1;
voters[toVoter].voted = false;
}
| function register(address toVoter) public onlyOwner{
if(voters[toVoter].weight != 0) revert();
voters[toVoter].weight = 1;
voters[toVoter].voted = false;
}
| 4,191 |
16 | // Returns the address that signed a hashed message (`hash`) with`signature`. This address can then be used for verification purposes. The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:this function rejects them by requiring the `s` value to be in the lowerhalf order, and the `v` value to be either 27 or 28. IMPORTANT: `hash` _must_ be the result of a hash operation for theverification to be secure: it is possible to craft signatures thatrecover to arbitrary addresses for non-hashed data. A safe way to ensurethis is by receiving a hash of the original message (which may otherwise | * be too long), and then calling {toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
// Check the signature length
// - case 65: r,s,v signature (standard)
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return recover(hash, v, r, s);
} else if (signature.length == 64) {
bytes32 r;
bytes32 vs;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
vs := mload(add(signature, 0x40))
}
return recover(hash, r, vs);
} else {
revert('ECDSA: invalid signature length');
}
}
| * be too long), and then calling {toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
// Check the signature length
// - case 65: r,s,v signature (standard)
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return recover(hash, v, r, s);
} else if (signature.length == 64) {
bytes32 r;
bytes32 vs;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
vs := mload(add(signature, 0x40))
}
return recover(hash, r, vs);
} else {
revert('ECDSA: invalid signature length');
}
}
| 28,613 |
16 | // Set T365days _baseInsuredPeriod is period, not point / | function setBaseInsuredPeriod(uint256 _baseInsuredPeriod) public onlyOwner {
baseInsuredPeriod = _baseInsuredPeriod;
}
| function setBaseInsuredPeriod(uint256 _baseInsuredPeriod) public onlyOwner {
baseInsuredPeriod = _baseInsuredPeriod;
}
| 4,241 |
90 | // Unset pause | paused = false;
| paused = false;
| 4,793 |
6 | // Retrieves the result (if already available) of one data request from the WRB./_id The unique identifier of the data request./ return The result of the DR | function readResult (uint256 _id) external view returns(bytes memory);
| function readResult (uint256 _id) external view returns(bytes memory);
| 33,024 |
418 | // Calculate and deposit owedToken | uint256 maxHeldTokenFromSell = MathHelpers.maxUint256();
if (!transaction.depositInHeldToken) {
transaction.depositAmount =
getOwedTokenDeposit(transaction, collateralToAdd, orderData);
BorrowShared.doDepositOwedToken(state, transaction);
maxHeldTokenFromSell = collateralToAdd;
}
| uint256 maxHeldTokenFromSell = MathHelpers.maxUint256();
if (!transaction.depositInHeldToken) {
transaction.depositAmount =
getOwedTokenDeposit(transaction, collateralToAdd, orderData);
BorrowShared.doDepositOwedToken(state, transaction);
maxHeldTokenFromSell = collateralToAdd;
}
| 24,597 |
36 | // ------------------------------------------------------------------------ Burning tokens function _valueTokens: Amount tokens for burning. _aTokenPrice: One token price. _trxForTokens: Calculate the trx for burning tokens. _forDividendes: Calculate the are common Dividendes. _contracBalance: Get contract balance. _dividendesAmount: Get the percentage of dividends burned tokens. ------------------------------------------------------------------------ | function withdraw(uint256 _valueTokens) public payable returns(bool success) {
uint256 _tokensOwner = balanceOf(msg.sender);
require(_valueTokens > 0, "cannot pass 0 value");
require(_tokensOwner >= _valueTokens, "you do not have so many tokens");
uint256 _aTokenPrice = tokenPrice();
uint256 _trxForTokens = tokensTotrxeum(_valueTokens, _aTokenPrice);
uint256 _contracBalance = contracBalance();
uint256 _forDividendes = onDividendes(_trxForTokens, forWithdrawCosts);
uint256 _dividendesAmount = dividendesCalc(_tokensOwner);
_trxForTokens = _trxForTokens.sub(_forDividendes);
totalSupply = totalSupply.sub(_valueTokens);
if (_dividendesAmount > 0) {
dividendes = dividendes.sub(_dividendesAmount);
_trxForTokens = _trxForTokens.add(_dividendesAmount);
emit WithdrawDividendes(msg.sender, _dividendesAmount);
}
if (_tokensOwner == _valueTokens) {
// if the owner out of system //
bookKeeper[msg.sender] = 0;
balances[msg.sender] = 0;
} else {
bookKeeper[msg.sender] = block.number;
balances[msg.sender] = balances[msg.sender].sub(_valueTokens);
}
if (_trxForTokens > _contracBalance) {
_trxForTokens = _contracBalance;
}
msg.sender.transfer(_trxForTokens);
emit WithdrawTokens(msg.sender, _trxForTokens);
emit SendOnDividend(address(0), _forDividendes);
return true;
}
| function withdraw(uint256 _valueTokens) public payable returns(bool success) {
uint256 _tokensOwner = balanceOf(msg.sender);
require(_valueTokens > 0, "cannot pass 0 value");
require(_tokensOwner >= _valueTokens, "you do not have so many tokens");
uint256 _aTokenPrice = tokenPrice();
uint256 _trxForTokens = tokensTotrxeum(_valueTokens, _aTokenPrice);
uint256 _contracBalance = contracBalance();
uint256 _forDividendes = onDividendes(_trxForTokens, forWithdrawCosts);
uint256 _dividendesAmount = dividendesCalc(_tokensOwner);
_trxForTokens = _trxForTokens.sub(_forDividendes);
totalSupply = totalSupply.sub(_valueTokens);
if (_dividendesAmount > 0) {
dividendes = dividendes.sub(_dividendesAmount);
_trxForTokens = _trxForTokens.add(_dividendesAmount);
emit WithdrawDividendes(msg.sender, _dividendesAmount);
}
if (_tokensOwner == _valueTokens) {
// if the owner out of system //
bookKeeper[msg.sender] = 0;
balances[msg.sender] = 0;
} else {
bookKeeper[msg.sender] = block.number;
balances[msg.sender] = balances[msg.sender].sub(_valueTokens);
}
if (_trxForTokens > _contracBalance) {
_trxForTokens = _contracBalance;
}
msg.sender.transfer(_trxForTokens);
emit WithdrawTokens(msg.sender, _trxForTokens);
emit SendOnDividend(address(0), _forDividendes);
return true;
}
| 53,095 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.