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 |
|---|---|---|---|---|
127 | // Updates balance of winner with entire game pot | balances[_winner] += _pot;
| balances[_winner] += _pot;
| 36,149 |
41 | // Set the symbol for display purposes | symbol = "BIANG";
| symbol = "BIANG";
| 58,231 |
231 | // Checks whether _spender is approved to spend tokens on _owners behalf or owner itself/_spender address Address of spender/_owner address Address of owner/_tokenId address tokenId of interest/ return Returns whether _spender is approved to spend tokens | function isApprovedOrOwner(
address _spender,
address _owner,
uint256 _tokenId
| function isApprovedOrOwner(
address _spender,
address _owner,
uint256 _tokenId
| 29,840 |
171 | // No need to challenge again if a handle is already being challenged. | require(
challengeExpiryOf[_handle] == 0,
"Projects::challenge: HANDLE_ALREADY_BEING_CHALLENGED"
);
| require(
challengeExpiryOf[_handle] == 0,
"Projects::challenge: HANDLE_ALREADY_BEING_CHALLENGED"
);
| 74,599 |
10 | // update state | weiRaised = weiRaised.add(weiAmount);
_processPurchase(_beneficiary, tokens);
emit TokenPurchase(
msg.sender,
_beneficiary,
weiAmount,
tokens
);
| weiRaised = weiRaised.add(weiAmount);
_processPurchase(_beneficiary, tokens);
emit TokenPurchase(
msg.sender,
_beneficiary,
weiAmount,
tokens
);
| 4,167 |
20 | // DAO treasury address | address public treasury;
| address public treasury;
| 17,691 |
38 | // No.of Staking Blocks | uint256 public noOfStakingBlocks;
| uint256 public noOfStakingBlocks;
| 41,805 |
1 | // if `xy < 2 ^ 256` | if (xyhi == 0) {
return xylo / z;
}
| if (xyhi == 0) {
return xylo / z;
}
| 13,906 |
14 | // Copy remaining bytes | uint mask = 256 ** (32 - len) - 1;
assembly {
let srcpart := and(mload(src), not(mask))
let destpart := and(mload(dest), mask)
mstore(dest, or(destpart, srcpart))
}
| uint mask = 256 ** (32 - len) - 1;
assembly {
let srcpart := and(mload(src), not(mask))
let destpart := and(mload(dest), mask)
mstore(dest, or(destpart, srcpart))
}
| 11,604 |
0 | // Maximum percentage factor (100.00%) | uint256 internal constant PERCENTAGE_FACTOR = 1e4;
| uint256 internal constant PERCENTAGE_FACTOR = 1e4;
| 8,594 |
89 | // approve fractionalized NFT Factory to withdraw NFT | nftContract.approve(address(tokenVaultFactory), tokenId);
| nftContract.approve(address(tokenVaultFactory), tokenId);
| 38,305 |
26 | // 3x1 ^ 2 | let t5 := addmod(add(t3, t3), t3, N)
| let t5 := addmod(add(t3, t3), t3, N)
| 18,563 |
11 | // Contract "ERC20Basic"Purpose: Defining ERC20 standard with basic functionality like - CheckBalance and Transfer including Transfer event / | contract ERC20Basic {
//Give realtime totalSupply of IAC token
uint256 public totalSupply;
//Get IAC token balance for provided address
function balanceOf(address who) view public returns (uint256);
//Transfer IAC token to provided address
function transfer(address _to, uint256 _value) public returns(bool ok);
//Emit Transfer event outside of blockchain for every IAC token transfer
event Transfer(address indexed _from, address indexed _to, uint256 _value);
}
| contract ERC20Basic {
//Give realtime totalSupply of IAC token
uint256 public totalSupply;
//Get IAC token balance for provided address
function balanceOf(address who) view public returns (uint256);
//Transfer IAC token to provided address
function transfer(address _to, uint256 _value) public returns(bool ok);
//Emit Transfer event outside of blockchain for every IAC token transfer
event Transfer(address indexed _from, address indexed _to, uint256 _value);
}
| 42,483 |
34 | // 1501016 means 1.51018 |
rounds.push(Round(
150 * 10**(16 + usdtDecimals - misDecimals),
1619161200, // start
72 * 3600,
20000 * 10**usdtDecimals,
50000 * 10**usdtDecimals,
270000 * 10**usdtDecimals // token supply in usdt
));
rounds.push(Round(
|
rounds.push(Round(
150 * 10**(16 + usdtDecimals - misDecimals),
1619161200, // start
72 * 3600,
20000 * 10**usdtDecimals,
50000 * 10**usdtDecimals,
270000 * 10**usdtDecimals // token supply in usdt
));
rounds.push(Round(
| 29,736 |
16 | // Unpauses all allocation claims (token payouts). | * See {Pausable-_unpause}.
*
* Requirements:
* - the caller must have the `PAUSER_ROLE`.
*/
function unpause() public {
require(hasRole(PAUSER_ROLE, _msgSender()), "Must have pauser role to unpause");
_unpause();
}
| * See {Pausable-_unpause}.
*
* Requirements:
* - the caller must have the `PAUSER_ROLE`.
*/
function unpause() public {
require(hasRole(PAUSER_ROLE, _msgSender()), "Must have pauser role to unpause");
_unpause();
}
| 32,905 |
15 | // function EIP712_EXCHANGE_DOMAIN_NAME() | bytes4 constant internal EIP_712_EXCHANGE_DOMAIN_NAME_SELECTOR = 0x63c4e8cc;
| bytes4 constant internal EIP_712_EXCHANGE_DOMAIN_NAME_SELECTOR = 0x63c4e8cc;
| 34,227 |
3 | // address usdtAddress = 0xA4001E78DBF93b929D1d558901c14D8154F31542; usdtInterface usdtContract = usdtInterface(usdtAddress); |
IERC20 usdtContract;
|
IERC20 usdtContract;
| 30,454 |
3 | // Gets all facet addresses and their four byte function selectors./ return facets_ Facet | function facets() external view returns (Facet[] memory facets_);
| function facets() external view returns (Facet[] memory facets_);
| 8,404 |
3 | // Release principal | msg.sender.transfer(futureRelease.amount);
| msg.sender.transfer(futureRelease.amount);
| 14,672 |
7 | // low level token purchase DO NOT OVERRIDE / | function buyTokens() public payable {
uint256 weiAmount = msg.value;
_preValidatePurchase(weiAmount);
uint256 tokens = _getTokenAmount(weiAmount);
_deliverTokens(tokens);
emit TokenPurchase(msg.sender, weiAmount, tokens);
_forwardFunds();
}
| function buyTokens() public payable {
uint256 weiAmount = msg.value;
_preValidatePurchase(weiAmount);
uint256 tokens = _getTokenAmount(weiAmount);
_deliverTokens(tokens);
emit TokenPurchase(msg.sender, weiAmount, tokens);
_forwardFunds();
}
| 14,383 |
17 | // seeds that are used to associate unique traits to each degen. all seeds are unique across combinations of degen id + rarity + generation. we use bitmaps for efficient storage and lookup. | library Seeds {
using Bitmaps for Bitmaps.Bitmap;
// stores unique seeds for each degen.
struct UniqueSeeds {
// mapping of unique seed to whether or not it's in use.
// mapping is
// generation
// \_ Rarity
// \_ inUseSeeds
mapping(uint256 => mapping(Rarity => Bitmaps.Bitmap)) inUseSeeds;
// so we can retrieve the seed for the degen
mapping(uint256 => uint256) degenSeeds;
}
// add a generation of seeds to storage
// owner is allowed to add new generations by adjusting the mint rules.
function addGeneration(
UniqueSeeds storage _seeds,
uint256 _generation,
MintRules calldata _mintRules
) internal {
// allocate a new set of seeds (bitmask) for the generation
_seeds.inUseSeeds[_generation][Rarity.COMMON] = Bitmaps.makeBitmap(_mintRules.common.maxSupply);
_seeds.inUseSeeds[_generation][Rarity.RARE] = Bitmaps.makeBitmap(_mintRules.rare.maxSupply);
_seeds.inUseSeeds[_generation][Rarity.MYTHIC] = Bitmaps.makeBitmap(_mintRules.mythic.maxSupply);
}
// get a random unused seed for within a generation
// WARNING: this function may incur a high gas cost that scales with _maxSupply.
function getUniqueSeed(
UniqueSeeds storage _seeds,
uint256 _generation,
Rarity _rarity,
uint256 _maxSupply
) internal view returns (uint256) {
// choose a random index and start counting in our bitmap
uint256 _startIndex = randInt(0, _maxSupply);
for (uint256 i = _startIndex; i < _maxSupply; i++) {
if (seedInUse(_seeds, i, _generation, _rarity)) {
continue;
}
// stop on the first random seed after our start index
return i;
}
// start from the beginning of the loop and continue until the start index
for (uint256 i = 0; i < _startIndex; i++) {
if (seedInUse(_seeds, i, _generation, _rarity)) {
continue;
}
// return the first available seed
return i;
}
// no available seeds
revert('No available seeds for this generation.');
}
function seedInUse(
UniqueSeeds storage _seeds,
uint256 _seed,
uint256 _generation,
Rarity _rarity
) internal view returns (bool) {
return _seeds.inUseSeeds[_generation][_rarity].get(_seed);
}
function updateDegenSeed(
UniqueSeeds storage _seeds,
uint256 _degen,
uint256 _generation,
Rarity _rarity,
uint256 _seed
) internal {
uint256 _originalSeed = _seeds.degenSeeds[_degen];
_seeds.inUseSeeds[_generation][_rarity].set(_originalSeed, false);
_seeds.inUseSeeds[_generation][_rarity].set(_seed, true);
_seeds.degenSeeds[_degen] = _seed;
}
function randInt(uint256 _min, uint256 _max) internal view returns (uint256) {
require(_min < _max, 'min must be less than max');
return
_min +
(uint256(
keccak256(abi.encodePacked(_min, _max, block.timestamp, block.number, block.difficulty, msg.sender))
) % (_max - _min));
}
}
| library Seeds {
using Bitmaps for Bitmaps.Bitmap;
// stores unique seeds for each degen.
struct UniqueSeeds {
// mapping of unique seed to whether or not it's in use.
// mapping is
// generation
// \_ Rarity
// \_ inUseSeeds
mapping(uint256 => mapping(Rarity => Bitmaps.Bitmap)) inUseSeeds;
// so we can retrieve the seed for the degen
mapping(uint256 => uint256) degenSeeds;
}
// add a generation of seeds to storage
// owner is allowed to add new generations by adjusting the mint rules.
function addGeneration(
UniqueSeeds storage _seeds,
uint256 _generation,
MintRules calldata _mintRules
) internal {
// allocate a new set of seeds (bitmask) for the generation
_seeds.inUseSeeds[_generation][Rarity.COMMON] = Bitmaps.makeBitmap(_mintRules.common.maxSupply);
_seeds.inUseSeeds[_generation][Rarity.RARE] = Bitmaps.makeBitmap(_mintRules.rare.maxSupply);
_seeds.inUseSeeds[_generation][Rarity.MYTHIC] = Bitmaps.makeBitmap(_mintRules.mythic.maxSupply);
}
// get a random unused seed for within a generation
// WARNING: this function may incur a high gas cost that scales with _maxSupply.
function getUniqueSeed(
UniqueSeeds storage _seeds,
uint256 _generation,
Rarity _rarity,
uint256 _maxSupply
) internal view returns (uint256) {
// choose a random index and start counting in our bitmap
uint256 _startIndex = randInt(0, _maxSupply);
for (uint256 i = _startIndex; i < _maxSupply; i++) {
if (seedInUse(_seeds, i, _generation, _rarity)) {
continue;
}
// stop on the first random seed after our start index
return i;
}
// start from the beginning of the loop and continue until the start index
for (uint256 i = 0; i < _startIndex; i++) {
if (seedInUse(_seeds, i, _generation, _rarity)) {
continue;
}
// return the first available seed
return i;
}
// no available seeds
revert('No available seeds for this generation.');
}
function seedInUse(
UniqueSeeds storage _seeds,
uint256 _seed,
uint256 _generation,
Rarity _rarity
) internal view returns (bool) {
return _seeds.inUseSeeds[_generation][_rarity].get(_seed);
}
function updateDegenSeed(
UniqueSeeds storage _seeds,
uint256 _degen,
uint256 _generation,
Rarity _rarity,
uint256 _seed
) internal {
uint256 _originalSeed = _seeds.degenSeeds[_degen];
_seeds.inUseSeeds[_generation][_rarity].set(_originalSeed, false);
_seeds.inUseSeeds[_generation][_rarity].set(_seed, true);
_seeds.degenSeeds[_degen] = _seed;
}
function randInt(uint256 _min, uint256 _max) internal view returns (uint256) {
require(_min < _max, 'min must be less than max');
return
_min +
(uint256(
keccak256(abi.encodePacked(_min, _max, block.timestamp, block.number, block.difficulty, msg.sender))
) % (_max - _min));
}
}
| 49,256 |
36 | // Underlying asset for the strategyreturn address Underlying asset address / | function underlying() external view returns (address);
| function underlying() external view returns (address);
| 51,330 |
21 | // Updates the treasury's fee variables, as detailed in speedBump[1]param: speedBump[1].uint16s[0] - the fee the mapp has to pay for any dispute raised, chargeable per gatewayparam: speedBump[1].uint16s[1] - the commission divider charged for every mapp to gateway transaction. param: speedBump[1].uint16s[2] - the penalty multiplier for the treasury hasto pay if it has be found in breach of one of its verification rules.param: speedBump[1].uint16s[3] - the penalty multiplier a gateway has to pay if it has be found in breach of one of its verification rules./ | function updateTreasuryFeeVariables() external onlyOperator() {
uint8 sb = 1;
uint256 sBTimeCreated = speedBumpTimeCreated(sb);
require(sBTimeCreated > 0, "Time created must be >0 (to stop replays of the speed bump)");
require(now > sBTimeCreated + (speedBumpCurrentSBHours(sb)*1 hours), "The speed bump time period must have passed");
// make the key state changes
mappDisputeFeeMultipler(speedBumpUint16s(sb, 0));
commissionDivider(speedBumpUint16s(sb, 1));
treasuryPenaltyMultipler(speedBumpUint16s(sb, 2));
gatewayPenaltyMultipler(speedBumpUint16s(sb, 3));
// wipe the speed bump
speedBumpUint16s(sb, 0, 0);
speedBumpUint16s(sb, 1, 0);
speedBumpUint16s(sb, 2, 0);
speedBumpUint16s(sb, 3, 0);
speedBumpTimeCreated(sb,0);
speedBumpCurrentSBHours(sb,0);
//emit event
emit updatedTreasuryVariables(mappDisputeFeeMultipler(),commissionDivider(),gatewayPenaltyMultipler(),treasuryPenaltyMultipler());
}
| function updateTreasuryFeeVariables() external onlyOperator() {
uint8 sb = 1;
uint256 sBTimeCreated = speedBumpTimeCreated(sb);
require(sBTimeCreated > 0, "Time created must be >0 (to stop replays of the speed bump)");
require(now > sBTimeCreated + (speedBumpCurrentSBHours(sb)*1 hours), "The speed bump time period must have passed");
// make the key state changes
mappDisputeFeeMultipler(speedBumpUint16s(sb, 0));
commissionDivider(speedBumpUint16s(sb, 1));
treasuryPenaltyMultipler(speedBumpUint16s(sb, 2));
gatewayPenaltyMultipler(speedBumpUint16s(sb, 3));
// wipe the speed bump
speedBumpUint16s(sb, 0, 0);
speedBumpUint16s(sb, 1, 0);
speedBumpUint16s(sb, 2, 0);
speedBumpUint16s(sb, 3, 0);
speedBumpTimeCreated(sb,0);
speedBumpCurrentSBHours(sb,0);
//emit event
emit updatedTreasuryVariables(mappDisputeFeeMultipler(),commissionDivider(),gatewayPenaltyMultipler(),treasuryPenaltyMultipler());
}
| 13,809 |
12 | // As per the EIP-165 spec, no interface should ever match 0xffffffff | bytes4 private constant _INTERFACE_ID_INVALID = 0xffffffff;
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
| bytes4 private constant _INTERFACE_ID_INVALID = 0xffffffff;
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
| 47,947 |
34 | // ERC721 START | event Transfer(address indexed _from, address indexed _to, uint indexed _tokenId);
event Approval(address indexed _owner, address indexed _approved, uint indexed _tokenId);
event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved);
bytes4 private constant InterfaceId_ERC721 = 0x80ac58cd;
| event Transfer(address indexed _from, address indexed _to, uint indexed _tokenId);
event Approval(address indexed _owner, address indexed _approved, uint indexed _tokenId);
event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved);
bytes4 private constant InterfaceId_ERC721 = 0x80ac58cd;
| 5,463 |
101 | // Returns the downcasted int64 from int256, reverting onoverflow (when the input is less than smallest int64 orgreater 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);
}
| 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);
}
| 8,344 |
7 | // ERC20 token address | address token;
| address token;
| 25,087 |
69 | // Calculate the average reward for the current periodstakingInfo the struct containing staking infototalReward the total reward in current periodexcludeLast whether or not exclude the last block return (uint256) number of blocks in history/ | function getCurrentPeriodAverageReward(
StakingInfo storage stakingInfo,
uint256 totalReward,
bool excludeLast
)
public
view
returns(uint256)
| function getCurrentPeriodAverageReward(
StakingInfo storage stakingInfo,
uint256 totalReward,
bool excludeLast
)
public
view
returns(uint256)
| 67,907 |
6 | // nonReentrant is a modifier to prevent reentry attack verify that msg.sender is the owner of tokenId | require(IERC721(nftContract).ownerOf(tokenId) == msg.sender, "You are not the owner");
require(price > 10, "Price must be greater than 10");
uint256 power = _erc721factory.quoOfId(tokenId).power;
uint256 level = _erc721factory.quoOfId(tokenId).lvl;
uint lastClaim = _erc721factory.quoOfId(tokenId).lastClaim;
_tokenIds.increment();
uint256 itemId = _tokenIds.current();
| require(IERC721(nftContract).ownerOf(tokenId) == msg.sender, "You are not the owner");
require(price > 10, "Price must be greater than 10");
uint256 power = _erc721factory.quoOfId(tokenId).power;
uint256 level = _erc721factory.quoOfId(tokenId).lvl;
uint lastClaim = _erc721factory.quoOfId(tokenId).lastClaim;
_tokenIds.increment();
uint256 itemId = _tokenIds.current();
| 53,738 |
30 | // Check loan asset | require(_loanAsset != address(0), "2");
| require(_loanAsset != address(0), "2");
| 40,415 |
447 | // Interface of the global ERC1820 Registry, as defined in theimplementers for interfaces in this registry, as well as query support. Implementers may be shared by multiple accounts, and can also implement morethan a single interface for each account. Contracts can implement interfacesfor themselves, but externally-owned accounts (EOA) must delegate this to acontract. | * {IERC165} interfaces can also be queried via the registry.
*
* For an in-depth explanation and source code analysis, see the EIP text.
*/
interface IERC1820Registry {
/**
* @dev Sets `newManager` as the manager for `account`. A manager of an
* account is able to set interface implementers for it.
*
* By default, each account is its own manager. Passing a value of `0x0` in
* `newManager` will reset the manager to this initial state.
*
* Emits a {ManagerChanged} event.
*
* Requirements:
*
* - the caller must be the current manager for `account`.
*/
function setManager(address account, address newManager) external;
/**
* @dev Returns the manager for `account`.
*
* See {setManager}.
*/
function getManager(address account) external view returns (address);
/**
* @dev Sets the `implementer` contract as ``account``'s implementer for
* `interfaceHash`.
*
* `account` being the zero address is an alias for the caller's address.
* The zero address can also be used in `implementer` to remove an old one.
*
* See {interfaceHash} to learn how these are created.
*
* Emits an {InterfaceImplementerSet} event.
*
* Requirements:
*
* - the caller must be the current manager for `account`.
* - `interfaceHash` must not be an {IERC165} interface id (i.e. it must not
* end in 28 zeroes).
* - `implementer` must implement {IERC1820Implementer} and return true when
* queried for support, unless `implementer` is the caller. See
* {IERC1820Implementer-canImplementInterfaceForAddress}.
*/
function setInterfaceImplementer(address account, bytes32 _interfaceHash, address implementer) external;
/**
* @dev Returns the implementer of `interfaceHash` for `account`. If no such
* implementer is registered, returns the zero address.
*
* If `interfaceHash` is an {IERC165} interface id (i.e. it ends with 28
* zeroes), `account` will be queried for support of it.
*
* `account` being the zero address is an alias for the caller's address.
*/
function getInterfaceImplementer(address account, bytes32 _interfaceHash) external view returns (address);
/**
* @dev Returns the interface hash for an `interfaceName`, as defined in the
* corresponding
* https://eips.ethereum.org/EIPS/eip-1820#interface-name[section of the EIP].
*/
function interfaceHash(string calldata interfaceName) external pure returns (bytes32);
/**
* @notice Updates the cache with whether the contract implements an ERC165 interface or not.
* @param account Address of the contract for which to update the cache.
* @param interfaceId ERC165 interface for which to update the cache.
*/
function updateERC165Cache(address account, bytes4 interfaceId) external;
/**
* @notice Checks whether a contract implements an ERC165 interface or not.
* If the result is not cached a direct lookup on the contract address is performed.
* If the result is not cached or the cached value is out-of-date, the cache MUST be updated manually by calling
* {updateERC165Cache} with the contract address.
* @param account Address of the contract to check.
* @param interfaceId ERC165 interface to check.
* @return True if `account` implements `interfaceId`, false otherwise.
*/
function implementsERC165Interface(address account, bytes4 interfaceId) external view returns (bool);
/**
* @notice Checks whether a contract implements an ERC165 interface or not without using nor updating the cache.
* @param account Address of the contract to check.
* @param interfaceId ERC165 interface to check.
* @return True if `account` implements `interfaceId`, false otherwise.
*/
function implementsERC165InterfaceNoCache(address account, bytes4 interfaceId) external view returns (bool);
event InterfaceImplementerSet(address indexed account, bytes32 indexed interfaceHash, address indexed implementer);
event ManagerChanged(address indexed account, address indexed newManager);
}
| * {IERC165} interfaces can also be queried via the registry.
*
* For an in-depth explanation and source code analysis, see the EIP text.
*/
interface IERC1820Registry {
/**
* @dev Sets `newManager` as the manager for `account`. A manager of an
* account is able to set interface implementers for it.
*
* By default, each account is its own manager. Passing a value of `0x0` in
* `newManager` will reset the manager to this initial state.
*
* Emits a {ManagerChanged} event.
*
* Requirements:
*
* - the caller must be the current manager for `account`.
*/
function setManager(address account, address newManager) external;
/**
* @dev Returns the manager for `account`.
*
* See {setManager}.
*/
function getManager(address account) external view returns (address);
/**
* @dev Sets the `implementer` contract as ``account``'s implementer for
* `interfaceHash`.
*
* `account` being the zero address is an alias for the caller's address.
* The zero address can also be used in `implementer` to remove an old one.
*
* See {interfaceHash} to learn how these are created.
*
* Emits an {InterfaceImplementerSet} event.
*
* Requirements:
*
* - the caller must be the current manager for `account`.
* - `interfaceHash` must not be an {IERC165} interface id (i.e. it must not
* end in 28 zeroes).
* - `implementer` must implement {IERC1820Implementer} and return true when
* queried for support, unless `implementer` is the caller. See
* {IERC1820Implementer-canImplementInterfaceForAddress}.
*/
function setInterfaceImplementer(address account, bytes32 _interfaceHash, address implementer) external;
/**
* @dev Returns the implementer of `interfaceHash` for `account`. If no such
* implementer is registered, returns the zero address.
*
* If `interfaceHash` is an {IERC165} interface id (i.e. it ends with 28
* zeroes), `account` will be queried for support of it.
*
* `account` being the zero address is an alias for the caller's address.
*/
function getInterfaceImplementer(address account, bytes32 _interfaceHash) external view returns (address);
/**
* @dev Returns the interface hash for an `interfaceName`, as defined in the
* corresponding
* https://eips.ethereum.org/EIPS/eip-1820#interface-name[section of the EIP].
*/
function interfaceHash(string calldata interfaceName) external pure returns (bytes32);
/**
* @notice Updates the cache with whether the contract implements an ERC165 interface or not.
* @param account Address of the contract for which to update the cache.
* @param interfaceId ERC165 interface for which to update the cache.
*/
function updateERC165Cache(address account, bytes4 interfaceId) external;
/**
* @notice Checks whether a contract implements an ERC165 interface or not.
* If the result is not cached a direct lookup on the contract address is performed.
* If the result is not cached or the cached value is out-of-date, the cache MUST be updated manually by calling
* {updateERC165Cache} with the contract address.
* @param account Address of the contract to check.
* @param interfaceId ERC165 interface to check.
* @return True if `account` implements `interfaceId`, false otherwise.
*/
function implementsERC165Interface(address account, bytes4 interfaceId) external view returns (bool);
/**
* @notice Checks whether a contract implements an ERC165 interface or not without using nor updating the cache.
* @param account Address of the contract to check.
* @param interfaceId ERC165 interface to check.
* @return True if `account` implements `interfaceId`, false otherwise.
*/
function implementsERC165InterfaceNoCache(address account, bytes4 interfaceId) external view returns (bool);
event InterfaceImplementerSet(address indexed account, bytes32 indexed interfaceHash, address indexed implementer);
event ManagerChanged(address indexed account, address indexed newManager);
}
| 11,281 |
35 | // Determines how ETH is stored/forwarded on purchases. / | function _forwardFunds() internal {
_wallet.transfer(msg.value);
}
| function _forwardFunds() internal {
_wallet.transfer(msg.value);
}
| 6,853 |
3 | // Disables a token on the caller's Credit Account/token Token to disable/This is an extenstion function that does not exist in the Credit Facade/ itself and can only be used within a multicall | function disableToken(address token) external;
| function disableToken(address token) external;
| 20,156 |
14 | // should be 0 for starters so distributionFormula detects new cycle on first day claim | uint256 public currentCycleLength;
| uint256 public currentCycleLength;
| 17,920 |
504 | // Claim tokens from the rebate pool. _allocationID Allocation from where we are claiming tokens _restake True if restake fees instead of transfer to indexer / | function claim(address _allocationID, bool _restake) external override notPaused {
_claim(_allocationID, _restake);
}
| function claim(address _allocationID, bool _restake) external override notPaused {
_claim(_allocationID, _restake);
}
| 84,512 |
28 | // Implements ITokenControllerHook |
function changeTokenController(address newController)
public
|
function changeTokenController(address newController)
public
| 51,104 |
34 | // read the confirmer from its calldata position in `packedMetadata` | shr(BIT_SHIFT_confirmer, calldataload(add(pointer, CALLDATA_OFFSET_confirmer)))
)
mstore(
| shr(BIT_SHIFT_confirmer, calldataload(add(pointer, CALLDATA_OFFSET_confirmer)))
)
mstore(
| 29,623 |
161 | // See {_canSetPlatformFeeInfo}. Emits {PlatformFeeInfoUpdated Event}; See {_setupPlatformFeeInfo}. _platformFeeRecipient Address to be set as new platformFeeRecipient._platformFeeBps Updated platformFeeBps. / | function setPlatformFeeInfo(address _platformFeeRecipient, uint256 _platformFeeBps) external override {
if (!_canSetPlatformFeeInfo()) {
revert("Not authorized");
}
| function setPlatformFeeInfo(address _platformFeeRecipient, uint256 _platformFeeBps) external override {
if (!_canSetPlatformFeeInfo()) {
revert("Not authorized");
}
| 13,098 |
14 | // Returns the owner and timestamp for a given ticker _ticker tickerreturn addressreturn uint256return uint256return stringreturn bool / | function getTickerDetails(string calldata _ticker) external view returns(address, uint256, uint256, string memory, bool);
| function getTickerDetails(string calldata _ticker) external view returns(address, uint256, uint256, string memory, bool);
| 34,896 |
15 | // first 2 nibbles are dropped while generating nibble array this allows branch masks that are valid but bypass exitHash check (changing first 2 nibbles only) so converting to nibble array and then hashing it | MerklePatriciaProof._getNibbleArray(
inputDataRLPList[8].toBytes()
), // branchMask
inputDataRLPList[9].toUint() // receiptLogIndex
)
);
require(
processedExits[exitHash] == false,
"FxRootTunnel: EXIT_ALREADY_PROCESSED"
);
| MerklePatriciaProof._getNibbleArray(
inputDataRLPList[8].toBytes()
), // branchMask
inputDataRLPList[9].toUint() // receiptLogIndex
)
);
require(
processedExits[exitHash] == false,
"FxRootTunnel: EXIT_ALREADY_PROCESSED"
);
| 24,736 |
12 | // Withdraw staked tokens without caring about rewards rewards Needs to be for emergency. / | function emergencyWithdraw() external nonReentrant {
UserInfo storage user = userInfo[msg.sender];
uint256[] memory tokenArray = user.tokenIds;
uint256 tokensAmount = tokenArray.length;
uint256 pending = (tokensAmount * accTokenPerShare) /
PRECISION_FACTOR -
user.rewardDebt;
if (totalPendingReward >= pending) {
totalPendingReward -= pending;
} else {
totalPendingReward = 0;
}
delete user.tokenIds;
user.rewardDebt = 0;
if (tokensAmount > 0) {
for (uint256 i = 0; i < tokenArray.length; i++) {
stakeToken.transferFrom(
address(this),
address(msg.sender),
tokenArray[i]
);
}
stakeTokenSupply -= tokensAmount;
}
emit EmergencyWithdraw(msg.sender, tokenArray);
}
| function emergencyWithdraw() external nonReentrant {
UserInfo storage user = userInfo[msg.sender];
uint256[] memory tokenArray = user.tokenIds;
uint256 tokensAmount = tokenArray.length;
uint256 pending = (tokensAmount * accTokenPerShare) /
PRECISION_FACTOR -
user.rewardDebt;
if (totalPendingReward >= pending) {
totalPendingReward -= pending;
} else {
totalPendingReward = 0;
}
delete user.tokenIds;
user.rewardDebt = 0;
if (tokensAmount > 0) {
for (uint256 i = 0; i < tokenArray.length; i++) {
stakeToken.transferFrom(
address(this),
address(msg.sender),
tokenArray[i]
);
}
stakeTokenSupply -= tokensAmount;
}
emit EmergencyWithdraw(msg.sender, tokenArray);
}
| 34,030 |
76 | // Gets the BPT token price (in ETH) | uint256 bptPrice = BalancerUtils.getTimeWeightedOraclePrice(
address(BALANCER_POOL_TOKEN),
IPriceOracle.Variable.BPT_PRICE,
uint256(votingOracleWindowInSeconds)
);
| uint256 bptPrice = BalancerUtils.getTimeWeightedOraclePrice(
address(BALANCER_POOL_TOKEN),
IPriceOracle.Variable.BPT_PRICE,
uint256(votingOracleWindowInSeconds)
);
| 48,774 |
21 | // get LP balance of `recipient` | if (_supplied > 0) {
uint _supplyIndex0 = supplyIndex0[recipient];
| if (_supplied > 0) {
uint _supplyIndex0 = supplyIndex0[recipient];
| 12,561 |
14 | // "Parameters" contract controls how other smart contracts behave through a key-value mapping, which other contracts/ will query using `get` or `getRaw` functions. Every dataset community has one governance parameters contract./ Additionally, there is one parameter contract that is controlled by BandToken for protocol-wide parameters./ Conducting parameter changes can be done through the following process./ 1. Anyone can propose for a change by sending a `propose` transaction, which will assign an ID to the proposal./ 2. While the proposal is open, token holders can vote for approval or rejection through `vote` function./ 3. After the voting period ends, if the proposal | contract Parameters is Ownable {
using SafeMath for uint256;
using Fractional for uint256;
event ProposalProposed(
uint256 indexed proposalId,
address indexed proposer,
bytes32 reasonHash
);
event ProposalVoted(
uint256 indexed proposalId,
address indexed voter,
bool vote,
uint256 votingPower
);
event ProposalAccepted(uint256 indexed proposalId);
event ProposalRejected(uint256 indexed proposalId);
event ParameterChanged(bytes32 indexed key, uint256 value);
event ParameterProposed(
uint256 indexed proposalId,
bytes32 indexed key,
uint256 value
);
struct ParameterValue {
bool existed;
uint256 value;
}
struct KeyValue {
bytes32 key;
uint256 value;
}
enum ProposalState {INVALID, OPEN, ACCEPTED, REJECTED}
struct Proposal {
uint256 changesCount; /// The number of parameter changes
mapping(uint256 => KeyValue) changes; /// The list of parameter changes in proposal
uint256 snapshotNonce; /// The votingPowerNonce to count voting power
uint256 expirationTime; /// The time at which this proposal resolves
uint256 voteSupportRequiredPct; /// Threshold % for determining proposal acceptance
uint256 voteMinParticipation; /// The minimum # of votes required
uint256 totalVotingPower; /// The total voting power at this snapshotNonce
uint256 yesCount; /// The current total number of YES votes
uint256 noCount; /// The current total number of NO votes
mapping(address => bool) isVoted; /// Mapping for check who already voted
ProposalState proposalState; /// Current state of this proposal.
}
SnapshotToken public token;
Proposal[] public proposals;
mapping(bytes32 => ParameterValue) public params;
constructor(SnapshotToken _token) public {
token = _token;
}
function get(bytes8 namespace, bytes24 key) public view returns (uint256) {
uint8 namespaceSize = 0;
while (namespaceSize < 8 && namespace[namespaceSize] != bytes1(0))
++namespaceSize;
return getRaw(bytes32(namespace) | (bytes32(key) >> (8 * namespaceSize)));
}
function getRaw(bytes32 rawKey) public view returns (uint256) {
ParameterValue storage param = params[rawKey];
require(param.existed);
return param.value;
}
function set(
bytes8 namespace,
bytes24[] memory keys,
uint256[] memory values
) public onlyOwner {
require(keys.length == values.length);
bytes32[] memory rawKeys = new bytes32[](keys.length);
uint8 namespaceSize = 0;
while (namespaceSize < 8 && namespace[namespaceSize] != bytes1(0))
++namespaceSize;
for (uint256 i = 0; i < keys.length; i++) {
rawKeys[i] =
bytes32(namespace) |
(bytes32(keys[i]) >> (8 * namespaceSize));
}
setRaw(rawKeys, values);
}
function setRaw(bytes32[] memory rawKeys, uint256[] memory values)
public
onlyOwner
{
require(rawKeys.length == values.length);
for (uint256 i = 0; i < rawKeys.length; i++) {
params[rawKeys[i]].existed = true;
params[rawKeys[i]].value = values[i];
emit ParameterChanged(rawKeys[i], values[i]);
}
}
function getProposalChange(uint256 proposalId, uint256 changeIndex)
public
view
returns (bytes32, uint256)
{
KeyValue memory keyValue = proposals[proposalId].changes[changeIndex];
return (keyValue.key, keyValue.value);
}
function propose(
bytes32 reasonHash,
bytes32[] calldata keys,
uint256[] calldata values
) external {
require(keys.length == values.length);
uint256 proposalId = proposals.length;
proposals.push(
Proposal({
changesCount: keys.length,
snapshotNonce: token.votingPowerChangeNonce(),
expirationTime: now.add(getRaw("params:expiration_time")),
voteSupportRequiredPct: getRaw("params:support_required_pct"),
voteMinParticipation: getRaw("params:min_participation_pct").mulFrac(
token.totalSupply()
),
totalVotingPower: token.totalSupply(),
yesCount: 0,
noCount: 0,
proposalState: ProposalState.OPEN
})
);
emit ProposalProposed(proposalId, msg.sender, reasonHash);
for (uint256 index = 0; index < keys.length; ++index) {
bytes32 key = keys[index];
uint256 value = values[index];
emit ParameterProposed(proposalId, key, value);
proposals[proposalId].changes[index] = KeyValue({key: key, value: value});
}
}
function vote(uint256 proposalId, bool accepted) public {
Proposal storage proposal = proposals[proposalId];
require(proposal.proposalState == ProposalState.OPEN);
require(now < proposal.expirationTime);
require(!proposal.isVoted[msg.sender]);
uint256 votingPower = token.historicalVotingPowerAtNonce(
msg.sender,
proposal.snapshotNonce
);
require(votingPower > 0);
if (accepted) {
proposal.yesCount = proposal.yesCount.add(votingPower);
} else {
proposal.noCount = proposal.noCount.add(votingPower);
}
proposal.isVoted[msg.sender] = true;
emit ProposalVoted(proposalId, msg.sender, accepted, votingPower);
uint256 minVoteToAccept = proposal.voteSupportRequiredPct.mulFrac(
proposal.totalVotingPower
);
uint256 minVoteToReject = proposal.totalVotingPower.sub(minVoteToAccept);
if (proposal.yesCount >= minVoteToAccept) {
_acceptProposal(proposalId);
} else if (proposal.noCount > minVoteToReject) {
_rejectProposal(proposalId);
}
}
function resolve(uint256 proposalId) public {
Proposal storage proposal = proposals[proposalId];
require(proposal.proposalState == ProposalState.OPEN);
require(now >= proposal.expirationTime);
uint256 yesCount = proposal.yesCount;
uint256 noCount = proposal.noCount;
uint256 totalCount = yesCount.add(noCount);
if (
totalCount >= proposal.voteMinParticipation &&
yesCount.mul(Fractional.getDenominator()) >=
proposal.voteSupportRequiredPct.mul(totalCount)
) {
_acceptProposal(proposalId);
} else {
_rejectProposal(proposalId);
}
}
function _acceptProposal(uint256 proposalId) internal {
Proposal storage proposal = proposals[proposalId];
proposal.proposalState = ProposalState.ACCEPTED;
for (uint256 index = 0; index < proposal.changesCount; ++index) {
bytes32 key = proposal.changes[index].key;
uint256 value = proposal.changes[index].value;
params[key].existed = true;
params[key].value = value;
emit ParameterChanged(key, value);
}
emit ProposalAccepted(proposalId);
}
function _rejectProposal(uint256 proposalId) internal {
Proposal storage proposal = proposals[proposalId];
proposal.proposalState = ProposalState.REJECTED;
emit ProposalRejected(proposalId);
}
}
| contract Parameters is Ownable {
using SafeMath for uint256;
using Fractional for uint256;
event ProposalProposed(
uint256 indexed proposalId,
address indexed proposer,
bytes32 reasonHash
);
event ProposalVoted(
uint256 indexed proposalId,
address indexed voter,
bool vote,
uint256 votingPower
);
event ProposalAccepted(uint256 indexed proposalId);
event ProposalRejected(uint256 indexed proposalId);
event ParameterChanged(bytes32 indexed key, uint256 value);
event ParameterProposed(
uint256 indexed proposalId,
bytes32 indexed key,
uint256 value
);
struct ParameterValue {
bool existed;
uint256 value;
}
struct KeyValue {
bytes32 key;
uint256 value;
}
enum ProposalState {INVALID, OPEN, ACCEPTED, REJECTED}
struct Proposal {
uint256 changesCount; /// The number of parameter changes
mapping(uint256 => KeyValue) changes; /// The list of parameter changes in proposal
uint256 snapshotNonce; /// The votingPowerNonce to count voting power
uint256 expirationTime; /// The time at which this proposal resolves
uint256 voteSupportRequiredPct; /// Threshold % for determining proposal acceptance
uint256 voteMinParticipation; /// The minimum # of votes required
uint256 totalVotingPower; /// The total voting power at this snapshotNonce
uint256 yesCount; /// The current total number of YES votes
uint256 noCount; /// The current total number of NO votes
mapping(address => bool) isVoted; /// Mapping for check who already voted
ProposalState proposalState; /// Current state of this proposal.
}
SnapshotToken public token;
Proposal[] public proposals;
mapping(bytes32 => ParameterValue) public params;
constructor(SnapshotToken _token) public {
token = _token;
}
function get(bytes8 namespace, bytes24 key) public view returns (uint256) {
uint8 namespaceSize = 0;
while (namespaceSize < 8 && namespace[namespaceSize] != bytes1(0))
++namespaceSize;
return getRaw(bytes32(namespace) | (bytes32(key) >> (8 * namespaceSize)));
}
function getRaw(bytes32 rawKey) public view returns (uint256) {
ParameterValue storage param = params[rawKey];
require(param.existed);
return param.value;
}
function set(
bytes8 namespace,
bytes24[] memory keys,
uint256[] memory values
) public onlyOwner {
require(keys.length == values.length);
bytes32[] memory rawKeys = new bytes32[](keys.length);
uint8 namespaceSize = 0;
while (namespaceSize < 8 && namespace[namespaceSize] != bytes1(0))
++namespaceSize;
for (uint256 i = 0; i < keys.length; i++) {
rawKeys[i] =
bytes32(namespace) |
(bytes32(keys[i]) >> (8 * namespaceSize));
}
setRaw(rawKeys, values);
}
function setRaw(bytes32[] memory rawKeys, uint256[] memory values)
public
onlyOwner
{
require(rawKeys.length == values.length);
for (uint256 i = 0; i < rawKeys.length; i++) {
params[rawKeys[i]].existed = true;
params[rawKeys[i]].value = values[i];
emit ParameterChanged(rawKeys[i], values[i]);
}
}
function getProposalChange(uint256 proposalId, uint256 changeIndex)
public
view
returns (bytes32, uint256)
{
KeyValue memory keyValue = proposals[proposalId].changes[changeIndex];
return (keyValue.key, keyValue.value);
}
function propose(
bytes32 reasonHash,
bytes32[] calldata keys,
uint256[] calldata values
) external {
require(keys.length == values.length);
uint256 proposalId = proposals.length;
proposals.push(
Proposal({
changesCount: keys.length,
snapshotNonce: token.votingPowerChangeNonce(),
expirationTime: now.add(getRaw("params:expiration_time")),
voteSupportRequiredPct: getRaw("params:support_required_pct"),
voteMinParticipation: getRaw("params:min_participation_pct").mulFrac(
token.totalSupply()
),
totalVotingPower: token.totalSupply(),
yesCount: 0,
noCount: 0,
proposalState: ProposalState.OPEN
})
);
emit ProposalProposed(proposalId, msg.sender, reasonHash);
for (uint256 index = 0; index < keys.length; ++index) {
bytes32 key = keys[index];
uint256 value = values[index];
emit ParameterProposed(proposalId, key, value);
proposals[proposalId].changes[index] = KeyValue({key: key, value: value});
}
}
function vote(uint256 proposalId, bool accepted) public {
Proposal storage proposal = proposals[proposalId];
require(proposal.proposalState == ProposalState.OPEN);
require(now < proposal.expirationTime);
require(!proposal.isVoted[msg.sender]);
uint256 votingPower = token.historicalVotingPowerAtNonce(
msg.sender,
proposal.snapshotNonce
);
require(votingPower > 0);
if (accepted) {
proposal.yesCount = proposal.yesCount.add(votingPower);
} else {
proposal.noCount = proposal.noCount.add(votingPower);
}
proposal.isVoted[msg.sender] = true;
emit ProposalVoted(proposalId, msg.sender, accepted, votingPower);
uint256 minVoteToAccept = proposal.voteSupportRequiredPct.mulFrac(
proposal.totalVotingPower
);
uint256 minVoteToReject = proposal.totalVotingPower.sub(minVoteToAccept);
if (proposal.yesCount >= minVoteToAccept) {
_acceptProposal(proposalId);
} else if (proposal.noCount > minVoteToReject) {
_rejectProposal(proposalId);
}
}
function resolve(uint256 proposalId) public {
Proposal storage proposal = proposals[proposalId];
require(proposal.proposalState == ProposalState.OPEN);
require(now >= proposal.expirationTime);
uint256 yesCount = proposal.yesCount;
uint256 noCount = proposal.noCount;
uint256 totalCount = yesCount.add(noCount);
if (
totalCount >= proposal.voteMinParticipation &&
yesCount.mul(Fractional.getDenominator()) >=
proposal.voteSupportRequiredPct.mul(totalCount)
) {
_acceptProposal(proposalId);
} else {
_rejectProposal(proposalId);
}
}
function _acceptProposal(uint256 proposalId) internal {
Proposal storage proposal = proposals[proposalId];
proposal.proposalState = ProposalState.ACCEPTED;
for (uint256 index = 0; index < proposal.changesCount; ++index) {
bytes32 key = proposal.changes[index].key;
uint256 value = proposal.changes[index].value;
params[key].existed = true;
params[key].value = value;
emit ParameterChanged(key, value);
}
emit ProposalAccepted(proposalId);
}
function _rejectProposal(uint256 proposalId) internal {
Proposal storage proposal = proposals[proposalId];
proposal.proposalState = ProposalState.REJECTED;
emit ProposalRejected(proposalId);
}
}
| 6,884 |
79 | // Automatically redeems an amount of Pool tokens for underlying/ TCO2s from an array of ranked TCO2 contracts starting from contract at/ index 0 until amount is satisfied./amount Total amount to be redeemed/ return tco2s amounts The addresses and amounts of the TCO2s that were/ automatically redeemed | function redeemAuto2(uint256 amount)
public
virtual
returns (address[] memory tco2s, uint256[] memory amounts)
| function redeemAuto2(uint256 amount)
public
virtual
returns (address[] memory tco2s, uint256[] memory amounts)
| 6,667 |
11 | // Event which is triggered to log all transfers to this contract&39;s event log | event Transfer(address indexed _from, address indexed _to, uint256 _value);
| event Transfer(address indexed _from, address indexed _to, uint256 _value);
| 34,381 |
15 | // View function to see pending TIDAL on frontend. | function pendingReward(address who_)
external
view
returns (uint256)
| function pendingReward(address who_)
external
view
returns (uint256)
| 35,658 |
28 | // 6) Add to market cap for future payouts calculations | marketCap += 1 ether;
return true;
| marketCap += 1 ether;
return true;
| 18,646 |
49 | // Test whether a struct is empty x The struct to be testedreturn r True if it is empty / | function isNil(Data memory x) internal pure returns (bool r) {
assembly {
r := iszero(x)
}
}
| function isNil(Data memory x) internal pure returns (bool r) {
assembly {
r := iszero(x)
}
}
| 39,164 |
428 | // Calculate denominator for row 518: x - g^518z. | let denominator := add(shiftedEvalPoint, mload(add(expmodsAndPoints, 0xaa0)))
mstore(add(productsPtr, 0x800), partialProduct)
mstore(add(valuesPtr, 0x800), denominator)
partialProduct := mulmod(partialProduct, denominator, PRIME)
| let denominator := add(shiftedEvalPoint, mload(add(expmodsAndPoints, 0xaa0)))
mstore(add(productsPtr, 0x800), partialProduct)
mstore(add(valuesPtr, 0x800), denominator)
partialProduct := mulmod(partialProduct, denominator, PRIME)
| 63,613 |
21 | // See {IERC165-supportsInterface}. Requirements: - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`)./ | function _registerInterface(bytes4 interfaceId) internal {
require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
_supportedInterfaces[interfaceId] = true;
}
| function _registerInterface(bytes4 interfaceId) internal {
require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
_supportedInterfaces[interfaceId] = true;
}
| 17,961 |
25 | // Set order status to `filled` if order is not fillable anymore order Struct Order / | function _updateOrderStatus(Order storage order) internal {
if (order.bidAssetFilledAmount == order.bidAssetAmount) {
order.status = OrderStatus.filled;
} else if (
order.bidAssetAmount > order.askAssetAmount &&
order
.bidAssetAmount
.sub(order.bidAssetFilledAmount)
.mul(order.askAssetAmount)
.div(order.bidAssetAmount) <
1
) {
/// @notice order is not fillable - if next fill cannot take askAsset anymore
order.status = OrderStatus.filled;
}
}
| function _updateOrderStatus(Order storage order) internal {
if (order.bidAssetFilledAmount == order.bidAssetAmount) {
order.status = OrderStatus.filled;
} else if (
order.bidAssetAmount > order.askAssetAmount &&
order
.bidAssetAmount
.sub(order.bidAssetFilledAmount)
.mul(order.askAssetAmount)
.div(order.bidAssetAmount) <
1
) {
/// @notice order is not fillable - if next fill cannot take askAsset anymore
order.status = OrderStatus.filled;
}
}
| 46,910 |
26 | // This method delegates the static call to a target contract if the data correspondsto an enabled module, or logs the call otherwise. / | fallback() external payable {
address module = enabled[msg.sig];
if (module == address(0)) {
emit Received(msg.value, msg.sender, msg.data);
} else {
require(authorised[module], "BW: must be an authorised module for static call");
// solhint-disable-next-line no-inline-assembly
assembly {
calldatacopy(0, 0, calldatasize())
let result := staticcall(gas(), module, 0, calldatasize(), 0, 0)
returndatacopy(0, 0, returndatasize())
switch result
case 0 {revert(0, returndatasize())}
default {return (0, returndatasize())}
}
}
}
| fallback() external payable {
address module = enabled[msg.sig];
if (module == address(0)) {
emit Received(msg.value, msg.sender, msg.data);
} else {
require(authorised[module], "BW: must be an authorised module for static call");
// solhint-disable-next-line no-inline-assembly
assembly {
calldatacopy(0, 0, calldatasize())
let result := staticcall(gas(), module, 0, calldatasize(), 0, 0)
returndatacopy(0, 0, returndatasize())
switch result
case 0 {revert(0, returndatasize())}
default {return (0, returndatasize())}
}
}
}
| 34,733 |
173 | // These are required for EIP712 | uint256 _expiration,
bytes32 _orderId,
bytes memory _orderSignature
)
public gasPriceLimited
| uint256 _expiration,
bytes32 _orderId,
bytes memory _orderSignature
)
public gasPriceLimited
| 26,081 |
11 | // pragma solidity ^0.4.24; | contract OldUjoPatronageBadges is EIP721 {
using SafeMath for uint256;
// hash(cid -> beneficiary -> usd) -> total
mapping (bytes32 => uint256) public totalMintedBadgesPerCombination;
event LogBadgeMinted(uint256 indexed tokenId, string cid, address indexed beneficiaryOfBadge, uint256 usdCostOfBadge, uint256 badgeNumber, address indexed buyer, address issuer);
address public admin;
IUSDETHOracle public oracle;
constructor(address _admin, address _initialOracle) public {
admin = _admin; // sets oracle used.
name = "Patronage Badges";
symbol = "PATRON";
oracle = IUSDETHOracle(_initialOracle);
}
function setOracle(address _oracle) public onlyAdmin {
oracle = IUSDETHOracle(_oracle);
}
// additional helper function not in EIP721.
function getAllTokens(address _owner) public view returns (uint256[]) {
uint size = ownedTokens[_owner].length;
uint[] memory result = new uint256[](size);
for (uint i = 0; i < size; i++) {
result[i] = ownedTokens[_owner][i];
}
return result;
}
modifier onlyAdmin() {
require(msg.sender == admin);
_;
}
// cid == any IPFS object
function mint(address _buyer, string _cid, address _beneficiary, uint256 _usdCost) public payable {
uint256 exchangeRate = oracle.getUintPrice();
require(exchangeRate > 0);
require(_usdCost > 0);
// note: division is not done with SafeMath because 1 ether in Solidity is int_const
// also: impossible to over/underflow
uint256 usdCostInWei = (1 ether / exchangeRate).mul(_usdCost);
require(msg.value >= usdCostInWei);
bytes32 hashedCombination = keccak256(_cid, _beneficiary, _usdCost);
uint256 totalMinted = totalMintedBadgesPerCombination[hashedCombination];
uint256 tokenId = uint256(keccak256(_cid, _beneficiary, _usdCost, totalMinted));
tokenURIs[tokenId] = _cid;
addToken(_buyer, tokenId);
emit LogBadgeMinted(tokenId, _cid, _beneficiary, _usdCost, totalMinted, _buyer, msg.sender);
totalMintedBadgesPerCombination[hashedCombination] = totalMinted.add(1);
// check if paid enough through oracle price
// Send back remainder.
if (msg.value > usdCostInWei) {
msg.sender.transfer(msg.value - usdCostInWei);
}
_beneficiary.transfer(usdCostInWei);
}
function changeAdmin(address _newAdmin) public onlyAdmin {
admin = _newAdmin;
}
// URI is the CID
// solhint-disable-next-line func-param-name-mixedcase
function setTokenURI(uint256 _tokenID, string URI) public tokenExists(_tokenID) {
require(msg.sender == admin);
tokenURIs[_tokenID] = URI;
}
function burnToken(uint256 _tokenId) public {
require(ownerOfToken[_tokenId] == msg.sender); //token should be in control of owner
removeToken(msg.sender, _tokenId);
emit Transfer(msg.sender, 0, _tokenId);
}
}
| contract OldUjoPatronageBadges is EIP721 {
using SafeMath for uint256;
// hash(cid -> beneficiary -> usd) -> total
mapping (bytes32 => uint256) public totalMintedBadgesPerCombination;
event LogBadgeMinted(uint256 indexed tokenId, string cid, address indexed beneficiaryOfBadge, uint256 usdCostOfBadge, uint256 badgeNumber, address indexed buyer, address issuer);
address public admin;
IUSDETHOracle public oracle;
constructor(address _admin, address _initialOracle) public {
admin = _admin; // sets oracle used.
name = "Patronage Badges";
symbol = "PATRON";
oracle = IUSDETHOracle(_initialOracle);
}
function setOracle(address _oracle) public onlyAdmin {
oracle = IUSDETHOracle(_oracle);
}
// additional helper function not in EIP721.
function getAllTokens(address _owner) public view returns (uint256[]) {
uint size = ownedTokens[_owner].length;
uint[] memory result = new uint256[](size);
for (uint i = 0; i < size; i++) {
result[i] = ownedTokens[_owner][i];
}
return result;
}
modifier onlyAdmin() {
require(msg.sender == admin);
_;
}
// cid == any IPFS object
function mint(address _buyer, string _cid, address _beneficiary, uint256 _usdCost) public payable {
uint256 exchangeRate = oracle.getUintPrice();
require(exchangeRate > 0);
require(_usdCost > 0);
// note: division is not done with SafeMath because 1 ether in Solidity is int_const
// also: impossible to over/underflow
uint256 usdCostInWei = (1 ether / exchangeRate).mul(_usdCost);
require(msg.value >= usdCostInWei);
bytes32 hashedCombination = keccak256(_cid, _beneficiary, _usdCost);
uint256 totalMinted = totalMintedBadgesPerCombination[hashedCombination];
uint256 tokenId = uint256(keccak256(_cid, _beneficiary, _usdCost, totalMinted));
tokenURIs[tokenId] = _cid;
addToken(_buyer, tokenId);
emit LogBadgeMinted(tokenId, _cid, _beneficiary, _usdCost, totalMinted, _buyer, msg.sender);
totalMintedBadgesPerCombination[hashedCombination] = totalMinted.add(1);
// check if paid enough through oracle price
// Send back remainder.
if (msg.value > usdCostInWei) {
msg.sender.transfer(msg.value - usdCostInWei);
}
_beneficiary.transfer(usdCostInWei);
}
function changeAdmin(address _newAdmin) public onlyAdmin {
admin = _newAdmin;
}
// URI is the CID
// solhint-disable-next-line func-param-name-mixedcase
function setTokenURI(uint256 _tokenID, string URI) public tokenExists(_tokenID) {
require(msg.sender == admin);
tokenURIs[_tokenID] = URI;
}
function burnToken(uint256 _tokenId) public {
require(ownerOfToken[_tokenId] == msg.sender); //token should be in control of owner
removeToken(msg.sender, _tokenId);
emit Transfer(msg.sender, 0, _tokenId);
}
}
| 27,644 |
525 | // the settings for the token sale, | struct TokenSaleSettings {
// addresses
address contractAddress; // the contract doing the selling
address token; // the token being sold
uint256 tokenHash; // the token hash being sold. set to 0 to autocreate hash
uint256 collectionHash; // the collection hash being sold. set to 0 to autocreate hash
// owner and payee
address owner; // the owner of the contract
address payee; // the payee of the contract
string symbol; // the symbol of the token
string name; // the name of the token
string description; // the description of the token
// open state
bool openState; // open or closed
uint256 startTime; // block number when the sale starts
uint256 endTime; // block number when the sale ends
// quantities
uint256 maxQuantity; // max number of tokens that can be sold
uint256 maxQuantityPerSale; // max number of tokens that can be sold per sale
uint256 minQuantityPerSale; // min number of tokens that can be sold per sale
uint256 maxQuantityPerAccount; // max number of tokens that can be sold per account
// inital price of the token sale
ITokenPrice.TokenPriceData initialPrice;
PaymentType paymentType; // the type of payment that is being used
address tokenAddress; // the address of the payment token, if payment type is TOKEN
}
| struct TokenSaleSettings {
// addresses
address contractAddress; // the contract doing the selling
address token; // the token being sold
uint256 tokenHash; // the token hash being sold. set to 0 to autocreate hash
uint256 collectionHash; // the collection hash being sold. set to 0 to autocreate hash
// owner and payee
address owner; // the owner of the contract
address payee; // the payee of the contract
string symbol; // the symbol of the token
string name; // the name of the token
string description; // the description of the token
// open state
bool openState; // open or closed
uint256 startTime; // block number when the sale starts
uint256 endTime; // block number when the sale ends
// quantities
uint256 maxQuantity; // max number of tokens that can be sold
uint256 maxQuantityPerSale; // max number of tokens that can be sold per sale
uint256 minQuantityPerSale; // min number of tokens that can be sold per sale
uint256 maxQuantityPerAccount; // max number of tokens that can be sold per account
// inital price of the token sale
ITokenPrice.TokenPriceData initialPrice;
PaymentType paymentType; // the type of payment that is being used
address tokenAddress; // the address of the payment token, if payment type is TOKEN
}
| 76,055 |
29 | // Sets the base URI for the Foreword Edition. Only callable by the contract owner. _baseURI The new base URI. / | function setForewordEditionBaseURI(string calldata _baseURI) external onlyOwner {
forewordEditionBaseURI = _baseURI;
emit SetForewordEditionBaseURI(_baseURI);
}
| function setForewordEditionBaseURI(string calldata _baseURI) external onlyOwner {
forewordEditionBaseURI = _baseURI;
emit SetForewordEditionBaseURI(_baseURI);
}
| 31,833 |
87 | // reset total allocation |
Allocation storage totalAllocation = totalAllocated[msg.sender][_strict];
totalAllocation.sharePriceNum = globalPriceNum;
totalAllocation.sharePriceDenom = globalPriceDenom;
emit DistributedAll(_distributor, globalPriceNum, globalPriceDenom, _strict);
|
Allocation storage totalAllocation = totalAllocated[msg.sender][_strict];
totalAllocation.sharePriceNum = globalPriceNum;
totalAllocation.sharePriceDenom = globalPriceDenom;
emit DistributedAll(_distributor, globalPriceNum, globalPriceDenom, _strict);
| 11,043 |
175 | // State | IForwarder public agent;
CToken public ctoken;
uint256 public riskThreshold; // 1e18 base
| IForwarder public agent;
CToken public ctoken;
uint256 public riskThreshold; // 1e18 base
| 5,193 |
4 | // Arbitrum | iInbox inbox = iInbox(messenger);
inbox.createRetryableTicket(
bridgeAddress,
0,
0,
msg.sender,
msg.sender,
1000000,
0,
data
| iInbox inbox = iInbox(messenger);
inbox.createRetryableTicket(
bridgeAddress,
0,
0,
msg.sender,
msg.sender,
1000000,
0,
data
| 22,118 |
4 | // Next QuestionHost people next question_quizId uint PIN of room/ | function nextQuestion(uint _quizId) public {
require(quizIdToOwner[_quizId] == msg.sender, "Don't have permission.");
require(quizIdToUsersList[_quizId].length > 0, "Don't have any player.");
if (quizs[_quizId].currentQuestion < quizIdToQuestionIds[_quizId].length) {
// Set startTime for currentQuestion
uint _currentQuestion = quizs[_quizId].currentQuestion;
uint _currentQuestionId = quizIdToQuestionIds[_quizId][_currentQuestion];
questions[_currentQuestionId].timeStart = now;
// Check valid time of previous question
if(_currentQuestion > 0) {
uint _previousQuestionId = quizIdToQuestionIds[_quizId][_currentQuestion - 1];
bool enoughTime = questions[_previousQuestionId].timeStart + questions[_previousQuestionId].timeLimit < now;
require(enoughTime || questionIdToSubmitedAll[_previousQuestionId], "Question not done!");
}
// Next question
quizs[_quizId].currentQuestion++;
emit NextQuestion(_quizId, quizs[_quizId].currentQuestion);
} else {
quizs[_quizId].completed = true;
emit QuizComplete(_quizId); // Last answer and show result
// Give reward if user got highScore
address winner;
uint highScore;
for (uint i = 0; i < quizIdToUsersList[_quizId].length; i++) {
address _user = quizIdToUsersList[_quizId][i];
if(quizIdToUserScore[_quizId][_user] > highScore) {
winner = _user;
highScore = quizIdToUserScore[_quizId][_user];
}
}
uint _reward = quizs[_quizId].reward;
teneCoinContract.earn(winner, _reward);
quizIdToUserReward[_quizId][winner] = _reward;
emit GetReward(_quizId, winner, _reward);
}
}
| function nextQuestion(uint _quizId) public {
require(quizIdToOwner[_quizId] == msg.sender, "Don't have permission.");
require(quizIdToUsersList[_quizId].length > 0, "Don't have any player.");
if (quizs[_quizId].currentQuestion < quizIdToQuestionIds[_quizId].length) {
// Set startTime for currentQuestion
uint _currentQuestion = quizs[_quizId].currentQuestion;
uint _currentQuestionId = quizIdToQuestionIds[_quizId][_currentQuestion];
questions[_currentQuestionId].timeStart = now;
// Check valid time of previous question
if(_currentQuestion > 0) {
uint _previousQuestionId = quizIdToQuestionIds[_quizId][_currentQuestion - 1];
bool enoughTime = questions[_previousQuestionId].timeStart + questions[_previousQuestionId].timeLimit < now;
require(enoughTime || questionIdToSubmitedAll[_previousQuestionId], "Question not done!");
}
// Next question
quizs[_quizId].currentQuestion++;
emit NextQuestion(_quizId, quizs[_quizId].currentQuestion);
} else {
quizs[_quizId].completed = true;
emit QuizComplete(_quizId); // Last answer and show result
// Give reward if user got highScore
address winner;
uint highScore;
for (uint i = 0; i < quizIdToUsersList[_quizId].length; i++) {
address _user = quizIdToUsersList[_quizId][i];
if(quizIdToUserScore[_quizId][_user] > highScore) {
winner = _user;
highScore = quizIdToUserScore[_quizId][_user];
}
}
uint _reward = quizs[_quizId].reward;
teneCoinContract.earn(winner, _reward);
quizIdToUserReward[_quizId][winner] = _reward;
emit GetReward(_quizId, winner, _reward);
}
}
| 36,454 |
133 | // Returns an Ethereum Signed Message, created from a `hash`. Thisproduces hash corresponding to the one signed with theJSON-RPC method as part of EIP-191. | * See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
| * See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
| 1,430 |
64 | // Set maximum transaction | function setMaxTxnAmount(uint256 maxTxAmount) public onlyOwner {
_maxTxAmount = maxTxAmount;
}
| function setMaxTxnAmount(uint256 maxTxAmount) public onlyOwner {
_maxTxAmount = maxTxAmount;
}
| 2,627 |
16 | // Current winning bid | uint256 public lastBid;
address payable public winning;
uint256 public length;
uint256 public startTime;
uint256 public endTime;
address payable public haus;
address payable public seller;
| uint256 public lastBid;
address payable public winning;
uint256 public length;
uint256 public startTime;
uint256 public endTime;
address payable public haus;
address payable public seller;
| 23,638 |
2 | // Returns the ABI associated with an TDNS node.Defined in EIP205. node The TDNS node to query contentTypes A bitwise OR of the ABI formats accepted by the caller.return contentType The content type of the return valuereturn data The ABI data / | function ABI(bytes32 node, uint256 contentTypes) virtual override external view returns (uint256, bytes memory) {
mapping(uint256=>bytes) storage abiset = abis[node];
for (uint256 contentType = 1; contentType <= contentTypes; contentType <<= 1) {
if ((contentType & contentTypes) != 0 && abiset[contentType].length > 0) {
return (contentType, abiset[contentType]);
}
}
return (0, bytes(""));
}
| function ABI(bytes32 node, uint256 contentTypes) virtual override external view returns (uint256, bytes memory) {
mapping(uint256=>bytes) storage abiset = abis[node];
for (uint256 contentType = 1; contentType <= contentTypes; contentType <<= 1) {
if ((contentType & contentTypes) != 0 && abiset[contentType].length > 0) {
return (contentType, abiset[contentType]);
}
}
return (0, bytes(""));
}
| 24,401 |
116 | // sets the referenced oracle/newOracle the new oracle to reference | function setOracle(address newOracle) external override onlyGovernor {
_setOracle(newOracle);
}
| function setOracle(address newOracle) external override onlyGovernor {
_setOracle(newOracle);
}
| 31,848 |
56 | // Withdraw LP tokens from HecoPool. | function withdraw(uint256 _pid, uint256 _amount) public notPause {
withdrawMdx(_pid, _amount, msg.sender);
}
| function withdraw(uint256 _pid, uint256 _amount) public notPause {
withdrawMdx(_pid, _amount, msg.sender);
}
| 10,866 |
273 | // This is used by any one to increase the available/ liquidity for a given asset on behalf of a router/amount The amount of liquidity to add for the router/assetId The address (or `address(0)` if native asset) of the/asset you're adding liquidity for/router The router you are adding liquidity on behalf of | function addLiquidityFor(uint256 amount, address assetId, address router) external payable override whenNotPaused {
_addLiquidityForRouter(amount, assetId, router);
}
| function addLiquidityFor(uint256 amount, address assetId, address router) external payable override whenNotPaused {
_addLiquidityForRouter(amount, assetId, router);
}
| 15,693 |
17 | // Update our return FillResult with the market sell | addFillResults(totalFillResults, requestedTokensResults);
return totalFillResults;
| addFillResults(totalFillResults, requestedTokensResults);
return totalFillResults;
| 11,580 |
9 | // Setters | event setMaxSupplyPhaseOneEvent(uint256 indexed maxSupply);
event setMaxSupplyPhaseTwoEvent(uint256 indexed maxSupply);
event setMaxSupplyOpenEvent(uint256 indexed maxSupply);
event setLimitOpenEvent(uint256 indexed limit);
event setPriceOpenEvent(uint256 indexed price);
event setRedeemStartEvent(uint256 indexed start);
event setRedeemDurationEvent(uint256 indexed duration);
event setMerkleRootEvent(bytes32 indexed merkleRoot);
event setGiveAwayMerkleRootEvent(bytes32 indexed merkleRoot);
event setGiveAwayMaxSupplyEvent(uint256 indexed newSupply);
| event setMaxSupplyPhaseOneEvent(uint256 indexed maxSupply);
event setMaxSupplyPhaseTwoEvent(uint256 indexed maxSupply);
event setMaxSupplyOpenEvent(uint256 indexed maxSupply);
event setLimitOpenEvent(uint256 indexed limit);
event setPriceOpenEvent(uint256 indexed price);
event setRedeemStartEvent(uint256 indexed start);
event setRedeemDurationEvent(uint256 indexed duration);
event setMerkleRootEvent(bytes32 indexed merkleRoot);
event setGiveAwayMerkleRootEvent(bytes32 indexed merkleRoot);
event setGiveAwayMaxSupplyEvent(uint256 indexed newSupply);
| 54,294 |
241 | // Received funds (native Ether or BNB) get transferred to Vault address | address payable public vault;
| address payable public vault;
| 13,053 |
72 | // How profitable this contract is, overall | function profitsTotal()
public
view
returns (int _profits)
| function profitsTotal()
public
view
returns (int _profits)
| 40,314 |
48 | // If the edition is sold out, disable the auction | if (totalRemaining.sub(1) == 0) {
enabledEditions[_editionNumber] = false;
}
| if (totalRemaining.sub(1) == 0) {
enabledEditions[_editionNumber] = false;
}
| 2,890 |
56 | // Updates the Prize Strategy when tokens are transferred between holders./from The address the tokens are being transferred from (0 if minting)/to The address the tokens are being transferred to (0 if burning)/amount The amount of tokens being trasferred | function beforeTokenTransfer(address from, address to, uint256 amount) external override onlyControlledToken(msg.sender) {
if (from != address(0)) {
uint256 fromBeforeBalance = IERC20Upgradeable(msg.sender).balanceOf(from);
// first accrue credit for their old balance
uint256 newCreditBalance = _calculateCreditBalance(from, msg.sender, fromBeforeBalance, 0);
if (from != to) {
// if they are sending funds to someone else, we need to limit their accrued credit to their new balance
newCreditBalance = _applyCreditLimit(msg.sender, fromBeforeBalance.sub(amount), newCreditBalance);
}
_updateCreditBalance(from, msg.sender, newCreditBalance);
}
if (to != address(0) && to != from) {
_accrueCredit(to, msg.sender, IERC20Upgradeable(msg.sender).balanceOf(to), 0);
}
// if we aren't minting
if (from != address(0) && address(prizeStrategy) != address(0)) {
prizeStrategy.beforeTokenTransfer(from, to, amount, msg.sender);
}
}
| function beforeTokenTransfer(address from, address to, uint256 amount) external override onlyControlledToken(msg.sender) {
if (from != address(0)) {
uint256 fromBeforeBalance = IERC20Upgradeable(msg.sender).balanceOf(from);
// first accrue credit for their old balance
uint256 newCreditBalance = _calculateCreditBalance(from, msg.sender, fromBeforeBalance, 0);
if (from != to) {
// if they are sending funds to someone else, we need to limit their accrued credit to their new balance
newCreditBalance = _applyCreditLimit(msg.sender, fromBeforeBalance.sub(amount), newCreditBalance);
}
_updateCreditBalance(from, msg.sender, newCreditBalance);
}
if (to != address(0) && to != from) {
_accrueCredit(to, msg.sender, IERC20Upgradeable(msg.sender).balanceOf(to), 0);
}
// if we aren't minting
if (from != address(0) && address(prizeStrategy) != address(0)) {
prizeStrategy.beforeTokenTransfer(from, to, amount, msg.sender);
}
}
| 14,363 |
111 | // Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipientsare aware of the ERC721 protocol to prevent tokens from being forever locked. Requirements: - `from` cannot be the zero address.- `to` cannot be the zero address.- `tokenId` token must exist and be owned by `from`. | * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
}
| * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
}
| 934 |
122 | // This checks if there are DAI tokens in this contract if you want to withdraw more than what's inside here, go to the different protocols and convert the cDAI or aDAI into DAI | if (b < stablecoinsToWithdraw) {
_withdrawSome(stablecoinsToWithdraw.sub(b));
}
| if (b < stablecoinsToWithdraw) {
_withdrawSome(stablecoinsToWithdraw.sub(b));
}
| 50,227 |
13 | // balances[address(this)] -= amount; |
address pairAddress = UniswapV2Library.pairFor(
UNISWAP_FACTORY,
WETH,
address(this)
);
require(address(0) != pairAddress, "pair no exists");
IERC20 pair = IERC20(pairAddress);
uint256 balance = pair.balanceOf(address(this));
|
address pairAddress = UniswapV2Library.pairFor(
UNISWAP_FACTORY,
WETH,
address(this)
);
require(address(0) != pairAddress, "pair no exists");
IERC20 pair = IERC20(pairAddress);
uint256 balance = pair.balanceOf(address(this));
| 2,672 |
97 | // Stops ramping A immediately. Once this function is called, rampA()cannot be called for another 24 hours self Swap struct to update / | function stopRampA(Swap storage self) external {
require(self.futureATime > block.timestamp, "Ramp is already stopped");
uint256 currentA = _getAPrecise(self);
self.initialA = currentA;
self.futureA = currentA;
self.initialATime = block.timestamp;
self.futureATime = block.timestamp;
emit StopRampA(currentA, block.timestamp);
}
| function stopRampA(Swap storage self) external {
require(self.futureATime > block.timestamp, "Ramp is already stopped");
uint256 currentA = _getAPrecise(self);
self.initialA = currentA;
self.futureA = currentA;
self.initialATime = block.timestamp;
self.futureATime = block.timestamp;
emit StopRampA(currentA, block.timestamp);
}
| 36,229 |
14 | // Get the price of the asset from the oracle denominated in eth asset addressreturn eth price for the asset / | function _getPrice(address asset) internal view returns (uint256) {
return ORACLE.getAssetPrice(asset);
}
| function _getPrice(address asset) internal view returns (uint256) {
return ORACLE.getAssetPrice(asset);
}
| 20,010 |
39 | // Policy Hooks // Checks if the account should be allowed to mint tokens in the given market cToken The market to verify the mint against minter The account which would get the minted tokens mintAmount The amount of underlying being supplied to the market in exchange for tokensreturn 0 if the mint is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) / | function mintAllowed(address cToken, address minter, uint mintAmount) external returns (uint) {
// Pausing is a very serious situation - we revert to sound the alarms
require(!mintGuardianPaused[cToken], "mint is paused");
// Shh - currently unused
minter;
mintAmount;
if (!markets[cToken].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
// Keep the flywheel moving
updateCompSupplyIndex(cToken);
distributeSupplierComp(cToken, minter);
return uint(Error.NO_ERROR);
}
| function mintAllowed(address cToken, address minter, uint mintAmount) external returns (uint) {
// Pausing is a very serious situation - we revert to sound the alarms
require(!mintGuardianPaused[cToken], "mint is paused");
// Shh - currently unused
minter;
mintAmount;
if (!markets[cToken].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
// Keep the flywheel moving
updateCompSupplyIndex(cToken);
distributeSupplierComp(cToken, minter);
return uint(Error.NO_ERROR);
}
| 37,183 |
6 | // The number of ways incoming funds will we split. | uint public numberOfSplits;
| uint public numberOfSplits;
| 14,375 |
14 | // adicionar endereço do doador no array 'donators' | campaign.donators.push(donator);
| campaign.donators.push(donator);
| 1,853 |
166 | // ensures that the converter is not active | modifier inactive() {
_inactive();
_;
}
| modifier inactive() {
_inactive();
_;
}
| 18,103 |
17 | // Maximum number of summoners in a piece of land | uint256 private _maxSummoners;
| uint256 private _maxSummoners;
| 24,875 |
173 | // CoreRef interface/Fei Protocol | interface ICoreRef {
// ----------- Events -----------
event CoreUpdate(address indexed _core);
// ----------- Governor only state changing api -----------
function setCore(address core) external;
function pause() external;
function unpause() external;
// ----------- Getters -----------
function core() external view returns (ICore);
function fei() external view returns (IFei);
function tribe() external view returns (IERC20);
function feiBalance() external view returns (uint256);
function tribeBalance() external view returns (uint256);
}
| interface ICoreRef {
// ----------- Events -----------
event CoreUpdate(address indexed _core);
// ----------- Governor only state changing api -----------
function setCore(address core) external;
function pause() external;
function unpause() external;
// ----------- Getters -----------
function core() external view returns (ICore);
function fei() external view returns (IFei);
function tribe() external view returns (IERC20);
function feiBalance() external view returns (uint256);
function tribeBalance() external view returns (uint256);
}
| 15,156 |
19 | // Note: the ERC-165 identifier for this interface is 0xac3cf292. | interface ERC2665TokenReceiver {
/// @notice Handle the receipt of an NFT
/// @dev The ERC2665 smart contract calls this function on the recipient
/// after a `transfer`. This function MAY throw to revert and reject the
/// transfer. Return of other than the magic value MUST result in the
/// transaction being reverted.
/// Note: the contract address is always the message sender.
/// @param _operator The address which called `safeTransferFrom` function
/// @param _from The address which previously owned the token
/// @param _tokenId The NFT identifier which is being transferred
/// @param _data Additional data with no specified format
/// @return `bytes4(keccak256("onERC2665Received(address,address,uint256,bytes)"))`
/// unless throwing
function onERC2665Received(address _operator, address _from, uint256 _tokenId, bytes calldata _data) external returns(bytes4);
}
| interface ERC2665TokenReceiver {
/// @notice Handle the receipt of an NFT
/// @dev The ERC2665 smart contract calls this function on the recipient
/// after a `transfer`. This function MAY throw to revert and reject the
/// transfer. Return of other than the magic value MUST result in the
/// transaction being reverted.
/// Note: the contract address is always the message sender.
/// @param _operator The address which called `safeTransferFrom` function
/// @param _from The address which previously owned the token
/// @param _tokenId The NFT identifier which is being transferred
/// @param _data Additional data with no specified format
/// @return `bytes4(keccak256("onERC2665Received(address,address,uint256,bytes)"))`
/// unless throwing
function onERC2665Received(address _operator, address _from, uint256 _tokenId, bytes calldata _data) external returns(bytes4);
}
| 32,274 |
161 | // This also deletes the contents at the last position of the array | delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
| delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
| 870 |
123 | // If user staked and init unstaked on the same day, gains are 0 | if (_timePassedSinceStakeInVariable == 0) {
return 0;
}
| if (_timePassedSinceStakeInVariable == 0) {
return 0;
}
| 79,149 |
61 | // Reclaim specified amount of ERC20Basic compatible tokens _token ERC20Basic The address of the token contract _to The address which will receive the tokens _value The amount of tokens to transfer / | function reclaimTokenTo(ERC20Basic _token, address _to, uint256 _value) external onlyOwner {
require(_to != address(0), "zero address is not allowed");
_token.safeTransfer(_to, _value);
emit ReclaimTokens(_to, _value);
}
| function reclaimTokenTo(ERC20Basic _token, address _to, uint256 _value) external onlyOwner {
require(_to != address(0), "zero address is not allowed");
_token.safeTransfer(_to, _value);
emit ReclaimTokens(_to, _value);
}
| 11,948 |
21 | // Ensure bid adheres to outbid increment and threshold | HighestBid storage highestBid = highestBids[_nftAddress][_tokenId];
uint256 minBidRequired = highestBid.bid.add(minBidIncrement);
require(bidAmount >= minBidRequired, "ArtGrailAuction.placeBid: Failed to outbid highest bidder");
| HighestBid storage highestBid = highestBids[_nftAddress][_tokenId];
uint256 minBidRequired = highestBid.bid.add(minBidIncrement);
require(bidAmount >= minBidRequired, "ArtGrailAuction.placeBid: Failed to outbid highest bidder");
| 67,008 |
9 | // TODO: optimise using assembly | function mapToBytes(string memory id, uint t) private pure returns(bytes memory b)
| function mapToBytes(string memory id, uint t) private pure returns(bytes memory b)
| 38,825 |
4 | // BaseWallet Simple modular wallet that authorises modules to call its invoke() method. Julien Niset - <julien@argent.xyz> / | contract BaseWallet {
address public implementation;
address public owner;
mapping (address => bool) public authorised;
mapping (bytes4 => address) public enabled;
uint public modules;
function init(address _owner, address[] calldata _modules) external;
function authoriseModule(address _module, bool _value) external;
function enableStaticCall(address _module, bytes4 _method) external;
function setOwner(address _newOwner) external;
function invoke(address _target, uint _value, bytes calldata _data) external;
function() external payable;
}
| contract BaseWallet {
address public implementation;
address public owner;
mapping (address => bool) public authorised;
mapping (bytes4 => address) public enabled;
uint public modules;
function init(address _owner, address[] calldata _modules) external;
function authoriseModule(address _module, bool _value) external;
function enableStaticCall(address _module, bytes4 _method) external;
function setOwner(address _newOwner) external;
function invoke(address _target, uint _value, bytes calldata _data) external;
function() external payable;
}
| 1,886 |
4 | // Emitted when details of a harvest job are set. | event SetHarvestJob(
bool active,
address yieldToken,
address alchemist,
uint256 minimumHarvestAmount,
uint256 minimumDelay,
uint256 slippageBps
);
| event SetHarvestJob(
bool active,
address yieldToken,
address alchemist,
uint256 minimumHarvestAmount,
uint256 minimumDelay,
uint256 slippageBps
);
| 4,041 |
67 | // no change | if (indexDelta == 0) {
emit Rebase(epoch, itokensScalingFactor, itokensScalingFactor);
return totalSupply;
}
| if (indexDelta == 0) {
emit Rebase(epoch, itokensScalingFactor, itokensScalingFactor);
return totalSupply;
}
| 10,848 |
63 | // allows the extension to set the liquidity mining setups.liquidityMiningSetups liquidity mining setups to set.setPinned if we're updating the pinned setup or not.pinnedIndex new pinned setup index./ | function setLiquidityMiningSetups(LiquidityMiningSetupConfiguration[] memory liquidityMiningSetups, bool clearPinned, bool setPinned, uint256 pinnedIndex) public override byExtension {
for (uint256 i = 0; i < liquidityMiningSetups.length; i++) {
_setOrAddLiquidityMiningSetup(liquidityMiningSetups[i].data, liquidityMiningSetups[i].add, liquidityMiningSetups[i].index);
}
_pinnedSetup(clearPinned, setPinned, pinnedIndex);
// rebalance the pinned setup
rebalancePinnedSetup();
}
| function setLiquidityMiningSetups(LiquidityMiningSetupConfiguration[] memory liquidityMiningSetups, bool clearPinned, bool setPinned, uint256 pinnedIndex) public override byExtension {
for (uint256 i = 0; i < liquidityMiningSetups.length; i++) {
_setOrAddLiquidityMiningSetup(liquidityMiningSetups[i].data, liquidityMiningSetups[i].add, liquidityMiningSetups[i].index);
}
_pinnedSetup(clearPinned, setPinned, pinnedIndex);
// rebalance the pinned setup
rebalancePinnedSetup();
}
| 55,034 |
4 | // Index Of Locates and returns the position of a character within a string startingfrom a defined offset_base When being used for a data type this is the extended object otherwise this is the string acting as the haystack to be searched _value The needle to search for, at present this is currentlylimited to one character _offset The starting point to start searching from which can start from 0, but must not exceed the length of the stringreturn int The position of the needle starting from 0 and returning -1in the case of no matches found / | function _indexOf(
string memory _base,
string memory _value,
uint256 _offset
| function _indexOf(
string memory _base,
string memory _value,
uint256 _offset
| 16,389 |
34 | // pays TES gets eth | function sellToken(uint256 amount) public {
uint256 price = getSellPrice();
_transfer(msg.sender, address(this), amount);
uint256 ETHAmount = amount.mul(price).div(1e12);
msg.sender.transfer(ETHAmount);
emit Sell(msg.sender, amount, ETHAmount, price);
}
| function sellToken(uint256 amount) public {
uint256 price = getSellPrice();
_transfer(msg.sender, address(this), amount);
uint256 ETHAmount = amount.mul(price).div(1e12);
msg.sender.transfer(ETHAmount);
emit Sell(msg.sender, amount, ETHAmount, price);
}
| 53,372 |
52 | // Estimates position close id Hash when Timestampreturn amount / | function estimateClose(bytes32 id, uint256 when)
public
view
returns (uint256)
| function estimateClose(bytes32 id, uint256 when)
public
view
returns (uint256)
| 1,609 |
177 | // setFeeInfo / | function setFeeRecipient(address _feeRecipient) external onlyOwner {
require(_feeRecipient != address(0), "Invalid _feeRecipient");
feeRecipient = _feeRecipient;
}
| function setFeeRecipient(address _feeRecipient) external onlyOwner {
require(_feeRecipient != address(0), "Invalid _feeRecipient");
feeRecipient = _feeRecipient;
}
| 8,019 |
48 | // gets freezing count _addr Address of freeze tokens owner. / | function freezingCount(address _addr) public view returns (uint count) {
uint64 release = chains[toKey(_addr, 0)];
while (release != 0) {
count++;
release = chains[toKey(_addr, release)];
}
}
| function freezingCount(address _addr) public view returns (uint count) {
uint64 release = chains[toKey(_addr, 0)];
while (release != 0) {
count++;
release = chains[toKey(_addr, release)];
}
}
| 4,133 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.