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 |
|---|---|---|---|---|
327 | // 12 = payout pending, 14 = payout succeeded | uint nextStatus = payoutSucceeded ? 14 : 12;
c1.setClaimStatus(claimid, nextStatus);
| uint nextStatus = payoutSucceeded ? 14 : 12;
c1.setClaimStatus(claimid, nextStatus);
| 54,592 |
111 | // Update participant cap for tier 2_participantCapTier2 Tier cap / | function updateParticipantCapTier2(uint256 _participantCapTier2) external OnlyOwner {
participantCapTier2 = _participantCapTier2;
}
| function updateParticipantCapTier2(uint256 _participantCapTier2) external OnlyOwner {
participantCapTier2 = _participantCapTier2;
}
| 33,975 |
103 | // tracks all current bondings (time) | mapping(address => mapping(address => uint)) public bondings;
| mapping(address => mapping(address => uint)) public bondings;
| 37,089 |
9 | // register msg.sender as claimer | register(_nftAddress);
| register(_nftAddress);
| 10,002 |
117 | // get owner's specfic contract address's all NFT array ownerAddress owner addresscontractAddressNFT's contract address return NFT's array/ | function getOwnerTokens(
address ownerAddress,
address contractAddress
)
external
view
returns (uint256[] memory)
| function getOwnerTokens(
address ownerAddress,
address contractAddress
)
external
view
returns (uint256[] memory)
| 30,983 |
84 | // The minimum number of seconds between harvest calls NOTE: Override this value with your own, or set dynamically below | uint256 public minReportDelay = 86400; // ~ once a day
| uint256 public minReportDelay = 86400; // ~ once a day
| 30,784 |
81 | // Re-approve | IERC20(_token).safeApprove(pancakeRouterAddress, MAX_INT);
| IERC20(_token).safeApprove(pancakeRouterAddress, MAX_INT);
| 10,511 |
0 | // TODO: Add more attribtes. Author, Price, Description | uint id;
string name;
uint voteCount;
| uint id;
string name;
uint voteCount;
| 5,100 |
38 | // Offeror must own the NFT being offered. | if (balanceOf[offeror][tradeTokenId] != 1) {
revert("Offeror must own the NFT being offered");
}
| if (balanceOf[offeror][tradeTokenId] != 1) {
revert("Offeror must own the NFT being offered");
}
| 32,488 |
25 | // Clear unnecessary info about previous collection round. | _clearOldCiphers(currentRound);
| _clearOldCiphers(currentRound);
| 12,480 |
182 | // Chosen code (string) get's assigned to address. Whenever the code is used in mint, assigned address is paid. | function createRefferalCode(address _address, string memory _code) public payable {
require(keccak256(abi.encodePacked(_code)) != keccak256(abi.encodePacked("")), "Referral Code can't be empty");
require(!codeIsTaken[_code], "Referral Code is already taken");
if (msg.sender != owner()) {
require(msg.value >= costToCreateReferral, "Value should be equal or greater than ReferralCost");
}
codeIsTaken[_code] = true;
ownerOfCode[_code] = _address;
}
| function createRefferalCode(address _address, string memory _code) public payable {
require(keccak256(abi.encodePacked(_code)) != keccak256(abi.encodePacked("")), "Referral Code can't be empty");
require(!codeIsTaken[_code], "Referral Code is already taken");
if (msg.sender != owner()) {
require(msg.value >= costToCreateReferral, "Value should be equal or greater than ReferralCost");
}
codeIsTaken[_code] = true;
ownerOfCode[_code] = _address;
}
| 35,529 |
32 | // eg. TOKEN - AVAX | IERC20(tokenTo).safeTransfer(bar, amount0);
tokenOut = _toToken(token1, amount1, slippage).add(amount0);
| IERC20(tokenTo).safeTransfer(bar, amount0);
tokenOut = _toToken(token1, amount1, slippage).add(amount0);
| 42,219 |
265 | // ============ State Variables ============ / Wrapped ETH address | IWETH public immutable weth;
| IWETH public immutable weth;
| 52,160 |
84 | // close vault call | function closeVault() public onlyOwner {
require(!vaultClosed);
require(goalReached());
vault.close();
vaultClosed = true;
}
| function closeVault() public onlyOwner {
require(!vaultClosed);
require(goalReached());
vault.close();
vaultClosed = true;
}
| 12,775 |
408 | // If the data at the starting slot does not exist, start the scan. | if (packed == 0) {
if (tokenId >= _currentIndex) {
_revert(OwnerQueryForNonexistentToken.selector);
}
| if (packed == 0) {
if (tokenId >= _currentIndex) {
_revert(OwnerQueryForNonexistentToken.selector);
}
| 38,166 |
28 | // Register a future flight for insuring./ | function registerFlight
(
uint32 _flightNumber,
address _airlineAddress
)
external
| function registerFlight
(
uint32 _flightNumber,
address _airlineAddress
)
external
| 2,895 |
40 | // Modifies The BrightList Active Sale State / | function ___ModifySaleStateBrightList(uint SaleIndex, bool State) external onlyOwner
| function ___ModifySaleStateBrightList(uint SaleIndex, bool State) external onlyOwner
| 36,221 |
69 | // Guaranteed swap desired to prevent trade blockages, return values ignored | router.addLiquidityETH{value: amountLiquidity}(
| router.addLiquidityETH{value: amountLiquidity}(
| 8,356 |
6 | // role id => node id => index + 1 | mapping(uint64 => mapping(uint64 => uint16)) public nodesRoles;
| mapping(uint64 => mapping(uint64 => uint16)) public nodesRoles;
| 28,943 |
100 | // Info of each Token Currency Rate with PKF: amountrate / 10decimals Default PKF: rate=1, decimals=0 | struct ExternalToken {
address contractAddress;
uint256 decimals;
uint256 rate;
bool isERC721;
bool canStake;
}
| struct ExternalToken {
address contractAddress;
uint256 decimals;
uint256 rate;
bool isERC721;
bool canStake;
}
| 36,622 |
0 | // Pool state that is not stored/Contains view functions to provide information about the pool that is computed rather than stored on the/ blockchain. The functions here may have variable gas costs. | interface IElkDexV3PoolDerivedState {
/// @notice Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp
/// @dev To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing
/// the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick,
/// you must call it with secondsAgos = [3600, 0].
/// @dev The time weighted average tick represents the geometric time weighted average price of the pool, in
/// log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio.
/// @param secondsAgos From how long ago each cumulative tick and liquidity value should be returned
/// @return tickCumulatives Cumulative tick values as of each `secondsAgos` from the current block timestamp
/// @return secondsPerLiquidityCumulativeX128s Cumulative seconds per liquidity-in-range value as of each `secondsAgos` from the current block
/// timestamp
function observe(uint32[] calldata secondsAgos)
external
view
returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s);
/// @notice Returns a snapshot of the tick cumulative, seconds per liquidity and seconds inside a tick range
/// @dev Snapshots must only be compared to other snapshots, taken over a period for which a position existed.
/// I.e., snapshots cannot be compared if a position is not held for the entire period between when the first
/// snapshot is taken and the second snapshot is taken.
/// @param tickLower The lower tick of the range
/// @param tickUpper The upper tick of the range
/// @return tickCumulativeInside The snapshot of the tick accumulator for the range
/// @return secondsPerLiquidityInsideX128 The snapshot of seconds per liquidity for the range
/// @return secondsInside The snapshot of seconds per liquidity for the range
function snapshotCumulativesInside(int24 tickLower, int24 tickUpper)
external
view
returns (
int56 tickCumulativeInside,
uint160 secondsPerLiquidityInsideX128,
uint32 secondsInside
);
}
| interface IElkDexV3PoolDerivedState {
/// @notice Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp
/// @dev To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing
/// the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick,
/// you must call it with secondsAgos = [3600, 0].
/// @dev The time weighted average tick represents the geometric time weighted average price of the pool, in
/// log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio.
/// @param secondsAgos From how long ago each cumulative tick and liquidity value should be returned
/// @return tickCumulatives Cumulative tick values as of each `secondsAgos` from the current block timestamp
/// @return secondsPerLiquidityCumulativeX128s Cumulative seconds per liquidity-in-range value as of each `secondsAgos` from the current block
/// timestamp
function observe(uint32[] calldata secondsAgos)
external
view
returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s);
/// @notice Returns a snapshot of the tick cumulative, seconds per liquidity and seconds inside a tick range
/// @dev Snapshots must only be compared to other snapshots, taken over a period for which a position existed.
/// I.e., snapshots cannot be compared if a position is not held for the entire period between when the first
/// snapshot is taken and the second snapshot is taken.
/// @param tickLower The lower tick of the range
/// @param tickUpper The upper tick of the range
/// @return tickCumulativeInside The snapshot of the tick accumulator for the range
/// @return secondsPerLiquidityInsideX128 The snapshot of seconds per liquidity for the range
/// @return secondsInside The snapshot of seconds per liquidity for the range
function snapshotCumulativesInside(int24 tickLower, int24 tickUpper)
external
view
returns (
int56 tickCumulativeInside,
uint160 secondsPerLiquidityInsideX128,
uint32 secondsInside
);
}
| 1,557 |
24 | // Gas optimization: this is cheaper than requiring 'a' not being zero, but the benefit is lost if 'b' is also tested. See: https:github.com/OpenZeppelin/openzeppelin-contracts/pull/522 | if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
| if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
| 7,284 |
73 | // Check policy include target group/_policyHash policy hash (sig, contract address)/_groupName group id/ return bool | function isGroupInPolicy(bytes32 _policyHash, bytes32 _groupName) public view returns (bool) {
Policy storage _policy = policyId2policy[_policyHash];
return _policy.groupName2index[_groupName] != 0;
}
| function isGroupInPolicy(bytes32 _policyHash, bytes32 _groupName) public view returns (bool) {
Policy storage _policy = policyId2policy[_policyHash];
return _policy.groupName2index[_groupName] != 0;
}
| 26,610 |
50 | // Get the underlying amount of tokens per shares given/_amount The amount of shares you want to know the value of/ return Value of shares in underlying token | function _underlying(uint256 _amount)
internal
override
view
returns (uint256)
| function _underlying(uint256 _amount)
internal
override
view
returns (uint256)
| 27,673 |
21 | // Release the tokens of a Zamzam Project Releases `tokenAmount` tokens of a Zamzam project `projectId` to the admin wallet `_adminWallet`The Zamzam admin then releases the tokens to the appropriate addresses. projectId The ID of the project whose tokens will be released tokenAmount The amount of tokens which will be released receiver The amount of tokens which will be releasedreturn Returns true if the release of tokens was successful / | function releaseFunds(
| function releaseFunds(
| 3,905 |
517 | // Normal farming reward | uint256 reward;
uint256 rewardPerTokenPaid;
| uint256 reward;
uint256 rewardPerTokenPaid;
| 49,353 |
371 | // Reward referred | if (canFund(rateReferral)) {
| if (canFund(rateReferral)) {
| 14,333 |
66 | // initialize the farming contract. This is called only once upon farm creation and the FarmGenerator ensures the farm has the correct paramaters / | function init (IERC20 _rewardToken, uint256 _amount, IERC20 _lpToken, uint256 _blockReward, uint256 _startBlock, uint256 _endBlock, uint256 _bonusEndBlock, uint256 _bonus) public {
require(msg.sender == address(farmGenerator), 'FORBIDDEN');
TransferHelper.safeTransferFrom(address(_rewardToken), msg.sender, address(this), _amount);
farmInfo.rewardToken = _rewardToken;
farmInfo.startBlock = _startBlock;
farmInfo.blockReward = _blockReward;
farmInfo.bonusEndBlock = _bonusEndBlock;
farmInfo.bonus = _bonus;
uint256 lastRewardBlock = block.number > _startBlock ? block.number : _startBlock;
farmInfo.lpToken = _lpToken;
farmInfo.lastRewardBlock = lastRewardBlock;
farmInfo.accRewardPerShare = 0;
farmInfo.endBlock = _endBlock;
farmInfo.farmableSupply = _amount;
}
| function init (IERC20 _rewardToken, uint256 _amount, IERC20 _lpToken, uint256 _blockReward, uint256 _startBlock, uint256 _endBlock, uint256 _bonusEndBlock, uint256 _bonus) public {
require(msg.sender == address(farmGenerator), 'FORBIDDEN');
TransferHelper.safeTransferFrom(address(_rewardToken), msg.sender, address(this), _amount);
farmInfo.rewardToken = _rewardToken;
farmInfo.startBlock = _startBlock;
farmInfo.blockReward = _blockReward;
farmInfo.bonusEndBlock = _bonusEndBlock;
farmInfo.bonus = _bonus;
uint256 lastRewardBlock = block.number > _startBlock ? block.number : _startBlock;
farmInfo.lpToken = _lpToken;
farmInfo.lastRewardBlock = lastRewardBlock;
farmInfo.accRewardPerShare = 0;
farmInfo.endBlock = _endBlock;
farmInfo.farmableSupply = _amount;
}
| 16,836 |
55 | // Calc max coin amount to be deposit | function calcMaxCoinAmountToBeDeposit(uint8 coinIndex) public view returns (uint256) {
uint256 availableTokenAmount = totalSaleAmount.sub(totalSoldAmount);
(uint256 _coinAmount,) = calcCoinAmount(availableTokenAmount, coinIndex);
return _coinAmount;
}
| function calcMaxCoinAmountToBeDeposit(uint8 coinIndex) public view returns (uint256) {
uint256 availableTokenAmount = totalSaleAmount.sub(totalSoldAmount);
(uint256 _coinAmount,) = calcCoinAmount(availableTokenAmount, coinIndex);
return _coinAmount;
}
| 65,378 |
146 | // if the proposal is still open | if (proposals[_id].open) {
| if (proposals[_id].open) {
| 30,474 |
158 | // P4D interface | interface P4D {
function buy(address) external payable returns(uint256);
function sell(uint256) external;
function transfer(address, uint256) external returns(bool);
function myTokens() external view returns(uint256);
function myStoredDividends() external view returns(uint256);
function mySubdividends() external view returns(uint256);
function withdraw(bool) external;
function withdrawSubdivs(bool) external;
function P3D_address() external view returns(address);
function setCanAcceptTokens(address) external;
}
| interface P4D {
function buy(address) external payable returns(uint256);
function sell(uint256) external;
function transfer(address, uint256) external returns(bool);
function myTokens() external view returns(uint256);
function myStoredDividends() external view returns(uint256);
function mySubdividends() external view returns(uint256);
function withdraw(bool) external;
function withdrawSubdivs(bool) external;
function P3D_address() external view returns(address);
function setCanAcceptTokens(address) external;
}
| 47,301 |
0 | // set owner of contract // a variable to track the most recent sku of a food item // an enum to store food item state / | enum State {ForSale, Sold}
/* add event to emit when a new food item is added to cart */
event ForSale(string name, uint8 sku, uint16 price, uint8 state, bool foodItemExist);
/* add event to emit when a new food item is sold */
event Sold(string name, uint8 sku, uint16 price, uint8 state, bool foodItemExist);
/* a struct to store details of a food item */
struct FoodItem {
string name;
uint8 sku;
uint16 price;
State state;
bool foodItemExist;
}
| enum State {ForSale, Sold}
/* add event to emit when a new food item is added to cart */
event ForSale(string name, uint8 sku, uint16 price, uint8 state, bool foodItemExist);
/* add event to emit when a new food item is sold */
event Sold(string name, uint8 sku, uint16 price, uint8 state, bool foodItemExist);
/* a struct to store details of a food item */
struct FoodItem {
string name;
uint8 sku;
uint16 price;
State state;
bool foodItemExist;
}
| 10,144 |
4 | // Gets address associated with the given identifierHash. identifierHash Identifier hash of contract whose address we want to look up. Throws if address not set. / | function getAddressForOrDie(bytes32 identifierHash)
external
view
returns (address)
| function getAddressForOrDie(bytes32 identifierHash)
external
view
returns (address)
| 17,751 |
100 | // We take the precision out here | uint256 delfaForPool = deltaForPoolAndReserve.mul(percentOfBalanceToReserves).div(1000);
| uint256 delfaForPool = deltaForPoolAndReserve.mul(percentOfBalanceToReserves).div(1000);
| 17,591 |
19 | // This also checks if oracle is registered w/ an initialized curve | uint256 issued = getDotsIssued(oracleAddress, endpoint);
require(issued + numDots <= dotLimit(oracleAddress, endpoint), "Error: Dot limit exceeded");
uint256 numZap = currentCost._costOfNDots(oracleAddress, endpoint, issued + 1, numDots - 1);
| uint256 issued = getDotsIssued(oracleAddress, endpoint);
require(issued + numDots <= dotLimit(oracleAddress, endpoint), "Error: Dot limit exceeded");
uint256 numZap = currentCost._costOfNDots(oracleAddress, endpoint, issued + 1, numDots - 1);
| 1,345 |
121 | // fire an event | emit Join(asset, msg.sender, mainAmount, 0);
| emit Join(asset, msg.sender, mainAmount, 0);
| 25,416 |
0 | // Network: Avalanche Fuji TestnetAggregator: AVAX/USDAddress: 0x5498BB86BC934c8D34FDA08E81D444153d0D06aDDecimals: 8 / | constructor() public {
priceFeed = AggregatorV3Interface(0x5498BB86BC934c8D34FDA08E81D444153d0D06aD);
}
| constructor() public {
priceFeed = AggregatorV3Interface(0x5498BB86BC934c8D34FDA08E81D444153d0D06aD);
}
| 943 |
5 | // Mouth N°6 => Big Smile | function item_6() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
'<path fill="#FFFFFF" stroke="#000000" stroke-miterlimit="10" d="M238.1,255.9c-26.1,4-68.5,0.3-68.5,0.3C170.7,256.3,199.6,296.4,238.1,255.9"/>',
'<path fill-rule="evenodd" clip-rule="evenodd" fill="#FFFFFF" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" d="M176.4,262.7c0,0,7.1,2.2,12,2.1"/>',
'<path fill-rule="evenodd" clip-rule="evenodd" fill="#FFFFFF" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" d="M230.6,262.8c0,0-10.4,2.1-17.7,1.8"/>'
)
)
);
}
| function item_6() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
'<path fill="#FFFFFF" stroke="#000000" stroke-miterlimit="10" d="M238.1,255.9c-26.1,4-68.5,0.3-68.5,0.3C170.7,256.3,199.6,296.4,238.1,255.9"/>',
'<path fill-rule="evenodd" clip-rule="evenodd" fill="#FFFFFF" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" d="M176.4,262.7c0,0,7.1,2.2,12,2.1"/>',
'<path fill-rule="evenodd" clip-rule="evenodd" fill="#FFFFFF" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" d="M230.6,262.8c0,0-10.4,2.1-17.7,1.8"/>'
)
)
);
}
| 40,878 |
146 | // by either {approve} or {setApprovalForAll}.- If `to` refers to a smart contract, it must implement{IERC721Receiver-onERC721Received}, which is called upon a safe transfer. Emits a {Transfer} event. / | function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public payable virtual override {
transferFrom(from, to, tokenId);
if (to.code.length != 0)
if (!_checkContractOnERC721Received(from, to, tokenId, _data)) {
revert TransferToNonERC721ReceiverImplementer();
| function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public payable virtual override {
transferFrom(from, to, tokenId);
if (to.code.length != 0)
if (!_checkContractOnERC721Received(from, to, tokenId, _data)) {
revert TransferToNonERC721ReceiverImplementer();
| 6,287 |
12 | // send stMTRG to stMTRG/MTRG pair | IERC20(STMTRG).safeTransfer(STMTRG_PAIR, amountIn);
| IERC20(STMTRG).safeTransfer(STMTRG_PAIR, amountIn);
| 28,889 |
6 | // uint256 videoId = numberOfVideos; | User memory userDetails;
address[] memory emptyAddress;
userDetails = getMyProfile();
video.owner = msg.sender;
video.id = numberOfVideos;
video.uuid = uuid;
video.title = title;
video.videoUrl = videoUrl;
| User memory userDetails;
address[] memory emptyAddress;
userDetails = getMyProfile();
video.owner = msg.sender;
video.id = numberOfVideos;
video.uuid = uuid;
video.title = title;
video.videoUrl = videoUrl;
| 29,096 |
13 | // Moves `amount` tokens from the caller's account to `recipient`. Returns a boolean value indicating whether the operation succeeded. | * Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
function decimals() external view returns (uint8);
/**
* Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
| * Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
function decimals() external view returns (uint8);
/**
* Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
| 4,380 |
11 | // Name of the item | string name;
| string name;
| 11,708 |
38 | // Get the current supply of a token./resource Address of the resource token contract./ return The supply the resource, in wei, in canonical order. | function getSupply(address resource) external view returns (uint256) {
Token storage token = _tokens[resource];
require(resource != ZERO_ADDRESS && token.token == resource,
ERROR_INVALID);
return token.supply;
}
| function getSupply(address resource) external view returns (uint256) {
Token storage token = _tokens[resource];
require(resource != ZERO_ADDRESS && token.token == resource,
ERROR_INVALID);
return token.supply;
}
| 52,469 |
14 | // decreaseLiquidity function which interact with Uniswap v3 / | function _decreaseLiquidity(
uint256 _tokenId,
uint128 _liquidity,
uint256 _amount0Min,
uint256 _amount1Min
| function _decreaseLiquidity(
uint256 _tokenId,
uint128 _liquidity,
uint256 _amount0Min,
uint256 _amount1Min
| 46,816 |
245 | // withdraw a long oToken from a vault only the account owner or operator can withdraw a long oToken, cannot be called when system is partiallyPaused or fullyPaused _args WithdrawArgs structure / | function _withdrawLong(Actions.WithdrawArgs memory _args)
internal
notPartiallyPaused
onlyAuthorized(msg.sender, _args.owner)
| function _withdrawLong(Actions.WithdrawArgs memory _args)
internal
notPartiallyPaused
onlyAuthorized(msg.sender, _args.owner)
| 647 |
161 | // Checking if distribution is on | require(distributionsOn == true, "109");
| require(distributionsOn == true, "109");
| 39,388 |
109 | // Just pull all pickle and all WETH | if(_stakedPickle > 0){
PickleStake(pickleStakeAddress).exit(); // Will pull all pickle and all WETH (should be near empty)
_stakedPickle = 0;
}
| if(_stakedPickle > 0){
PickleStake(pickleStakeAddress).exit(); // Will pull all pickle and all WETH (should be near empty)
_stakedPickle = 0;
}
| 45,933 |
72 | // Incentivizer address of YAM protocol / | address public incentivizer;
| address public incentivizer;
| 10,849 |
36 | // Revoke the lock approval from the previous owner on the current token. | delete _lockApprovals[tokenId];
| delete _lockApprovals[tokenId];
| 37,428 |
200 | // User supplies assets into the market and receives bTokens in exchange Assumes interest has already been accrued up to the current block minter The address of the account which is supplying the assets mintAmount The amount of the underlying asset to supplyreturn (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount. / | function mintFresh(address minter, uint mintAmount) internal returns (uint, uint) {
/* Fail if mint not allowed */
uint allowed = bController.mintAllowed(address(this), minter, mintAmount);
if (allowed != 0) {
return (failOpaque(Error.BCONTROLLER_REJECTION, FailureInfo.MINT_BCONTROLLER_REJECTION, allowed), 0);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.MINT_FRESHNESS_CHECK), 0);
}
MintLocalVars memory vars;
(vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal();
if (vars.mathErr != MathError.NO_ERROR) {
return (failOpaque(Error.MATH_ERROR, FailureInfo.MINT_EXCHANGE_RATE_READ_FAILED, uint(vars.mathErr)), 0);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We call `doTransferIn` for the minter and the mintAmount.
* Note: The bToken must handle variations between ERC-20 and ETH underlying.
* `doTransferIn` reverts if anything goes wrong, since we can't be sure if
* side-effects occurred. The function returns the amount actually transferred,
* in case of a fee. On success, the bToken holds an additional `actualMintAmount`
* of cash.
*/
vars.actualMintAmount = doTransferIn(minter, mintAmount);
/*
* We get the current exchange rate and calculate the number of bTokens to be minted:
* mintTokens = actualMintAmount / exchangeRate
*/
(vars.mathErr, vars.mintTokens) = divScalarByExpTruncate(vars.actualMintAmount, Exp({mantissa: vars.exchangeRateMantissa}));
require(vars.mathErr == MathError.NO_ERROR, "MINT_EXCHANGE_CALCULATION_FAILED");
/*
* We calculate the new total supply of bTokens and minter token balance, checking for overflow:
* totalSupplyNew = totalSupply + mintTokens
* accountTokensNew = accountTokens[minter] + mintTokens
*/
(vars.mathErr, vars.totalSupplyNew) = addUInt(totalSupply, vars.mintTokens);
require(vars.mathErr == MathError.NO_ERROR, "MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED");
(vars.mathErr, vars.accountTokensNew) = addUInt(accountTokens[minter], vars.mintTokens);
require(vars.mathErr == MathError.NO_ERROR, "MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED");
/* We write previously calculated values into storage */
totalSupply = vars.totalSupplyNew;
accountTokens[minter] = vars.accountTokensNew;
/* We emit a Mint event, and a Transfer event */
emit MintToken(minter, vars.actualMintAmount, vars.mintTokens);
emit Transfer(address(this), minter, vars.mintTokens);
/* We call the defense hook */
bController.mintVerify(address(this), minter, vars.actualMintAmount, vars.mintTokens);
return (uint(Error.NO_ERROR), vars.actualMintAmount);
}
| function mintFresh(address minter, uint mintAmount) internal returns (uint, uint) {
/* Fail if mint not allowed */
uint allowed = bController.mintAllowed(address(this), minter, mintAmount);
if (allowed != 0) {
return (failOpaque(Error.BCONTROLLER_REJECTION, FailureInfo.MINT_BCONTROLLER_REJECTION, allowed), 0);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.MINT_FRESHNESS_CHECK), 0);
}
MintLocalVars memory vars;
(vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal();
if (vars.mathErr != MathError.NO_ERROR) {
return (failOpaque(Error.MATH_ERROR, FailureInfo.MINT_EXCHANGE_RATE_READ_FAILED, uint(vars.mathErr)), 0);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We call `doTransferIn` for the minter and the mintAmount.
* Note: The bToken must handle variations between ERC-20 and ETH underlying.
* `doTransferIn` reverts if anything goes wrong, since we can't be sure if
* side-effects occurred. The function returns the amount actually transferred,
* in case of a fee. On success, the bToken holds an additional `actualMintAmount`
* of cash.
*/
vars.actualMintAmount = doTransferIn(minter, mintAmount);
/*
* We get the current exchange rate and calculate the number of bTokens to be minted:
* mintTokens = actualMintAmount / exchangeRate
*/
(vars.mathErr, vars.mintTokens) = divScalarByExpTruncate(vars.actualMintAmount, Exp({mantissa: vars.exchangeRateMantissa}));
require(vars.mathErr == MathError.NO_ERROR, "MINT_EXCHANGE_CALCULATION_FAILED");
/*
* We calculate the new total supply of bTokens and minter token balance, checking for overflow:
* totalSupplyNew = totalSupply + mintTokens
* accountTokensNew = accountTokens[minter] + mintTokens
*/
(vars.mathErr, vars.totalSupplyNew) = addUInt(totalSupply, vars.mintTokens);
require(vars.mathErr == MathError.NO_ERROR, "MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED");
(vars.mathErr, vars.accountTokensNew) = addUInt(accountTokens[minter], vars.mintTokens);
require(vars.mathErr == MathError.NO_ERROR, "MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED");
/* We write previously calculated values into storage */
totalSupply = vars.totalSupplyNew;
accountTokens[minter] = vars.accountTokensNew;
/* We emit a Mint event, and a Transfer event */
emit MintToken(minter, vars.actualMintAmount, vars.mintTokens);
emit Transfer(address(this), minter, vars.mintTokens);
/* We call the defense hook */
bController.mintVerify(address(this), minter, vars.actualMintAmount, vars.mintTokens);
return (uint(Error.NO_ERROR), vars.actualMintAmount);
}
| 68,842 |
17 | // PUT ETHERS IN THE HOUSE ------------------------------------------------------------------------- | function invest(uint numberOfSqi) public payable {
require(msg.value >= sqiPrice * numberOfSqi);
require(numberOfSqi <= currentAvailableSqi);
currentAvailableSqi = currentAvailableSqi - numberOfSqi;
UnitsFactory f = UnitsFactory(factory);
f.updateCurrentAvailableSqi(address(this), currentAvailableSqi);
}
| function invest(uint numberOfSqi) public payable {
require(msg.value >= sqiPrice * numberOfSqi);
require(numberOfSqi <= currentAvailableSqi);
currentAvailableSqi = currentAvailableSqi - numberOfSqi;
UnitsFactory f = UnitsFactory(factory);
f.updateCurrentAvailableSqi(address(this), currentAvailableSqi);
}
| 9,061 |
168 | // Mapping owner address to address data. Bits Layout: - [0..63]`balance` - [64..127]`numberMinted` - [128..191] `numberBurned` - [192..255] `aux` | mapping(address => uint256) internal _packedAddressData;
| mapping(address => uint256) internal _packedAddressData;
| 18,360 |
1 | // Get the subprotocol metadata that is associated with a subprotocol NFT/NFTs assigned to the zero address are considered invalid, and this/function throws for queries about the zero address./_tokenID The NFT to query/ return Subprotocol metadata as JSON | function metadata(uint256 _tokenID) external view returns (string memory);
| function metadata(uint256 _tokenID) external view returns (string memory);
| 12,361 |
3 | // function get Morph value | function getMorphValue(uint256 workContractObjectiveId) public view returns(string memory){
return MvpContractObj[workContractObjectiveId].ModuleInfo;
}
| function getMorphValue(uint256 workContractObjectiveId) public view returns(string memory){
return MvpContractObj[workContractObjectiveId].ModuleInfo;
}
| 41,086 |
100 | // Transfer ERC20 from on owner to another passing by a third party. / | function transferFrom(
address _sender,
address _recipient,
uint256 _amount
| function transferFrom(
address _sender,
address _recipient,
uint256 _amount
| 24,543 |
139 | // This Strategy's name. You can use this field to manage the "version" of this Strategy, e.g. `StrategySomethingOrOtherV1`. However, "API Version" is managed by `apiVersion()` function above.return This Strategy's name. / | function name() external view virtual returns (string memory);
| function name() external view virtual returns (string memory);
| 4,298 |
34 | // Revert upon overflow. | if lt(allowanceAfter, allowanceBefore) {
mstore(0x00, 0xf9067066) // `AllowanceOverflow()`.
revert(0x1c, 0x04)
}
| if lt(allowanceAfter, allowanceBefore) {
mstore(0x00, 0xf9067066) // `AllowanceOverflow()`.
revert(0x1c, 0x04)
}
| 19,140 |
1 | // Store latest day that distributored added reward for the user | mapping(address => mapping(address => uint256)) private latestAddRewardDate;
| mapping(address => mapping(address => uint256)) private latestAddRewardDate;
| 20,122 |
79 | // Function that lets user stake NFY | function stakeNFY(uint256 _amount) public {
require(_amount > 0, "Can not stake 0 NFY");
require(NFYToken.balanceOf(_msgSender()) >= _amount, "Do not have enough NFY to stake");
updatePool();
if(StakingNFT.nftTokenId(_msgSender()) == 0){
addStakeholder(_msgSender());
}
NFT storage nft = NFTDetails[StakingNFT.nftTokenId(_msgSender())];
if(nft._NFYDeposited > 0) {
uint256 _pendingRewards = nft._NFYDeposited.mul(accNfyPerShare).div(1e18).sub(nft._rewardDebt);
if(_pendingRewards > 0) {
NFYToken.transfer(_msgSender(), _pendingRewards);
emit RewardsClaimed(_msgSender(), _pendingRewards, StakingNFT.nftTokenId(_msgSender()), now);
}
}
NFYToken.transferFrom(_msgSender(), address(this), _amount);
nft._NFYDeposited = nft._NFYDeposited.add(_amount);
totalStaked = totalStaked.add(_amount);
nft._rewardDebt = nft._NFYDeposited.mul(accNfyPerShare).div(1e18);
emit StakeCompleted(_msgSender(), _amount, StakingNFT.nftTokenId(_msgSender()), nft._NFYDeposited, now);
}
| function stakeNFY(uint256 _amount) public {
require(_amount > 0, "Can not stake 0 NFY");
require(NFYToken.balanceOf(_msgSender()) >= _amount, "Do not have enough NFY to stake");
updatePool();
if(StakingNFT.nftTokenId(_msgSender()) == 0){
addStakeholder(_msgSender());
}
NFT storage nft = NFTDetails[StakingNFT.nftTokenId(_msgSender())];
if(nft._NFYDeposited > 0) {
uint256 _pendingRewards = nft._NFYDeposited.mul(accNfyPerShare).div(1e18).sub(nft._rewardDebt);
if(_pendingRewards > 0) {
NFYToken.transfer(_msgSender(), _pendingRewards);
emit RewardsClaimed(_msgSender(), _pendingRewards, StakingNFT.nftTokenId(_msgSender()), now);
}
}
NFYToken.transferFrom(_msgSender(), address(this), _amount);
nft._NFYDeposited = nft._NFYDeposited.add(_amount);
totalStaked = totalStaked.add(_amount);
nft._rewardDebt = nft._NFYDeposited.mul(accNfyPerShare).div(1e18);
emit StakeCompleted(_msgSender(), _amount, StakingNFT.nftTokenId(_msgSender()), nft._NFYDeposited, now);
}
| 45,465 |
5 | // Percentage precision | uint public percentagePrecision = 10 ** 2;
| uint public percentagePrecision = 10 ** 2;
| 74,400 |
131 | // The total SNX owned by this account, both escrowed and unescrowed,against which synths can be issued.This includes those already being used as collateral (locked), and thoseavailable for further issuance (unlocked). / | function collateral(address account)
public
view
returns (uint)
| function collateral(address account)
public
view
returns (uint)
| 8,648 |
230 | // Directly sets the extra data for the ownership data `index`. / | function _setExtraDataAt(uint256 index, uint24 extraData) internal virtual {
uint256 packed = _packedOwnerships[index];
if (packed == 0) revert OwnershipNotInitializedForExtraData();
uint256 extraDataCasted;
// Cast `extraData` with assembly to avoid redundant masking.
assembly {
extraDataCasted := extraData
}
packed = (packed & _BITMASK_EXTRA_DATA_COMPLEMENT) | (extraDataCasted << _BITPOS_EXTRA_DATA);
_packedOwnerships[index] = packed;
}
| function _setExtraDataAt(uint256 index, uint24 extraData) internal virtual {
uint256 packed = _packedOwnerships[index];
if (packed == 0) revert OwnershipNotInitializedForExtraData();
uint256 extraDataCasted;
// Cast `extraData` with assembly to avoid redundant masking.
assembly {
extraDataCasted := extraData
}
packed = (packed & _BITMASK_EXTRA_DATA_COMPLEMENT) | (extraDataCasted << _BITPOS_EXTRA_DATA);
_packedOwnerships[index] = packed;
}
| 5,771 |
33 | // Update user information / | function updateStakerInfo(
address _user,
uint256 _amount,
uint256 _rewardAllowed,
uint256 _rewardDebt,
uint256 _distributed
| function updateStakerInfo(
address _user,
uint256 _amount,
uint256 _rewardAllowed,
uint256 _rewardDebt,
uint256 _distributed
| 53,712 |
41 | // Mints a specific amount of tokens._value The amount of token to be Minted./ | function mint(uint256 _value) onlyCOO whenNotPaused public {
_mint(_value);
}
| function mint(uint256 _value) onlyCOO whenNotPaused public {
_mint(_value);
}
| 8,054 |
312 | // if the first sale already happened, then give the artist + platform the secondary royalty percentage | if (tokenDidHaveFirstSale[tokenId]) {
| if (tokenDidHaveFirstSale[tokenId]) {
| 28,489 |
14 | // Constructors | constructor(
address payable _owner,
uint256 _minimumBid,
address _auctioneer
| constructor(
address payable _owner,
uint256 _minimumBid,
address _auctioneer
| 20,971 |
81 | // If whitelist enforcement is not enabled, then allow all | if(!isWhitelistEnabled){
return true;
}
| if(!isWhitelistEnabled){
return true;
}
| 17,303 |
62 | // SimpleERC20 Implementation of the SimpleERC20 / | contract SimpleERC20 is ERC20, ServicePayer, GeneratorCopyright("v5.0.1") {
constructor (
string memory name_,
string memory symbol_,
uint256 initialBalance_,
address payable feeReceiver_
)
ERC20(name_, symbol_)
ServicePayer(feeReceiver_, "SimpleERC20")
payable
{
require(initialBalance_ > 0, "SimpleERC20: supply cannot be zero");
_mint(_msgSender(), initialBalance_);
}
}
| contract SimpleERC20 is ERC20, ServicePayer, GeneratorCopyright("v5.0.1") {
constructor (
string memory name_,
string memory symbol_,
uint256 initialBalance_,
address payable feeReceiver_
)
ERC20(name_, symbol_)
ServicePayer(feeReceiver_, "SimpleERC20")
payable
{
require(initialBalance_ > 0, "SimpleERC20: supply cannot be zero");
_mint(_msgSender(), initialBalance_);
}
}
| 932 |
114 | // ORIGINALS - DIAMOND // ORIGINALS - GOLD // ORIGINALS - SILVER (020 to 032) / Move to the next deploy step. | deployStep = DeployStep.WaitingForStepTwo;
| deployStep = DeployStep.WaitingForStepTwo;
| 4,567 |
4 | // Load the length (first 32 bytes) | let len := mload(sig)
| let len := mload(sig)
| 36,452 |
17 | // sets a new admin role for this contract | function setContractAdminRole(bytes32 newContractAdminRole) external override onlyGovernor {
_setContractAdminRole(newContractAdminRole);
}
| function setContractAdminRole(bytes32 newContractAdminRole) external override onlyGovernor {
_setContractAdminRole(newContractAdminRole);
}
| 23,012 |
2 | // +STRUCTS ------------------------------------------------- | struct MarketItem {
uint itemId;
uint256 tokenId;
address payable seller;
address payable owner;
uint256 price;
bool sold;
bool isActive;
}
| struct MarketItem {
uint itemId;
uint256 tokenId;
address payable seller;
address payable owner;
uint256 price;
bool sold;
bool isActive;
}
| 30,062 |
265 | // Represents a single sponsor's position. All collateral is held by this contract. This struct acts as bookkeeping for how much of that collateral is allocated to each sponsor. | struct PositionData {
FixedPoint.Unsigned tokensOutstanding;
| struct PositionData {
FixedPoint.Unsigned tokensOutstanding;
| 8,051 |
13 | // BlockHash only works for the most 256 recent blocks. | uint256 _block_shift = uint(keccak256(abi.encodePacked(block.difficulty, block.timestamp)));
_block_shift = 1 + (_block_shift % 255);
| uint256 _block_shift = uint(keccak256(abi.encodePacked(block.difficulty, block.timestamp)));
_block_shift = 1 + (_block_shift % 255);
| 28,394 |
38 | // Return the current liquidity value. | function getLiquidity() public view override returns (uint112) {
( , uint112 _reserve1, ) = pair.getReserves();
return _reserve1;
}
| function getLiquidity() public view override returns (uint112) {
( , uint112 _reserve1, ) = pair.getReserves();
return _reserve1;
}
| 15,163 |
71 | // Send same amount KYLv2 | ERC20(kylV2).transferFrom(kylV2Treasure, sender, amount);
emit Swap_KYL(sender, amount);
| ERC20(kylV2).transferFrom(kylV2Treasure, sender, amount);
emit Swap_KYL(sender, amount);
| 33,818 |
196 | // File: @opengsn/gsn/contracts/utils/RLPReader.sol/// solhint-disable / | library RLPReader {
uint8 constant STRING_SHORT_START = 0x80;
uint8 constant STRING_LONG_START = 0xb8;
uint8 constant LIST_SHORT_START = 0xc0;
uint8 constant LIST_LONG_START = 0xf8;
uint8 constant WORD_SIZE = 32;
struct RLPItem {
uint len;
uint memPtr;
}
using RLPReader for bytes;
using RLPReader for uint;
using RLPReader for RLPReader.RLPItem;
// helper function to decode rlp encoded ethereum transaction
/*
* @param rawTransaction RLP encoded ethereum transaction
* @return tuple (nonce,gasPrice,gasLimit,to,value,data)
*/
function decodeTransaction(bytes memory rawTransaction) internal pure returns (uint, uint, uint, address, uint, bytes memory){
RLPReader.RLPItem[] memory values = rawTransaction.toRlpItem().toList(); // must convert to an rlpItem first!
return (values[0].toUint(), values[1].toUint(), values[2].toUint(), values[3].toAddress(), values[4].toUint(), values[5].toBytes());
}
/*
* @param item RLP encoded bytes
*/
function toRlpItem(bytes memory item) internal pure returns (RLPItem memory) {
if (item.length == 0)
return RLPItem(0, 0);
uint memPtr;
assembly {
memPtr := add(item, 0x20)
}
return RLPItem(item.length, memPtr);
}
/*
* @param item RLP encoded list in bytes
*/
function toList(RLPItem memory item) internal pure returns (RLPItem[] memory result) {
require(isList(item), "isList failed");
uint items = numItems(item);
result = new RLPItem[](items);
uint memPtr = item.memPtr + _payloadOffset(item.memPtr);
uint dataLen;
for (uint i = 0; i < items; i++) {
dataLen = _itemLength(memPtr);
result[i] = RLPItem(dataLen, memPtr);
memPtr = memPtr + dataLen;
}
}
/*
* Helpers
*/
// @return indicator whether encoded payload is a list. negate this function call for isData.
function isList(RLPItem memory item) internal pure returns (bool) {
uint8 byte0;
uint memPtr = item.memPtr;
assembly {
byte0 := byte(0, mload(memPtr))
}
if (byte0 < LIST_SHORT_START)
return false;
return true;
}
// @return number of payload items inside an encoded list.
function numItems(RLPItem memory item) internal pure returns (uint) {
uint count = 0;
uint currPtr = item.memPtr + _payloadOffset(item.memPtr);
uint endPtr = item.memPtr + item.len;
while (currPtr < endPtr) {
currPtr = currPtr + _itemLength(currPtr);
// skip over an item
count++;
}
return count;
}
// @return entire rlp item byte length
function _itemLength(uint memPtr) internal pure returns (uint len) {
uint byte0;
assembly {
byte0 := byte(0, mload(memPtr))
}
if (byte0 < STRING_SHORT_START)
return 1;
else if (byte0 < STRING_LONG_START)
return byte0 - STRING_SHORT_START + 1;
else if (byte0 < LIST_SHORT_START) {
assembly {
let byteLen := sub(byte0, 0xb7) // # of bytes the actual length is
memPtr := add(memPtr, 1) // skip over the first byte
/* 32 byte word size */
let dataLen := div(mload(memPtr), exp(256, sub(32, byteLen))) // right shifting to get the len
len := add(dataLen, add(byteLen, 1))
}
}
else if (byte0 < LIST_LONG_START) {
return byte0 - LIST_SHORT_START + 1;
}
else {
assembly {
let byteLen := sub(byte0, 0xf7)
memPtr := add(memPtr, 1)
let dataLen := div(mload(memPtr), exp(256, sub(32, byteLen))) // right shifting to the correct length
len := add(dataLen, add(byteLen, 1))
}
}
}
// @return number of bytes until the data
function _payloadOffset(uint memPtr) internal pure returns (uint) {
uint byte0;
assembly {
byte0 := byte(0, mload(memPtr))
}
if (byte0 < STRING_SHORT_START)
return 0;
else if (byte0 < STRING_LONG_START || (byte0 >= LIST_SHORT_START && byte0 < LIST_LONG_START))
return 1;
else if (byte0 < LIST_SHORT_START) // being explicit
return byte0 - (STRING_LONG_START - 1) + 1;
else
return byte0 - (LIST_LONG_START - 1) + 1;
}
/** RLPItem conversions into data types **/
// @returns raw rlp encoding in bytes
function toRlpBytes(RLPItem memory item) internal pure returns (bytes memory) {
bytes memory result = new bytes(item.len);
uint ptr;
assembly {
ptr := add(0x20, result)
}
copy(item.memPtr, ptr, item.len);
return result;
}
function toBoolean(RLPItem memory item) internal pure returns (bool) {
require(item.len == 1, "Invalid RLPItem. Booleans are encoded in 1 byte");
uint result;
uint memPtr = item.memPtr;
assembly {
result := byte(0, mload(memPtr))
}
return result == 0 ? false : true;
}
function toAddress(RLPItem memory item) internal pure returns (address) {
// 1 byte for the length prefix according to RLP spec
require(item.len <= 21, "Invalid RLPItem. Addresses are encoded in 20 bytes or less");
return address(toUint(item));
}
function toUint(RLPItem memory item) internal pure returns (uint) {
uint offset = _payloadOffset(item.memPtr);
uint len = item.len - offset;
uint memPtr = item.memPtr + offset;
uint result;
assembly {
result := div(mload(memPtr), exp(256, sub(32, len))) // shift to the correct location
}
return result;
}
function toBytes(RLPItem memory item) internal pure returns (bytes memory) {
uint offset = _payloadOffset(item.memPtr);
uint len = item.len - offset;
// data length
bytes memory result = new bytes(len);
uint destPtr;
assembly {
destPtr := add(0x20, result)
}
copy(item.memPtr + offset, destPtr, len);
return result;
}
/*
* @param src Pointer to source
* @param dest Pointer to destination
* @param len Amount of memory to copy from the source
*/
function copy(uint src, uint dest, uint len) internal pure {
// copy as many word sizes as possible
for (; len >= WORD_SIZE; len -= WORD_SIZE) {
assembly {
mstore(dest, mload(src))
}
src += WORD_SIZE;
dest += WORD_SIZE;
}
// left over bytes. Mask is used to remove unwanted bytes from the word
uint mask = 256 ** (WORD_SIZE - len) - 1;
assembly {
let srcpart := and(mload(src), not(mask)) // zero out src
let destpart := and(mload(dest), mask) // retrieve the bytes
mstore(dest, or(destpart, srcpart))
}
}
}
| library RLPReader {
uint8 constant STRING_SHORT_START = 0x80;
uint8 constant STRING_LONG_START = 0xb8;
uint8 constant LIST_SHORT_START = 0xc0;
uint8 constant LIST_LONG_START = 0xf8;
uint8 constant WORD_SIZE = 32;
struct RLPItem {
uint len;
uint memPtr;
}
using RLPReader for bytes;
using RLPReader for uint;
using RLPReader for RLPReader.RLPItem;
// helper function to decode rlp encoded ethereum transaction
/*
* @param rawTransaction RLP encoded ethereum transaction
* @return tuple (nonce,gasPrice,gasLimit,to,value,data)
*/
function decodeTransaction(bytes memory rawTransaction) internal pure returns (uint, uint, uint, address, uint, bytes memory){
RLPReader.RLPItem[] memory values = rawTransaction.toRlpItem().toList(); // must convert to an rlpItem first!
return (values[0].toUint(), values[1].toUint(), values[2].toUint(), values[3].toAddress(), values[4].toUint(), values[5].toBytes());
}
/*
* @param item RLP encoded bytes
*/
function toRlpItem(bytes memory item) internal pure returns (RLPItem memory) {
if (item.length == 0)
return RLPItem(0, 0);
uint memPtr;
assembly {
memPtr := add(item, 0x20)
}
return RLPItem(item.length, memPtr);
}
/*
* @param item RLP encoded list in bytes
*/
function toList(RLPItem memory item) internal pure returns (RLPItem[] memory result) {
require(isList(item), "isList failed");
uint items = numItems(item);
result = new RLPItem[](items);
uint memPtr = item.memPtr + _payloadOffset(item.memPtr);
uint dataLen;
for (uint i = 0; i < items; i++) {
dataLen = _itemLength(memPtr);
result[i] = RLPItem(dataLen, memPtr);
memPtr = memPtr + dataLen;
}
}
/*
* Helpers
*/
// @return indicator whether encoded payload is a list. negate this function call for isData.
function isList(RLPItem memory item) internal pure returns (bool) {
uint8 byte0;
uint memPtr = item.memPtr;
assembly {
byte0 := byte(0, mload(memPtr))
}
if (byte0 < LIST_SHORT_START)
return false;
return true;
}
// @return number of payload items inside an encoded list.
function numItems(RLPItem memory item) internal pure returns (uint) {
uint count = 0;
uint currPtr = item.memPtr + _payloadOffset(item.memPtr);
uint endPtr = item.memPtr + item.len;
while (currPtr < endPtr) {
currPtr = currPtr + _itemLength(currPtr);
// skip over an item
count++;
}
return count;
}
// @return entire rlp item byte length
function _itemLength(uint memPtr) internal pure returns (uint len) {
uint byte0;
assembly {
byte0 := byte(0, mload(memPtr))
}
if (byte0 < STRING_SHORT_START)
return 1;
else if (byte0 < STRING_LONG_START)
return byte0 - STRING_SHORT_START + 1;
else if (byte0 < LIST_SHORT_START) {
assembly {
let byteLen := sub(byte0, 0xb7) // # of bytes the actual length is
memPtr := add(memPtr, 1) // skip over the first byte
/* 32 byte word size */
let dataLen := div(mload(memPtr), exp(256, sub(32, byteLen))) // right shifting to get the len
len := add(dataLen, add(byteLen, 1))
}
}
else if (byte0 < LIST_LONG_START) {
return byte0 - LIST_SHORT_START + 1;
}
else {
assembly {
let byteLen := sub(byte0, 0xf7)
memPtr := add(memPtr, 1)
let dataLen := div(mload(memPtr), exp(256, sub(32, byteLen))) // right shifting to the correct length
len := add(dataLen, add(byteLen, 1))
}
}
}
// @return number of bytes until the data
function _payloadOffset(uint memPtr) internal pure returns (uint) {
uint byte0;
assembly {
byte0 := byte(0, mload(memPtr))
}
if (byte0 < STRING_SHORT_START)
return 0;
else if (byte0 < STRING_LONG_START || (byte0 >= LIST_SHORT_START && byte0 < LIST_LONG_START))
return 1;
else if (byte0 < LIST_SHORT_START) // being explicit
return byte0 - (STRING_LONG_START - 1) + 1;
else
return byte0 - (LIST_LONG_START - 1) + 1;
}
/** RLPItem conversions into data types **/
// @returns raw rlp encoding in bytes
function toRlpBytes(RLPItem memory item) internal pure returns (bytes memory) {
bytes memory result = new bytes(item.len);
uint ptr;
assembly {
ptr := add(0x20, result)
}
copy(item.memPtr, ptr, item.len);
return result;
}
function toBoolean(RLPItem memory item) internal pure returns (bool) {
require(item.len == 1, "Invalid RLPItem. Booleans are encoded in 1 byte");
uint result;
uint memPtr = item.memPtr;
assembly {
result := byte(0, mload(memPtr))
}
return result == 0 ? false : true;
}
function toAddress(RLPItem memory item) internal pure returns (address) {
// 1 byte for the length prefix according to RLP spec
require(item.len <= 21, "Invalid RLPItem. Addresses are encoded in 20 bytes or less");
return address(toUint(item));
}
function toUint(RLPItem memory item) internal pure returns (uint) {
uint offset = _payloadOffset(item.memPtr);
uint len = item.len - offset;
uint memPtr = item.memPtr + offset;
uint result;
assembly {
result := div(mload(memPtr), exp(256, sub(32, len))) // shift to the correct location
}
return result;
}
function toBytes(RLPItem memory item) internal pure returns (bytes memory) {
uint offset = _payloadOffset(item.memPtr);
uint len = item.len - offset;
// data length
bytes memory result = new bytes(len);
uint destPtr;
assembly {
destPtr := add(0x20, result)
}
copy(item.memPtr + offset, destPtr, len);
return result;
}
/*
* @param src Pointer to source
* @param dest Pointer to destination
* @param len Amount of memory to copy from the source
*/
function copy(uint src, uint dest, uint len) internal pure {
// copy as many word sizes as possible
for (; len >= WORD_SIZE; len -= WORD_SIZE) {
assembly {
mstore(dest, mload(src))
}
src += WORD_SIZE;
dest += WORD_SIZE;
}
// left over bytes. Mask is used to remove unwanted bytes from the word
uint mask = 256 ** (WORD_SIZE - len) - 1;
assembly {
let srcpart := and(mload(src), not(mask)) // zero out src
let destpart := and(mload(dest), mask) // retrieve the bytes
mstore(dest, or(destpart, srcpart))
}
}
}
| 6,677 |
13 | // Given an address, check what charity this address has set | function charityOf(address tokenOwner) public view returns (uint8 charityIndex, address charity, string memory description) {
uint8 index = charityState[tokenOwner];
if(index >= listOfCharityAddresses.length) index = 0;
return (index, listOfCharityAddresses[index], listOfCharities[index]);
}
| function charityOf(address tokenOwner) public view returns (uint8 charityIndex, address charity, string memory description) {
uint8 index = charityState[tokenOwner];
if(index >= listOfCharityAddresses.length) index = 0;
return (index, listOfCharityAddresses[index], listOfCharities[index]);
}
| 2,996 |
55 | // staking fee percent | uint public stakingFeeRate = 0;
| uint public stakingFeeRate = 0;
| 65,024 |
1 | // Query all subdomains. Must revert if the list of domains is unknown or infinite./ return The list of all subdomains. | function listDomains() external view returns (string[] memory);
| function listDomains() external view returns (string[] memory);
| 3,281 |
1 | // bytes4(keccak256("isValidSignature(bytes,bytes)") | bytes4 constant internal MAGICVALUE = 0x20c13b0b;
| bytes4 constant internal MAGICVALUE = 0x20c13b0b;
| 24,225 |
111 | // erc20 address => status | mapping(address => bool) public erc20Whitelist;
| mapping(address => bool) public erc20Whitelist;
| 1,430 |
283 | // contract to be paused and set to max tokenIds first. | function hatch(address player, uint256 trait, string memory tokenURI)
public onlyHatchery
whenNotPaused
returns (uint256)
| function hatch(address player, uint256 trait, string memory tokenURI)
public onlyHatchery
whenNotPaused
returns (uint256)
| 42,741 |
0 | // Interface de nuestro token ERC20 | interface IERC20 {
// Devuelve la cantidad de tokens en existencia
function totalSupply() external view returns ( uint256 );
// Devuelve la cantidad de tokens para una direccion indicada por parametro
function balanceOf( address account ) external view returns ( uint256 );
// Devuelve el numero de token que el spender podrá gastar en nombre del propietario (owner)
function allowance( address owner, address spender ) external view returns ( uint256 );
// Devuelve un valor booleano resultado de la operacion indicada
function transfer( address recipient, uint256 amount ) external returns ( bool );
// Devuelve un valor booleano con el resultado de la operacion de gasto
function approve( address spender, uint256 amount ) external returns ( bool );
// Devuelve un valor booleano con el resultado de la operacion de paso de una cantidad de tokens usando el metodo allowance()
function transferFrom( address sender, address recipient, uint256 amount) external returns ( bool );
// Evento que se debe emitir cuando una cantidad de tokens pase de un origen a un destino
event Transfer( address indexed from, address indexed to, uint256 value );
// Evento que se debe emitir cuando se establece una asignación con el metodo allowance()
event Approval( address indexed owner, address indexed spender, uint256 value);
}
| interface IERC20 {
// Devuelve la cantidad de tokens en existencia
function totalSupply() external view returns ( uint256 );
// Devuelve la cantidad de tokens para una direccion indicada por parametro
function balanceOf( address account ) external view returns ( uint256 );
// Devuelve el numero de token que el spender podrá gastar en nombre del propietario (owner)
function allowance( address owner, address spender ) external view returns ( uint256 );
// Devuelve un valor booleano resultado de la operacion indicada
function transfer( address recipient, uint256 amount ) external returns ( bool );
// Devuelve un valor booleano con el resultado de la operacion de gasto
function approve( address spender, uint256 amount ) external returns ( bool );
// Devuelve un valor booleano con el resultado de la operacion de paso de una cantidad de tokens usando el metodo allowance()
function transferFrom( address sender, address recipient, uint256 amount) external returns ( bool );
// Evento que se debe emitir cuando una cantidad de tokens pase de un origen a un destino
event Transfer( address indexed from, address indexed to, uint256 value );
// Evento que se debe emitir cuando se establece una asignación con el metodo allowance()
event Approval( address indexed owner, address indexed spender, uint256 value);
}
| 25,806 |
0 | // Next 5 lines from https:ethereum.stackexchange.com/a/83577 | if (result.length < 68) revert();
assembly {
result := add(result, 0x04)
}
| if (result.length < 68) revert();
assembly {
result := add(result, 0x04)
}
| 10,206 |
11 | // purchase(): purchase and transfer point from the seller to the buyer | function purchase(uint32 _point, uint96 _amount, address _token)
external
payable
| function purchase(uint32 _point, uint96 _amount, address _token)
external
payable
| 3,133 |
55 | // Create uniswap pair for this token, add liquidity, and mint the developer's token cut. | function listToken() internal {
require(uniswapPair == address(0), "Token already listed.");
_approve(address(this), address(kUniswapRouter), 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
uint tokens = kPresaleTokensPerEth.mul(address(this).balance);
_mint(developer, tokens.mul(kDeveloperTokenCut).div(100));
uniswapPair = kUniswapFactory.getPair(address(this), kWeth);
if (uniswapPair == address(0)) {
_mint(address(this), tokens);
kUniswapRouter.addLiquidityETH{value:address(this).balance}(address(this), tokens, 0, 0, address(this), block.timestamp);
uniswapPair = kUniswapFactory.getPair(address(this), kWeth);
} else {
// Sigh, someone has already pointlessly created the pair. Now we have to do some math :(
(uint reserveA, uint reserveB,) = IUniswapV2Pair(uniswapPair).getReserves();
if (address(this) < kWeth) {
// Round up tokens to ensure that all of the eth will be taken by the router.
tokens = reserveA.mul(address(this).balance).add(reserveB).sub(1).div(reserveB);
} else {
// Round up tokens to ensure that all of the eth will be taken by the router.
tokens = reserveB.mul(address(this).balance).add(reserveA).sub(1).div(reserveA);
}
_mint(address(this), tokens);
kUniswapRouter.addLiquidityETH{value:address(this).balance}(address(this), tokens, 0, 0, address(this), block.timestamp);
// Adjust price to match presale.
adjustPrice();
// Might have a very small amount of tokens left in our contract. Tidy up.
uint leftoverTokens = balanceOf(address(this));
if (leftoverTokens > 0) {
_burn(address(this), leftoverTokens);
}
}
// Don't think these can fail, but just in case ...
require(uniswapPair != address(0));
// Set lastRepriceTime to nearest day since presaleStartTime to avoid reprices
// occurring at some horrible time in the middle of the night.
lastRepriceTime = presaleStartTime + ((uint32(block.timestamp) - presaleStartTime + 43200) / 86400) * 86400;
}
| function listToken() internal {
require(uniswapPair == address(0), "Token already listed.");
_approve(address(this), address(kUniswapRouter), 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
uint tokens = kPresaleTokensPerEth.mul(address(this).balance);
_mint(developer, tokens.mul(kDeveloperTokenCut).div(100));
uniswapPair = kUniswapFactory.getPair(address(this), kWeth);
if (uniswapPair == address(0)) {
_mint(address(this), tokens);
kUniswapRouter.addLiquidityETH{value:address(this).balance}(address(this), tokens, 0, 0, address(this), block.timestamp);
uniswapPair = kUniswapFactory.getPair(address(this), kWeth);
} else {
// Sigh, someone has already pointlessly created the pair. Now we have to do some math :(
(uint reserveA, uint reserveB,) = IUniswapV2Pair(uniswapPair).getReserves();
if (address(this) < kWeth) {
// Round up tokens to ensure that all of the eth will be taken by the router.
tokens = reserveA.mul(address(this).balance).add(reserveB).sub(1).div(reserveB);
} else {
// Round up tokens to ensure that all of the eth will be taken by the router.
tokens = reserveB.mul(address(this).balance).add(reserveA).sub(1).div(reserveA);
}
_mint(address(this), tokens);
kUniswapRouter.addLiquidityETH{value:address(this).balance}(address(this), tokens, 0, 0, address(this), block.timestamp);
// Adjust price to match presale.
adjustPrice();
// Might have a very small amount of tokens left in our contract. Tidy up.
uint leftoverTokens = balanceOf(address(this));
if (leftoverTokens > 0) {
_burn(address(this), leftoverTokens);
}
}
// Don't think these can fail, but just in case ...
require(uniswapPair != address(0));
// Set lastRepriceTime to nearest day since presaleStartTime to avoid reprices
// occurring at some horrible time in the middle of the night.
lastRepriceTime = presaleStartTime + ((uint32(block.timestamp) - presaleStartTime + 43200) / 86400) * 86400;
}
| 3,341 |
97 | // Remove the collateral and outstanding from the overall total position. | FixedPoint.Unsigned memory remainingRawCollateral = positionToLiquidate.rawCollateral;
rawTotalPositionCollateral = rawTotalPositionCollateral.sub(remainingRawCollateral);
totalTokensOutstanding = totalTokensOutstanding.sub(positionToLiquidate.tokensOutstanding);
| FixedPoint.Unsigned memory remainingRawCollateral = positionToLiquidate.rawCollateral;
rawTotalPositionCollateral = rawTotalPositionCollateral.sub(remainingRawCollateral);
totalTokensOutstanding = totalTokensOutstanding.sub(positionToLiquidate.tokensOutstanding);
| 27,515 |
71 | // 2% during the first round, and the normal fraction otherwise | _div = wmul(rnd.totalInvested, 2 * 10**16);
| _div = wmul(rnd.totalInvested, 2 * 10**16);
| 26,704 |
8 | // revert InsufficientBalance({ requested: amount, available: balances[msg.sender] }); | revert InsufficientBalance(amount, balances[msg.sender]);
| revert InsufficientBalance(amount, balances[msg.sender]);
| 21,477 |
128 | // Function for borrower to reclaim stuck currencyTokenCan only call this function after the loan is Closedand all of LoanToken holders have been burnt / | function reclaim() external override onlyClosed onlyBorrower {
require(totalSupply() == 0, "LoanToken: Cannot reclaim when LoanTokens are in circulation");
uint256 balanceRemaining = _balance();
require(balanceRemaining > 0, "LoanToken: Cannot reclaim when balance 0");
require(currencyToken.transfer(borrower, balanceRemaining));
emit Reclaimed(borrower, balanceRemaining);
}
| function reclaim() external override onlyClosed onlyBorrower {
require(totalSupply() == 0, "LoanToken: Cannot reclaim when LoanTokens are in circulation");
uint256 balanceRemaining = _balance();
require(balanceRemaining > 0, "LoanToken: Cannot reclaim when balance 0");
require(currencyToken.transfer(borrower, balanceRemaining));
emit Reclaimed(borrower, balanceRemaining);
}
| 46,177 |
33 | // Withdraw full unlocked balance | function exit(address onBehalfOf) external {
require(onBehalfOf == msg.sender || exitDelegatee[onBehalfOf] == msg.sender, "Not authorized");
_updateReward(onBehalfOf);
(uint256 amount, uint256 penaltyAmount, ) = withdrawableBalance(onBehalfOf);
delete userEarnings[onBehalfOf];
Balances storage bal = balances[onBehalfOf];
bal.earned = 0;
rewardToken.safeTransfer(onBehalfOf, amount);
if (penaltyAmount > 0) {
incentivesController.claim(address(this), new address[](0));
_notifyReward(address(rewardToken), penaltyAmount);
}
emit Exit(onBehalfOf, amount, penaltyAmount);
}
| function exit(address onBehalfOf) external {
require(onBehalfOf == msg.sender || exitDelegatee[onBehalfOf] == msg.sender, "Not authorized");
_updateReward(onBehalfOf);
(uint256 amount, uint256 penaltyAmount, ) = withdrawableBalance(onBehalfOf);
delete userEarnings[onBehalfOf];
Balances storage bal = balances[onBehalfOf];
bal.earned = 0;
rewardToken.safeTransfer(onBehalfOf, amount);
if (penaltyAmount > 0) {
incentivesController.claim(address(this), new address[](0));
_notifyReward(address(rewardToken), penaltyAmount);
}
emit Exit(onBehalfOf, amount, penaltyAmount);
}
| 36,670 |
83 | // swapX2Y | (amountIn, amountOut) = IiZiSwapPool(poolAddr).swapX2Y(
recipient, params.amount, -799999,
abi.encode(SwapCallbackData({
tokenX: params.tokenIn,
fee: params.fee,
tokenY: params.tokenOut,
payer: msg.sender
}))
| (amountIn, amountOut) = IiZiSwapPool(poolAddr).swapX2Y(
recipient, params.amount, -799999,
abi.encode(SwapCallbackData({
tokenX: params.tokenIn,
fee: params.fee,
tokenY: params.tokenOut,
payer: msg.sender
}))
| 15,498 |
338 | // Calcs user share depending on deposited amounts | function _calcShare(uint128 liquidity)
internal
view
returns (
uint256 shares
)
| function _calcShare(uint128 liquidity)
internal
view
returns (
uint256 shares
)
| 10,687 |
53 | // Applies `scalingFactor` to `amount`, resulting in a larger or equal value depending on whether it neededscaling or not. / | function _upscale(uint256 amount, uint256 scalingFactor) internal pure returns (uint256) {
// Upscale rounding wouldn't necessarily always go in the same direction: in a swap for example the balance of
// token in should be rounded up, and that of token out rounded down. This is the only place where we round in
// the same direction for all amounts, as the impact of this rounding is expected to be minimal (and there's no
// rounding error unless `_scalingFactor()` is overriden).
return FixedPoint.mulDown(amount, scalingFactor);
}
| function _upscale(uint256 amount, uint256 scalingFactor) internal pure returns (uint256) {
// Upscale rounding wouldn't necessarily always go in the same direction: in a swap for example the balance of
// token in should be rounded up, and that of token out rounded down. This is the only place where we round in
// the same direction for all amounts, as the impact of this rounding is expected to be minimal (and there's no
// rounding error unless `_scalingFactor()` is overriden).
return FixedPoint.mulDown(amount, scalingFactor);
}
| 22,051 |
26 | // Returns the downcasted uint112 from uint256, reverting onoverflow (when the input is greater than largest uint112). Counterpart to Solidity's `uint112` operator. Requirements: - input must fit into 112 bits _Available since v4.7._ / | function toUint112(uint256 value) internal pure returns (uint112) {
require(value <= type(uint112).max, "SafeCast: value doesn't fit in 112 bits");
return uint112(value);
}
| function toUint112(uint256 value) internal pure returns (uint112) {
require(value <= type(uint112).max, "SafeCast: value doesn't fit in 112 bits");
return uint112(value);
}
| 26,474 |
28 | // Fetches the list of all blocklisted addressesreturn array The list of currently blocklisted addresses / | function getFullList() public view returns(address[] memory) {
return _userList;
}
| function getFullList() public view returns(address[] memory) {
return _userList;
}
| 19,135 |
22 | // Throws if the sender is not a SetToken operator / | modifier onlyOperator(ISetToken _setToken) {
require(_manager(_setToken).operatorAllowlist(msg.sender), "Must be approved operator");
_;
}
| modifier onlyOperator(ISetToken _setToken) {
require(_manager(_setToken).operatorAllowlist(msg.sender), "Must be approved operator");
_;
}
| 66,695 |
59 | // NOTE: Only the admin can call this function. See {ProxyAdmin-upgradeAndCall}. / | function upgradeToAndCall(address newImplementation, bytes calldata data)
external
payable
ifAdmin
{
_upgradeTo(newImplementation);
| function upgradeToAndCall(address newImplementation, bytes calldata data)
external
payable
ifAdmin
{
_upgradeTo(newImplementation);
| 42,528 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.