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 |
|---|---|---|---|---|
160 | // Minimum fees (in wei) to create a proposal | uint minBoardMeetingFees;
| uint minBoardMeetingFees;
| 45,539 |
36 | // Throws if called by other contract / | modifier isContractCheck(address _user) {
require(!isContract(_user), "Jupiter: Invalid address");
_;
}
| modifier isContractCheck(address _user) {
require(!isContract(_user), "Jupiter: Invalid address");
_;
}
| 25,089 |
9 | // prefix | mstore(0, 0x1901000000000000000000000000000000000000000000000000000000000000)
| mstore(0, 0x1901000000000000000000000000000000000000000000000000000000000000)
| 44,276 |
1 | // Increase the custody limit of a custodian either directly or via signed authorization | function increaseCustodyAllowance(address custodian, uint256 amount) external;
| function increaseCustodyAllowance(address custodian, uint256 amount) external;
| 11,564 |
11 | // Sets a new URI for all token types, by relying on the token type ID substitution mechanism _newURI New URI for all tokens / | function setURI(
string memory _newURI
| function setURI(
string memory _newURI
| 40,393 |
44 | // this is deployed on mainnet at:0x8F59323d8400CC0deE71ee91f92961989D508160 | contract Forwarder {
// lets create some tracking vars
bool public depositSuccessful_;
uint256 public successfulTransactions_;
uint256 public gasBefore_;
uint256 public gasAfter_;
// create an instance of the jekyll island bank
Bank currentCorpBank_;
// take an address in the constructor arguments to set up bank with
constructor(address _addr)
public
{
// point the created instance to the address given
currentCorpBank_ = Bank(_addr);
}
function deposit()
public
payable
returns(bool)
{
// grab gas at start
gasBefore_ = gasleft();
if (currentCorpBank_.deposit.value(msg.value)(msg.sender) == true) {
depositSuccessful_ = true;
successfulTransactions_++;
gasAfter_ = gasleft();
return(true);
} else {
depositSuccessful_ = false;
gasAfter_ = gasleft();
return(false);
}
}
function deposit2()
public
payable
returns(bool)
{
// grab gas at start
gasBefore_ = gasleft();
if (currentCorpBank_.deposit2.value(msg.value)(msg.sender) == true) {
depositSuccessful_ = true;
successfulTransactions_++;
gasAfter_ = gasleft();
return(true);
} else {
depositSuccessful_ = false;
gasAfter_ = gasleft();
return(false);
}
}
function deposit3()
public
payable
returns(bool)
{
// grab gas at start
gasBefore_ = gasleft();
if (currentCorpBank_.deposit3.value(msg.value)(msg.sender) == true) {
depositSuccessful_ = true;
successfulTransactions_++;
gasAfter_ = gasleft();
return(true);
} else {
depositSuccessful_ = false;
gasAfter_ = gasleft();
return(false);
}
}
function deposit4()
public
payable
returns(bool)
{
// grab gas at start
gasBefore_ = gasleft();
if (currentCorpBank_.deposit4.value(msg.value)(msg.sender) == true) {
depositSuccessful_ = true;
successfulTransactions_++;
gasAfter_ = gasleft();
return(true);
} else {
depositSuccessful_ = false;
gasAfter_ = gasleft();
return(false);
}
}
// for data tracking lets make a function to check this contracts balance
function checkBalance()
public
view
returns(uint256)
{
return(address(this).balance);
}
}
| contract Forwarder {
// lets create some tracking vars
bool public depositSuccessful_;
uint256 public successfulTransactions_;
uint256 public gasBefore_;
uint256 public gasAfter_;
// create an instance of the jekyll island bank
Bank currentCorpBank_;
// take an address in the constructor arguments to set up bank with
constructor(address _addr)
public
{
// point the created instance to the address given
currentCorpBank_ = Bank(_addr);
}
function deposit()
public
payable
returns(bool)
{
// grab gas at start
gasBefore_ = gasleft();
if (currentCorpBank_.deposit.value(msg.value)(msg.sender) == true) {
depositSuccessful_ = true;
successfulTransactions_++;
gasAfter_ = gasleft();
return(true);
} else {
depositSuccessful_ = false;
gasAfter_ = gasleft();
return(false);
}
}
function deposit2()
public
payable
returns(bool)
{
// grab gas at start
gasBefore_ = gasleft();
if (currentCorpBank_.deposit2.value(msg.value)(msg.sender) == true) {
depositSuccessful_ = true;
successfulTransactions_++;
gasAfter_ = gasleft();
return(true);
} else {
depositSuccessful_ = false;
gasAfter_ = gasleft();
return(false);
}
}
function deposit3()
public
payable
returns(bool)
{
// grab gas at start
gasBefore_ = gasleft();
if (currentCorpBank_.deposit3.value(msg.value)(msg.sender) == true) {
depositSuccessful_ = true;
successfulTransactions_++;
gasAfter_ = gasleft();
return(true);
} else {
depositSuccessful_ = false;
gasAfter_ = gasleft();
return(false);
}
}
function deposit4()
public
payable
returns(bool)
{
// grab gas at start
gasBefore_ = gasleft();
if (currentCorpBank_.deposit4.value(msg.value)(msg.sender) == true) {
depositSuccessful_ = true;
successfulTransactions_++;
gasAfter_ = gasleft();
return(true);
} else {
depositSuccessful_ = false;
gasAfter_ = gasleft();
return(false);
}
}
// for data tracking lets make a function to check this contracts balance
function checkBalance()
public
view
returns(uint256)
{
return(address(this).balance);
}
}
| 45,444 |
93 | // first 32 bytes, after the length prefix | r := mload(add(sig, 32))
| r := mload(add(sig, 32))
| 19,592 |
21 | // Internal function to create a Silica V2.1 | function _createSilicaV2_1(
address _rewardTokenAddress,
address _paymentTokenAddress,
uint256 _resourceAmount,
uint256 _lastDueDay,
uint256 _unitPrice,
address _sellerAddress,
uint256 _additionalCollateralPercent
| function _createSilicaV2_1(
address _rewardTokenAddress,
address _paymentTokenAddress,
uint256 _resourceAmount,
uint256 _lastDueDay,
uint256 _unitPrice,
address _sellerAddress,
uint256 _additionalCollateralPercent
| 9,911 |
33 | // This function is runned for owner and participants | function finishRaffle(uint256 _idRaffle) isBlocked() checkIfTheRaffleExist(_idRaffle) checkIfRaffleFinish(_idRaffle) public {
require(raffles[_idRaffle].status == statusRaffle.InProgress,'This raffle are finished or closed');
require(raffles[_idRaffle].ownerOfRaffle == msg.sender,'You need to be the owner of this raffle');
require(raffles[_idRaffle].counterTickets > gettingTheMinimunTickets(raffles[_idRaffle].maxTickets),'You dont sell the minimun percentage of the raffle, you can close it');
// Do the process to get the winner
uint256 winnerTicket = random(raffles[_idRaffle].counterTickets);
// Setting the winner
raffles[_idRaffle].winner = raffles[_idRaffle].participants[winnerTicket];
raffles[_idRaffle].status = statusRaffle.Finished;
raffles[_idRaffle].statusRewarded = true;
payable(address(raffles[_idRaffle].participants[winnerTicket])).transfer(raffles[_idRaffle].rewardAmount * 1 ether);
}
| function finishRaffle(uint256 _idRaffle) isBlocked() checkIfTheRaffleExist(_idRaffle) checkIfRaffleFinish(_idRaffle) public {
require(raffles[_idRaffle].status == statusRaffle.InProgress,'This raffle are finished or closed');
require(raffles[_idRaffle].ownerOfRaffle == msg.sender,'You need to be the owner of this raffle');
require(raffles[_idRaffle].counterTickets > gettingTheMinimunTickets(raffles[_idRaffle].maxTickets),'You dont sell the minimun percentage of the raffle, you can close it');
// Do the process to get the winner
uint256 winnerTicket = random(raffles[_idRaffle].counterTickets);
// Setting the winner
raffles[_idRaffle].winner = raffles[_idRaffle].participants[winnerTicket];
raffles[_idRaffle].status = statusRaffle.Finished;
raffles[_idRaffle].statusRewarded = true;
payable(address(raffles[_idRaffle].participants[winnerTicket])).transfer(raffles[_idRaffle].rewardAmount * 1 ether);
}
| 28,984 |
1 | // What type of collateral the borrower deposited (ERC721 or ERC20) | uint8 borrowerBackingType;
| uint8 borrowerBackingType;
| 38,558 |
16 | // Sends rewards to the specified recipients. recipients The addresses of the recipients to send rewards to. reward The total amount of rewards to send. / | function _sendReward(address[] memory recipients, uint128 reward) internal {
uint128 perReward = uint128(reward / recipients.length);
for (uint i = 0; i < recipients.length; i++) {
_enforceAndUpdateMemberLimits(recipients[i], perReward);
settings.rewardToken.safeTransfer(recipients[i], perReward);
}
_enforceAndUpdateGlobalLimits(reward);
}
| function _sendReward(address[] memory recipients, uint128 reward) internal {
uint128 perReward = uint128(reward / recipients.length);
for (uint i = 0; i < recipients.length; i++) {
_enforceAndUpdateMemberLimits(recipients[i], perReward);
settings.rewardToken.safeTransfer(recipients[i], perReward);
}
_enforceAndUpdateGlobalLimits(reward);
}
| 37,768 |
121 | // To store user staked amount for a sale -POOL => USER => LP_TOKEN | mapping (uint256 => mapping (address => mapping (address => uint256))) public userStakeInfo;
| mapping (uint256 => mapping (address => mapping (address => uint256))) public userStakeInfo;
| 24,512 |
1 | // Output token that users will receive | ERC20Votes public vestedToken;
| ERC20Votes public vestedToken;
| 19,436 |
1,059 | // Schains Contains functions to manage Schains such as Schain creation,deletion, and rotation. / | contract Schains is Permissions, ISchains {
import "./KeyStorage.sol";
import "./SkaleVerifier.sol";
import "./utils/FieldOperations.sol";
import "./NodeRotation.sol";
import "./interfaces/ISkaleDKG.sol";
import "./Wallets.sol";
struct SchainParameters {
uint lifetime;
uint8 typeOfSchain;
uint16 nonce;
string name;
}
| contract Schains is Permissions, ISchains {
import "./KeyStorage.sol";
import "./SkaleVerifier.sol";
import "./utils/FieldOperations.sol";
import "./NodeRotation.sol";
import "./interfaces/ISkaleDKG.sol";
import "./Wallets.sol";
struct SchainParameters {
uint lifetime;
uint8 typeOfSchain;
uint16 nonce;
string name;
}
| 29,171 |
17 | // Allows to fetch Escrow address for the given Raise id./_raiseId Id of the Raise./ return Escrow address. | function getEscrow(string memory _raiseId) internal view returns (address) {
// get escrow address
return escrowStorage().escrows[_raiseId];
}
| function getEscrow(string memory _raiseId) internal view returns (address) {
// get escrow address
return escrowStorage().escrows[_raiseId];
}
| 3,931 |
17 | // Handle after the SGR for ETH exchange operation. _sender The address of the sender. _sgrAmount The amount of SGR received. _ethAmount The amount of ETH given.return The is success result. / | function afterExchangeSgrForEth(address _sender, uint256 _sgrAmount, uint256 _ethAmount) external returns (bool);
| function afterExchangeSgrForEth(address _sender, uint256 _sgrAmount, uint256 _ethAmount) external returns (bool);
| 11,248 |
299 | // Ensure invoke newInterestRateModel.isInterestRateModel() returns true | require(newInterestRateModel.isInterestRateModel(), "marker method returned false");
| require(newInterestRateModel.isInterestRateModel(), "marker method returned false");
| 65,995 |
3 | // Compress a FixedPoint value to 31 bits / | function compress31(uint256 value) internal pure returns (uint256) {
return value.mulUp(_UINT31_MAX).divUp(FixedPoint.ONE);
}
| function compress31(uint256 value) internal pure returns (uint256) {
return value.mulUp(_UINT31_MAX).divUp(FixedPoint.ONE);
}
| 25,371 |
32 | // Validates mint and reverts on rejection. May emit logs. cToken Asset being minted minter The address minting the tokens mintAmount The amount of the underlying asset being minted mintTokens The number of tokens being minted / | function mintVerify(address cToken, address minter, uint mintAmount, uint mintTokens) external {
cToken; // currently unused
minter; // currently unused
mintAmount; // currently unused
mintTokens; // currently unused
if (false) {
maxAssets = maxAssets; // not pure
}
}
| function mintVerify(address cToken, address minter, uint mintAmount, uint mintTokens) external {
cToken; // currently unused
minter; // currently unused
mintAmount; // currently unused
mintTokens; // currently unused
if (false) {
maxAssets = maxAssets; // not pure
}
}
| 35,283 |
195 | // Burns cluster tokens after the trade./requires underlyings to be present/_clusterAmount Cluster token amount to be minted. | function disassembleByAdapter(uint256 _clusterAmount) external override notFarmer onlyRole(ADAPTER_ROLE) {
uint256[] memory underlyingAmounts = getUnderlyingsAmountsFromClusterAmount(_clusterAmount);
_burn(_msgSender(), _clusterAmount);
for (uint256 i = 0; i < underlyingAmounts.length; i++) {
IERC20(underlyings[i]).safeTransfer(_msgSender(), underlyingAmounts[i]);
}
emit ClusterDisassembled(address(this), _msgSender(), _clusterAmount);
}
| function disassembleByAdapter(uint256 _clusterAmount) external override notFarmer onlyRole(ADAPTER_ROLE) {
uint256[] memory underlyingAmounts = getUnderlyingsAmountsFromClusterAmount(_clusterAmount);
_burn(_msgSender(), _clusterAmount);
for (uint256 i = 0; i < underlyingAmounts.length; i++) {
IERC20(underlyings[i]).safeTransfer(_msgSender(), underlyingAmounts[i]);
}
emit ClusterDisassembled(address(this), _msgSender(), _clusterAmount);
}
| 35,628 |
167 | // ERC1155TradableERC1155Tradable - ERC1155 contract that whitelists an operator address, has create and mint functionality, and supports useful standards from OpenZeppelin, / | contract ERC1155Tradable is ContextMixin, ERC1155, NativeMetaTransaction, Ownable {
using Strings for string;
using SafeMath for uint256;
address proxyRegistryAddress;
mapping (uint256 => address) public creators;
mapping (uint256 => uint256) public tokenSupply;
mapping (uint256 => string) customUri;
// Contract name
string public name;
// Contract symbol
string public symbol;
/**
* @dev Require _msgSender() to be the creator of the token id
*/
modifier creatorOnly(uint256 _id) {
require(creators[_id] == _msgSender(), "ERC1155Tradable#creatorOnly: ONLY_CREATOR_ALLOWED");
_;
}
/**
* @dev Require _msgSender() to own more than 0 of the token id
*/
modifier ownersOnly(uint256 _id) {
require(balanceOf(_msgSender(), _id) > 0, "ERC1155Tradable#ownersOnly: ONLY_OWNERS_ALLOWED");
_;
}
constructor(
string memory _name,
string memory _symbol,
string memory _uri,
address _proxyRegistryAddress
) ERC1155(_uri) {
name = _name;
symbol = _symbol;
proxyRegistryAddress = _proxyRegistryAddress;
_initializeEIP712(name);
}
function uri(
uint256 _id
) override public view returns (string memory) {
require(_exists(_id), "ERC1155Tradable#uri: NONEXISTENT_TOKEN");
// We have to convert string to bytes to check for existence
bytes memory customUriBytes = bytes(customUri[_id]);
if (customUriBytes.length > 0) {
return customUri[_id];
} else {
return super.uri(_id);
}
}
/**
* @dev Returns the total quantity for a token ID
* @param _id uint256 ID of the token to query
* @return amount of token in existence
*/
function totalSupply(
uint256 _id
) public view returns (uint256) {
return tokenSupply[_id];
}
/**
* @dev Sets a new URI for all token types, by relying on the token type ID
* substitution mechanism
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
* @param _newURI New URI for all tokens
*/
function setURI(
string memory _newURI
) public onlyOwner {
_setURI(_newURI);
}
/**
* @dev Will update the base URI for the token
* @param _tokenId The token to update. _msgSender() must be its creator.
* @param _newURI New URI for the token.
*/
function setCustomURI(
uint256 _tokenId,
string memory _newURI
) public creatorOnly(_tokenId) {
customUri[_tokenId] = _newURI;
emit URI(_newURI, _tokenId);
}
/**
* @dev Creates a new token type and assigns _initialSupply to an address
* NOTE: remove onlyOwner if you want third parties to create new tokens on
* your contract (which may change your IDs)
* NOTE: The token id must be passed. This allows lazy creation of tokens or
* creating NFTs by setting the id's high bits with the method
* described in ERC1155 or to use ids representing values other than
* successive small integers. If you wish to create ids as successive
* small integers you can either subclass this class to count onchain
* or maintain the offchain cache of identifiers recommended in
* ERC1155 and calculate successive ids from that.
* @param _initialOwner address of the first owner of the token
* @param _id The id of the token to create (must not currenty exist).
* @param _initialSupply amount to supply the first owner
* @param _uri Optional URI for this token type
* @param _data Data to pass if receiver is contract
* @return The newly created token ID
*/
function create(
address _initialOwner,
uint256 _id,
uint256 _initialSupply,
string memory _uri,
bytes memory _data
) public onlyOwner returns (uint256) {
require(!_exists(_id), "token _id already exists");
creators[_id] = _msgSender();
if (bytes(_uri).length > 0) {
customUri[_id] = _uri;
emit URI(_uri, _id);
}
_mint(_initialOwner, _id, _initialSupply, _data);
tokenSupply[_id] = _initialSupply;
return _id;
}
/**
* @dev Mints some amount of tokens to an address
* @param _to Address of the future owner of the token
* @param _id Token ID to mint
* @param _quantity Amount of tokens to mint
* @param _data Data to pass if receiver is contract
*/
function mint(
address _to,
uint256 _id,
uint256 _quantity,
bytes memory _data
) virtual public /* creatorOnly(_id) */ {
_mint(_to, _id, _quantity, _data);
tokenSupply[_id] = tokenSupply[_id].add(_quantity);
}
/**
* @dev Mint tokens for each id in _ids
* @param _to The address to mint tokens to
* @param _ids Array of ids to mint
* @param _quantities Array of amounts of tokens to mint per id
* @param _data Data to pass if receiver is contract
*/
function batchMint(
address _to,
uint256[] memory _ids,
uint256[] memory _quantities,
bytes memory _data
) public {
for (uint256 i = 0; i < _ids.length; i++) {
uint256 _id = _ids[i];
/* require(creators[_id] == _msgSender(), "ERC1155Tradable#batchMint: ONLY_CREATOR_ALLOWED"); */
uint256 quantity = _quantities[i];
tokenSupply[_id] = tokenSupply[_id].add(quantity);
}
_mintBatch(_to, _ids, _quantities, _data);
}
/**
* @dev Change the creator address for given tokens
* @param _to Address of the new creator
* @param _ids Array of Token IDs to change creator
*/
function setCreator(
address _to,
uint256[] memory _ids
) public {
require(_to != address(0), "ERC1155Tradable#setCreator: INVALID_ADDRESS.");
for (uint256 i = 0; i < _ids.length; i++) {
uint256 id = _ids[i];
_setCreator(_to, id);
}
}
/**
* Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-free listings.
*/
function isApprovedForAll(
address _owner,
address _operator
) override public view returns (bool isOperator) {
// Whitelist OpenSea proxy contract for easy trading.
ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress);
if (address(proxyRegistry.proxies(_owner)) == _operator) {
return true;
}
return ERC1155.isApprovedForAll(_owner, _operator);
}
/**
* @dev Change the creator address for given token
* @param _to Address of the new creator
* @param _id Token IDs to change creator of
*/
function _setCreator(address _to, uint256 _id) internal creatorOnly(_id)
{
creators[_id] = _to;
}
/**
* @dev Returns whether the specified token exists by checking to see if it has a creator
* @param _id uint256 ID of the token to query the existence of
* @return bool whether the token exists
*/
function _exists(
uint256 _id
) internal view returns (bool) {
return creators[_id] != address(0);
}
function exists(
uint256 _id
) external view returns (bool) {
return _exists(_id);
}
/**
* This is used instead of msg.sender as transactions won't be sent by the original token owner, but by OpenSea.
*/
function _msgSender()
internal
override
view
returns (address sender)
{
return ContextMixin.msgSender();
}
}
| contract ERC1155Tradable is ContextMixin, ERC1155, NativeMetaTransaction, Ownable {
using Strings for string;
using SafeMath for uint256;
address proxyRegistryAddress;
mapping (uint256 => address) public creators;
mapping (uint256 => uint256) public tokenSupply;
mapping (uint256 => string) customUri;
// Contract name
string public name;
// Contract symbol
string public symbol;
/**
* @dev Require _msgSender() to be the creator of the token id
*/
modifier creatorOnly(uint256 _id) {
require(creators[_id] == _msgSender(), "ERC1155Tradable#creatorOnly: ONLY_CREATOR_ALLOWED");
_;
}
/**
* @dev Require _msgSender() to own more than 0 of the token id
*/
modifier ownersOnly(uint256 _id) {
require(balanceOf(_msgSender(), _id) > 0, "ERC1155Tradable#ownersOnly: ONLY_OWNERS_ALLOWED");
_;
}
constructor(
string memory _name,
string memory _symbol,
string memory _uri,
address _proxyRegistryAddress
) ERC1155(_uri) {
name = _name;
symbol = _symbol;
proxyRegistryAddress = _proxyRegistryAddress;
_initializeEIP712(name);
}
function uri(
uint256 _id
) override public view returns (string memory) {
require(_exists(_id), "ERC1155Tradable#uri: NONEXISTENT_TOKEN");
// We have to convert string to bytes to check for existence
bytes memory customUriBytes = bytes(customUri[_id]);
if (customUriBytes.length > 0) {
return customUri[_id];
} else {
return super.uri(_id);
}
}
/**
* @dev Returns the total quantity for a token ID
* @param _id uint256 ID of the token to query
* @return amount of token in existence
*/
function totalSupply(
uint256 _id
) public view returns (uint256) {
return tokenSupply[_id];
}
/**
* @dev Sets a new URI for all token types, by relying on the token type ID
* substitution mechanism
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
* @param _newURI New URI for all tokens
*/
function setURI(
string memory _newURI
) public onlyOwner {
_setURI(_newURI);
}
/**
* @dev Will update the base URI for the token
* @param _tokenId The token to update. _msgSender() must be its creator.
* @param _newURI New URI for the token.
*/
function setCustomURI(
uint256 _tokenId,
string memory _newURI
) public creatorOnly(_tokenId) {
customUri[_tokenId] = _newURI;
emit URI(_newURI, _tokenId);
}
/**
* @dev Creates a new token type and assigns _initialSupply to an address
* NOTE: remove onlyOwner if you want third parties to create new tokens on
* your contract (which may change your IDs)
* NOTE: The token id must be passed. This allows lazy creation of tokens or
* creating NFTs by setting the id's high bits with the method
* described in ERC1155 or to use ids representing values other than
* successive small integers. If you wish to create ids as successive
* small integers you can either subclass this class to count onchain
* or maintain the offchain cache of identifiers recommended in
* ERC1155 and calculate successive ids from that.
* @param _initialOwner address of the first owner of the token
* @param _id The id of the token to create (must not currenty exist).
* @param _initialSupply amount to supply the first owner
* @param _uri Optional URI for this token type
* @param _data Data to pass if receiver is contract
* @return The newly created token ID
*/
function create(
address _initialOwner,
uint256 _id,
uint256 _initialSupply,
string memory _uri,
bytes memory _data
) public onlyOwner returns (uint256) {
require(!_exists(_id), "token _id already exists");
creators[_id] = _msgSender();
if (bytes(_uri).length > 0) {
customUri[_id] = _uri;
emit URI(_uri, _id);
}
_mint(_initialOwner, _id, _initialSupply, _data);
tokenSupply[_id] = _initialSupply;
return _id;
}
/**
* @dev Mints some amount of tokens to an address
* @param _to Address of the future owner of the token
* @param _id Token ID to mint
* @param _quantity Amount of tokens to mint
* @param _data Data to pass if receiver is contract
*/
function mint(
address _to,
uint256 _id,
uint256 _quantity,
bytes memory _data
) virtual public /* creatorOnly(_id) */ {
_mint(_to, _id, _quantity, _data);
tokenSupply[_id] = tokenSupply[_id].add(_quantity);
}
/**
* @dev Mint tokens for each id in _ids
* @param _to The address to mint tokens to
* @param _ids Array of ids to mint
* @param _quantities Array of amounts of tokens to mint per id
* @param _data Data to pass if receiver is contract
*/
function batchMint(
address _to,
uint256[] memory _ids,
uint256[] memory _quantities,
bytes memory _data
) public {
for (uint256 i = 0; i < _ids.length; i++) {
uint256 _id = _ids[i];
/* require(creators[_id] == _msgSender(), "ERC1155Tradable#batchMint: ONLY_CREATOR_ALLOWED"); */
uint256 quantity = _quantities[i];
tokenSupply[_id] = tokenSupply[_id].add(quantity);
}
_mintBatch(_to, _ids, _quantities, _data);
}
/**
* @dev Change the creator address for given tokens
* @param _to Address of the new creator
* @param _ids Array of Token IDs to change creator
*/
function setCreator(
address _to,
uint256[] memory _ids
) public {
require(_to != address(0), "ERC1155Tradable#setCreator: INVALID_ADDRESS.");
for (uint256 i = 0; i < _ids.length; i++) {
uint256 id = _ids[i];
_setCreator(_to, id);
}
}
/**
* Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-free listings.
*/
function isApprovedForAll(
address _owner,
address _operator
) override public view returns (bool isOperator) {
// Whitelist OpenSea proxy contract for easy trading.
ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress);
if (address(proxyRegistry.proxies(_owner)) == _operator) {
return true;
}
return ERC1155.isApprovedForAll(_owner, _operator);
}
/**
* @dev Change the creator address for given token
* @param _to Address of the new creator
* @param _id Token IDs to change creator of
*/
function _setCreator(address _to, uint256 _id) internal creatorOnly(_id)
{
creators[_id] = _to;
}
/**
* @dev Returns whether the specified token exists by checking to see if it has a creator
* @param _id uint256 ID of the token to query the existence of
* @return bool whether the token exists
*/
function _exists(
uint256 _id
) internal view returns (bool) {
return creators[_id] != address(0);
}
function exists(
uint256 _id
) external view returns (bool) {
return _exists(_id);
}
/**
* This is used instead of msg.sender as transactions won't be sent by the original token owner, but by OpenSea.
*/
function _msgSender()
internal
override
view
returns (address sender)
{
return ContextMixin.msgSender();
}
}
| 57,196 |
495 | // Update the given pool's ability to withdraw tokens Note contract owner is meant to be a governance contract allowing ENCORE governance consensus | function setPoolWithdrawable(
uint256 _pid,
bool _withdrawable
| function setPoolWithdrawable(
uint256 _pid,
bool _withdrawable
| 47,472 |
150 | // Transfers a specific NFT (`tokenId`) from one account (`from`) toanother (`to`). Requirements:- `from`, `to` cannot be zero.- `tokenId` must be owned by `from`.- If the caller is not `from`, it must be have been allowed to move thisNFT by either `approve` or `setApproveForAll`. / | function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public;
| function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public;
| 27,120 |
20 | // Get the order info buyer buyer of the order orderId order id products products to sell finalTimestamp timestamp of the end of the order / | function _directSell(address buyer, uint64 orderId, Product[] memory products, uint256 finalTimestamp) internal
checkRequest(orderId, finalTimestamp)
| function _directSell(address buyer, uint64 orderId, Product[] memory products, uint256 finalTimestamp) internal
checkRequest(orderId, finalTimestamp)
| 21,059 |
48 | // Get current oracle fee where `multiplier` equals 100% of bettor winnings. / | function getOracleFee() external view override returns (uint128 fee) {
return oracleFee;
}
| function getOracleFee() external view override returns (uint128 fee) {
return oracleFee;
}
| 7,969 |
31 | // ServiceController// Base implementation/ Serves for managing service instances | contract ServiceControllerInterface {
/// @notice Check target address is service
/// @param _address target address
/// @return `true` when an address is a service, `false` otherwise
function isService(address _address) public view returns (bool);
}
| contract ServiceControllerInterface {
/// @notice Check target address is service
/// @param _address target address
/// @return `true` when an address is a service, `false` otherwise
function isService(address _address) public view returns (bool);
}
| 28,963 |
68 | // The minimum number of blocks between harvest calls NOTE: Override this value with your own, or set dynamically below | uint256 public minReportDelay = 6300; // ~ once a day
| uint256 public minReportDelay = 6300; // ~ once a day
| 2,936 |
69 | // The eMoon TOKEN! | EmoonToken public emoon;
| EmoonToken public emoon;
| 29,901 |
19 | // If current allowance for _spender is equal to _currentValue, then overwrite it with _value and return true, otherwise return false. |
if (allowances_[msg.sender][_spender] == _currentValue)
return approve(_spender, _value);
return false;
|
if (allowances_[msg.sender][_spender] == _currentValue)
return approve(_spender, _value);
return false;
| 16,660 |
22 | // B|R = B - RCF | return (
heap.maxRedeemable,
sub_(
heap.underlyingLiquidity, //borrow power
mul_ScalarTruncate(
| return (
heap.maxRedeemable,
sub_(
heap.underlyingLiquidity, //borrow power
mul_ScalarTruncate(
| 14,321 |
36 | // NOTE: yDai will be sent to this contractTransfer dai from this contract to dai lending adapter and then call a new save function that will not use transferFrom internallyApprove the daiLendingAdapter so it can spend our Dai on our behalf | address daiLendingAdapterContractAddress = _iDaiLendingService
.GetDaiLendingAdapterAddress();
_dai.approve(daiLendingAdapterContractAddress, esusuCycleBalance);
_iDaiLendingService.save(esusuCycleBalance);
| address daiLendingAdapterContractAddress = _iDaiLendingService
.GetDaiLendingAdapterAddress();
_dai.approve(daiLendingAdapterContractAddress, esusuCycleBalance);
_iDaiLendingService.save(esusuCycleBalance);
| 21,013 |
0 | // We do some fancy math here. Basically, any point in time, the amount of NERDs entitled to a user but is pending to be distributed is: pending reward = (user.amountpool.accNerdPerShare) - user.rewardDebt Whenever a user deposits or withdrawstokens to a pool. Here's what happens: 1. The pool's `accNerdPerShare` (and `lastRewardBlock`) gets updated. 2. User receives the pending reward sent to his/her address. 3. User's `amount` gets updated. 4. User's `rewardDebt` gets updated. |
uint256 depositTime; //See explanation below.
|
uint256 depositTime; //See explanation below.
| 10,608 |
4 | // The multiplication in the next line has the same exact purpose as the one above. | let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), 27)
| let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), 27)
| 18,748 |
173 | // Callback for `IKyberBridge`. Tries to buy `amount` of/`toTokenAddress` tokens by selling the entirety of the opposing asset/to the `KyberNetworkProxy` contract, then transfers the bought/tokens to `to`./toTokenAddress The token to give to `to`./from The maker (this contract)./to The recipient of the bought tokens./bridgeData The abi-encoeded "from" token address./ return success The magic bytes if successful. | function bridgeTransferFrom(
address toTokenAddress,
address from,
address to,
uint256 /* amount */,
bytes calldata bridgeData
)
external
returns (bytes4 success)
{
| function bridgeTransferFrom(
address toTokenAddress,
address from,
address to,
uint256 /* amount */,
bytes calldata bridgeData
)
external
returns (bytes4 success)
{
| 33,110 |
11 | // Storage contract | contract EtherTrackDataStore is owned, mortal {
/// Hash table that pair address with public name
mapping(address => uint64) private nameByNode;
mapping(address => bool) private registeredByNode;
mapping(uint64 => address) private nodeByName;
function EtherTrackDataStore(address target) public {
if(target != address(0))
{
delegateOwnership(target);
}
}
function getNamebyNode (address node) external view returns (uint64) {
return nameByNode[node];
}
function getNodebyName (uint64 name) external view returns (address) {
return nodeByName[name];
}
function setNamebyNode (address node, uint64 name) external onlyOwner returns (uint64) {
require(!registeredByNode[node]);
nameByNode[node] = name;
nodeByName[name] = node;
registeredByNode[node] = true;
return name;
}
}
| contract EtherTrackDataStore is owned, mortal {
/// Hash table that pair address with public name
mapping(address => uint64) private nameByNode;
mapping(address => bool) private registeredByNode;
mapping(uint64 => address) private nodeByName;
function EtherTrackDataStore(address target) public {
if(target != address(0))
{
delegateOwnership(target);
}
}
function getNamebyNode (address node) external view returns (uint64) {
return nameByNode[node];
}
function getNodebyName (uint64 name) external view returns (address) {
return nodeByName[name];
}
function setNamebyNode (address node, uint64 name) external onlyOwner returns (uint64) {
require(!registeredByNode[node]);
nameByNode[node] = name;
nodeByName[name] = node;
registeredByNode[node] = true;
return name;
}
}
| 30,951 |
107 | // Wrappers over Solidity's uintXX/intXX casting operators with added overflowchecks. Downcasting from uint256/int256 in Solidity does not revert on overflow. This caneasily result in undesired exploitation or bugs, since developers usuallyassume that overflows raise errors. `SafeCast` restores this intuition byreverting the transaction when such an operation overflows. Using this library instead of the unchecked operations eliminates an entireclass of bugs, so it's recommended to use it always. | * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing
* all math on `uint256` and `int256` and then downcasting.
*/
library SafeCast {
/**
* @dev Returns the downcasted uint224 from uint256, reverting on
* overflow (when the input is greater than largest uint224).
*
* Counterpart to Solidity's `uint224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*/
function toUint224(uint256 value) internal pure returns (uint224) {
require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits");
return uint224(value);
}
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
require(value <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits");
return uint128(value);
}
/**
* @dev Returns the downcasted uint96 from uint256, reverting on
* overflow (when the input is greater than largest uint96).
*
* Counterpart to Solidity's `uint96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/
function toUint96(uint256 value) internal pure returns (uint96) {
require(value <= type(uint96).max, "SafeCast: value doesn't fit in 96 bits");
return uint96(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
require(value <= type(uint64).max, "SafeCast: value doesn't fit in 64 bits");
return uint64(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
require(value <= type(uint32).max, "SafeCast: value doesn't fit in 32 bits");
return uint32(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
require(value <= type(uint16).max, "SafeCast: value doesn't fit in 16 bits");
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*/
function toUint8(uint256 value) internal pure returns (uint8) {
require(value <= type(uint8).max, "SafeCast: value doesn't fit in 8 bits");
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/
function toUint256(int256 value) internal pure returns (uint256) {
require(value >= 0, "SafeCast: value must be positive");
return uint256(value);
}
/**
* @dev Returns the downcasted int128 from int256, reverting on
* overflow (when the input is less than smallest int128 or
* greater than largest int128).
*
* Counterpart to Solidity's `int128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*
* _Available since v3.1._
*/
function toInt128(int256 value) internal pure returns (int128) {
require(value >= type(int128).min && value <= type(int128).max, "SafeCast: value doesn't fit in 128 bits");
return int128(value);
}
/**
* @dev Returns the downcasted int64 from int256, reverting on
* overflow (when the input is less than smallest int64 or
* greater than largest int64).
*
* Counterpart to Solidity's `int64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*
* _Available since v3.1._
*/
function toInt64(int256 value) internal pure returns (int64) {
require(value >= type(int64).min && value <= type(int64).max, "SafeCast: value doesn't fit in 64 bits");
return int64(value);
}
/**
* @dev Returns the downcasted int32 from int256, reverting on
* overflow (when the input is less than smallest int32 or
* greater than largest int32).
*
* Counterpart to Solidity's `int32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*
* _Available since v3.1._
*/
function toInt32(int256 value) internal pure returns (int32) {
require(value >= type(int32).min && value <= type(int32).max, "SafeCast: value doesn't fit in 32 bits");
return int32(value);
}
/**
* @dev Returns the downcasted int16 from int256, reverting on
* overflow (when the input is less than smallest int16 or
* greater than largest int16).
*
* Counterpart to Solidity's `int16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*
* _Available since v3.1._
*/
function toInt16(int256 value) internal pure returns (int16) {
require(value >= type(int16).min && value <= type(int16).max, "SafeCast: value doesn't fit in 16 bits");
return int16(value);
}
/**
* @dev Returns the downcasted int8 from int256, reverting on
* overflow (when the input is less than smallest int8 or
* greater than largest int8).
*
* Counterpart to Solidity's `int8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*
* _Available since v3.1._
*/
function toInt8(int256 value) internal pure returns (int8) {
require(value >= type(int8).min && value <= type(int8).max, "SafeCast: value doesn't fit in 8 bits");
return int8(value);
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
// Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
require(value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256");
return int256(value);
}
}
| * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing
* all math on `uint256` and `int256` and then downcasting.
*/
library SafeCast {
/**
* @dev Returns the downcasted uint224 from uint256, reverting on
* overflow (when the input is greater than largest uint224).
*
* Counterpart to Solidity's `uint224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*/
function toUint224(uint256 value) internal pure returns (uint224) {
require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits");
return uint224(value);
}
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
require(value <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits");
return uint128(value);
}
/**
* @dev Returns the downcasted uint96 from uint256, reverting on
* overflow (when the input is greater than largest uint96).
*
* Counterpart to Solidity's `uint96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/
function toUint96(uint256 value) internal pure returns (uint96) {
require(value <= type(uint96).max, "SafeCast: value doesn't fit in 96 bits");
return uint96(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
require(value <= type(uint64).max, "SafeCast: value doesn't fit in 64 bits");
return uint64(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
require(value <= type(uint32).max, "SafeCast: value doesn't fit in 32 bits");
return uint32(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
require(value <= type(uint16).max, "SafeCast: value doesn't fit in 16 bits");
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*/
function toUint8(uint256 value) internal pure returns (uint8) {
require(value <= type(uint8).max, "SafeCast: value doesn't fit in 8 bits");
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/
function toUint256(int256 value) internal pure returns (uint256) {
require(value >= 0, "SafeCast: value must be positive");
return uint256(value);
}
/**
* @dev Returns the downcasted int128 from int256, reverting on
* overflow (when the input is less than smallest int128 or
* greater than largest int128).
*
* Counterpart to Solidity's `int128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*
* _Available since v3.1._
*/
function toInt128(int256 value) internal pure returns (int128) {
require(value >= type(int128).min && value <= type(int128).max, "SafeCast: value doesn't fit in 128 bits");
return int128(value);
}
/**
* @dev Returns the downcasted int64 from int256, reverting on
* overflow (when the input is less than smallest int64 or
* greater than largest int64).
*
* Counterpart to Solidity's `int64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*
* _Available since v3.1._
*/
function toInt64(int256 value) internal pure returns (int64) {
require(value >= type(int64).min && value <= type(int64).max, "SafeCast: value doesn't fit in 64 bits");
return int64(value);
}
/**
* @dev Returns the downcasted int32 from int256, reverting on
* overflow (when the input is less than smallest int32 or
* greater than largest int32).
*
* Counterpart to Solidity's `int32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*
* _Available since v3.1._
*/
function toInt32(int256 value) internal pure returns (int32) {
require(value >= type(int32).min && value <= type(int32).max, "SafeCast: value doesn't fit in 32 bits");
return int32(value);
}
/**
* @dev Returns the downcasted int16 from int256, reverting on
* overflow (when the input is less than smallest int16 or
* greater than largest int16).
*
* Counterpart to Solidity's `int16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*
* _Available since v3.1._
*/
function toInt16(int256 value) internal pure returns (int16) {
require(value >= type(int16).min && value <= type(int16).max, "SafeCast: value doesn't fit in 16 bits");
return int16(value);
}
/**
* @dev Returns the downcasted int8 from int256, reverting on
* overflow (when the input is less than smallest int8 or
* greater than largest int8).
*
* Counterpart to Solidity's `int8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*
* _Available since v3.1._
*/
function toInt8(int256 value) internal pure returns (int8) {
require(value >= type(int8).min && value <= type(int8).max, "SafeCast: value doesn't fit in 8 bits");
return int8(value);
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
// Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
require(value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256");
return int256(value);
}
}
| 8,350 |
15 | // You may alter the vote weight according to your program specifications We take a basic example of equal voting weights for each user./ | function calculateVoteWeight(address citizen) private {
voters[citizen].weight = 1;
}
| function calculateVoteWeight(address citizen) private {
voters[citizen].weight = 1;
}
| 19,384 |
9 | // no overflow in `a + b` | uint256 x = roundDiv(newN, newD); // we can now safely compute `scale - x`
uint256 y = scale - x;
return (x, y);
| uint256 x = roundDiv(newN, newD); // we can now safely compute `scale - x`
uint256 y = scale - x;
return (x, y);
| 12,221 |
31 | // Cell 22 | eend.allWhiteCollateral = _collateralForWhite;
emit AllWhiteCollateral(eend.allWhiteCollateral);
if(eend.allWhiteCollateral == 0) {
return;
}
| eend.allWhiteCollateral = _collateralForWhite;
emit AllWhiteCollateral(eend.allWhiteCollateral);
if(eend.allWhiteCollateral == 0) {
return;
}
| 26,202 |
42 | // verify that this function is only called by the correct V3 Pool | CallbackValidation.verifyCallback(
address(FACTORY_V3),
PoolAddress.PoolKey({
token0: token0,
token1: token1,
fee: uint24(fee)
})
| CallbackValidation.verifyCallback(
address(FACTORY_V3),
PoolAddress.PoolKey({
token0: token0,
token1: token1,
fee: uint24(fee)
})
| 7,898 |
12 | // Returns the subtraction of two unsigned integers, reverting with custom message onoverflow (when the result is negative). CAUTION: This function is deprecated because it requires allocating memory for the error | * message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
| * message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
| 7,159 |
31 | // Define the contract | contract FundForward {
// Define the struct for Campaigns
struct Campaign {
address owner;
string title;
string description;
uint256 target;
uint256 deadline;
uint256 amountCollected;
string image;
address[] donators;
uint256[] donations;
}
// Define the struct for Proposals
struct Proposal {
string description;
uint256 yesVotes;
uint256 noVotes;
uint256 abstainVotes;
bool open;
address creator;
}
// Create a mapping to store campaigns by ID
mapping(uint256 => Campaign) public campaigns;
// Set the initial number of campaigns to 0
uint256 public numberOfCampaigns = 0;
// This creates a mapping from proposal ID to Proposal struct
mapping(uint256 => Proposal) public proposals;
// This creates a mapping from proposal ID to a mapping of addresses to a boolean indicating whether the address has voted or not
mapping(uint256 => mapping(address => bool)) public hasVoted;
// Set the initial number of proposals to 0
uint256 public numberOfProposals = 0;
// Crowdfunding Functions ///
// Function to create a new campaign and return its ID
function createCampaign(address _owner, string memory _title, string memory _description, uint256 _target, uint256 _deadline, string memory _image) public returns (uint256) {
// Create a storage reference to the new Campaign
Campaign storage campaign = campaigns[numberOfCampaigns];
// Require that the deadline is a date in the future
require(campaign.deadline < block.timestamp, "The deadline should be a date in the future.");
// Initialize the Campaign with the given parameters
campaign.owner = _owner;
campaign.title = _title;
campaign.description = _description;
campaign.target = _target;
campaign.deadline = _deadline;
campaign.amountCollected = 0;
campaign.image = _image;
// Increment the number of campaigns and return its ID
numberOfCampaigns++;
return numberOfCampaigns - 1;
}
// Function to donate to a campaign by ID
function donateToCampaign(uint256 _id) public payable {
// Get the amount of the donation
uint256 amount = msg.value;
// Get the Campaign by ID
Campaign storage campaign = campaigns[_id];
// Add the donator and donation amount to the Campaign
campaign.donators.push(msg.sender);
campaign.donations.push(amount);
// Send the donated amount to the Campaign owner
(bool sent, ) = payable(campaign.owner).call{value: amount}("");
// If the donation was sent, add it to the amount collected by the Campaign
if(sent) {
campaign.amountCollected = campaign.amountCollected + amount;
}
}
// Function to get the donators and donations for a Campaign by ID
function getDonators(uint256 _id) view public returns (address[] memory, uint256[] memory) {
return (campaigns[_id].donators, campaigns[_id].donations);
}
// Function to get all Campaigns
function getCampaigns() public view returns (Campaign[] memory) {
// Initialize an array to store all Campaigns
Campaign[] memory allCampaigns = new Campaign[](numberOfCampaigns);
// Loop through all Campaigns and add them to the array
for(uint i = 0; i < numberOfCampaigns; i++) {
Campaign storage item = campaigns[i];
allCampaigns[i] = item;
}
// Return the array of all Campaigns
return allCampaigns;
}
// Voting Functions /////
// This function creates a new proposal and returns its ID
function createProposal(string memory _description) public returns (uint256) {
Proposal storage proposal = proposals[numberOfProposals];
proposal.description = _description;
proposal.yesVotes = 0;
proposal.noVotes = 0;
proposal.abstainVotes = 0;
proposal.open = true;
proposal.creator = msg.sender;
numberOfProposals++;
return numberOfProposals - 1;
}
// This function casts a vote for a proposal
function vote(uint256 _id, string memory _vote) public {
Proposal storage proposal = proposals[_id];
require(proposal.open == true, "Proposal is closed");
require(bytes(_vote).length > 0, "Vote cannot be empty");
require(hasVoted[_id][msg.sender] == false, "Address has already voted");
if (keccak256(bytes(_vote)) == keccak256(bytes("yes"))) {
proposal.yesVotes++;
} else if (keccak256(bytes(_vote)) == keccak256(bytes("no"))) {
proposal.noVotes++;
} else if (keccak256(bytes(_vote)) == keccak256(bytes("abstain"))) {
proposal.abstainVotes++;
} else {
revert("Invalid vote option");
}
// Mark the address as having voted
hasVoted[_id][msg.sender] = true;
}
// This function returns an array of all proposals
function getProposals() public view returns (Proposal[] memory) {
Proposal[] memory allProposals = new Proposal[](numberOfProposals);
for(uint i = 0; i < numberOfProposals; i++) {
Proposal storage proposal = proposals[i];
allProposals[i] = proposal;
}
return allProposals;
}
// This function closes a proposal
function closeProposal(uint256 _id) public {
Proposal storage proposal = proposals[_id];
require(proposal.open == true, "Proposal is already closed");
require(msg.sender == proposal.creator, "Only the proposal creator can close it");
proposal.open = false;
}
// This function returns the results of a closed proposal
function getProposalResult(uint256 _id) public view returns (uint256 yesVotes, uint256 noVotes, uint256 abstainVotes) {
Proposal storage proposal = proposals[_id];
require(proposal.open == false, "Proposal is still open");
return (proposal.yesVotes, proposal.noVotes, proposal.abstainVotes);
}
}
| contract FundForward {
// Define the struct for Campaigns
struct Campaign {
address owner;
string title;
string description;
uint256 target;
uint256 deadline;
uint256 amountCollected;
string image;
address[] donators;
uint256[] donations;
}
// Define the struct for Proposals
struct Proposal {
string description;
uint256 yesVotes;
uint256 noVotes;
uint256 abstainVotes;
bool open;
address creator;
}
// Create a mapping to store campaigns by ID
mapping(uint256 => Campaign) public campaigns;
// Set the initial number of campaigns to 0
uint256 public numberOfCampaigns = 0;
// This creates a mapping from proposal ID to Proposal struct
mapping(uint256 => Proposal) public proposals;
// This creates a mapping from proposal ID to a mapping of addresses to a boolean indicating whether the address has voted or not
mapping(uint256 => mapping(address => bool)) public hasVoted;
// Set the initial number of proposals to 0
uint256 public numberOfProposals = 0;
// Crowdfunding Functions ///
// Function to create a new campaign and return its ID
function createCampaign(address _owner, string memory _title, string memory _description, uint256 _target, uint256 _deadline, string memory _image) public returns (uint256) {
// Create a storage reference to the new Campaign
Campaign storage campaign = campaigns[numberOfCampaigns];
// Require that the deadline is a date in the future
require(campaign.deadline < block.timestamp, "The deadline should be a date in the future.");
// Initialize the Campaign with the given parameters
campaign.owner = _owner;
campaign.title = _title;
campaign.description = _description;
campaign.target = _target;
campaign.deadline = _deadline;
campaign.amountCollected = 0;
campaign.image = _image;
// Increment the number of campaigns and return its ID
numberOfCampaigns++;
return numberOfCampaigns - 1;
}
// Function to donate to a campaign by ID
function donateToCampaign(uint256 _id) public payable {
// Get the amount of the donation
uint256 amount = msg.value;
// Get the Campaign by ID
Campaign storage campaign = campaigns[_id];
// Add the donator and donation amount to the Campaign
campaign.donators.push(msg.sender);
campaign.donations.push(amount);
// Send the donated amount to the Campaign owner
(bool sent, ) = payable(campaign.owner).call{value: amount}("");
// If the donation was sent, add it to the amount collected by the Campaign
if(sent) {
campaign.amountCollected = campaign.amountCollected + amount;
}
}
// Function to get the donators and donations for a Campaign by ID
function getDonators(uint256 _id) view public returns (address[] memory, uint256[] memory) {
return (campaigns[_id].donators, campaigns[_id].donations);
}
// Function to get all Campaigns
function getCampaigns() public view returns (Campaign[] memory) {
// Initialize an array to store all Campaigns
Campaign[] memory allCampaigns = new Campaign[](numberOfCampaigns);
// Loop through all Campaigns and add them to the array
for(uint i = 0; i < numberOfCampaigns; i++) {
Campaign storage item = campaigns[i];
allCampaigns[i] = item;
}
// Return the array of all Campaigns
return allCampaigns;
}
// Voting Functions /////
// This function creates a new proposal and returns its ID
function createProposal(string memory _description) public returns (uint256) {
Proposal storage proposal = proposals[numberOfProposals];
proposal.description = _description;
proposal.yesVotes = 0;
proposal.noVotes = 0;
proposal.abstainVotes = 0;
proposal.open = true;
proposal.creator = msg.sender;
numberOfProposals++;
return numberOfProposals - 1;
}
// This function casts a vote for a proposal
function vote(uint256 _id, string memory _vote) public {
Proposal storage proposal = proposals[_id];
require(proposal.open == true, "Proposal is closed");
require(bytes(_vote).length > 0, "Vote cannot be empty");
require(hasVoted[_id][msg.sender] == false, "Address has already voted");
if (keccak256(bytes(_vote)) == keccak256(bytes("yes"))) {
proposal.yesVotes++;
} else if (keccak256(bytes(_vote)) == keccak256(bytes("no"))) {
proposal.noVotes++;
} else if (keccak256(bytes(_vote)) == keccak256(bytes("abstain"))) {
proposal.abstainVotes++;
} else {
revert("Invalid vote option");
}
// Mark the address as having voted
hasVoted[_id][msg.sender] = true;
}
// This function returns an array of all proposals
function getProposals() public view returns (Proposal[] memory) {
Proposal[] memory allProposals = new Proposal[](numberOfProposals);
for(uint i = 0; i < numberOfProposals; i++) {
Proposal storage proposal = proposals[i];
allProposals[i] = proposal;
}
return allProposals;
}
// This function closes a proposal
function closeProposal(uint256 _id) public {
Proposal storage proposal = proposals[_id];
require(proposal.open == true, "Proposal is already closed");
require(msg.sender == proposal.creator, "Only the proposal creator can close it");
proposal.open = false;
}
// This function returns the results of a closed proposal
function getProposalResult(uint256 _id) public view returns (uint256 yesVotes, uint256 noVotes, uint256 abstainVotes) {
Proposal storage proposal = proposals[_id];
require(proposal.open == false, "Proposal is still open");
return (proposal.yesVotes, proposal.noVotes, proposal.abstainVotes);
}
}
| 12,328 |
19 | // Get size of "_to" address, if 0 it's a wallet | uint32 size;
assembly {
size := extcodesize(_to)
}
| uint32 size;
assembly {
size := extcodesize(_to)
}
| 20,988 |
97 | // The minimum price of the first bid | uint256 reservePrice;
| uint256 reservePrice;
| 14,796 |
32 | // the first stage 15% + community operation 15% | balances[msg.sender] = peerSupply.mul(30);
| balances[msg.sender] = peerSupply.mul(30);
| 12,528 |
111 | // keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)') | 0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f,
keccak256(bytes(Strings.toHexString(uint160(address(this))))),
0xc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6, // keccak256(bytes("1"))
block.chainid,
address(this)
)
);
| 0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f,
keccak256(bytes(Strings.toHexString(uint160(address(this))))),
0xc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6, // keccak256(bytes("1"))
block.chainid,
address(this)
)
);
| 68,613 |
5 | // This emits when ability of beeing able to transfer Xcerts changes (paused/unpaused). / | event IsPaused(bool isPaused);
| event IsPaused(bool isPaused);
| 14,980 |
14 | // Safely transfer using an anonymous ERC20 token Requires token to return true on transfer token address to recipient address value amount / | function _safeTransfer(
address token,
address to,
uint256 value
| function _safeTransfer(
address token,
address to,
uint256 value
| 10,678 |
79 | // Allows external read `getVersion()` to return a version for the auction. | uint256 private constant RESERVE_AUCTION_VERSION = 1;
| uint256 private constant RESERVE_AUCTION_VERSION = 1;
| 25,328 |
3 | // @inheritdoc IAuthorizeMints/this authorizer does not restrict reservations | function authorizeReservation(address) external pure override returns (bool) {
return true;
}
| function authorizeReservation(address) external pure override returns (bool) {
return true;
}
| 3,129 |
5 | // Returns the metadata URI for an NFT. See `BatchMintMetadata` for handling of metadata in this contract. _tokenId The tokenId of an NFT. / | function tokenURI(uint256 _tokenId) public view virtual override returns (string memory) {
string memory batchUri = getBaseURI(_tokenId);
return string(abi.encodePacked(batchUri, _tokenId.toString()));
}
| function tokenURI(uint256 _tokenId) public view virtual override returns (string memory) {
string memory batchUri = getBaseURI(_tokenId);
return string(abi.encodePacked(batchUri, _tokenId.toString()));
}
| 17,097 |
3 | // effects | holdings[channelId] = balance;
if (numNewAllocationItems > 0) {
| holdings[channelId] = balance;
if (numNewAllocationItems > 0) {
| 22,101 |
1,304 | // nodeIndex - index of Node which is in process of rotation (left from schain)newNodeIndex - index of Node which is rotated(added to schain)freezeUntil - time till which Node should be turned onrotationCounter - how many rotations were on this schain / | struct Rotation {
| struct Rotation {
| 29,225 |
14 | // Revokes authorisation of an operator previously given for a specified partition of `tokenHolder`/_partition The partition to which the operator is de-authorised/_operator An address which is being de-authorised | function revokeOperatorByPartition(
bytes32 _partition,
address _operator,
address tokenHolder
| function revokeOperatorByPartition(
bytes32 _partition,
address _operator,
address tokenHolder
| 2,028 |
1 | // recode if you're the initiator | mapping(string => bool) htlcRoles;
mapping(string => uint) proposalIndexs;
| mapping(string => bool) htlcRoles;
mapping(string => uint) proposalIndexs;
| 24,444 |
13 | // This tracks whether the root has been proven to exist within the given aggregate root. Tracking this is an optimization so you dont have to prove inclusion of the same constituentroot many times. / | mapping(bytes32 => bool) public provenMessageRoots;
| mapping(bytes32 => bool) public provenMessageRoots;
| 11,459 |
130 | // ========== MODIFIER ========== / | modifier onlyApprovedConsumer() {
require(
approvedConsumers.contains(_msgSender()),
"BRDSupplier: unauthorized"
);
_;
}
| modifier onlyApprovedConsumer() {
require(
approvedConsumers.contains(_msgSender()),
"BRDSupplier: unauthorized"
);
_;
}
| 30,276 |
10 | // SafeMath - the lowest gas library / | library SafeMath {
function mul(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal constant returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal constant returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
| library SafeMath {
function mul(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal constant returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal constant returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
| 76,767 |
31 | // Set the operator of this contract/newOperator The address of the new operator | function setOperator(address newOperator)
public
onlyOperator
notNullOrThisAddress(newOperator)
| function setOperator(address newOperator)
public
onlyOperator
notNullOrThisAddress(newOperator)
| 29,001 |
30 | // view the current parameters of the curve/ return alpha_ the current alpha value/beta_ the current beta value/delta_ the current delta value/epsilon_ the current epsilon value/lambda_ the current lambda value/omega_ the current omega value | function viewCurve()
external
view
returns (
uint256 alpha_,
uint256 beta_,
uint256 delta_,
uint256 epsilon_,
uint256 lambda_
)
| function viewCurve()
external
view
returns (
uint256 alpha_,
uint256 beta_,
uint256 delta_,
uint256 epsilon_,
uint256 lambda_
)
| 14,944 |
0 | // the video offline on the IPFS | Video public thisVideo;
| Video public thisVideo;
| 36,079 |
138 | // can later be changed with {transferOwnership}. State variables |
address private _owner;
|
address private _owner;
| 40,282 |
37 | // can later be changed with {transferOwnership}. This module is used through inheritance. It will make available the modifier`onlyOwner`, which can be applied to your functions to restrict their use tothe owner. / | contract Ownable is Context {
address private _owner;
address private _previousOwner;
uint256 private _lockTime;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
| contract Ownable is Context {
address private _owner;
address private _previousOwner;
uint256 private _lockTime;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
| 7,550 |
18 | // Find PoolContributor contract by index | function getPoolContributor(uint256 _poolContributorIndex)
public
view
returns (address)
| function getPoolContributor(uint256 _poolContributorIndex)
public
view
returns (address)
| 29,847 |
10 | // ERC20Basic | contract ERC20Basic is ERC20If {
using SafeMath for uint256;
mapping(address => uint256) internal balances;
mapping(address => mapping(address => uint256)) internal allowed;
uint256 internal totalSupply_;
function _notPaused() virtual internal view returns (bool){return false;}
function _notBlocked(address) virtual internal view returns (bool){return false;}
modifier notPaused() {
require(_notPaused(), "contract has been paused");
_;
}
modifier notBlocked() {
require(_notBlocked(msg.sender), "sender has been blocked");
_;
}
function totalSupply() override public view returns (uint256) {
return totalSupply_;
}
function transfer(address _to, uint256 _value) override public notPaused notBlocked returns (bool) {
require(_notBlocked(_to), "to-address has been blocked");
require(_value <= balances[msg.sender], "insufficient balance");
require(_to != address(0), "invalid to-address");
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) override public view returns (uint256) {
return balances[_owner];
}
function transferFrom(
address _from,
address _to,
uint256 _value
)
override public notPaused notBlocked
returns (bool)
{
require(_notBlocked(_from), "from-address has been blocked");
require(_notBlocked(_to), "to-address has been blocked");
require(_value <= balances[_from], "insufficient balance");
require(_to != address(0), "invalid to-address");
if (_from == msg.sender){
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
return true;
}
require(_value <= allowed[_from][msg.sender], "value > allowed");
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value)
override public notPaused notBlocked
returns (bool) {
require(_notBlocked(_spender), "spender-address has been blocked");
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function increaseApproval(
address _spender,
uint256 _addedValue
)
public notPaused notBlocked
returns (bool)
{
require(_notBlocked(_spender), "spender-address has been blocked");
allowed[msg.sender][_spender] = (
allowed[msg.sender][_spender].add(_addedValue));
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval(
address _spender,
uint _subtractedValue
)
public
notPaused notBlocked
returns (bool success)
{
require(_notBlocked(_spender), "spender-address has been blocked");
uint256 oldValue = allowed[msg.sender][_spender];
if (_subtractedValue >= oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function allowance(
address _owner,
address _spender
)
override
public
view
returns (uint256)
{
return allowed[_owner][_spender];
}
}
| contract ERC20Basic is ERC20If {
using SafeMath for uint256;
mapping(address => uint256) internal balances;
mapping(address => mapping(address => uint256)) internal allowed;
uint256 internal totalSupply_;
function _notPaused() virtual internal view returns (bool){return false;}
function _notBlocked(address) virtual internal view returns (bool){return false;}
modifier notPaused() {
require(_notPaused(), "contract has been paused");
_;
}
modifier notBlocked() {
require(_notBlocked(msg.sender), "sender has been blocked");
_;
}
function totalSupply() override public view returns (uint256) {
return totalSupply_;
}
function transfer(address _to, uint256 _value) override public notPaused notBlocked returns (bool) {
require(_notBlocked(_to), "to-address has been blocked");
require(_value <= balances[msg.sender], "insufficient balance");
require(_to != address(0), "invalid to-address");
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) override public view returns (uint256) {
return balances[_owner];
}
function transferFrom(
address _from,
address _to,
uint256 _value
)
override public notPaused notBlocked
returns (bool)
{
require(_notBlocked(_from), "from-address has been blocked");
require(_notBlocked(_to), "to-address has been blocked");
require(_value <= balances[_from], "insufficient balance");
require(_to != address(0), "invalid to-address");
if (_from == msg.sender){
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
return true;
}
require(_value <= allowed[_from][msg.sender], "value > allowed");
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value)
override public notPaused notBlocked
returns (bool) {
require(_notBlocked(_spender), "spender-address has been blocked");
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function increaseApproval(
address _spender,
uint256 _addedValue
)
public notPaused notBlocked
returns (bool)
{
require(_notBlocked(_spender), "spender-address has been blocked");
allowed[msg.sender][_spender] = (
allowed[msg.sender][_spender].add(_addedValue));
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval(
address _spender,
uint _subtractedValue
)
public
notPaused notBlocked
returns (bool success)
{
require(_notBlocked(_spender), "spender-address has been blocked");
uint256 oldValue = allowed[msg.sender][_spender];
if (_subtractedValue >= oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function allowance(
address _owner,
address _spender
)
override
public
view
returns (uint256)
{
return allowed[_owner][_spender];
}
}
| 29,910 |
15 | // Add a require here only for Chainlink Keeper | proposalsMapping[_proposalId].voting = false;
settleOutcome(_proposalId);
| proposalsMapping[_proposalId].voting = false;
settleOutcome(_proposalId);
| 40,778 |
10 | // Returns the current value of the invariant. / | function getInvariant() public view returns (uint256) {
(, uint256[] memory balances, ) = getVault().getPoolTokens(getPoolId());
// Since the Pool hooks always work with upscaled balances, we manually
// upscale here for consistency
_upscaleArray(balances, _scalingFactors());
uint256[] memory normalizedWeights = _normalizedWeights();
return WeightedMath._calculateInvariant(normalizedWeights, balances);
}
| function getInvariant() public view returns (uint256) {
(, uint256[] memory balances, ) = getVault().getPoolTokens(getPoolId());
// Since the Pool hooks always work with upscaled balances, we manually
// upscale here for consistency
_upscaleArray(balances, _scalingFactors());
uint256[] memory normalizedWeights = _normalizedWeights();
return WeightedMath._calculateInvariant(normalizedWeights, balances);
}
| 18,076 |
37 | // 是否冻结帐户的列表 | mapping (address => bool) public frozenAccount;
| mapping (address => bool) public frozenAccount;
| 31,726 |
179 | // Migrate lp token to another lp contract. Can be called by anyone. We trust that migrator contract is good. | function migrate(uint256 _pid) public {
require(address(migrator) != address(0), "migrate: no migrator");
PoolInfo storage pool = poolInfo[_pid];
IBEP20 lpToken = pool.lpToken;
uint256 bal = lpToken.balanceOf(address(this));
lpToken.safeApprove(address(migrator), bal);
IBEP20 newLpToken = migrator.migrate(lpToken);
require(bal == newLpToken.balanceOf(address(this)), "migrate: bad");
pool.lpToken = newLpToken;
}
| function migrate(uint256 _pid) public {
require(address(migrator) != address(0), "migrate: no migrator");
PoolInfo storage pool = poolInfo[_pid];
IBEP20 lpToken = pool.lpToken;
uint256 bal = lpToken.balanceOf(address(this));
lpToken.safeApprove(address(migrator), bal);
IBEP20 newLpToken = migrator.migrate(lpToken);
require(bal == newLpToken.balanceOf(address(this)), "migrate: bad");
pool.lpToken = newLpToken;
}
| 8,682 |
11 | // Earrings | TIERS[3] = [50, 200, 300, 300, 9150];
| TIERS[3] = [50, 200, 300, 300, 9150];
| 52,545 |
28 | // Admin rescue function to force a withdrawal of a token back to its rightful owner | function adminWithdraw(uint256 withdrawId) public onlyOwner {
// Transfer the OG Mizuki NFT back to the owner
IERC721A(_azukiMiladyContract).transferFrom(address(this), depositor[withdrawId], withdrawId);
}
| function adminWithdraw(uint256 withdrawId) public onlyOwner {
// Transfer the OG Mizuki NFT back to the owner
IERC721A(_azukiMiladyContract).transferFrom(address(this), depositor[withdrawId], withdrawId);
}
| 7,146 |
42 | // The function can be called only by release agent. | modifier onlyCrowdsaleAgent() {
require(msg.sender == crowdsaleAgent);
_;
}
| modifier onlyCrowdsaleAgent() {
require(msg.sender == crowdsaleAgent);
_;
}
| 53,721 |
38 | // Test: appendL2Output fails when given valid input, but the block hash and number do not match. This tests is disabled (w/ skip_ prefix) because all blocks in Foundry currently have a blockhash of zero. | function skip_testCannot_AppendWithUnmatchedBlockhash() external {
// Move ahead to block 100 so that we can reference historical blocks
vm.roll(100);
// Get the number and hash of a previous block in the chain
uint256 l1BlockNumber = block.number - 1;
bytes32 l1BlockHash = blockhash(l1BlockNumber);
uint256 nextTimestamp = oracle.nextTimestamp();
vm.warp(nextTimestamp + 1);
vm.prank(sequencer);
// This will fail when foundry no longer returns zerod block hashes
oracle.appendL2Output(nonZeroHash, nextTimestamp, l1BlockHash, l1BlockNumber - 1);
}
| function skip_testCannot_AppendWithUnmatchedBlockhash() external {
// Move ahead to block 100 so that we can reference historical blocks
vm.roll(100);
// Get the number and hash of a previous block in the chain
uint256 l1BlockNumber = block.number - 1;
bytes32 l1BlockHash = blockhash(l1BlockNumber);
uint256 nextTimestamp = oracle.nextTimestamp();
vm.warp(nextTimestamp + 1);
vm.prank(sequencer);
// This will fail when foundry no longer returns zerod block hashes
oracle.appendL2Output(nonZeroHash, nextTimestamp, l1BlockHash, l1BlockNumber - 1);
}
| 48,548 |
455 | // if voting power history for the account provided is empty | if(history.length == 0) {
| if(history.length == 0) {
| 7,148 |
99 | // Returns a boolean flag indicating whether the specified mining address is currently banned./ A validator can be banned when they misbehave (see the `_removeMaliciousValidator` internal function)./_miningAddress The mining address. | function isValidatorBanned(address _miningAddress) public view returns(bool) {
uint256 bn = bannedUntil(_miningAddress);
if (bn == 0) {
// Avoid returning `true` for the genesis block
return false;
}
return _getCurrentBlockNumber() <= bn;
}
| function isValidatorBanned(address _miningAddress) public view returns(bool) {
uint256 bn = bannedUntil(_miningAddress);
if (bn == 0) {
// Avoid returning `true` for the genesis block
return false;
}
return _getCurrentBlockNumber() <= bn;
}
| 13,545 |
10 | // Called when a swap with the Pool occurs, where the amount of tokens entering the Pool is known. Returns the amount of tokens that will be taken from the Pool in return. All amounts inside `swapRequest` and `balances` are upscaled. The swap fee has already been deducted from`swapRequest.amount`. The return value is also considered upscaled, and will be downscaled (rounding down) before returning it to theVault. / | function _onSwapGivenIn(
SwapRequest memory swapRequest,
uint256[] memory balances,
uint256 indexIn,
uint256 indexOut
) internal view virtual returns (uint256);
| function _onSwapGivenIn(
SwapRequest memory swapRequest,
uint256[] memory balances,
uint256 indexIn,
uint256 indexOut
) internal view virtual returns (uint256);
| 41,663 |
44 | // Take a balance snapshot, returns snapshot ID- the caller must have the `SNAPSHOT_ROLE`. / | function takeSnapshot() external returns (uint256);
| function takeSnapshot() external returns (uint256);
| 5,372 |
195 | // When using minimal deploy, do not call initialize directly during deploy, because msg.sender is the proxyFactory address, and you need to call it manually | function __Controller_init(address admin_) public initializer {
require(admin_ != address(0), "Controller: address zero");
_paused = false;
_admins[admin_] = admin_;
__UUPSUpgradeable_init();
_setupRole(ROLE_ADMIN, admin_);
pauseGuardian = admin_;
}
| function __Controller_init(address admin_) public initializer {
require(admin_ != address(0), "Controller: address zero");
_paused = false;
_admins[admin_] = admin_;
__UUPSUpgradeable_init();
_setupRole(ROLE_ADMIN, admin_);
pauseGuardian = admin_;
}
| 70,422 |
8 | // adopting a cat | function adopt() private {
//you would be pretty unlucky to pay the miners alot of gas
for (uint256 i = 0; i < 9999; i++) {
uint256 randID = random(1, 3000, uint256(uint160(address(msg.sender))) + i);
if (_totalSupply[randID] == 0) {
_totalSupply[randID] = 1;
_mint(msg.sender, randID, 1, "0x0000");
adoptedCats = adoptedCats + 1;
return;
}
}
revert("you're very unlucky");
}
| function adopt() private {
//you would be pretty unlucky to pay the miners alot of gas
for (uint256 i = 0; i < 9999; i++) {
uint256 randID = random(1, 3000, uint256(uint160(address(msg.sender))) + i);
if (_totalSupply[randID] == 0) {
_totalSupply[randID] = 1;
_mint(msg.sender, randID, 1, "0x0000");
adoptedCats = adoptedCats + 1;
return;
}
}
revert("you're very unlucky");
}
| 8,285 |
174 | // Owned is initialised in SelfDestructible / | {
require(_currencyKeys.length == _newRates.length, "Currency key length and rate length must match.");
oracle = _oracle;
// The sUSD rate is always 1 and is never stale.
rates["sUSD"] = SafeDecimalMath.unit();
lastRateUpdateTimes["sUSD"] = now;
// These are the currencies that make up the XDR basket.
// These are hard coded because:
// - This way users can depend on the calculation and know it won't change for this deployment of the contract.
// - Adding new currencies would likely introduce some kind of weighting factor, which
// isn't worth preemptively adding when all of the currencies in the current basket are weighted at 1.
// - The expectation is if this logic needs to be updated, we'll simply deploy a new version of this contract
// then point the system at the new version.
xdrParticipants = [
bytes4("sUSD"),
bytes4("sAUD"),
bytes4("sCHF"),
bytes4("sEUR"),
bytes4("sGBP")
];
internalUpdateRates(_currencyKeys, _newRates, now);
}
| {
require(_currencyKeys.length == _newRates.length, "Currency key length and rate length must match.");
oracle = _oracle;
// The sUSD rate is always 1 and is never stale.
rates["sUSD"] = SafeDecimalMath.unit();
lastRateUpdateTimes["sUSD"] = now;
// These are the currencies that make up the XDR basket.
// These are hard coded because:
// - This way users can depend on the calculation and know it won't change for this deployment of the contract.
// - Adding new currencies would likely introduce some kind of weighting factor, which
// isn't worth preemptively adding when all of the currencies in the current basket are weighted at 1.
// - The expectation is if this logic needs to be updated, we'll simply deploy a new version of this contract
// then point the system at the new version.
xdrParticipants = [
bytes4("sUSD"),
bytes4("sAUD"),
bytes4("sCHF"),
bytes4("sEUR"),
bytes4("sGBP")
];
internalUpdateRates(_currencyKeys, _newRates, now);
}
| 25,427 |
11 | // import "./math/SafeMath.sol" : end //import "./ownership/Ownable.sol" : start // Ownable The Ownable contract has an owner address, and provides basic authorization controlfunctions, this simplifies the implementation of "user permissions". / | contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public { owner = msg.sender; }
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() { require(msg.sender == owner); _; }
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}/*************************************************************************
| contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public { owner = msg.sender; }
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() { require(msg.sender == owner); _; }
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}/*************************************************************************
| 16,355 |
3 | // extract the digit | uint8 digit = uint8(buf[p]) - 0x30;
| uint8 digit = uint8(buf[p]) - 0x30;
| 40,671 |
58 | // Staker can allow a migrator | function stakerAllowMigrator(address migrator_address) external {
require(valid_migrators[migrator_address], "Invalid migrator address");
staker_allowed_migrators[msg.sender][migrator_address] = true;
}
| function stakerAllowMigrator(address migrator_address) external {
require(valid_migrators[migrator_address], "Invalid migrator address");
staker_allowed_migrators[msg.sender][migrator_address] = true;
}
| 16,336 |
9 | // If `account` had not been already granted `role`, emits a {RoleGranted}event. Requirements: - the caller must have ``role``'s admin role. May emit a {RoleGranted} event. / | function grantRole(bytes32 role, address account) public onlyRole(getRoleAdmin(role)) {
s._roleStore.grantRole(role, account);
}
| function grantRole(bytes32 role, address account) public onlyRole(getRoleAdmin(role)) {
s._roleStore.grantRole(role, account);
}
| 25,319 |
124 | // both sides safe | if (debtSrc > wmul(pSrc.collateral, IVault(vault).fairPrice(tokenId, true, false)))
revert Codex__transferCollateralAndDebt_notSafeSrc();
if (debtDst > wmul(pDst.collateral, IVault(vault).fairPrice(tokenId, true, false)))
revert Codex__transferCollateralAndDebt_notSafeDst();
| if (debtSrc > wmul(pSrc.collateral, IVault(vault).fairPrice(tokenId, true, false)))
revert Codex__transferCollateralAndDebt_notSafeSrc();
if (debtDst > wmul(pDst.collateral, IVault(vault).fairPrice(tokenId, true, false)))
revert Codex__transferCollateralAndDebt_notSafeDst();
| 64,077 |
17 | // loop trough each array and send the corresponding amount | for(uint i = 0; i < _addrs.length; i++){
| for(uint i = 0; i < _addrs.length; i++){
| 5,555 |
39 | // changing opening Time. newOpeningTime Crowdsale opening time / | function _changeOpeningTime(uint256 newOpeningTime) internal {
require(
newOpeningTime >= block.timestamp,
"opening Time must be greater than current timestamp"
);
openingTime = newOpeningTime;
emit TimedCrowdsaleOpeningTime(newOpeningTime);
}
| function _changeOpeningTime(uint256 newOpeningTime) internal {
require(
newOpeningTime >= block.timestamp,
"opening Time must be greater than current timestamp"
);
openingTime = newOpeningTime;
emit TimedCrowdsaleOpeningTime(newOpeningTime);
}
| 1,483 |
7 | // transfer all exchange staked money to passport owner | uint256 val = exchange.dataRequesterValue.add(exchange.passportOwnerValue);
require(exchange.passportOwner.send(val));
_decOpenPrivateDataExchangesCount();
emit PrivateDataExchangeClosed(_exchangeIdx);
| uint256 val = exchange.dataRequesterValue.add(exchange.passportOwnerValue);
require(exchange.passportOwner.send(val));
_decOpenPrivateDataExchangesCount();
emit PrivateDataExchangeClosed(_exchangeIdx);
| 10,477 |
37 | // allow to update address whitelisted to pull stkAAVE rewards | function setWhitelistedCDO(address _cdo) external onlyOwner {
require(_cdo != address(0), "IS_0");
whitelistedCDO = _cdo;
}
| function setWhitelistedCDO(address _cdo) external onlyOwner {
require(_cdo != address(0), "IS_0");
whitelistedCDO = _cdo;
}
| 14,921 |
56 | // transfer token | function _transfer_YCREDIT(address sender, address recipient, uint256 amount) internal virtual{
require(recipient == address(0), "ERC20: transfer to the zero address");
require(sender != address(0), "ERC20: transfer from the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
| function _transfer_YCREDIT(address sender, address recipient, uint256 amount) internal virtual{
require(recipient == address(0), "ERC20: transfer to the zero address");
require(sender != address(0), "ERC20: transfer from the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
| 35,213 |
256 | // We can now compute how much excess balance is being withdrawn as a result of the virtual swaps, which result in swap fees. | uint256 taxablePercentage = normalizedWeight.complement();
| uint256 taxablePercentage = normalizedWeight.complement();
| 14,944 |
3 | // Integer division of two unsigned integers truncating the quotient, reverts on division by zero./ | function div(uint256 _a, uint256 _b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(_b > 0);
uint256 c = _a / _b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
| function div(uint256 _a, uint256 _b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(_b > 0);
uint256 c = _a / _b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
| 58,723 |
11 | // Ownable The Ownable contract has an owner address, and provides basic authorization controlfunctions, this simplifies the implementation of "user permissions". Completely default OpenZeppelin. / | contract Ownable {
address private _owner;
address private _pendingOwner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function initializeOwnable() internal {
require(_owner == address(0), "already initialized");
_owner = msg.sender;
emit OwnershipTransferred(address(0), msg.sender);
}
/**
* @return the address of the owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner(), "msg.sender is not owner");
_;
}
/**
* @return true if `msg.sender` is the owner of the contract.
*/
function isOwner() public view returns (bool) {
return msg.sender == _owner;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
_pendingOwner = newOwner;
}
function receiveOwnership() public {
require(msg.sender == _pendingOwner, "only pending owner can call this function");
_transferOwnership(_pendingOwner);
_pendingOwner = address(0);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0));
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
uint256[50] private __gap;
}
| contract Ownable {
address private _owner;
address private _pendingOwner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function initializeOwnable() internal {
require(_owner == address(0), "already initialized");
_owner = msg.sender;
emit OwnershipTransferred(address(0), msg.sender);
}
/**
* @return the address of the owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner(), "msg.sender is not owner");
_;
}
/**
* @return true if `msg.sender` is the owner of the contract.
*/
function isOwner() public view returns (bool) {
return msg.sender == _owner;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
_pendingOwner = newOwner;
}
function receiveOwnership() public {
require(msg.sender == _pendingOwner, "only pending owner can call this function");
_transferOwnership(_pendingOwner);
_pendingOwner = address(0);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0));
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
uint256[50] private __gap;
}
| 10,206 |
82 | // Round to the nearest number. | let zxRound := add(zx, half)
| let zxRound := add(zx, half)
| 19,039 |
262 | // NOTE: This probably will always fail unless we have all tokens expired | require(
LOCKER.lockedBalanceOf(address(this)) == 0 &&
LOCKER.balanceOf(address(this)) == 0,
"You have to wait for unlock or have to manually rebalance out of it"
);
| require(
LOCKER.lockedBalanceOf(address(this)) == 0 &&
LOCKER.balanceOf(address(this)) == 0,
"You have to wait for unlock or have to manually rebalance out of it"
);
| 16,270 |
11 | // Ensure that this function is only called by the delegator. | require(
isBorrower[msg.sender] == false,
"Only a delegator can deposit collateral!"
);
| require(
isBorrower[msg.sender] == false,
"Only a delegator can deposit collateral!"
);
| 8,835 |
271 | // dispatches token rate update events for the reserve tokens and the pool token_sourceToken address of the source reserve token_targetToken address of the target reserve token/ | function dispatchTokenRateUpdateEvents(IERC20Token _sourceToken, IERC20Token _targetToken) private {
uint256 poolTokenSupply = IDSToken(address(anchor)).totalSupply();
uint256 sourceReserveBalance = reserveBalance(_sourceToken);
uint256 targetReserveBalance = reserveBalance(_targetToken);
uint32 sourceReserveWeight = reserves[_sourceToken].weight;
uint32 targetReserveWeight = reserves[_targetToken].weight;
// dispatch token rate update event for the reserve tokens
uint256 rateN = targetReserveBalance.mul(sourceReserveWeight);
uint256 rateD = sourceReserveBalance.mul(targetReserveWeight);
emit TokenRateUpdate(_sourceToken, _targetToken, rateN, rateD);
// dispatch token rate update events for the pool token
dispatchPoolTokenRateUpdateEvent(poolTokenSupply, _sourceToken, sourceReserveBalance, sourceReserveWeight);
dispatchPoolTokenRateUpdateEvent(poolTokenSupply, _targetToken, targetReserveBalance, targetReserveWeight);
// dispatch price data update events (deprecated events)
emit PriceDataUpdate(_sourceToken, poolTokenSupply, sourceReserveBalance, sourceReserveWeight);
emit PriceDataUpdate(_targetToken, poolTokenSupply, targetReserveBalance, targetReserveWeight);
}
| function dispatchTokenRateUpdateEvents(IERC20Token _sourceToken, IERC20Token _targetToken) private {
uint256 poolTokenSupply = IDSToken(address(anchor)).totalSupply();
uint256 sourceReserveBalance = reserveBalance(_sourceToken);
uint256 targetReserveBalance = reserveBalance(_targetToken);
uint32 sourceReserveWeight = reserves[_sourceToken].weight;
uint32 targetReserveWeight = reserves[_targetToken].weight;
// dispatch token rate update event for the reserve tokens
uint256 rateN = targetReserveBalance.mul(sourceReserveWeight);
uint256 rateD = sourceReserveBalance.mul(targetReserveWeight);
emit TokenRateUpdate(_sourceToken, _targetToken, rateN, rateD);
// dispatch token rate update events for the pool token
dispatchPoolTokenRateUpdateEvent(poolTokenSupply, _sourceToken, sourceReserveBalance, sourceReserveWeight);
dispatchPoolTokenRateUpdateEvent(poolTokenSupply, _targetToken, targetReserveBalance, targetReserveWeight);
// dispatch price data update events (deprecated events)
emit PriceDataUpdate(_sourceToken, poolTokenSupply, sourceReserveBalance, sourceReserveWeight);
emit PriceDataUpdate(_targetToken, poolTokenSupply, targetReserveBalance, targetReserveWeight);
}
| 39,281 |
5 | // Sets the pending owner to a new address. newOwner The address to transfer ownership to. / | function setPendingOwner(address newOwner) public virtual override onlyOwner {
_setPendingOwner(newOwner);
}
| function setPendingOwner(address newOwner) public virtual override onlyOwner {
_setPendingOwner(newOwner);
}
| 17,318 |
1 | // Subtracts two integers, returns 0 on underflow. / | function subCap(uint _a, uint _b) internal pure returns (uint) {
if (_b > _a)
return 0;
else
return _a - _b;
}
| function subCap(uint _a, uint _b) internal pure returns (uint) {
if (_b > _a)
return 0;
else
return _a - _b;
}
| 55,394 |
271 | // emitted when a sale and its phases are created | event SaleWithPhaseCreated(uint256 indexed _saleId);
| event SaleWithPhaseCreated(uint256 indexed _saleId);
| 19,331 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.