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
18
// see calculateUserClaimableReward() docs requires that reward token has the same decimals as stake token _stakeRewardFactor time in secondsamount of staked token to receive 1 reward token /
function setStakeRewardFactor(uint256 _stakeRewardFactor) external onlyRole(DEFAULT_ADMIN_ROLE) { stakeRewardFactor = _stakeRewardFactor; emit StakeRewardFactorChanged(_stakeRewardFactor); }
function setStakeRewardFactor(uint256 _stakeRewardFactor) external onlyRole(DEFAULT_ADMIN_ROLE) { stakeRewardFactor = _stakeRewardFactor; emit StakeRewardFactorChanged(_stakeRewardFactor); }
14,718
218
// returns the current controller configurationreturn whitelist, the address of the whitelist modulereturn oracle, the address of the oracle modulereturn calculator, the address of the calculator modulereturn pool, the address of the pool module /
function getConfiguration() external view returns ( address, address, address, address )
function getConfiguration() external view returns ( address, address, address, address )
627
43
// SafeTransfer MELD
_safeTransfer(burnAdmin, pendingMELDToBurn); lastBurnedBlock = block.number;
_safeTransfer(burnAdmin, pendingMELDToBurn); lastBurnedBlock = block.number;
10,809
356
// Clone and initialize a LPToken contract
LPToken lpToken = LPToken(Clones.clone(lpTokenTargetAddress)); require( lpToken.initialize(lpTokenName, lpTokenSymbol), "could not init lpToken clone" );
LPToken lpToken = LPToken(Clones.clone(lpTokenTargetAddress)); require( lpToken.initialize(lpTokenName, lpTokenSymbol), "could not init lpToken clone" );
88,247
8
// Internal visibility modifier doesn't let external calls. This modifiers lets to call functions inside the same contract, from contract, externally.
{ require(msg.sender == address(this), "Caller must be the contract itself."); _; }
{ require(msg.sender == address(this), "Caller must be the contract itself."); _; }
13,228
103
// CityToken with Governance.
contract CityToken is ERC20, Ownable { /** * World population was estimated to have reached 7,800,000,000 people as of March 2020. */ uint256 public constant INITIAL_SUPPLY = 7800000000 * 10**18; /** * @dev Constructor that gives msg.sender all of existing tokens. */ constructor () public ERC20("CITY.finance", "CITY") { _mint(msg.sender, INITIAL_SUPPLY); } /** * @notice Creates `_amount` token to `_to`. Must only be called by the owner (TravelAgency). */ function mint(address _to, uint256 _amount) public onlyOwner { _mint(_to, _amount); } }
contract CityToken is ERC20, Ownable { /** * World population was estimated to have reached 7,800,000,000 people as of March 2020. */ uint256 public constant INITIAL_SUPPLY = 7800000000 * 10**18; /** * @dev Constructor that gives msg.sender all of existing tokens. */ constructor () public ERC20("CITY.finance", "CITY") { _mint(msg.sender, INITIAL_SUPPLY); } /** * @notice Creates `_amount` token to `_to`. Must only be called by the owner (TravelAgency). */ function mint(address _to, uint256 _amount) public onlyOwner { _mint(_to, _amount); } }
9,306
122
// Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately. _Available since v4.2._ /
function recover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, r, vs); _throwError(error); return recovered; }
function recover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, r, vs); _throwError(error); return recovered; }
14,981
6
// We add a hard cap to prevent raising more funds than deemed reasonable.
uint256 public fundingCap; uint256 public feePercentage;
uint256 public fundingCap; uint256 public feePercentage;
47,320
54
// 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);
function isApprovedForAll(address owner, address operator) external view returns (bool);
52,316
66
// Dont allow deposits greater than current balance
Token = IERC20(tokenaddress); require(Token.balanceOf(msg.sender) >= amount,'Exceeds your current wallet balance');
Token = IERC20(tokenaddress); require(Token.balanceOf(msg.sender) >= amount,'Exceeds your current wallet balance');
39,467
156
// Set revenue controller /
function setRevenueController(address controller) external;
function setRevenueController(address controller) external;
20,267
103
// Subtract and store the updated total supply.
sstore(_TOTAL_SUPPLY_SLOT, sub(sload(_TOTAL_SUPPLY_SLOT), amount))
sstore(_TOTAL_SUPPLY_SLOT, sub(sload(_TOTAL_SUPPLY_SLOT), amount))
20,348
142
// give rewards
uint256 reward = _earned( msg.sender, accountBalance, rewardPerToken_, rewards[msg.sender] ); if (reward > 0) { rewards[msg.sender] = 0; }
uint256 reward = _earned( msg.sender, accountBalance, rewardPerToken_, rewards[msg.sender] ); if (reward > 0) { rewards[msg.sender] = 0; }
44,233
5
// Add a function to add contestant
function addContestant (string memory _name) private { contestantsCount ++; contestants[contestantsCount] = Contestant(contestantsCount, _name, 0); }
function addContestant (string memory _name) private { contestantsCount ++; contestants[contestantsCount] = Contestant(contestantsCount, _name, 0); }
16,411
11
// Grants spender ability to spend on owner's behalf.Handle's tokens that return true or null. If other value returned, reverts. _tokenThe address of the ERC20 token_spenderThe address to approve for transfer_quantity The amount of tokens to approve spender for /
function approve( address _token, address _spender, uint256 _quantity ) internal
function approve( address _token, address _spender, uint256 _quantity ) internal
17,919
7
// Define a variable called 'sku' for Stock Keeping Unit (SKU)
uint sku;
uint sku;
29,715
306
// check price has moved enough
int24 tick = getTick(); int24 tickMove = tick > lastTick ? tick - lastTick : lastTick - tick; if (tickMove < minTickMove) { return false; }
int24 tick = getTick(); int24 tickMove = tick > lastTick ? tick - lastTick : lastTick - tick; if (tickMove < minTickMove) { return false; }
38,665
210
// Address for WETH
address public weth;
address public weth;
7,656
18
// Deduct price-band from a given amount of SDR. _sdrAmount The amount of SDR. _sgrTotal The total amount of SGR. _alpha The alpha-value of the current interval. _beta The beta-value of the current interval.return The amount of SDR minus the price-band. /
function buy(uint256 _sdrAmount, uint256 _sgrTotal, uint256 _alpha, uint256 _beta) external pure returns (uint256);
function buy(uint256 _sdrAmount, uint256 _sgrTotal, uint256 _alpha, uint256 _beta) external pure returns (uint256);
36,664
4
//
event TransferSingle( address indexed operator, address indexed from, address indexed to, uint256 id, uint256 amount ); event TransferBatch(
event TransferSingle( address indexed operator, address indexed from, address indexed to, uint256 id, uint256 amount ); event TransferBatch(
2,757
31
// Function that allows the municipality to remove a specific station from the list stations
function removeCoordinatesStation (int _latitude, int _longitude) public { // Only the municipality has the power to remove a station require(msg.sender == owner); for (uint i=0; i < stations.length; i++) { Station memory myStation = stations[i]; if (myStation.latitude == _latitude && myStation.longitude == _longitude) { delete stations[i]; break; } } }
function removeCoordinatesStation (int _latitude, int _longitude) public { // Only the municipality has the power to remove a station require(msg.sender == owner); for (uint i=0; i < stations.length; i++) { Station memory myStation = stations[i]; if (myStation.latitude == _latitude && myStation.longitude == _longitude) { delete stations[i]; break; } } }
23,347
8
// default to sending no callvalue to the L1
0, _from, counterpartGateway, _outboundCalldata );
0, _from, counterpartGateway, _outboundCalldata );
34,282
0
// |/ Query if an address is a game manager/ _manager Address to query/return True if `_manager` is a game manager,False otherwise
function isGameManager(address _manager) external view returns (bool) { return s.gameManagers[_manager].limit != 0; }
function isGameManager(address _manager) external view returns (bool) { return s.gameManagers[_manager].limit != 0; }
23,274
9
// |/
* @dev See {ERC1155-_beforeTokenTransfer}. */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual override { require(!paused(), "token transfer paused"); super._beforeTokenTransfer(operator, from, to, ids, amounts, data); if (from == address(0)) { for (uint256 i = 0; i < ids.length; ++i) { _totalSupply[ids[i]] += amounts[i]; } } if (to == address(0)) { for (uint256 i = 0; i < ids.length; ++i) { _totalSupply[ids[i]] -= amounts[i]; } } }
* @dev See {ERC1155-_beforeTokenTransfer}. */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual override { require(!paused(), "token transfer paused"); super._beforeTokenTransfer(operator, from, to, ids, amounts, data); if (from == address(0)) { for (uint256 i = 0; i < ids.length; ++i) { _totalSupply[ids[i]] += amounts[i]; } } if (to == address(0)) { for (uint256 i = 0; i < ids.length; ++i) { _totalSupply[ids[i]] -= amounts[i]; } } }
3,220
15
// we check that the article exists
require(_id > 0 && _id <= articleCounter);
require(_id > 0 && _id <= articleCounter);
38,062
5
// Swaps tokens for ETH using Uniswap.Tokens are first approved for the Uniswap router before swapping.The contract balance should have enough tokens to perform the swap. amount The amount of tokens to swap. /
function swapTokensForEth(uint256 amount) private { require(swappingEnabled, "Swapping is not enabled"); address[] memory path = new address[](2); path[0] = address(this); path[1] = IUniswapV2Router02(uniswapRouter).WETH(); _approve(address(this), uniswapRouter, amount); IUniswapV2Router02(uniswapRouter).swapExactTokensForETHSupportingFeeOnTransferTokens( amount, 0, path, address(this), block.timestamp ); }
function swapTokensForEth(uint256 amount) private { require(swappingEnabled, "Swapping is not enabled"); address[] memory path = new address[](2); path[0] = address(this); path[1] = IUniswapV2Router02(uniswapRouter).WETH(); _approve(address(this), uniswapRouter, amount); IUniswapV2Router02(uniswapRouter).swapExactTokensForETHSupportingFeeOnTransferTokens( amount, 0, path, address(this), block.timestamp ); }
21,132
90
// todo add last ocsp check timestamp todo add function to run post ocsp callback optional
struct Certificate { // uint id; string commonName; PublicKey publicKey; bytes signature; byte sigAlgorithm; // 05 = sha1, // 0b = sha256 bytes20 parentId; bytes bodyHash; }
struct Certificate { // uint id; string commonName; PublicKey publicKey; bytes signature; byte sigAlgorithm; // 05 = sha1, // 0b = sha256 bytes20 parentId; bytes bodyHash; }
48,037
2
// Checks time bounds for contract
abstract contract Timeboundable { uint256 public immutable start; uint256 public immutable finish; /// @param _start The block timestamp to start from (in secs). Use 0 for unbounded start. /// @param _finish The block timestamp to finish in (in secs). Use 0 for unbounded finish. constructor(uint256 _start, uint256 _finish) internal { require( (_start != 0) || (_finish != 0), "Timebound: either start or finish must be nonzero" ); require( (_finish == 0) || (_finish > _start), "Timebound: finish must be zero or greater than start" ); uint256 s = _start; if (s == 0) { s = block.timestamp; } uint256 f = _finish; if (f == 0) { f = uint256(-1); } start = s; finish = f; } /// Checks if timebounds are satisfied modifier inTimeBounds() { require(block.timestamp >= start, "Timeboundable: Not started yet"); require(block.timestamp <= finish, "Timeboundable: Already finished"); _; } }
abstract contract Timeboundable { uint256 public immutable start; uint256 public immutable finish; /// @param _start The block timestamp to start from (in secs). Use 0 for unbounded start. /// @param _finish The block timestamp to finish in (in secs). Use 0 for unbounded finish. constructor(uint256 _start, uint256 _finish) internal { require( (_start != 0) || (_finish != 0), "Timebound: either start or finish must be nonzero" ); require( (_finish == 0) || (_finish > _start), "Timebound: finish must be zero or greater than start" ); uint256 s = _start; if (s == 0) { s = block.timestamp; } uint256 f = _finish; if (f == 0) { f = uint256(-1); } start = s; finish = f; } /// Checks if timebounds are satisfied modifier inTimeBounds() { require(block.timestamp >= start, "Timeboundable: Not started yet"); require(block.timestamp <= finish, "Timeboundable: Already finished"); _; } }
25,174
118
// Migrates the stake of msg.sender from this staking contract to a new approved staking contract./_newStakingContract IMigratableStakingContract The new staking contract which supports stake migration./_amount uint256 The amount of tokens to migrate.
function migrateStakedTokens(IMigratableStakingContract _newStakingContract, uint256 _amount) external; event Staked(address indexed stakeOwner, uint256 amount, uint256 totalStakedAmount); event Unstaked(address indexed stakeOwner, uint256 amount, uint256 totalStakedAmount); event Withdrew(address indexed stakeOwner, uint256 amount, uint256 totalStakedAmount); event Restaked(address indexed stakeOwner, uint256 amount, uint256 totalStakedAmount); event MigratedStake(address indexed stakeOwner, uint256 amount, uint256 totalStakedAmount);
function migrateStakedTokens(IMigratableStakingContract _newStakingContract, uint256 _amount) external; event Staked(address indexed stakeOwner, uint256 amount, uint256 totalStakedAmount); event Unstaked(address indexed stakeOwner, uint256 amount, uint256 totalStakedAmount); event Withdrew(address indexed stakeOwner, uint256 amount, uint256 totalStakedAmount); event Restaked(address indexed stakeOwner, uint256 amount, uint256 totalStakedAmount); event MigratedStake(address indexed stakeOwner, uint256 amount, uint256 totalStakedAmount);
43,035
7
// Function to change the Manager contract that a strategy interacts with./ This function can only be called by the owner of the strategy contract./newManager Address of the new Manager contract the strategy should interact with.
function changeManager(address newManager) external;
function changeManager(address newManager) external;
22,468
35
// Returns the downcasted int232 from int256, reverting onoverflow (when the input is less than smallest int232 orgreater than largest int232). Counterpart to Solidity's `int232` operator. Requirements: - input must fit into 232 bits _Available since v4.7._ /
function toInt232(int256 value) internal pure returns (int232 downcasted) { downcasted = int232(value); require(downcasted == value, "SafeCast: value doesn't fit in 232 bits"); }
function toInt232(int256 value) internal pure returns (int232 downcasted) { downcasted = int232(value); require(downcasted == value, "SafeCast: value doesn't fit in 232 bits"); }
30,753
73
// Info for creating new bonds
struct Terms { uint controlVariable; // scaling variable for price uint vestingTerm; // in blocks uint minimumPrice; // vs principal value uint maxPayout; // in thousandths of a %. i.e. 500 = 0.5% uint maxDebt; // payout token decimal debt ratio, max % total supply created as debt }
struct Terms { uint controlVariable; // scaling variable for price uint vestingTerm; // in blocks uint minimumPrice; // vs principal value uint maxPayout; // in thousandths of a %. i.e. 500 = 0.5% uint maxDebt; // payout token decimal debt ratio, max % total supply created as debt }
3,124
217
// Get most recent user Point to block
uint256 userEpoch = _findUserBlockEpoch(_owner, _blockNumber); if(userEpoch == 0){ return 0; }
uint256 userEpoch = _findUserBlockEpoch(_owner, _blockNumber); if(userEpoch == 0){ return 0; }
22,198
143
// uncomment in production
require(now > gameEnd); require(numElements > 0); require(randomNumber > 0);
require(now > gameEnd); require(numElements > 0); require(randomNumber > 0);
49,554
20
// Determines whether a value is greater than another. a the first value b the second valuereturn isTrue whether a is greater than b /
function isGreaterThan(uint256 a, uint256 b) public pure returns (bool isTrue) { isTrue = a > b; }
function isGreaterThan(uint256 a, uint256 b) public pure returns (bool isTrue) { isTrue = a > b; }
66,227
12
// Allows tenant to pay the required deposit for a property/_propertyId ID of property./payable function that reverts if msg.value != Deposit.depositAmount
function payDeposit(uint _propertyId) external payable nonReentrant { require(depositByProperty[_propertyId].agreementState == AgreementState.Created, "Agreement is either active or ended, cannot accept deposit payment"); require(landlord != msg.sender, "Deposit cannot be paid by landlord"); require(depositByProperty[_propertyId].depositAmount == msg.value, "Please pay exact deposit amount"); tenantByProperty[_propertyId] = msg.sender; depositByProperty[_propertyId].tenant = payable(msg.sender); depositByProperty[_propertyId].agreementState = AgreementState.Active; (bool sent, ) = address(this).call{ value: msg.value }(""); require(sent, "Deposit payment failed."); emit DepositPaid(depositByProperty[_propertyId].tenant, _propertyId, depositByProperty[_propertyId].depositAmount, uint(depositByProperty[_propertyId].agreementState)); }
function payDeposit(uint _propertyId) external payable nonReentrant { require(depositByProperty[_propertyId].agreementState == AgreementState.Created, "Agreement is either active or ended, cannot accept deposit payment"); require(landlord != msg.sender, "Deposit cannot be paid by landlord"); require(depositByProperty[_propertyId].depositAmount == msg.value, "Please pay exact deposit amount"); tenantByProperty[_propertyId] = msg.sender; depositByProperty[_propertyId].tenant = payable(msg.sender); depositByProperty[_propertyId].agreementState = AgreementState.Active; (bool sent, ) = address(this).call{ value: msg.value }(""); require(sent, "Deposit payment failed."); emit DepositPaid(depositByProperty[_propertyId].tenant, _propertyId, depositByProperty[_propertyId].depositAmount, uint(depositByProperty[_propertyId].agreementState)); }
15,182
4
// impersonate the account
vm.startPrank(who); uint256 balanceBefore = weth.balanceOf(who); emit log_uint(balanceBefore);
vm.startPrank(who); uint256 balanceBefore = weth.balanceOf(who); emit log_uint(balanceBefore);
2,358
41
// Refund any payment amount that would bring up over the raising amount
if (totalAmount + amount > raisingAmount) { paymentToken.safeTransfer(user, (totalAmount + amount) - raisingAmount); amount = raisingAmount - totalAmount; }
if (totalAmount + amount > raisingAmount) { paymentToken.safeTransfer(user, (totalAmount + amount) - raisingAmount); amount = raisingAmount - totalAmount; }
34,899
48
// Function to check the amount of tokens that an owner allowed to a spender._ownerthe address which owns the funds_spenderthe address which will spend the funds returnthe amount of tokens still avaible for the spender/
function allowance(address _owner, address _spender) constant returns (uint) { return allowed[_owner][_spender]; }
function allowance(address _owner, address _spender) constant returns (uint) { return allowed[_owner][_spender]; }
1,528
46
// fallback function DO NOT OVERRIDENote that other contracts will transfer funds with a base gas stipendof 2300, which is not enough to call buyTokens. Consider callingbuyTokens directly when purchasing tokens from a contract. /
fallback() external payable { buyTokens(msg.sender); }
fallback() external payable { buyTokens(msg.sender); }
899
10
// adapterBalances List of AdapterBalance structs. nonZeroAdapterBalancesNumber Number of non-empty AdapterBalance structs. nonZeroTokenBalancesNumbers List of non-zero TokenBalance structs numbers.return Non-empty AdapterBalance structs with non-zero TokenBalance structs. /
function getNonZeroAdapterBalances( AdapterBalance[] memory adapterBalances, uint256 nonZeroAdapterBalancesNumber, uint256[] memory nonZeroTokenBalancesNumbers
function getNonZeroAdapterBalances( AdapterBalance[] memory adapterBalances, uint256 nonZeroAdapterBalancesNumber, uint256[] memory nonZeroTokenBalancesNumbers
40,872
189
// Transfer a Kitty owned by another address, for which the calling address/has previously been granted transfer approval by the owner./_from The address that owns the Kitty to be transfered./_to The address that should take ownership of the Kitty. Can be any address,/including the caller./_tokenId The ID of the Kitty to be transferred./Required for ERC-721 compliance.
function transferFrom( address _from, address _to, uint256 _tokenId ) external whenNotPaused
function transferFrom( address _from, address _to, uint256 _tokenId ) external whenNotPaused
73,238
9
// Percorre o array de músicos
if (musicians[i].music[cod_music] != 0) {
if (musicians[i].music[cod_music] != 0) {
47,761
10
// Maintain a list of historical collateralised SLOT owners
if (!isCollateralisedOwner[_memberId][_user]) { collateralisedSLOTOwners[_memberId].push(_user); isCollateralisedOwner[_memberId][_user] = true; emit CollateralisedOwnerAddedToKnot(_memberId, _user); }
if (!isCollateralisedOwner[_memberId][_user]) { collateralisedSLOTOwners[_memberId].push(_user); isCollateralisedOwner[_memberId][_user] = true; emit CollateralisedOwnerAddedToKnot(_memberId, _user); }
17,077
159
// Returns the total amount of tokens burned in the contract. /
function _totalBurned() internal view returns (uint256) { unchecked { return _totalMinted() - _allTokens.length; } }
function _totalBurned() internal view returns (uint256) { unchecked { return _totalMinted() - _allTokens.length; } }
30,718
151
// Ensure that we are not staking more than the maximum
require(balanceOf(_from).add(_value) <= MAXIMUM_STAKE, "Value greater than maximum stake"); token.safeTransferFrom(_from, this, _value); deposits[_from].push(Deposit(block.number, _value)); emit NewDeposit(_from, _value); return true;
require(balanceOf(_from).add(_value) <= MAXIMUM_STAKE, "Value greater than maximum stake"); token.safeTransferFrom(_from, this, _value); deposits[_from].push(Deposit(block.number, _value)); emit NewDeposit(_from, _value); return true;
30,065
173
// Set block allow transfer onCan only be called by the current owner. /
function setAllowTransferOn(uint256 allowTransferOn_) external onlyOwner{ require(block.number < allowTransferOn && allowTransferOn_ < allowTransferOn, "SoneToken: invalid new allowTransferOn"); allowTransferOn = allowTransferOn_; }
function setAllowTransferOn(uint256 allowTransferOn_) external onlyOwner{ require(block.number < allowTransferOn && allowTransferOn_ < allowTransferOn, "SoneToken: invalid new allowTransferOn"); allowTransferOn = allowTransferOn_; }
63,157
2
// MintedCrowdsale Extension of Crowdsale contract whose tokens are minted in each purchase.Token ownership should be transferred to MintedCrowdsale for minting. /
contract MintedCrowdsale is Crowdsale { /** * @dev Overrides delivery by minting tokens upon purchase. * @param beneficiary Token purchaser * @param tokenAmount Number of tokens to be minted */ function _deliverTokens(address beneficiary, uint256 tokenAmount) internal { // Potentially dangerous assumption about the type of the token. require( ERC20Mintable(address(token())).mint(beneficiary, tokenAmount), "MintedCrowdsale: minting failed" ); } }
contract MintedCrowdsale is Crowdsale { /** * @dev Overrides delivery by minting tokens upon purchase. * @param beneficiary Token purchaser * @param tokenAmount Number of tokens to be minted */ function _deliverTokens(address beneficiary, uint256 tokenAmount) internal { // Potentially dangerous assumption about the type of the token. require( ERC20Mintable(address(token())).mint(beneficiary, tokenAmount), "MintedCrowdsale: minting failed" ); } }
3,773
6
// Retrieves the maximum number of tokens claimed for free by the specified recipient./recipient The address of the recipient to query for the maximum claimed free tokens./ return The maximum number of tokens claimed for free by the recipient.
function totalClaimed(address recipient) external view returns (uint256);
function totalClaimed(address recipient) external view returns (uint256);
1,622
29
// GenWaves contract /
contract Waves is ERC721A, Ownable, Pausable { uint256 public PRICE = 0.04269 ether; uint256 public PURCHASE_LIMIT = 1; uint256 public MAX_SUPPLY = 222; uint16[9] rarities; string[9][4] traitValues; mapping(uint256 => uint256) private tokenSeed; mapping(address => uint256) public whitelist; bool publicSale = false; error OriginIsNotEOA(); error NotOnWhitelist(); error ExceedsPurchaseLimit(); error SoldOut(); error WrongAmount(); error TokenNotFound(); constructor() ERC721A("Gen Waves", "WVS") { //Traits rarities (normal distribution) rarities = [ 0, 75, 125, 175, 225, 175, 125, 75, 25 ]; //Grid size traitValues[0] = ['0', '18', '20', '22', '24', '26', '28', '30', '32']; //Ellipse size traitValues[1] = ['0', '5', '7', '9', '11', '13', '15', '17', '19']; //Wave speed traitValues[2] = ['0.00', '0.005', '0.007', '0.008' , '0.009', '0.01', '0.011', '0.012', '0.014']; //Variation traitValues[3] = ['0', '180', '100', '69' , '45', '45', '69', '100', '360']; } /** * @dev Sets the 'paused' state to true */ function pause() external onlyOwner { _pause(); } /** * @dev Sets the 'paused' state to false */ function unpause() external onlyOwner { _unpause(); } /** * @dev Sets the 'publicSale' state to true */ function openPublicSale() external onlyOwner { publicSale = true; } /** * @dev Fills the whitelist array with the addresses passed as arguments */ function fillWhiteList(address[] calldata _users) external onlyOwner { for(uint256 i = 0; i < _users.length; i++){ address user = _users[i]; whitelist[user] = PURCHASE_LIMIT; } } /** * @dev Mints `numberOfTokens` new tokens */ function mint() external payable whenNotPaused { uint256 supply = _totalMinted(); if (tx.origin != msg.sender) revert OriginIsNotEOA(); if (!publicSale) { if (whitelist[msg.sender] < PURCHASE_LIMIT) revert NotOnWhitelist(); } if (supply + PURCHASE_LIMIT > MAX_SUPPLY) revert SoldOut(); if (msg.value < PRICE * PURCHASE_LIMIT) revert WrongAmount(); tokenSeed[supply] = uint256( keccak256(abi.encodePacked(block.timestamp, msg.sender, supply)) ); _safeMint(msg.sender, PURCHASE_LIMIT); if (whitelist[msg.sender] > 0) whitelist[msg.sender] -= PURCHASE_LIMIT; } /** * @dev Returns the base64-encoded metadata for the given tokenId */ function tokenURI(uint256 tokenId) public view virtual override returns(string memory) { if(!_exists(tokenId)) revert TokenNotFound(); (string memory image, string memory svg, string memory properties) = getTraits(tokenSeed[tokenId]); return string( abi.encodePacked( "data:application/json;base64,", Base64.encode( abi.encodePacked( '{"name":"Gen Wave #', ToString.toString(tokenId), '", "description": "Gen Waves is a fully on-chain & interactive piece of art that offers a unique and immersive experience for collectors.", "traits": [', properties, '], "image": "data:image/svg+xml;base64,', image, '", "animation_url":"data:text/html;base64,', svg, '"}' ) ) ) ); } /** * @dev Generates a random combination of traits and its corresponding image, animation and metadata */ function getTraits(uint256 seed) private view returns(string memory image, string memory svg, string memory properties) { uint16[5] memory randomInputs = expand(seed, 5); uint16[4] memory traits; //Base color string memory baseColor = ToString.toString(randomInputs[0] % 360); //Grid width traits[0] = getRandomIndex(rarities, randomInputs[1]); //Ellipse size traits[1] = getRandomIndex(rarities, randomInputs[2]); //Wave speed traits[2] = getRandomIndex(rarities, randomInputs[3]); //Color variation traits[3] = getRandomIndex(rarities, randomInputs[4]); //Render image string memory _image = ImageGenerator.createWave(baseColor, traitValues[1][traits[1]],traitValues[3][traits[3]]); image = Base64.encode(abi.encodePacked(_image)); //Render animation string memory _svg = CanvasGenerator.generateCustomCanvas(baseColor, traitValues[0][traits[0]],traitValues[1][traits[1]],traitValues[2][traits[2]],traitValues[3][traits[3]]); svg = Base64.encode(abi.encodePacked(_svg)); //Pack properties (put 1 after the last property for JSON to be formed correctly) bytes memory _properties = abi.encodePacked( packMetaData("Base Color", baseColor, 0), packMetaData("Grid Size", _getTrait(0, traits[0]), 0), packMetaData("Ellipse Size", _getTrait(1, traits[1]), 0), packMetaData("Wave Speed", _getTrait(2, traits[2]), 0), packMetaData("Color Variation", _getTrait(3, traits[3]), 1) ); properties = string(abi.encodePacked(_properties)); return (image, svg, properties); } /** * @dev Generates a random number for indexing an array position, credits to Anonymice */ function getRandomIndex(uint16[9] memory attributeRarities, uint256 randomNumber) private pure returns (uint16 index) { //1000 is the sum of the rarities uint16 random10k = uint16(randomNumber % 1000); uint16 lowerBound; for (uint16 i = 1; i <= 9; i++) { uint16 percentage = attributeRarities[i]; if (random10k < percentage + lowerBound && random10k >= lowerBound) { return i; } lowerBound = lowerBound + percentage; } revert(); } /** * @dev Generates an array of random numbers based on a random number */ function expand(uint256 _randomNumber, uint256 n) private pure returns(uint16[5] memory expandedValues) { for (uint256 i = 0; i < n; i++) { expandedValues[i] = bytes2uint(keccak256(abi.encode(_randomNumber, i))); } return expandedValues; } /** * @dev Converts bytes32 to uint16 */ function bytes2uint(bytes32 _a) private pure returns (uint16) { return uint16(uint256(_a)); } /** * @dev Gets the attribute name for the properties of the token by its index */ function _getTrait(uint256 _trait, uint256 index) private view returns (string memory) { return traitValues[_trait][index]; } /** * @dev Bundle metadata so it follows the standard */ function packMetaData(string memory name, string memory svg, uint256 last) private pure returns (bytes memory) { string memory comma = ","; if (last > 0) comma = ""; return abi.encodePacked( '{"trait_type": "', name, '", "value": "', svg, '"}', comma ); } /** * @dev Transfers all the contract balance to the owner address */ function withdraw() public payable onlyOwner { (bool os, ) = payable(owner()).call{value: address(this).balance}(""); require(os); } }
contract Waves is ERC721A, Ownable, Pausable { uint256 public PRICE = 0.04269 ether; uint256 public PURCHASE_LIMIT = 1; uint256 public MAX_SUPPLY = 222; uint16[9] rarities; string[9][4] traitValues; mapping(uint256 => uint256) private tokenSeed; mapping(address => uint256) public whitelist; bool publicSale = false; error OriginIsNotEOA(); error NotOnWhitelist(); error ExceedsPurchaseLimit(); error SoldOut(); error WrongAmount(); error TokenNotFound(); constructor() ERC721A("Gen Waves", "WVS") { //Traits rarities (normal distribution) rarities = [ 0, 75, 125, 175, 225, 175, 125, 75, 25 ]; //Grid size traitValues[0] = ['0', '18', '20', '22', '24', '26', '28', '30', '32']; //Ellipse size traitValues[1] = ['0', '5', '7', '9', '11', '13', '15', '17', '19']; //Wave speed traitValues[2] = ['0.00', '0.005', '0.007', '0.008' , '0.009', '0.01', '0.011', '0.012', '0.014']; //Variation traitValues[3] = ['0', '180', '100', '69' , '45', '45', '69', '100', '360']; } /** * @dev Sets the 'paused' state to true */ function pause() external onlyOwner { _pause(); } /** * @dev Sets the 'paused' state to false */ function unpause() external onlyOwner { _unpause(); } /** * @dev Sets the 'publicSale' state to true */ function openPublicSale() external onlyOwner { publicSale = true; } /** * @dev Fills the whitelist array with the addresses passed as arguments */ function fillWhiteList(address[] calldata _users) external onlyOwner { for(uint256 i = 0; i < _users.length; i++){ address user = _users[i]; whitelist[user] = PURCHASE_LIMIT; } } /** * @dev Mints `numberOfTokens` new tokens */ function mint() external payable whenNotPaused { uint256 supply = _totalMinted(); if (tx.origin != msg.sender) revert OriginIsNotEOA(); if (!publicSale) { if (whitelist[msg.sender] < PURCHASE_LIMIT) revert NotOnWhitelist(); } if (supply + PURCHASE_LIMIT > MAX_SUPPLY) revert SoldOut(); if (msg.value < PRICE * PURCHASE_LIMIT) revert WrongAmount(); tokenSeed[supply] = uint256( keccak256(abi.encodePacked(block.timestamp, msg.sender, supply)) ); _safeMint(msg.sender, PURCHASE_LIMIT); if (whitelist[msg.sender] > 0) whitelist[msg.sender] -= PURCHASE_LIMIT; } /** * @dev Returns the base64-encoded metadata for the given tokenId */ function tokenURI(uint256 tokenId) public view virtual override returns(string memory) { if(!_exists(tokenId)) revert TokenNotFound(); (string memory image, string memory svg, string memory properties) = getTraits(tokenSeed[tokenId]); return string( abi.encodePacked( "data:application/json;base64,", Base64.encode( abi.encodePacked( '{"name":"Gen Wave #', ToString.toString(tokenId), '", "description": "Gen Waves is a fully on-chain & interactive piece of art that offers a unique and immersive experience for collectors.", "traits": [', properties, '], "image": "data:image/svg+xml;base64,', image, '", "animation_url":"data:text/html;base64,', svg, '"}' ) ) ) ); } /** * @dev Generates a random combination of traits and its corresponding image, animation and metadata */ function getTraits(uint256 seed) private view returns(string memory image, string memory svg, string memory properties) { uint16[5] memory randomInputs = expand(seed, 5); uint16[4] memory traits; //Base color string memory baseColor = ToString.toString(randomInputs[0] % 360); //Grid width traits[0] = getRandomIndex(rarities, randomInputs[1]); //Ellipse size traits[1] = getRandomIndex(rarities, randomInputs[2]); //Wave speed traits[2] = getRandomIndex(rarities, randomInputs[3]); //Color variation traits[3] = getRandomIndex(rarities, randomInputs[4]); //Render image string memory _image = ImageGenerator.createWave(baseColor, traitValues[1][traits[1]],traitValues[3][traits[3]]); image = Base64.encode(abi.encodePacked(_image)); //Render animation string memory _svg = CanvasGenerator.generateCustomCanvas(baseColor, traitValues[0][traits[0]],traitValues[1][traits[1]],traitValues[2][traits[2]],traitValues[3][traits[3]]); svg = Base64.encode(abi.encodePacked(_svg)); //Pack properties (put 1 after the last property for JSON to be formed correctly) bytes memory _properties = abi.encodePacked( packMetaData("Base Color", baseColor, 0), packMetaData("Grid Size", _getTrait(0, traits[0]), 0), packMetaData("Ellipse Size", _getTrait(1, traits[1]), 0), packMetaData("Wave Speed", _getTrait(2, traits[2]), 0), packMetaData("Color Variation", _getTrait(3, traits[3]), 1) ); properties = string(abi.encodePacked(_properties)); return (image, svg, properties); } /** * @dev Generates a random number for indexing an array position, credits to Anonymice */ function getRandomIndex(uint16[9] memory attributeRarities, uint256 randomNumber) private pure returns (uint16 index) { //1000 is the sum of the rarities uint16 random10k = uint16(randomNumber % 1000); uint16 lowerBound; for (uint16 i = 1; i <= 9; i++) { uint16 percentage = attributeRarities[i]; if (random10k < percentage + lowerBound && random10k >= lowerBound) { return i; } lowerBound = lowerBound + percentage; } revert(); } /** * @dev Generates an array of random numbers based on a random number */ function expand(uint256 _randomNumber, uint256 n) private pure returns(uint16[5] memory expandedValues) { for (uint256 i = 0; i < n; i++) { expandedValues[i] = bytes2uint(keccak256(abi.encode(_randomNumber, i))); } return expandedValues; } /** * @dev Converts bytes32 to uint16 */ function bytes2uint(bytes32 _a) private pure returns (uint16) { return uint16(uint256(_a)); } /** * @dev Gets the attribute name for the properties of the token by its index */ function _getTrait(uint256 _trait, uint256 index) private view returns (string memory) { return traitValues[_trait][index]; } /** * @dev Bundle metadata so it follows the standard */ function packMetaData(string memory name, string memory svg, uint256 last) private pure returns (bytes memory) { string memory comma = ","; if (last > 0) comma = ""; return abi.encodePacked( '{"trait_type": "', name, '", "value": "', svg, '"}', comma ); } /** * @dev Transfers all the contract balance to the owner address */ function withdraw() public payable onlyOwner { (bool os, ) = payable(owner()).call{value: address(this).balance}(""); require(os); } }
23,884
80
// Due to final_price floor rounding, the number of assigned tokens may be higher than expected. Therefore, the number of remaining unassigned auction tokens may be smaller than the number of tokens needed for the last claimTokens call
uint auction_tokens_balance = token.balanceOf(address(this)); if (num > auction_tokens_balance) { num = auction_tokens_balance; }
uint auction_tokens_balance = token.balanceOf(address(this)); if (num > auction_tokens_balance) { num = auction_tokens_balance; }
40,688
8
// remove address from blacklist
function _removeBlacklist(address account) internal virtual { _blacklist[account] = false; emit Unblacklisted(account); }
function _removeBlacklist(address account) internal virtual { _blacklist[account] = false; emit Unblacklisted(account); }
22,087
30
// Standard ERC20 tokenImplementation of the basic standard token.Based on code by FirstBlood:/
contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); 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; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { require((_value == 0 ) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint 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; } }
contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); 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; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { require((_value == 0 ) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint 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; } }
71,668
29
// Add decimal places to format an 18 decimal mantissa
uint256 priceMantissa = uint256(price).mul(10**(MANTISSA_DECIMALS.sub(decimals))); return priceMantissa;
uint256 priceMantissa = uint256(price).mul(10**(MANTISSA_DECIMALS.sub(decimals))); return priceMantissa;
4,086
41
// Revert if _opPokeData is not challengeable.
if (!opPokeDataChallengeable) { revert NoOpPokeToChallenge(); }
if (!opPokeDataChallengeable) { revert NoOpPokeToChallenge(); }
20,765
67
// Move bet into 'processed' state already.
bet.amount = 0;
bet.amount = 0;
13,487
2
// --- ITokenVaultFactory
IWittyPixelsTokenVault tokenVaultPrototype; uint256 totalTokenVaults; mapping (uint256 => IWittyPixelsTokenVault) vaults;
IWittyPixelsTokenVault tokenVaultPrototype; uint256 totalTokenVaults; mapping (uint256 => IWittyPixelsTokenVault) vaults;
14,151
3
// Function to mint an NFT with a delayed reveal
function mintNFT(string memory _name, string memory _description, uint256 _price, string memory _placeholderImage, uint256 _revealDate, string memory _image) public returns (uint256) {
function mintNFT(string memory _name, string memory _description, uint256 _price, string memory _placeholderImage, uint256 _revealDate, string memory _image) public returns (uint256) {
7,773
409
// set new currency manager
TransferControllerManager oldTransferControllerManager = transferControllerManager; transferControllerManager = newTransferControllerManager;
TransferControllerManager oldTransferControllerManager = transferControllerManager; transferControllerManager = newTransferControllerManager;
35,685
88
// Collect any funds of the main token that are in the contract, including those that are sent accidentally to it. This does not include user funds that were deposited through staking.
function withdrawRewardsFunds() external onlyOwner { uint256 amountToTransfer = rewardsFunds; require(amountToTransfer > 0, "There are no funds to withdraw"); rewardsFunds = 0; mainToken.safeTransfer(owner(), amountToTransfer); }
function withdrawRewardsFunds() external onlyOwner { uint256 amountToTransfer = rewardsFunds; require(amountToTransfer > 0, "There are no funds to withdraw"); rewardsFunds = 0; mainToken.safeTransfer(owner(), amountToTransfer); }
19,423
260
// Converts an amount of Hop LP into their estimated underlying value. Uses get_virtual_price which is less suceptible to manipulation. But is also less accurate to how much could be withdrawn. _hopLpAmount Amount of Hop LP to convert.return The estimated value in the underlying. /
function _hopLpToUnderlying(uint256 _hopLpAmount) internal view returns (uint256) { return (_hopLpAmount / decimalMultiplier).scaledMul(curveHopPool.get_virtual_price()); }
function _hopLpToUnderlying(uint256 _hopLpAmount) internal view returns (uint256) { return (_hopLpAmount / decimalMultiplier).scaledMul(curveHopPool.get_virtual_price()); }
34,390
575
// Tenebrae/`Tenebrae` coordinates Global Settlement. This is an involved, stateful process that takes/ place over nine steps.// Uses End.sol from DSS (MakerDAO) / GlobalSettlement SafeEngine.sol from GEB (Reflexer Labs) as a blueprint/ Changes from End.sol / GlobalSettlement.sol:/ - only WAD precision is used (no RAD and RAY)/ - uses a method signature based authentication scheme/ - supports ERC1155, ERC721 style assets by TokenId// / First we freeze the system and lock the prices for each vault and TokenId.// 1. `lock()`:/ - freezes user entrypoints/ - cancels debtAuction/surplusAuction auctions/ - starts cooldown period// We must process some system state before it is
contract Tenebrae is Guarded, ITenebrae {
contract Tenebrae is Guarded, ITenebrae {
26,225
0
// Construct a new Chainlink Oracle med_ The address of the Medianizer link_ The LINK token address oracle_ The Chainlink Oracle address /
constructor(MedianizerInterface med_, ERC20 link_, address oracle_) public { med = med_; link = link_; setChainlinkToken(address(link_)); setChainlinkOracle(oracle_); asyncRequests[lastQueryId].payment = uint128(DEFAULT_LINK_PAYMENT); }
constructor(MedianizerInterface med_, ERC20 link_, address oracle_) public { med = med_; link = link_; setChainlinkToken(address(link_)); setChainlinkOracle(oracle_); asyncRequests[lastQueryId].payment = uint128(DEFAULT_LINK_PAYMENT); }
33,405
0
// Set the public company URI_companyURI The URI address of the company./
function setCompanyURI(string _companyURI) onlyOwner public { require(bytes(_companyURI).length > 0); companyURI = _companyURI; }
function setCompanyURI(string _companyURI) onlyOwner public { require(bytes(_companyURI).length > 0); companyURI = _companyURI; }
39,324
6
// Change the Description of an existing law Law_Title Title of the Lawnew_Description New description of the law We can't change the "Title" field of the Law as it's his ID/
function Change_Law_Description(bytes memory Law_Title, bytes memory new_Description)external Register_Authorities_Only { require(Lois[Law_Title].Timestamp !=0, "Loi: Law doesn't exist"); Lois[Law_Title].Description = new_Description; emit Description_Changed(Law_Title); }
function Change_Law_Description(bytes memory Law_Title, bytes memory new_Description)external Register_Authorities_Only { require(Lois[Law_Title].Timestamp !=0, "Loi: Law doesn't exist"); Lois[Law_Title].Description = new_Description; emit Description_Changed(Law_Title); }
30,615
17
// set the enabled status of this pool /
function setEnabled(bool _enabled) external override onlyController { poolData.enabled = _enabled; }
function setEnabled(bool _enabled) external override onlyController { poolData.enabled = _enabled; }
31,456
35
// returns true if Exp is exactly zero/
function isZeroExp(Exp memory value) pure internal returns (bool) { return value.mantissa == 0; }
function isZeroExp(Exp memory value) pure internal returns (bool) { return value.mantissa == 0; }
19,374
92
// Get the number of tokens `spender` is approved to spend on behalf of `account` account The address of the account holding the funds spender The address of the account spending the fundsreturn The number of tokens approved /
function allowance(address account, address spender) external view returns (uint256)
function allowance(address account, address spender) external view returns (uint256)
67,904
70
// Called by: Elections contract/ Notifies a new member applicable for committee (due to registration, unbanning, certification change)
function addMember(address addr, uint256 weight, bool isCertified) external returns (bool memberAdded) /* onlyElectionsContract */;
function addMember(address addr, uint256 weight, bool isCertified) external returns (bool memberAdded) /* onlyElectionsContract */;
8,477
29
// raised when a recipient address is not whitelisted
error RecipientNotWhitelisted(address addr);
error RecipientNotWhitelisted(address addr);
31,039
2
// deposits with fromDepositID < ID <= toDepositID are funded
uint256 fromDepositID; uint256 toDepositID; uint256 recordedFundedDepositAmount; // the current stablecoin amount earning interest for the funder uint256 recordedMoneyMarketIncomeIndex; // the income index at the last update (creation or withdrawal) uint256 creationTimestamp; // Unix timestamp at time of deposit, in seconds
uint256 fromDepositID; uint256 toDepositID; uint256 recordedFundedDepositAmount; // the current stablecoin amount earning interest for the funder uint256 recordedMoneyMarketIncomeIndex; // the income index at the last update (creation or withdrawal) uint256 creationTimestamp; // Unix timestamp at time of deposit, in seconds
21,081
106
// Creates a new fork with the given endpoint and block and returns the identifier of the fork
function createFork(string calldata urlOrAlias, uint256 blockNumber) external returns (uint256 forkId);
function createFork(string calldata urlOrAlias, uint256 blockNumber) external returns (uint256 forkId);
30,923
39
// check if user has another running vote
uint256 previousProposalId = latestProposalIds[msg.sender]; if (previousProposalId != 0) { require(_isLiveState(previousProposalId) == false, "One live proposal per proposer"); }
uint256 previousProposalId = latestProposalIds[msg.sender]; if (previousProposalId != 0) { require(_isLiveState(previousProposalId) == false, "One live proposal per proposer"); }
9,356
163
// Constants
uint256 constant DIVISION_FACTOR = 100000; address constant SUSHISWAP_ROUTER_ADDRESS = address(0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F); // Sushi swap router address constant UNISWAP_ROUTER_ADDRESS = address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); address constant SUSHISWAP_DIGG_LP = address(0x9a13867048e01c663ce8Ce2fE0cDAE69Ff9F35E3); // Will need to sync before trading address constant UNISWAP_DIGG_LP = address(0xE86204c4eDDd2f70eE00EAd6805f917671F56c52); address constant BTC_ORACLE_ADDRESS = address(0xF4030086522a5bEEa4988F8cA5B36dbC97BeE88c); // Chainlink BTC Oracle address constant DIGG_ORACLE_ADDRESS = address(0x418a6C98CD5B8275955f08F0b8C1c6838c8b1685); // Chainlink DIGG Oracle
uint256 constant DIVISION_FACTOR = 100000; address constant SUSHISWAP_ROUTER_ADDRESS = address(0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F); // Sushi swap router address constant UNISWAP_ROUTER_ADDRESS = address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); address constant SUSHISWAP_DIGG_LP = address(0x9a13867048e01c663ce8Ce2fE0cDAE69Ff9F35E3); // Will need to sync before trading address constant UNISWAP_DIGG_LP = address(0xE86204c4eDDd2f70eE00EAd6805f917671F56c52); address constant BTC_ORACLE_ADDRESS = address(0xF4030086522a5bEEa4988F8cA5B36dbC97BeE88c); // Chainlink BTC Oracle address constant DIGG_ORACLE_ADDRESS = address(0x418a6C98CD5B8275955f08F0b8C1c6838c8b1685); // Chainlink DIGG Oracle
5,581
45
// Returns total value passed through the contractreturn result total value in wei /
function getTotalValue() constant returns (uint result) { return totalValue; }
function getTotalValue() constant returns (uint result) { return totalValue; }
32,356
351
// Changes token base URI to the given string/_newBaseURI URI to change the base URI to
function setBaseURI(string memory _newBaseURI) public onlyOwner { baseUri = _newBaseURI; }
function setBaseURI(string memory _newBaseURI) public onlyOwner { baseUri = _newBaseURI; }
20,923
297
// Byterose March backpay and 2 month stream
pool.payout( pool.openStream( 0x0Da87C54F853c2CF1221dbE725018944C83BDA7C, 0, 1000 * (10**24) ) ); pool.openStream( 0x0Da87C54F853c2CF1221dbE725018944C83BDA7C, 60 days,
pool.payout( pool.openStream( 0x0Da87C54F853c2CF1221dbE725018944C83BDA7C, 0, 1000 * (10**24) ) ); pool.openStream( 0x0Da87C54F853c2CF1221dbE725018944C83BDA7C, 60 days,
29,205
6
// Moves `amount` tokens from `sender` to `recipient` using theallowance mechanism. `amount` is then deducted from the caller'sallowance. Returns a boolean value indicating whether the operation succeeded. Emits a {Transfer} event. /
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
177
34
// Returns the memory address of the first byte after the last occurrence of `needle` in `self`, or the address of `self` if not found.
function rfindPtr(uint selflen, uint selfptr, uint needlelen, uint needleptr) private returns (uint) { uint ptr; if (needlelen <= selflen) { if (needlelen <= 32) { // Optimized assembly for 69 gas per byte on short strings assembly { let mask := not(sub(exp(2, mul(8, sub(32, needlelen))), 1)) let needledata := and(mload(needleptr), mask) ptr := add(selfptr, sub(selflen, needlelen)) loop: jumpi(ret, eq(and(mload(ptr), mask), needledata)) ptr := sub(ptr, 1) jumpi(loop, gt(add(ptr, 1), selfptr)) ptr := selfptr jump(exit) ret: ptr := add(ptr, needlelen) exit: } return ptr; } else { // For long needles, use hashing bytes32 hash; assembly { hash := sha3(needleptr, needlelen) } ptr = selfptr + (selflen - needlelen); while (ptr >= selfptr) { bytes32 testHash; assembly { testHash := sha3(ptr, needlelen) } if (hash == testHash) return ptr + needlelen; ptr -= 1; } } } return selfptr; }
function rfindPtr(uint selflen, uint selfptr, uint needlelen, uint needleptr) private returns (uint) { uint ptr; if (needlelen <= selflen) { if (needlelen <= 32) { // Optimized assembly for 69 gas per byte on short strings assembly { let mask := not(sub(exp(2, mul(8, sub(32, needlelen))), 1)) let needledata := and(mload(needleptr), mask) ptr := add(selfptr, sub(selflen, needlelen)) loop: jumpi(ret, eq(and(mload(ptr), mask), needledata)) ptr := sub(ptr, 1) jumpi(loop, gt(add(ptr, 1), selfptr)) ptr := selfptr jump(exit) ret: ptr := add(ptr, needlelen) exit: } return ptr; } else { // For long needles, use hashing bytes32 hash; assembly { hash := sha3(needleptr, needlelen) } ptr = selfptr + (selflen - needlelen); while (ptr >= selfptr) { bytes32 testHash; assembly { testHash := sha3(ptr, needlelen) } if (hash == testHash) return ptr + needlelen; ptr -= 1; } } } return selfptr; }
15,939
7
// Price of underlying is the price value / Tokenconversion / scaling factor Values need to be converted based on full unit quantities
return underlyingPrice.preciseMul(conversionRate).mul(cTokenFullUnit).div(underlyingFullUnit);
return underlyingPrice.preciseMul(conversionRate).mul(cTokenFullUnit).div(underlyingFullUnit);
72,071
0
// obtained as bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1)
bytes32 private constant implPosition = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
bytes32 private constant implPosition = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
3,005
48
// Determine whether an exchange is using a constant sum pricing module exchange The exchange to checkreturn bool indicating if the exchange is using a constant sum pricing module /
function isConstantSum(PoolExchange memory exchange) internal view returns (bool) { return pricingModuleIdentifier(exchange) == CONSTANT_SUM; }
function isConstantSum(PoolExchange memory exchange) internal view returns (bool) { return pricingModuleIdentifier(exchange) == CONSTANT_SUM; }
25,968
384
// Modifier used by all methods that impact accounting to make sure accounting period is changed before the operation if needed NOTE: its use MUST be accompanied by an initialization check
modifier transitionsPeriod { bool completeTransition = _tryTransitionAccountingPeriod(getMaxPeriodTransitions()); require(completeTransition, ERROR_COMPLETE_TRANSITION); _; }
modifier transitionsPeriod { bool completeTransition = _tryTransitionAccountingPeriod(getMaxPeriodTransitions()); require(completeTransition, ERROR_COMPLETE_TRANSITION); _; }
5,719
0
// addresses (PrismCreationManagers) which are authorized to register prisms
mapping (address => bool) public creationManagers;
mapping (address => bool) public creationManagers;
531
46
// unlock start time 2019-04-10
uint256 unlock_time_0410 = 1554825600;
uint256 unlock_time_0410 = 1554825600;
19,405
256
// Interface for contracts using VRF randomness PURPOSEReggie the Random Oracle (not his real job) wants to provide randomness to Vera the verifier in such a way that Vera can be sure he's not making his output up to suit himself. Reggie provides Vera a public key to which he knows the secret key. Each time Vera provides a seed to Reggie, he gives back a value which is computed completely deterministically from the seed and the secret key.Reggie provides a proof by which Vera can verify that the output was correctly computed once Reggie tells it to her, but without
* @dev contract VRFConsumer { * @dev constuctor(<other arguments>, address _vrfCoordinator, address _link) * @dev VRFConsumerBase(_vrfCoordinator, _link) public { * @dev <initialization with other arguments goes here> * @dev } * @dev }
* @dev contract VRFConsumer { * @dev constuctor(<other arguments>, address _vrfCoordinator, address _link) * @dev VRFConsumerBase(_vrfCoordinator, _link) public { * @dev <initialization with other arguments goes here> * @dev } * @dev }
17,301
20
// Maps an address to a specific countries name
mapping(address => string) CountriesName;
mapping(address => string) CountriesName;
29,236
19
// reduce the outflow by flowRate; shouldn't overflow, because we just checked that it was bigger.
_updateFlow(to, outFlowRate - flowRate);
_updateFlow(to, outFlowRate - flowRate);
422
13
// Places `addr` in the first empty position in the queue /
function enqueue(address addr_) public { //Address must not exist require(indexes[addr_] == 0x0); //if queue is full, check whether the first one should expire if (qsize() >= queueSize){ if (releaseTime[addresses[0]] > now) dequeue(); else return; } //Queue has space, add input to the next empty spot if (qsize() < queueSize){ indexes[addr_] = headIndex; addresses[headIndex] = addr_; releaseTime[addr_] = now + TIME_DIFF; moveIndex(headIndex); } }
function enqueue(address addr_) public { //Address must not exist require(indexes[addr_] == 0x0); //if queue is full, check whether the first one should expire if (qsize() >= queueSize){ if (releaseTime[addresses[0]] > now) dequeue(); else return; } //Queue has space, add input to the next empty spot if (qsize() < queueSize){ indexes[addr_] = headIndex; addresses[headIndex] = addr_; releaseTime[addr_] = now + TIME_DIFF; moveIndex(headIndex); } }
1,973
0
// Token supply control
uint8 constant decimal = 18; uint8 constant decimalBUSD = 18; uint256 constant maxSupply = 50_000_000 * (10 ** decimal); uint256 public _maxTxAmount = maxSupply / 100; uint256 public _maxAccountAmount = maxSupply / 50; uint256 public totalBurned;
uint8 constant decimal = 18; uint8 constant decimalBUSD = 18; uint256 constant maxSupply = 50_000_000 * (10 ** decimal); uint256 public _maxTxAmount = maxSupply / 100; uint256 public _maxAccountAmount = maxSupply / 50; uint256 public totalBurned;
28,236
155
// Reserved for promotional giveaways, and rewards to those who helped inspire or enable Tiles. Owner may mint Tile for `_tileAddress` to `to`
function mintReserveTile(address to, address _tileAddress) external onlyOwner returns (uint256)
function mintReserveTile(address to, address _tileAddress) external onlyOwner returns (uint256)
66,437
36
// Destroy tokens Remove `_value` tokens from the system irreversibly_value the amount of tokens to burn/
function burn(uint256 _value) public returns (bool success) { require(!safeguard); //checking of enough token balance is done by SafeMath balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value); // Subtract from the sender totalSupply = totalSupply.sub(_value); // Updates totalSupply emit Burn(msg.sender, _value); emit Transfer(msg.sender, address(0), _value); return true; }
function burn(uint256 _value) public returns (bool success) { require(!safeguard); //checking of enough token balance is done by SafeMath balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value); // Subtract from the sender totalSupply = totalSupply.sub(_value); // Updates totalSupply emit Burn(msg.sender, _value); emit Transfer(msg.sender, address(0), _value); return true; }
71,165
128
// this cannot exceed 256 bits, all values are 224 bits
uint256 sum = uint256(upper << RESOLUTION) + uppers_lowero + uppero_lowers + (lower >> RESOLUTION);
uint256 sum = uint256(upper << RESOLUTION) + uppers_lowero + uppero_lowers + (lower >> RESOLUTION);
18,213
19
// calculate total rewards
uint256 newTotalFarmRewards = rewardToken.balanceOf(address(this)).add(totalClaimedRewards).mul(PRECISION);
uint256 newTotalFarmRewards = rewardToken.balanceOf(address(this)).add(totalClaimedRewards).mul(PRECISION);
40,678
9
// event sent when the smart contract calls Chainlink´s VRF v2 to generate a set of random numbers
event RandomNumberRequested(uint256 indexed raffleId, uint256 size);
event RandomNumberRequested(uint256 indexed raffleId, uint256 size);
7,362
34
// Register of all artworks and their details by their respective addresses
struct artwork { bytes32 SHA256Hash; uint256 editionSize; string title; string fileLink; uint256 ownerCommission; address artist; address factory; bool isIndexed; bool isOuroboros;}
struct artwork { bytes32 SHA256Hash; uint256 editionSize; string title; string fileLink; uint256 ownerCommission; address artist; address factory; bool isIndexed; bool isOuroboros;}
34,485
14
// if there is enough collateral to liquidate the fee, first transfer burn an equivalent amount ofaTokens of the user
collateralAtoken.burnOnLiquidation(_user, vars.liquidatedCollateralForFee);
collateralAtoken.burnOnLiquidation(_user, vars.liquidatedCollateralForFee);
39,963
169
// Allow the owner of the contract to recover funds accidentally/ sent to the contract. To withdraw ETH, the token should be set to `0x0`.
function recoverTokens(address _token) external onlyOwner { require( !recoverableTokensBlacklist[_token], "CanReclaimTokens: token is not recoverable" ); if (_token == address(0x0)) { msg.sender.transfer(address(this).balance); } else { ERC20(_token).safeTransfer( msg.sender, ERC20(_token).balanceOf(address(this)) ); } }
function recoverTokens(address _token) external onlyOwner { require( !recoverableTokensBlacklist[_token], "CanReclaimTokens: token is not recoverable" ); if (_token == address(0x0)) { msg.sender.transfer(address(this).balance); } else { ERC20(_token).safeTransfer( msg.sender, ERC20(_token).balanceOf(address(this)) ); } }
6,033
40
// Based on OpenZeppelin's Ownable contract:Contract module which provides a basic access control mechanism, wherethere is an account (an owner) that can be granted exclusive access tospecific functions. 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 { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), msg.sender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return msg.sender == _owner; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. * * NOTE: This function is not safe, as it doesn’t check owner is calling it. * Make sure you check it before calling it. */ function _renounceOwnership() internal { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } }
contract Ownable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), msg.sender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return msg.sender == _owner; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. * * NOTE: This function is not safe, as it doesn’t check owner is calling it. * Make sure you check it before calling it. */ function _renounceOwnership() internal { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } }
2,581
13
// import "./ERC223Basic.sol";
contract ERC223Basic { uint public totalSupply; function balanceOf(address who) constant returns (uint); function transfer(address to, uint value); function transfer(address to, uint value, bytes data); event Transfer(address indexed from, address indexed to, uint value, bytes indexed data); }
contract ERC223Basic { uint public totalSupply; function balanceOf(address who) constant returns (uint); function transfer(address to, uint value); function transfer(address to, uint value, bytes data); event Transfer(address indexed from, address indexed to, uint value, bytes indexed data); }
57,749