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
|
|---|---|---|---|---|
33
|
// to query balance of account
|
// @return _owner {address} address of user to query balance
function balanceOf(address _owner) public view returns(uint balance) {
return balances[_owner];
}
|
// @return _owner {address} address of user to query balance
function balanceOf(address _owner) public view returns(uint balance) {
return balances[_owner];
}
| 1,316
|
7
|
// A mapping of File Hash with current owner
|
mapping(bytes32 => address) FileHashCurrentOwnerMap;
event OwnershipEvent(bytes32 indexed filehash, address indexed filehashowner, uint eventtime);
constructor() public
|
mapping(bytes32 => address) FileHashCurrentOwnerMap;
event OwnershipEvent(bytes32 indexed filehash, address indexed filehashowner, uint eventtime);
constructor() public
| 24,940
|
287
|
// we do a flash loan to give us a big gap. from here on out it is cheaper to use normal deleverage. Use Aave for extremely large loans
|
if (DyDxActive) {
position = position.sub(doDyDxFlashLoan(deficit, position));
}
|
if (DyDxActive) {
position = position.sub(doDyDxFlashLoan(deficit, position));
}
| 9,089
|
283
|
// What's two? Two is pretty useful. /
|
int128 constant REAL_TWO = REAL_ONE << 1;
|
int128 constant REAL_TWO = REAL_ONE << 1;
| 18,514
|
6
|
// eth
|
require(msg.value == _sellAmount, "DeferSwap: sell amount error");
|
require(msg.value == _sellAmount, "DeferSwap: sell amount error");
| 8,885
|
60
|
// The counter starts at one to prevent changing it from zero to a non-zero value, which is a more expensive operation.
|
_guardCounter = 1;
|
_guardCounter = 1;
| 20,310
|
27
|
// Validate number of block on which proposition will no longer be active. startBlock block number endBlock block number /
|
modifier validEndBlock(uint256 startBlock, uint256 endBlock) {
require(
SafeMath.add(startBlock, getMinimumVotingBlockDifference()) <=
endBlock,
'Invalid end block number'
);
_;
}
|
modifier validEndBlock(uint256 startBlock, uint256 endBlock) {
require(
SafeMath.add(startBlock, getMinimumVotingBlockDifference()) <=
endBlock,
'Invalid end block number'
);
_;
}
| 13,816
|
95
|
// ensure that this function can only be executed by authorized addresses
|
if (msg.sender != LibDiamond.contractOwner()) {
LibAccess.enforceAccessControl();
}
|
if (msg.sender != LibDiamond.contractOwner()) {
LibAccess.enforceAccessControl();
}
| 20,308
|
158
|
// Returns a fraction roughly equaling E^((1/2)^x) for integer x /
|
function getPrecomputedEToTheHalfToThe(
uint256 x
)
internal
pure
returns (Fraction.Fraction128 memory)
|
function getPrecomputedEToTheHalfToThe(
uint256 x
)
internal
pure
returns (Fraction.Fraction128 memory)
| 5,662
|
1
|
// TGEN
|
IERC20 public immutable REWARD_TOKEN;
IERC20 public immutable EXTERNAL_REWARD_TOKEN;
mapping (address => mapping(address => uint256)) public externalRewards;
mapping (address => mapping(address => uint256)) public externalUserRewardPerTokenPaid;
mapping (address => uint256) public externalRewardPerTokenStored;
uint256 public override periodFinish = 0;
uint256 public override rewardRate = 0;
|
IERC20 public immutable REWARD_TOKEN;
IERC20 public immutable EXTERNAL_REWARD_TOKEN;
mapping (address => mapping(address => uint256)) public externalRewards;
mapping (address => mapping(address => uint256)) public externalUserRewardPerTokenPaid;
mapping (address => uint256) public externalRewardPerTokenStored;
uint256 public override periodFinish = 0;
uint256 public override rewardRate = 0;
| 9,619
|
371
|
// set the baseTokenURI of an extension.Can only be called by extension.For tokens with no uri configured, tokenURI will return "uri+tokenId" /
|
function setBaseTokenURIExtension(string calldata uri, bool identical) external;
|
function setBaseTokenURIExtension(string calldata uri, bool identical) external;
| 1,759
|
25
|
// update the amount currently staked after a user harvests
|
function _updNumStaked(uint256 _amount, string memory _operation) private {
if (_compareStr(_operation, 'remove')) {
pool.totalTokensStaked = pool.totalTokensStaked.sub(_amount);
} else {
pool.totalTokensStaked = pool.totalTokensStaked.add(_amount);
}
}
|
function _updNumStaked(uint256 _amount, string memory _operation) private {
if (_compareStr(_operation, 'remove')) {
pool.totalTokensStaked = pool.totalTokensStaked.sub(_amount);
} else {
pool.totalTokensStaked = pool.totalTokensStaked.add(_amount);
}
}
| 45,852
|
45
|
// This percent of a transaction will be added to the liquidity pool.
|
uint32[] public taxLiquify = [0, 0, 0];
|
uint32[] public taxLiquify = [0, 0, 0];
| 35,786
|
109
|
// derivative specification address
|
IDerivativeSpecification public derivativeSpecification;
|
IDerivativeSpecification public derivativeSpecification;
| 52,690
|
0
|
// clear any values if there are any (there shouldnt be)
|
delete (options[currentOptionIndex]);
options[currentOptionIndex] = OptionsModel.Option(
optionMarket,
optionType,
strikePrice,
expiryDate,
tokenAddress,
settlementAsset,
paymentAsset
|
delete (options[currentOptionIndex]);
options[currentOptionIndex] = OptionsModel.Option(
optionMarket,
optionType,
strikePrice,
expiryDate,
tokenAddress,
settlementAsset,
paymentAsset
| 49,892
|
48
|
// Adds single address to whitelist. _beneficiary Address to be added to the whitelist /
|
function addToWhitelist(address _beneficiary) onlyOwner public {
whitelist[_beneficiary] = true;
}
|
function addToWhitelist(address _beneficiary) onlyOwner public {
whitelist[_beneficiary] = true;
}
| 4,660
|
424
|
// ============ Parsing Functions ============
|
function parseDepositArgs(
Account.Info[] memory accounts,
ActionArgs memory args
)
internal
pure
returns (DepositArgs memory)
|
function parseDepositArgs(
Account.Info[] memory accounts,
ActionArgs memory args
)
internal
pure
returns (DepositArgs memory)
| 15,704
|
94
|
// Store the length of the first bytes array at the beginning of the memory for tempBytes.
|
let length := mload(_preBytes)
mstore(tempBytes, length)
|
let length := mload(_preBytes)
mstore(tempBytes, length)
| 12,692
|
355
|
// contract Example {using EnumerableMap for EnumerableMap.UintToAddressMap; EnumerableMap.UintToAddressMap private myMap;}``` As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) aresupported. /
|
library EnumerableMap {
|
library EnumerableMap {
| 43,809
|
68
|
// Internal implementation of getRoundData /
|
function _getRoundData(uint256 _roundId)
internal
view
returns (
uint256 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint256 answeredInRound
)
|
function _getRoundData(uint256 _roundId)
internal
view
returns (
uint256 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint256 answeredInRound
)
| 27,742
|
99
|
// manual update account here without withdrawing pending rewards
|
disburseTokens();
lastClaimedTime[msg.sender] = now;
lastDivPoints[msg.sender] = totalDivPoints;
uint fee = amountToWithdraw.mul(UNSTAKING_FEE_RATE_X_100).div(100e2);
uint amountAfterFee = amountToWithdraw.sub(fee);
require(Token(trustedDepositTokenAddress).transfer(owner, fee), "Fee transfer failed!");
require(Token(trustedDepositTokenAddress).transfer(msg.sender, amountAfterFee), "Could not transfer tokens.");
|
disburseTokens();
lastClaimedTime[msg.sender] = now;
lastDivPoints[msg.sender] = totalDivPoints;
uint fee = amountToWithdraw.mul(UNSTAKING_FEE_RATE_X_100).div(100e2);
uint amountAfterFee = amountToWithdraw.sub(fee);
require(Token(trustedDepositTokenAddress).transfer(owner, fee), "Fee transfer failed!");
require(Token(trustedDepositTokenAddress).transfer(msg.sender, amountAfterFee), "Could not transfer tokens.");
| 46,282
|
51
|
// if the token is of local origin, the tokens have been held in escrow in this contract while they have been circulating on remote chains; transfer the tokens to the recipient
|
_token.safeTransfer(_recipient, _action.amnt());
|
_token.safeTransfer(_recipient, _action.amnt());
| 36,393
|
46
|
// Check nonce
|
validateNonce(u);
bank.guess[yHash] = encGuess;
require(bank.burnverifier.verifyBurn(scratch[0], scratch[1], yPoint, bank.lastGlobalUpdate, uPoint, proof), "Burn verification failed!");
|
validateNonce(u);
bank.guess[yHash] = encGuess;
require(bank.burnverifier.verifyBurn(scratch[0], scratch[1], yPoint, bank.lastGlobalUpdate, uPoint, proof), "Burn verification failed!");
| 41,556
|
157
|
// Write the character to the pointer.The ASCII index of the '0' character is 48.
|
mstore8(str, add(48, mod(temp, 10)))
|
mstore8(str, add(48, mod(temp, 10)))
| 18,519
|
25
|
// Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also worksin modular arithmetic, doubling the correct bits in each step.
|
inverse *= 2 - denominator * inverse; // inverse mod 2^8
inverse *= 2 - denominator * inverse; // inverse mod 2^16
inverse *= 2 - denominator * inverse; // inverse mod 2^32
inverse *= 2 - denominator * inverse; // inverse mod 2^64
inverse *= 2 - denominator * inverse; // inverse mod 2^128
inverse *= 2 - denominator * inverse; // inverse mod 2^256
|
inverse *= 2 - denominator * inverse; // inverse mod 2^8
inverse *= 2 - denominator * inverse; // inverse mod 2^16
inverse *= 2 - denominator * inverse; // inverse mod 2^32
inverse *= 2 - denominator * inverse; // inverse mod 2^64
inverse *= 2 - denominator * inverse; // inverse mod 2^128
inverse *= 2 - denominator * inverse; // inverse mod 2^256
| 25,901
|
64
|
// Initial liquidity is amount deposited (Incorrect pricing will be arbitraged) uint256 initialLiquidity = _maxCurrency;
|
totalSupplies[tokenId] = maxCurrency;
|
totalSupplies[tokenId] = maxCurrency;
| 23,932
|
285
|
// Safely mints `tokenId` and transfers it to `to`. Requirements:- `tokenId` must not exist.
|
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
|
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
| 1,598
|
14
|
// ERC-1155 interface for accepting safe transfers. /
|
interface IERC1155TokenReceiver {
/**
* @notice Handle the receipt of a single ERC1155 token type
* @dev An ERC1155-compliant smart contract MUST call this function on the token recipient contract, at the end of a `safeTransferFrom` after the balance has been updated
* This function MAY throw to revert and reject the transfer
* Return of other amount than the magic value MUST result in the transaction being reverted
* Note: The token contract address is always the message sender
* @param _operator The address which called the `safeTransferFrom` function
* @param _from The address which previously owned the token
* @param _id The id of the token being transferred
* @param _amount The amount of tokens being transferred
* @param _data Additional data with no specified format
* @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
*/
function onERC1155Received(
address _operator,
address _from,
uint256 _id,
uint256 _amount,
bytes calldata _data
) external returns (bytes4);
/**
* @notice Handle the receipt of multiple ERC1155 token types
* @dev An ERC1155-compliant smart contract MUST call this function on the token recipient contract, at the end of a `safeBatchTransferFrom` after the balances have been updated
* This function MAY throw to revert and reject the transfer
* Return of other amount than the magic value WILL result in the transaction being reverted
* Note: The token contract address is always the message sender
* @param _operator The address which called the `safeBatchTransferFrom` function
* @param _from The address which previously owned the token
* @param _ids An array containing ids of each token being transferred
* @param _amounts An array containing amounts of each token being transferred
* @param _data Additional data with no specified format
* @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
*/
function onERC1155BatchReceived(
address _operator,
address _from,
uint256[] calldata _ids,
uint256[] calldata _amounts,
bytes calldata _data
) external returns (bytes4);
}
|
interface IERC1155TokenReceiver {
/**
* @notice Handle the receipt of a single ERC1155 token type
* @dev An ERC1155-compliant smart contract MUST call this function on the token recipient contract, at the end of a `safeTransferFrom` after the balance has been updated
* This function MAY throw to revert and reject the transfer
* Return of other amount than the magic value MUST result in the transaction being reverted
* Note: The token contract address is always the message sender
* @param _operator The address which called the `safeTransferFrom` function
* @param _from The address which previously owned the token
* @param _id The id of the token being transferred
* @param _amount The amount of tokens being transferred
* @param _data Additional data with no specified format
* @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
*/
function onERC1155Received(
address _operator,
address _from,
uint256 _id,
uint256 _amount,
bytes calldata _data
) external returns (bytes4);
/**
* @notice Handle the receipt of multiple ERC1155 token types
* @dev An ERC1155-compliant smart contract MUST call this function on the token recipient contract, at the end of a `safeBatchTransferFrom` after the balances have been updated
* This function MAY throw to revert and reject the transfer
* Return of other amount than the magic value WILL result in the transaction being reverted
* Note: The token contract address is always the message sender
* @param _operator The address which called the `safeBatchTransferFrom` function
* @param _from The address which previously owned the token
* @param _ids An array containing ids of each token being transferred
* @param _amounts An array containing amounts of each token being transferred
* @param _data Additional data with no specified format
* @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
*/
function onERC1155BatchReceived(
address _operator,
address _from,
uint256[] calldata _ids,
uint256[] calldata _amounts,
bytes calldata _data
) external returns (bytes4);
}
| 20,391
|
14
|
// 一个bool的标识,限制action的创建次数
|
bool public tag = true;
|
bool public tag = true;
| 18,584
|
9
|
// State Variables
|
uint256 public numberOfCertificates = 0; // a count for the number of stored certificate
uint256[] private certificateKeys; // an array to store the studentIDs of the certificates created (used for enumeration)
uint256[] private assertedKeys;
uint256[] private notAsserted;
|
uint256 public numberOfCertificates = 0; // a count for the number of stored certificate
uint256[] private certificateKeys; // an array to store the studentIDs of the certificates created (used for enumeration)
uint256[] private assertedKeys;
uint256[] private notAsserted;
| 856
|
105
|
// Check if `amountUSDTToBincentiveCold >= penalty`
|
if (amountUSDTToBincentiveCold < minPenalty) {
uint256 dif = minPenalty.sub(amountUSDTToBincentiveCold);
require(dif <= amountUSDTForInvestor, "Withdraw amount is not enough to cover minimum penalty");
amountUSDTForInvestor = amountUSDTForInvestor.sub(dif);
amountUSDTToBincentiveCold = minPenalty;
}
|
if (amountUSDTToBincentiveCold < minPenalty) {
uint256 dif = minPenalty.sub(amountUSDTToBincentiveCold);
require(dif <= amountUSDTForInvestor, "Withdraw amount is not enough to cover minimum penalty");
amountUSDTForInvestor = amountUSDTForInvestor.sub(dif);
amountUSDTToBincentiveCold = minPenalty;
}
| 41,059
|
11
|
// An event emitted when the governance proposal is created
|
event CrowdProposalProposed(address indexed proposal, address indexed author, uint proposalId);
|
event CrowdProposalProposed(address indexed proposal, address indexed author, uint proposalId);
| 13,187
|
15
|
// ------------------------------------------------------------------------ The whitelist of accounts and max contribution ------------------------------------------------------------------------
|
mapping(address => uint) public whitelist;
|
mapping(address => uint) public whitelist;
| 50,863
|
163
|
// Removes initial liquidity restriction. /
|
function removeLiquidityRestriction() external onlyOwner {
maxLiquidity = type(uint256).max;
emit LiquidityRestrictionRemoved();
}
|
function removeLiquidityRestriction() external onlyOwner {
maxLiquidity = type(uint256).max;
emit LiquidityRestrictionRemoved();
}
| 43,782
|
6
|
// If the collateral being liquidated is equal to the user balance, we set the currency as not being used as collateral anymore
|
if (vars.maxCollateralToLiquidate == vars.userCollateralBalance) {
userConfig.setUsingAsCollateral(collateralReserve.id, false);
emit ReserveUsedAsCollateralDisabled(params.collateralAsset, params.user);
}
|
if (vars.maxCollateralToLiquidate == vars.userCollateralBalance) {
userConfig.setUsingAsCollateral(collateralReserve.id, false);
emit ReserveUsedAsCollateralDisabled(params.collateralAsset, params.user);
}
| 10,005
|
130
|
// Buy WETH from Uniswap with tokens
|
sellBalance = gain.mul(10**tokenList[targetID].decimals).div(1e18); // Convert to target decimals
sellBalance = sellBalance.mul(uint256(100000).sub(percentDepositor)).div(DIVISION_FACTOR);
if(sellBalance <= tokenList[targetID].token.balanceOf(address(this))){
|
sellBalance = gain.mul(10**tokenList[targetID].decimals).div(1e18); // Convert to target decimals
sellBalance = sellBalance.mul(uint256(100000).sub(percentDepositor)).div(DIVISION_FACTOR);
if(sellBalance <= tokenList[targetID].token.balanceOf(address(this))){
| 11,958
|
4
|
// Function to allows recipients to claim allotted HAPcoins, with transaction fee exemptions handled
|
function enterprise_claimWHAPcoins() external nonReentrant returns (bool) {
uint256 amount = _Enterprise_Repository[msg.sender];
require(amount > 0, "No tokens to claim");
_Enterprise_Repository[msg.sender] = 0;
_Claimed_Tokens[msg.sender] += amount; // Track claimed tokens
_WHAPcoinContract.enterprise_transfer(address(this), msg.sender, amount);
emit ClaimedFromEnterpriseRepository(msg.sender, amount);
return true;
}
|
function enterprise_claimWHAPcoins() external nonReentrant returns (bool) {
uint256 amount = _Enterprise_Repository[msg.sender];
require(amount > 0, "No tokens to claim");
_Enterprise_Repository[msg.sender] = 0;
_Claimed_Tokens[msg.sender] += amount; // Track claimed tokens
_WHAPcoinContract.enterprise_transfer(address(this), msg.sender, amount);
emit ClaimedFromEnterpriseRepository(msg.sender, amount);
return true;
}
| 25,568
|
194
|
// Returns all the relevant information about a specific Collectible. Get details about your collectible _tokenIdThe token identifierreturn isAttached Is Object attachedreturn teamId team identifier of the asset/token/collectiblereturn positionId position identifier of the asset/token/collectiblereturn creationTime creation timestampreturn attributes attribute of the asset/token/collectiblereturn currentGameCardIdcurrent game card of the asset/token/collectiblereturn mlbGameIDmlb game identifier in which the asset/token/collectible was generatedreturn playerOverrideId player override identifier of the asset/token/collectiblereturn playerStatus status of the player (Rookie/Veteran/Historical)return playerHandedness handedness of the assetreturn mlbPlayerIdofficial MLB Player Identifier /
|
function getCollectibleDetails(uint256 _tokenId)
external
view
returns (
uint256 isAttached,
uint32 sequenceId,
uint8 teamId,
uint8 positionId,
uint64 creationTime,
uint256 attributes,
|
function getCollectibleDetails(uint256 _tokenId)
external
view
returns (
uint256 isAttached,
uint32 sequenceId,
uint8 teamId,
uint8 positionId,
uint64 creationTime,
uint256 attributes,
| 25,244
|
349
|
// Executes multiple calls of fillOrder./orders Array of order specifications./takerAssetFillAmounts Array of desired amounts of takerAsset to sell in orders./signatures Proofs that orders have been created by makers./ return Array of amounts filled and fees paid by makers and taker.
|
function batchFillOrders(
LibOrder.Order[] memory orders,
uint256[] memory takerAssetFillAmounts,
bytes[] memory signatures
)
public
payable
returns (LibFillResults.FillResults[] memory fillResults);
|
function batchFillOrders(
LibOrder.Order[] memory orders,
uint256[] memory takerAssetFillAmounts,
bytes[] memory signatures
)
public
payable
returns (LibFillResults.FillResults[] memory fillResults);
| 9,369
|
114
|
// Token information This wrapped token accepts multiple stablecoins DAI, USDC, USDT, sUSD
|
struct TokenInfo {
IERC20 token; // Reference of token
uint256 decimals; // Decimals of token
uint256 price; // Last price of token in USD
}
|
struct TokenInfo {
IERC20 token; // Reference of token
uint256 decimals; // Decimals of token
uint256 price; // Last price of token in USD
}
| 51,088
|
257
|
// enum describing Swap's duration, 28 days, 60 days or 90 days
|
enum SwapTenor {
DAYS_28,
DAYS_60,
DAYS_90
}
|
enum SwapTenor {
DAYS_28,
DAYS_60,
DAYS_90
}
| 43,102
|
33
|
// calls all the internal functions above, to transfer a token from one user to another changed to nullify the selling offer when a token changes hands
|
function _clearApprovalAndTransfer(address _from, address _to, uint _tokenId) internal
|
function _clearApprovalAndTransfer(address _from, address _to, uint _tokenId) internal
| 23,685
|
1,306
|
// Ensure the ExchangeRates contract has the feed for sADA;
|
exchangerates_i.addAggregator("sADA", 0xAE48c91dF1fE419994FFDa27da09D5aC69c30f55);
|
exchangerates_i.addAggregator("sADA", 0xAE48c91dF1fE419994FFDa27da09D5aC69c30f55);
| 4,125
|
26
|
// the PoW must contain work that includes a recent ethereum block hash (challenge number) and the msg.sender's address to prevent MITM attacks
|
bytes32 digest = keccak256(abi.encodePacked(challengeNumber, msg.sender, nonce ));
|
bytes32 digest = keccak256(abi.encodePacked(challengeNumber, msg.sender, nonce ));
| 17,592
|
17
|
// add liquidity amount from the leaf up to top node amount - adding amount /
|
function _nodeAddLiquidity(uint128 amount)
internal
returns (uint48 resNode)
|
function _nodeAddLiquidity(uint128 amount)
internal
returns (uint48 resNode)
| 23,112
|
203
|
// Determine minimum natural unit based on max of pre-defined minimum or (18 - decimals) of the component in the new Set.
|
uint256 kOne = Math.max(
MINIMUM_COLLATERAL_NATURAL_UNIT_DECIMALS,
uint256(18).sub(nextSetComponentDecimals)
);
|
uint256 kOne = Math.max(
MINIMUM_COLLATERAL_NATURAL_UNIT_DECIMALS,
uint256(18).sub(nextSetComponentDecimals)
);
| 6,553
|
23
|
// substract front
|
uint256 reminder = current_deposit.amount + current_extracted - requested;
_pushFront(store, reminder, current_deposit.timestamp);
current_extracted = requested;
|
uint256 reminder = current_deposit.amount + current_extracted - requested;
_pushFront(store, reminder, current_deposit.timestamp);
current_extracted = requested;
| 25,352
|
107
|
// get prior LP stake
|
uint256 lpTotalSupply = getPriorSupply(blockNumber);
if (lpTotalSupply == 0) {
return 0;
}
|
uint256 lpTotalSupply = getPriorSupply(blockNumber);
if (lpTotalSupply == 0) {
return 0;
}
| 61,375
|
1
|
// steal some eth from the players account :)
|
return "Looser";
|
return "Looser";
| 25,759
|
12
|
// Owner of account approves the transfer of an amount to another account
|
mapping(address => mapping (address => uint256)) allowed;
|
mapping(address => mapping (address => uint256)) allowed;
| 51,964
|
179
|
// Allows stakers to stake for `_period` of time/_period Period of time, in seconds,/should revert if already enabled
|
function enableStakingPeriod(uint256 _period) external;
|
function enableStakingPeriod(uint256 _period) external;
| 12,815
|
6
|
// BT_NP: Not paused
|
require(_status == IBaseToken.Status.Paused, "BT_NP");
_close(closedPrice);
|
require(_status == IBaseToken.Status.Paused, "BT_NP");
_close(closedPrice);
| 2,206
|
8
|
// vesting for Team Members
|
uint256 private constant teamVesting = 365 days * 4;
|
uint256 private constant teamVesting = 365 days * 4;
| 31,919
|
39
|
// ...check for a class match.
|
uint32 class;
(,class,,,,,) = EtheremonData(dataAddress).getMonsterObj(yourMon);
require(listedMonForClass[desiredMon] == class);
|
uint32 class;
(,class,,,,,) = EtheremonData(dataAddress).getMonsterObj(yourMon);
require(listedMonForClass[desiredMon] == class);
| 24,869
|
18
|
// Transfer tokens Send `_value` tokens to `_to` from your account_to The address of the recipient _value the amount to send /
|
function transfer(address _to, uint256 _value) public {
_transfer(msg.sender, _to, _value);
}
|
function transfer(address _to, uint256 _value) public {
_transfer(msg.sender, _to, _value);
}
| 14,324
|
402
|
// lease provenance is null and token exist only on initial mint
|
if (lease.provenance == address(0) && _exists(tokenId)) {
lease.provenance = ownerOf(tokenId);
}
|
if (lease.provenance == address(0) && _exists(tokenId)) {
lease.provenance = ownerOf(tokenId);
}
| 78,067
|
189
|
// Some exceptions
|
if (_from > _to) {
return 0;
}
|
if (_from > _to) {
return 0;
}
| 67,971
|
82
|
// Change the recipient of the wallet recipientExternalID - Recipient IDreturn True if success /
|
function changeRecipient(string memory recipientExternalID)
public
onlyController
returns (bool)
|
function changeRecipient(string memory recipientExternalID)
public
onlyController
returns (bool)
| 41,950
|
37
|
// 4th year effective annual interest rate is 75%
|
interest = (750 * maxMintProofOfStake).div(100);
|
interest = (750 * maxMintProofOfStake).div(100);
| 15,355
|
76
|
// The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor. /
|
bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;
|
bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;
| 4,432
|
62
|
// Returns the cap of a specific user._beneficiary Address whose cap is to be checkedreturn Current cap for individual user /
|
function getUserCap(address _beneficiary) public view returns (uint256) {
return caps[_beneficiary];
}
|
function getUserCap(address _beneficiary) public view returns (uint256) {
return caps[_beneficiary];
}
| 17,002
|
55
|
// Remove an address to the admin whitelist_admin - Address to be removed/
|
function removeAdmin(address _admin) external onlySupervisor {
_setAdmin(_admin, false);
}
|
function removeAdmin(address _admin) external onlySupervisor {
_setAdmin(_admin, false);
}
| 66,634
|
14
|
// Return the new Item ID
|
return itemId;
|
return itemId;
| 43,926
|
151
|
// No point in doing any more logic as the rewards have ended
|
if (multiplier == 0) {
return;
}
|
if (multiplier == 0) {
return;
}
| 54,423
|
29
|
// Slice the sighash.
|
_returnData := add(_returnData, 0x04)
|
_returnData := add(_returnData, 0x04)
| 3,794
|
149
|
// IERC20 ======= transfer()
|
function transfer(address dst, uint256 amount) external returns (bool) {
return _transfer(_myAvatar(), dst, amount);
}
|
function transfer(address dst, uint256 amount) external returns (bool) {
return _transfer(_myAvatar(), dst, amount);
}
| 38,630
|
34
|
// //called by the owner to allow transferts, triggers Transferable state/
|
function allowTransfert() onlyOwner whenNotTransferable public {
transferable = true;
emit Transferable();
}
|
function allowTransfert() onlyOwner whenNotTransferable public {
transferable = true;
emit Transferable();
}
| 6,827
|
80
|
// Skipped for compatability with existing FluxAggregator in which latestRoundData never reverts. require(roundId != 0, V3_NO_DATA_ERROR);
|
Transmission memory transmission = s_transmissions[uint32(roundId)];
return (
roundId,
transmission.answer,
transmission.timestamp,
transmission.timestamp,
roundId
);
|
Transmission memory transmission = s_transmissions[uint32(roundId)];
return (
roundId,
transmission.answer,
transmission.timestamp,
transmission.timestamp,
roundId
);
| 22,783
|
95
|
// tracks all current pending bonds (amount)
|
mapping(address => mapping(address => uint)) public pendingbonds;
|
mapping(address => mapping(address => uint)) public pendingbonds;
| 27,186
|
23
|
// burn will call _updateReward
|
_burn(msg.sender, _amount);
|
_burn(msg.sender, _amount);
| 23,598
|
93
|
// Calculates the exchange rate from the underlying to the BToken This function does not accrue interest before calculating the exchange ratereturn Calculated exchange rate scaled by 1e18 /
|
function exchangeRateStored() public view returns (uint) {
delegateToViewAndReturn();
}
|
function exchangeRateStored() public view returns (uint) {
delegateToViewAndReturn();
}
| 20,162
|
11
|
// Creates a stream with the provided segment milestones, implying the end time from the last milestone./ The stream is funded by `msg.sender` and is wrapped in an ERC-721 NFT.//Emits a {Transfer} and {CreateLockupDynamicStream} event.// Notes:/ - As long as the segment milestones are arranged in ascending order, it is not an error for some/ of them to be in the past.// Requirements:/ - Must not be delegate called./ - `params.totalAmount` must be greater than zero./ - If set, `params.broker.fee` must not be greater than `MAX_FEE`./ - `params.segments` must have at least one segment, but not more than `MAX_SEGMENT_COUNT`./ - `params.startTime`
|
function createWithMilestones(LockupDynamic.CreateWithMilestones calldata params)
external
returns (uint256 streamId);
|
function createWithMilestones(LockupDynamic.CreateWithMilestones calldata params)
external
returns (uint256 streamId);
| 25,217
|
258
|
// update last token global index to point to proper place in the collection preserve local index and ownership info
|
tokens[lastId] = tokens[lastId]
|
tokens[lastId] = tokens[lastId]
| 42,856
|
130
|
// Calculate token sell value./
|
function tokensToEthereum_(uint256 _tokens)
internal
view
returns(uint256)
|
function tokensToEthereum_(uint256 _tokens)
internal
view
returns(uint256)
| 3,305
|
297
|
// Iterate in reverse so we pull from the stack in a "last in, first out" manner. Will revert due to underflow if we empty the stack before pulling the desired amount.
|
for (; ; currentIndex--) {
|
for (; ; currentIndex--) {
| 55,525
|
25
|
// START FUNCTIONS FOR AUTHORS /
|
function createItem(string _name, uint _price, uint _celebId, uint[6] _traitValues) public onlyManufacturer {
require(_price >= MIN_STARTING_PRICE);
uint itemId = items.push(Item(_name)) - 1;
itemIdToOwner[itemId] = author;
itemIdToPrice[itemId] = _price;
itemIdToCelebId[itemId] = _celebId;
itemIdToTraitValues[itemId] = _traitValues; // TODO: fetch celeb traits later
userToNumItems[author]++;
}
|
function createItem(string _name, uint _price, uint _celebId, uint[6] _traitValues) public onlyManufacturer {
require(_price >= MIN_STARTING_PRICE);
uint itemId = items.push(Item(_name)) - 1;
itemIdToOwner[itemId] = author;
itemIdToPrice[itemId] = _price;
itemIdToCelebId[itemId] = _celebId;
itemIdToTraitValues[itemId] = _traitValues; // TODO: fetch celeb traits later
userToNumItems[author]++;
}
| 7,696
|
89
|
// Always round to negative infinity
|
if (tickCumulativesDelta < 0 && (tickCumulativesDelta % int(uint(period)) != 0)) timeWeightedAverageTick--;
|
if (tickCumulativesDelta < 0 && (tickCumulativesDelta % int(uint(period)) != 0)) timeWeightedAverageTick--;
| 37,571
|
17
|
// Search _txOutputVector for output paying the redeemer/ Require that outputs checked are witness/ _dDeposit storage pointer/_txOutputVectorAll transaction outputs prepended by the number of outputs encoded as a VarInt, max 0xFC(252) outputs/ return False if output paying redeemer was found, true otherwise
|
function validateRedeemerNotPaid(
DepositUtils.Deposit storage _d,
bytes memory _txOutputVector
|
function validateRedeemerNotPaid(
DepositUtils.Deposit storage _d,
bytes memory _txOutputVector
| 48,341
|
1
|
// Clear the bit of the uint 'self' at the given 'index'./self The integer./index The index. Must be between 0 and 255 (inclusive)./ return The modified integer.
|
function clearBit(uint self, uint index) internal constant returns (uint) {
if (index > 255)
throw;
return self & ~(2**index);
}
|
function clearBit(uint self, uint index) internal constant returns (uint) {
if (index > 255)
throw;
return self & ~(2**index);
}
| 34,870
|
45
|
// Returns true if `account` supports the {IERC165} interface, /
|
function supportsERC165(address account) internal view returns (bool) {
|
function supportsERC165(address account) internal view returns (bool) {
| 36,746
|
6
|
// This is needed because there is no way to return an array in a solidity method. You have to call tokenList(i) to get an element of the array/
|
function getTokenCount() public view returns(uint) {
return tokenList.length;
}
|
function getTokenCount() public view returns(uint) {
return tokenList.length;
}
| 20,180
|
5
|
// A method to check if an address is a stakeholder._address The address to verify. return bool, uint256 Whether the address is a stakeholder, and if so its position in the stakeholders array./
|
function isStakeholder(address _address)
public
view
returns(bool, uint256)
|
function isStakeholder(address _address)
public
view
returns(bool, uint256)
| 19,941
|
29
|
// Step 6: grant permission to the LM Committee to add reward tokens to Ethereum gauges and manage their distributors
|
authorizer.grantRole(
authorizerAdaptor.getActionId(IStakingLiquidityGauge.add_reward.selector),
lmCommitteeMultisig
);
authorizer.grantRole(
authorizerAdaptor.getActionId(IStakingLiquidityGauge.set_reward_distributor.selector),
lmCommitteeMultisig
);
|
authorizer.grantRole(
authorizerAdaptor.getActionId(IStakingLiquidityGauge.add_reward.selector),
lmCommitteeMultisig
);
authorizer.grantRole(
authorizerAdaptor.getActionId(IStakingLiquidityGauge.set_reward_distributor.selector),
lmCommitteeMultisig
);
| 70,077
|
2
|
// ID padding from PinkLock v1, as there is a lack of a pausing mechanism as of now the lastest id from v1 is about 22K, so this is probably a safe padding value.
|
uint256 private constant ID_PADDING = 1_000_000;
Lock[] private _locks;
mapping(address => EnumerableSet.UintSet) private _userLpLockIds;
mapping(address => EnumerableSet.UintSet) private _userNormalLockIds;
EnumerableSet.AddressSet private _lpLockedTokens;
EnumerableSet.AddressSet private _normalLockedTokens;
mapping(address => CumulativeLockInfo) public cumulativeLockInfo;
mapping(address => EnumerableSet.UintSet) private _tokenToLockIds;
|
uint256 private constant ID_PADDING = 1_000_000;
Lock[] private _locks;
mapping(address => EnumerableSet.UintSet) private _userLpLockIds;
mapping(address => EnumerableSet.UintSet) private _userNormalLockIds;
EnumerableSet.AddressSet private _lpLockedTokens;
EnumerableSet.AddressSet private _normalLockedTokens;
mapping(address => CumulativeLockInfo) public cumulativeLockInfo;
mapping(address => EnumerableSet.UintSet) private _tokenToLockIds;
| 38,184
|
288
|
// Compute the absolute value of (xy)÷denominator. The result must fit within int256.
|
uint256 rAbs = mulDiv(ax, ay, ad);
if (rAbs > uint256(type(int256).max)) {
revert PRBMath__MulDivSignedOverflow(rAbs);
}
|
uint256 rAbs = mulDiv(ax, ay, ad);
if (rAbs > uint256(type(int256).max)) {
revert PRBMath__MulDivSignedOverflow(rAbs);
}
| 3,218
|
2
|
// After new parameter is introduced new lib Parameters(n+1) inherited from Parameters(n) must be created Then use Parameters(n+1) for IParametersStorage /
|
library Parameters {
/// @dev auction duration in seconds
uint public constant PARAM_AUCTION_DURATION = 0;
function getAuctionDuration(IParametersStorage _storage) internal view returns (uint _auctionDurationSeconds) {
_auctionDurationSeconds = uint(_storage.customParams(PARAM_AUCTION_DURATION));
require(_auctionDurationSeconds > 0);
}
}
|
library Parameters {
/// @dev auction duration in seconds
uint public constant PARAM_AUCTION_DURATION = 0;
function getAuctionDuration(IParametersStorage _storage) internal view returns (uint _auctionDurationSeconds) {
_auctionDurationSeconds = uint(_storage.customParams(PARAM_AUCTION_DURATION));
require(_auctionDurationSeconds > 0);
}
}
| 16,445
|
11
|
// Mint ETHmx to sender.
|
uint256 amountOut = ethmxFromEth(amountIn);
_mint(_msgSender(), amountOut);
_totalGiven += amountIn;
|
uint256 amountOut = ethmxFromEth(amountIn);
_mint(_msgSender(), amountOut);
_totalGiven += amountIn;
| 17,849
|
6
|
// limits execution to when this contract is locked or approved
|
modifier onlyIfLockedOrApproved() {
require(status == Status.Locked ||
status == Status.Approved);
_;
}
|
modifier onlyIfLockedOrApproved() {
require(status == Status.Locked ||
status == Status.Approved);
_;
}
| 53,711
|
1
|
// events facilitate communication between smart contracts and their user interfaces i.e. we can create listeners for events in the client and use them in The Graph
|
event PostCreated(uint id, string title, string hash, string tags);
event PostUpdated(uint id, string title, string hash, string tags, bool published);
|
event PostCreated(uint id, string title, string hash, string tags);
event PostUpdated(uint id, string title, string hash, string tags, bool published);
| 27,592
|
4
|
// _exchangeName the exchange used for trading /
|
function rebalance(string memory _exchangeName) external onlyAllowedCaller(msg.sender) {
require(keccak256(abi.encodePacked(_exchangeName)) == keccak256(abi.encodePacked(exchangeName)), "Exchange names are not equal");
emit RebalanceEvent(ShouldRebalance.REBALANCE);
}
|
function rebalance(string memory _exchangeName) external onlyAllowedCaller(msg.sender) {
require(keccak256(abi.encodePacked(_exchangeName)) == keccak256(abi.encodePacked(exchangeName)), "Exchange names are not equal");
emit RebalanceEvent(ShouldRebalance.REBALANCE);
}
| 37,866
|
162
|
// Revokes a presale allocation from the contributor with address _contributor Updates the totalTokensSold property substracting the amount of tokens that where previously allocated
|
function revokePresale(address _contributor, uint8 _contributorPhase) external onlyAdmin returns (bool) {
require(_contributor != address(0));
// We can only revoke allocations from pre sale or strategic partners
// ContributionPhase.PreSaleContribution == 0, ContributionPhase.PartnerContribution == 1
require(_contributorPhase == 0 || _contributorPhase == 1);
uint256 luckys = ledgerContract.revokeAllocation(_contributor, _contributorPhase);
require(luckys > 0);
require(luckys <= totalTokensSold);
totalTokensSold = totalTokensSold.sub(luckys);
return true;
}
|
function revokePresale(address _contributor, uint8 _contributorPhase) external onlyAdmin returns (bool) {
require(_contributor != address(0));
// We can only revoke allocations from pre sale or strategic partners
// ContributionPhase.PreSaleContribution == 0, ContributionPhase.PartnerContribution == 1
require(_contributorPhase == 0 || _contributorPhase == 1);
uint256 luckys = ledgerContract.revokeAllocation(_contributor, _contributorPhase);
require(luckys > 0);
require(luckys <= totalTokensSold);
totalTokensSold = totalTokensSold.sub(luckys);
return true;
}
| 5,822
|
8
|
// change the arbitrum bridge and router address normally this function should not be called newBridge the new bridge address newRouter the new router address /
|
function changeArbToken(address newBridge, address newRouter) external onlyOwner {
bridge = newBridge;
router = newRouter;
emit ArbitrumGatewayRouterChanged(bridge, router);
}
|
function changeArbToken(address newBridge, address newRouter) external onlyOwner {
bridge = newBridge;
router = newRouter;
emit ArbitrumGatewayRouterChanged(bridge, router);
}
| 19,311
|
78
|
// The desired value to assign (`_amount`) can be either higher or lower than the current number of tokens of the address (`balances[_to]`). To calculate the new `totalSupply_` value, the difference between `_amount` and `balances[_to]` (`delta`) is calculated first, and then added or substracted to `totalSupply_` accordingly.
|
uint256 delta = 0;
if (balances[_to] < _amount) {
|
uint256 delta = 0;
if (balances[_to] < _amount) {
| 24,238
|
97
|
// Presale ended / emergency abort
|
require(!halted);
bytes32 hash = sha256(dataframe);
var (whitelistedAddress, customerId, minETH, maxETH, pricingInfo) = getKYCPresalePayload(dataframe);
uint multiplier = 10 ** 18;
address receiver = msg.sender;
uint weiAmount = msg.value;
|
require(!halted);
bytes32 hash = sha256(dataframe);
var (whitelistedAddress, customerId, minETH, maxETH, pricingInfo) = getKYCPresalePayload(dataframe);
uint multiplier = 10 ** 18;
address receiver = msg.sender;
uint weiAmount = msg.value;
| 4,085
|
775
|
// Increment totalPurchaseReceipts;
|
totalPurchaseReceipts++;
|
totalPurchaseReceipts++;
| 32,831
|
39
|
// this low-level function should be called from a contract which performsimportant safety checks
|
function mint(address to) external lock returns (uint liquidity) {
(uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
uint balance0 = IERC20(token0).balanceOf(address(this));
uint balance1 = IERC20(token1).balanceOf(address(this));
uint amount0 = balance0.sub(_reserve0);
uint amount1 = balance1.sub(_reserve1);
bool feeOn = _mintFee(_reserve0, _reserve1);
uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee
if (_totalSupply == 0) {
liquidity = Math.sqrt(amount0.mul(amount1)).sub(MINIMUM_LIQUIDITY);
_mint(address(0), MINIMUM_LIQUIDITY); // permanently lock the first MINIMUM_LIQUIDITY tokens
} else {
liquidity = Math.min(amount0.mul(_totalSupply) / _reserve0, amount1.mul(_totalSupply) / _reserve1);
}
require(liquidity > 0, 'UnicSwap: INSUFFICIENT_LIQUIDITY_MINTED');
_mint(to, liquidity);
_update(balance0, balance1, _reserve0, _reserve1);
if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date
emit Mint(msg.sender, amount0, amount1);
}
|
function mint(address to) external lock returns (uint liquidity) {
(uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
uint balance0 = IERC20(token0).balanceOf(address(this));
uint balance1 = IERC20(token1).balanceOf(address(this));
uint amount0 = balance0.sub(_reserve0);
uint amount1 = balance1.sub(_reserve1);
bool feeOn = _mintFee(_reserve0, _reserve1);
uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee
if (_totalSupply == 0) {
liquidity = Math.sqrt(amount0.mul(amount1)).sub(MINIMUM_LIQUIDITY);
_mint(address(0), MINIMUM_LIQUIDITY); // permanently lock the first MINIMUM_LIQUIDITY tokens
} else {
liquidity = Math.min(amount0.mul(_totalSupply) / _reserve0, amount1.mul(_totalSupply) / _reserve1);
}
require(liquidity > 0, 'UnicSwap: INSUFFICIENT_LIQUIDITY_MINTED');
_mint(to, liquidity);
_update(balance0, balance1, _reserve0, _reserve1);
if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date
emit Mint(msg.sender, amount0, amount1);
}
| 26,932
|
8
|
// Opens a new Offer, and sends the nft to an escrow. nftId id of the nft to offer. nftAddress address of the nft to offer. liquidation if the amount of liquidation+accumulatedFee is bigger than the collateral, the borrower is liquidated. fee fee amount that accumulates every hour. /
|
function createOffer(uint256 nftId, address nftAddress, uint256 liquidation, uint256 fee) external nonReentrant() {
require(addressToBool[nftAddress] == true);
require(IERC721(nftAddress).ownerOf(nftId) == msg.sender, "Not the owner of the NFT");
IERC721(nftAddress).safeTransferFrom(msg.sender, address(this), nftId);
uint current = offerCounter.current();
offerCounter.increment();
offers[current] = Offer(msg.sender, nftAddress, nftId, liquidation, fee, address(0), 0, 0, "Open");
addressToOffers[msg.sender].push(current);
emit OfferStatusChange(current, "Open");
}
|
function createOffer(uint256 nftId, address nftAddress, uint256 liquidation, uint256 fee) external nonReentrant() {
require(addressToBool[nftAddress] == true);
require(IERC721(nftAddress).ownerOf(nftId) == msg.sender, "Not the owner of the NFT");
IERC721(nftAddress).safeTransferFrom(msg.sender, address(this), nftId);
uint current = offerCounter.current();
offerCounter.increment();
offers[current] = Offer(msg.sender, nftAddress, nftId, liquidation, fee, address(0), 0, 0, "Open");
addressToOffers[msg.sender].push(current);
emit OfferStatusChange(current, "Open");
}
| 50,484
|
18
|
// update length
|
assembly {
let lengthReduction := sub(0x20, offset)
let len := mload(stringPtr)
mstore(stringPtr, sub(len, lengthReduction))
}
|
assembly {
let lengthReduction := sub(0x20, offset)
let len := mload(stringPtr)
mstore(stringPtr, sub(len, lengthReduction))
}
| 43,446
|
7
|
// Equivalent to "i % 2 == 1", but cheaper.
|
if (i & 1 == 1) {
assembly {
mstore(
|
if (i & 1 == 1) {
assembly {
mstore(
| 29,803
|
232
|
// 4dps resolution
|
currentVolumeUsd = parseInt(_result, 4);
rebasePrepared = true;
emit RebasePrepared(_result, currentTwapPrice);
|
currentVolumeUsd = parseInt(_result, 4);
rebasePrepared = true;
emit RebasePrepared(_result, currentTwapPrice);
| 28,195
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.