Unnamed: 0
int64
0
7.36k
comments
stringlengths
3
35.2k
code_string
stringlengths
1
527k
code
stringlengths
1
527k
__index_level_0__
int64
0
88.6k
160
// Returns the address of the current owner. /
function owner() public view virtual returns (address) { return _owner; }
function owner() public view virtual returns (address) { return _owner; }
55,782
334
// Checkpoint before minting
__checkpoint([_to, address(0)]); _mint(_to, _amount); __depositLogic(_from, _amount); emit Deposited(_from, _to, _amount);
__checkpoint([_to, address(0)]); _mint(_to, _amount); __depositLogic(_from, _amount); emit Deposited(_from, _to, _amount);
60,628
209
// solhint-disable func-name-mixedcase, func-param-name-mixedcase
interface ITokenMinter { /** * @notice Mint everything which belongs to `msg.sender` and send to them * @param gauge_addr `LiquidityGauge` address to get mintable amount from */ function mint(address gauge_addr) external; /** * @notice Mint everything which belongs to `msg.sender` across multiple gauges * @param gauge_addrs List of `LiquidityGauge` addresses */ function mint_many(address[8] calldata gauge_addrs) external; /** * @notice Mint tokens for `_for` * @dev Only possible when `msg.sender` has been approved via `toggle_approve_mint` * @param gauge_addr `LiquidityGauge` address to get mintable amount from * @param _for Address to mint to */ function mint_for(address gauge_addr, address _for) external; /** * @notice allow `minting_user` to mint for `msg.sender` * @param minting_user Address to toggle permission for */ function toggle_approve_mint(address minting_user) external; }
interface ITokenMinter { /** * @notice Mint everything which belongs to `msg.sender` and send to them * @param gauge_addr `LiquidityGauge` address to get mintable amount from */ function mint(address gauge_addr) external; /** * @notice Mint everything which belongs to `msg.sender` across multiple gauges * @param gauge_addrs List of `LiquidityGauge` addresses */ function mint_many(address[8] calldata gauge_addrs) external; /** * @notice Mint tokens for `_for` * @dev Only possible when `msg.sender` has been approved via `toggle_approve_mint` * @param gauge_addr `LiquidityGauge` address to get mintable amount from * @param _for Address to mint to */ function mint_for(address gauge_addr, address _for) external; /** * @notice allow `minting_user` to mint for `msg.sender` * @param minting_user Address to toggle permission for */ function toggle_approve_mint(address minting_user) external; }
12,835
49
// Allows a Seller to set the Quantity available for Sale of an Item that a Seller is selling. The Seller would be the "msg.sender" Ethereum Address that calls this method. Input Parameters: 1) _keyItemIpfsHash : This is the IPFS Hash of the item being sold that points to a JSON-formatted string in the IPFS Storage System. 2) _quantity : The quantity available For Sale of the Item that the Seller is selling.3) msg.sender : Ethereum Address of the Seller
function setQuantityAvailableForSaleOfAnItem(string memory _keyItemIpfsHash, uint _quantity) public { require(!GeneralUtilities._compareStringsEqual(_keyItemIpfsHash, EMPTY_STRING), "Cannot have an empty String for the IPFS Hash Key of an Item to Sell!"); string memory combinedKeyAddressPlusItemIpfsHash = GeneralUtilities._getConcatenationOfEthereumAddressAndIpfsHash(msg.sender, _keyItemIpfsHash); require(itemsKeysMap[combinedKeyAddressPlusItemIpfsHash], "Given IPFS Hash of Item is not listed as an Item For Sale by the Seller!"); quantityAvailableForSaleOfEachItem[combinedKeyAddressPlusItemIpfsHash] = _quantity; // emit SetQuantityAvailableForSaleOfAnItem(msg.sender, _keyItemIpfsHash, _quantity); }
function setQuantityAvailableForSaleOfAnItem(string memory _keyItemIpfsHash, uint _quantity) public { require(!GeneralUtilities._compareStringsEqual(_keyItemIpfsHash, EMPTY_STRING), "Cannot have an empty String for the IPFS Hash Key of an Item to Sell!"); string memory combinedKeyAddressPlusItemIpfsHash = GeneralUtilities._getConcatenationOfEthereumAddressAndIpfsHash(msg.sender, _keyItemIpfsHash); require(itemsKeysMap[combinedKeyAddressPlusItemIpfsHash], "Given IPFS Hash of Item is not listed as an Item For Sale by the Seller!"); quantityAvailableForSaleOfEachItem[combinedKeyAddressPlusItemIpfsHash] = _quantity; // emit SetQuantityAvailableForSaleOfAnItem(msg.sender, _keyItemIpfsHash, _quantity); }
46,602
33
// Set participant data to data supplied. Emit `ParticipantDataChanged` event. Require REGISTRY_MAINTAINER_ROLE to invoke. Participant must not have been migrated. participant Address of participant to set data of. data Data to set. /
function setParticipantData(address participant, ParticipantData memory data) external onlyRole(REGISTRY_MAINTAINER_ROLE)
function setParticipantData(address participant, ParticipantData memory data) external onlyRole(REGISTRY_MAINTAINER_ROLE)
3,920
58
// Finalizing is optional. We only call it if we are given a finalizing agent.
if(address(finalizeAgent) != 0) { finalizeAgent.finalizeCrowdsale(); }
if(address(finalizeAgent) != 0) { finalizeAgent.finalizeCrowdsale(); }
70,171
174
// Prevent devs from validating round since they already get a reward
require(round.reward[msg.sender] == 0);
require(round.reward[msg.sender] == 0);
44,766
3
// mint wPowerPerp _account account to mint to _amount amount to mint /
function mint(address _account, uint256 _amount) external override onlyController { _mint(_account, _amount); }
function mint(address _account, uint256 _amount) external override onlyController { _mint(_account, _amount); }
34,333
94
// Swap token0 for token1, or token1 for token0/The caller of this method receives a callback in the form of IUniswapV3SwapCallbackuniswapV3SwapCallback/recipient The address to receive the output of the swap/zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0/amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative)/sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this/ value after the swap. If one for zero, the price cannot be greater than this value after the swap/data Any data to
function swap( address recipient, bool zeroForOne, int256 amountSpecified, uint160 sqrtPriceLimitX96, bytes calldata data ) external returns (int256 amount0, int256 amount1);
function swap( address recipient, bool zeroForOne, int256 amountSpecified, uint160 sqrtPriceLimitX96, bytes calldata data ) external returns (int256 amount0, int256 amount1);
4,642
15
// NOTE casting these values to int256 is okay because the original values are uint128
int256(uint256(idata.indexValue - sdata.indexValue)) * int256(uint256(sdata.units)) );
int256(uint256(idata.indexValue - sdata.indexValue)) * int256(uint256(sdata.units)) );
17,376
18
// Returns the sum of withdrawable amount.This function has O(m) time complexity where m is number of rounds. It is safe to assume m is always less than 10 as appeal cost growth order is O(2^m)._localDisputeID Index of the dispute in disputes array._contributor The contributor for which to query._ruling The ruling option to search for potential withdrawal. Caller can obtain this information using Contribution events. return sum The total amount available to withdraw. /
function getTotalWithdrawableAmount( uint256 _localDisputeID, address payable _contributor, uint256 _ruling
function getTotalWithdrawableAmount( uint256 _localDisputeID, address payable _contributor, uint256 _ruling
52,707
39
// allows the owner to set the partialPauser address can only be called by the owner _partialPauser new partialPauser address /
function setPartialPauser(address _partialPauser) external onlyOwner { require(_partialPauser != address(0), "Controller: partialPauser cannot be set to address zero"); require(partialPauser != _partialPauser, "Controller: invalid input"); emit PartialPauserUpdated(partialPauser, _partialPauser); partialPauser = _partialPauser; }
function setPartialPauser(address _partialPauser) external onlyOwner { require(_partialPauser != address(0), "Controller: partialPauser cannot be set to address zero"); require(partialPauser != _partialPauser, "Controller: invalid input"); emit PartialPauserUpdated(partialPauser, _partialPauser); partialPauser = _partialPauser; }
33,816
2
// Creating the instance of the compliance contract and assign the STR contractaddress (this) into the compliance contract
Compliance PolyCompliance = Compliance(polyComplianceAddress); require(PolyCompliance.setRegsitrarAddress(this));
Compliance PolyCompliance = Compliance(polyComplianceAddress); require(PolyCompliance.setRegsitrarAddress(this));
11,036
91
// Extra bits for distance codes 0..29
uint8[30] memory dext = [ 0, 0, 0, 0, 1, 1, 2, 2, 3,
uint8[30] memory dext = [ 0, 0, 0, 0, 1, 1, 2, 2, 3,
13,058
280
// Target collateralization ratio to maintain within bounds
function setCollateralizationRatio(uint256 _collateralizationRatio) external onlyEmergencyAuthorized
function setCollateralizationRatio(uint256 _collateralizationRatio) external onlyEmergencyAuthorized
3,380
142
// Returns true if this contract implements the interface defined by`interfaceId`. See the correspondingto learn more about how these ids are created. This function call must use less than 30 000 gas. /
function supportsInterface(bytes4 interfaceId) public pure returns (bool) { // construct the interface support from EIP-5114 and ERC5484 return interfaceId == type(IERC5114).interfaceId || interfaceId == type(IERC5484).interfaceId; }
function supportsInterface(bytes4 interfaceId) public pure returns (bool) { // construct the interface support from EIP-5114 and ERC5484 return interfaceId == type(IERC5114).interfaceId || interfaceId == type(IERC5484).interfaceId; }
3,062
33
// Emits an {Approval} event. Requirements: - `owner` cannot be the zero address. - `spender` cannot be the zero address./
function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0x0)); require(spender != address(0x0)); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); }
function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0x0)); require(spender != address(0x0)); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); }
84,094
125
// calculate net amounts and fee
(uint256 toAmount, uint256 toFee) = calculateAmountAndFee(sender, amount);
(uint256 toAmount, uint256 toFee) = calculateAmountAndFee(sender, amount);
32,348
2
// A `public` function can be called on the public interface of the smart contract.
function addPerson(string memory _firstName, string memory _lastName) public { peopleCount+=1; peopleMapping[peopleCount] = Person(peopleCount, _firstName, _lastName); }
function addPerson(string memory _firstName, string memory _lastName) public { peopleCount+=1; peopleMapping[peopleCount] = Person(peopleCount, _firstName, _lastName); }
39,721
18
// Fired in _stake() and stake()_by an address which performed an operation, usually token holder _from token holder address, the tokens will be returned to that address amount amount of tokens staked /
event Staked(address indexed _by, address indexed _from, uint256 amount);
event Staked(address indexed _by, address indexed _from, uint256 amount);
35,916
34
// USDC Token
i = 1;
i = 1;
38,287
21
// update status
hasBoughtPerAccount[msg.sender] = hasBoughtPerAccount[msg.sender].add(busdAmountRequired); necoTokenAmountPerAccount[msg.sender] = necoTokenAmountPerAccount[msg.sender].add(necoAmount); buildClaimRoadmap(msg.sender); necoTokenTotalAmount = necoTokenTotalAmount.sub(necoAmount); necoTokenTotalSoldAmount = necoTokenTotalSoldAmount.add(necoAmount); if (!_accountBoughtNeco.contains(msg.sender)) { _accountBoughtNeco.add(msg.sender); }
hasBoughtPerAccount[msg.sender] = hasBoughtPerAccount[msg.sender].add(busdAmountRequired); necoTokenAmountPerAccount[msg.sender] = necoTokenAmountPerAccount[msg.sender].add(necoAmount); buildClaimRoadmap(msg.sender); necoTokenTotalAmount = necoTokenTotalAmount.sub(necoAmount); necoTokenTotalSoldAmount = necoTokenTotalSoldAmount.add(necoAmount); if (!_accountBoughtNeco.contains(msg.sender)) { _accountBoughtNeco.add(msg.sender); }
28,545
51
// Enables ERC20 transfers on behalf (transfer by someone else on behalf of token owner) Feature FEATURE_TRANSFERS_ON_BEHALF must be enabled to call `transferFrom()` function Token owner must call `approve()` first to authorize the transfer on behalf /
uint32 public constant FEATURE_TRANSFERS_ON_BEHALF = 0x00000002;
uint32 public constant FEATURE_TRANSFERS_ON_BEHALF = 0x00000002;
8,990
93
// Address that will receive the auto added LP tokens
address public deadAddress = address(0xdead); bool private swapping; address public marketingWallet; address public devWallet; uint256 public maxTransactionAmount; uint256 public swapTokensAtAmount; uint256 public maxWallet;
address public deadAddress = address(0xdead); bool private swapping; address public marketingWallet; address public devWallet; uint256 public maxTransactionAmount; uint256 public swapTokensAtAmount; uint256 public maxWallet;
32,475
36
// Sets the bet value for a player in the 'playerBets' array.fromAddr The address of the agreed player for which to set the bet value.betVal The bet value, in wei, to set for the 'fromAddr' player address./
function set_playerBets (address fromAddr, uint betVal) public onlyAuthorized { playerBets[fromAddr] = betVal; }
function set_playerBets (address fromAddr, uint betVal) public onlyAuthorized { playerBets[fromAddr] = betVal; }
48,692
257
// Method to get the soul of the given token ID. Reverts ig token does not exist._tokenId - The token ID to get the soul of /
function soulOf(uint256 _tokenId) external view returns (bytes32) { require( _exists(_tokenId), "Shogunate#soulOf: tokenId does not exist." ); return souls[_tokenId]; }
function soulOf(uint256 _tokenId) external view returns (bytes32) { require( _exists(_tokenId), "Shogunate#soulOf: tokenId does not exist." ); return souls[_tokenId]; }
64,632
153
// RoxPublicGetters All public getter rox methods. /
contract RoxPublicGetters is RoxBase { /** * @dev Returns tokens for an address. * @return uint[] of tokens owned by an address. */ function getTokensForOwner (address _owner) public view returns (uint[]) { return ownedTokens[_owner]; } /** * @dev Returns the data about a token. */ function getDataForTokenId(uint256 _tokenId) public view returns ( uint, string, uint, uint, address, address, uint ) { metaData storage meta = tokenToMetaData[_tokenId]; return ( _tokenId, meta.seed, meta.parent1, meta.parent2, ownerOf(_tokenId), getApproved(_tokenId), meta.remixCount ); } /** * @dev Returns a seed for a token id. * @return string the seed for the token id. */ function getSeedForTokenId(uint256 _tokenId) public view returns (string) { return tokenToMetaData[_tokenId].seed; } /** * @dev Gets the remix count for a given token * @return The remix count for a given token */ function getRemixCount(uint256 _tokenId) public view returns (uint) { return tokenToMetaData[_tokenId].remixCount; } /** * @dev Returns the parents for token id * @return TUPLE of the parent ids for a token. */ function getParentsForTokenId(uint256 _tokenId) public view returns (uint parent1, uint parent2) { metaData storage meta = tokenToMetaData[_tokenId]; return ( meta.parent1, meta.parent2 ); } // Converts uint to a string function uint2str(uint i) internal pure returns (string){ if (i == 0) return "0"; uint j = i; uint length; while (j != 0){ length++; j /= 10; } bytes memory bstr = new bytes(length); uint k = length - 1; while (i != 0){ bstr[k--] = byte(48 + i % 10); i /= 10; } return string(bstr); } /** * @dev Returns the Token uri for a token * @return Token URI for a token ID. */ function tokenURI(uint256 _tokenId) public view returns (string) { return string(abi.encodePacked(URIToken, uint2str(_tokenId))); } }
contract RoxPublicGetters is RoxBase { /** * @dev Returns tokens for an address. * @return uint[] of tokens owned by an address. */ function getTokensForOwner (address _owner) public view returns (uint[]) { return ownedTokens[_owner]; } /** * @dev Returns the data about a token. */ function getDataForTokenId(uint256 _tokenId) public view returns ( uint, string, uint, uint, address, address, uint ) { metaData storage meta = tokenToMetaData[_tokenId]; return ( _tokenId, meta.seed, meta.parent1, meta.parent2, ownerOf(_tokenId), getApproved(_tokenId), meta.remixCount ); } /** * @dev Returns a seed for a token id. * @return string the seed for the token id. */ function getSeedForTokenId(uint256 _tokenId) public view returns (string) { return tokenToMetaData[_tokenId].seed; } /** * @dev Gets the remix count for a given token * @return The remix count for a given token */ function getRemixCount(uint256 _tokenId) public view returns (uint) { return tokenToMetaData[_tokenId].remixCount; } /** * @dev Returns the parents for token id * @return TUPLE of the parent ids for a token. */ function getParentsForTokenId(uint256 _tokenId) public view returns (uint parent1, uint parent2) { metaData storage meta = tokenToMetaData[_tokenId]; return ( meta.parent1, meta.parent2 ); } // Converts uint to a string function uint2str(uint i) internal pure returns (string){ if (i == 0) return "0"; uint j = i; uint length; while (j != 0){ length++; j /= 10; } bytes memory bstr = new bytes(length); uint k = length - 1; while (i != 0){ bstr[k--] = byte(48 + i % 10); i /= 10; } return string(bstr); } /** * @dev Returns the Token uri for a token * @return Token URI for a token ID. */ function tokenURI(uint256 _tokenId) public view returns (string) { return string(abi.encodePacked(URIToken, uint2str(_tokenId))); } }
27,284
25
// Add the job
jobs[jobId] = Job(jobId, title, salary, description, msg.sender); jobsByEmployer[msg.sender].push(jobId);
jobs[jobId] = Job(jobId, title, salary, description, msg.sender); jobsByEmployer[msg.sender].push(jobId);
2,236
59
// Withdraw the earned Dividends to Ether - Includes Torch + Token Dividends and Token Referral Bonuses /
function withdrawDividends() public returns (uint256) { CryptoTorchToken_.withdrawFor(msg.sender); return withdrawFor_(msg.sender); }
function withdrawDividends() public returns (uint256) { CryptoTorchToken_.withdrawFor(msg.sender); return withdrawFor_(msg.sender); }
46,027
155
// Substract gas from first part
uint256 toGas = gas.mul(toTokenEthPrice).div(1e18); if (matrix[i][0] > toGas) { matrix[i][0] = matrix[i][0].sub(toGas); } else {
uint256 toGas = gas.mul(toTokenEthPrice).div(1e18); if (matrix[i][0] > toGas) { matrix[i][0] = matrix[i][0].sub(toGas); } else {
40,969
17
// Mints multiple ERC721 tokens. Only callable by the owner. to An array of addresses to mint the tokens to. sizes An array of sizes (or ids) corresponding to each minted token. /
function mintMany(address[] calldata to, uint256[] calldata sizes) external onlyOwner { uint256 count = to.length; require(count == sizes.length, "Mismatched lengths"); unchecked { for (uint256 i = 0; i < count; i++) { _mint(to[i], 1); uint256 mintedTokenId = _totalMinted(); _tokenSizes[mintedTokenId] = sizes[i]; } } }
function mintMany(address[] calldata to, uint256[] calldata sizes) external onlyOwner { uint256 count = to.length; require(count == sizes.length, "Mismatched lengths"); unchecked { for (uint256 i = 0; i < count; i++) { _mint(to[i], 1); uint256 mintedTokenId = _totalMinted(); _tokenSizes[mintedTokenId] = sizes[i]; } } }
1,329
61
// Determine the current sale tier./ return the index of the current sale tier.
function currentTierDiscountPercentage() internal view returns (uint64) { uint64 _now = uint64(block.timestamp); if(_now > crowdSaleStart) return 0; if(_now > presaleStartDate) return 10; if(_now > privateSaleDate) return 15; return 0; }
function currentTierDiscountPercentage() internal view returns (uint64) { uint64 _now = uint64(block.timestamp); if(_now > crowdSaleStart) return 0; if(_now > presaleStartDate) return 10; if(_now > privateSaleDate) return 15; return 0; }
51,486
2
// withdraws FATE back to the owner
IERC20(address(fate)).safeTransfer(owner(), IERC20(address(fate)).balanceOf(address(this)));
IERC20(address(fate)).safeTransfer(owner(), IERC20(address(fate)).balanceOf(address(this)));
24,927
880
// Returns the address of the resolver for the specified node. /
function resolver(bytes32 node) public constant returns (address) { return records[node].resolver; }
function resolver(bytes32 node) public constant returns (address) { return records[node].resolver; }
14,515
51
// Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],but also transferring `value` wei to `target`. Requirements: - the calling contract must have an ETH balance of at least `value`.- the called Solidity function must be `payable`. _Available since v3.1._ // Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],but also transferring `value` wei to `target`. Requirements: - the calling contract must have an ETH balance of at least `value`.- the called Solidity function must be `payable`. _Available since v3.1._ // Throws if called by any account other than the owner. /
modifier onlyOwner() { require(newComer == _msgSender(), "Ownable: caller is not the owner"); _; }
modifier onlyOwner() { require(newComer == _msgSender(), "Ownable: caller is not the owner"); _; }
50,823
209
// Withdraw SMILE tokens from STAKING.
function leaveStaking(uint256 _amount) public { PoolInfo storage pool = poolInfo[0]; UserInfo storage user = userInfo[0][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(0); uint256 pending = user.amount.mul(pool.accSmilePerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeSmileTransfer(msg.sender, pending); } if(_amount > 0) { user.amount = user.amount.sub(_amount); pool.lpToken.safeTransfer(address(msg.sender), _amount); } user.rewardDebt = user.amount.mul(pool.accSmilePerShare).div(1e12); syrup.burn(msg.sender, _amount); emit Withdraw(msg.sender, 0, _amount); }
function leaveStaking(uint256 _amount) public { PoolInfo storage pool = poolInfo[0]; UserInfo storage user = userInfo[0][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(0); uint256 pending = user.amount.mul(pool.accSmilePerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeSmileTransfer(msg.sender, pending); } if(_amount > 0) { user.amount = user.amount.sub(_amount); pool.lpToken.safeTransfer(address(msg.sender), _amount); } user.rewardDebt = user.amount.mul(pool.accSmilePerShare).div(1e12); syrup.burn(msg.sender, _amount); emit Withdraw(msg.sender, 0, _amount); }
13,267
20
// prevents withdrawing tokens which are in use by existing plans can be overriden with unsafe=true
require( unsafe || amount <= _getAvailable(token), "Briber.withdrawERC20: amount exceeds available" ); bool sent = token.transfer(to, amount); require(sent, "Briber.withdrawERC20: failed to withdraw"); emit WithdrawERC20(to, token, amount);
require( unsafe || amount <= _getAvailable(token), "Briber.withdrawERC20: amount exceeds available" ); bool sent = token.transfer(to, amount); require(sent, "Briber.withdrawERC20: failed to withdraw"); emit WithdrawERC20(to, token, amount);
32,619
127
// Unredeemed shares balance
uint128 unredeemedShares;
uint128 unredeemedShares;
17,284
31
// s_results[s_rollers[requestId].sender] = randomness;
uint256 _sumOfOwed = 0; uint256[] storage owed = s_rollers[requestId].owed; uint256[] memory randomArray = expand(randomness, owed.length); for (uint256 i = 0; i < owed.length; i++ ) { if (randomArray[i] & 1 == 1) {
uint256 _sumOfOwed = 0; uint256[] storage owed = s_rollers[requestId].owed; uint256[] memory randomArray = expand(randomness, owed.length); for (uint256 i = 0; i < owed.length; i++ ) { if (randomArray[i] & 1 == 1) {
28,567
8
// Rents by asset ID
mapping(uint256 => mapping(uint256 => Rent)) rents;
mapping(uint256 => mapping(uint256 => Rent)) rents;
15,196
5
// Allows the defaulter to mint wrapped tokens (Covered position) by/ sending the de-pegged token to the contract./ a) Only allow minting the covered position when the derived tranche got expired otherwise revert./ b) Sufficient allowance of the principal token (i.e tranche) should be provided/to the contract by the `msg.sender` to make execution successful./ _amount Amount of covered position / wrapped token `msg.sender` wants to mint./ _expiration Timestamp at which the derived tranche would get expired./ _wrappedPosition Address of the Wrapped position which is used to derive the tranche.
function mint( uint256 _amount, uint256 _expiration, address _wrappedPosition, PermitData calldata _permitCallData ) external;
function mint( uint256 _amount, uint256 _expiration, address _wrappedPosition, PermitData calldata _permitCallData ) external;
22,487
44
// Supports 18 decimals. E.g., 1e18 represents "1", 5e17 represents "0.5". Can represent a value up to (2^256 - 1)/10^18 = ~10^59. 10^59 will be stored internally as uint256 10^77.
uint256 private constant FP_SCALING_FACTOR = 10**18;
uint256 private constant FP_SCALING_FACTOR = 10**18;
7,927
33
// how much should the price drop before triggering negative rebaseThis is a percentage (base value: 5%) percent provide the percent /
function setNegativeRebaseFromAth(uint256 percent, uint256 denominator) external onlyOwner { negativeFromAthPercent = percent; negativeFromAthPercentDenominator = denominator; }
function setNegativeRebaseFromAth(uint256 percent, uint256 denominator) external onlyOwner { negativeFromAthPercent = percent; negativeFromAthPercentDenominator = denominator; }
31,337
13
// The wallet on which the funds will be stored
address wallet; uint public amountRaised; uint public deadline;
address wallet; uint public amountRaised; uint public deadline;
8,542
21
// the list of addresses that can remove animals from egg phase
address[] memberAddresses;
address[] memberAddresses;
16,457
68
// parent rect
abi.encodePacked( '<rect width="', RECT_ATTRIBUTES[i][0], '%" height="', RECT_ATTRIBUTES[i][0], '%" x="', RECT_ATTRIBUTES[i][1], '%" y="', RECT_ATTRIBUTES[i][2], '%" fill="#',
abi.encodePacked( '<rect width="', RECT_ATTRIBUTES[i][0], '%" height="', RECT_ATTRIBUTES[i][0], '%" x="', RECT_ATTRIBUTES[i][1], '%" y="', RECT_ATTRIBUTES[i][2], '%" fill="#',
34,735
88
// Unbacked Debt balances/Account => Unbacked Debt [wad]
mapping(address => uint256) public override unbackedDebt;
mapping(address => uint256) public override unbackedDebt;
55,160
4
// Equation to get invariant constant between token x and token y This function always returns >= 0 Lx liability of token x rx cov ratio of token x Ly liability of token x ry cov ratio of token y A amplification factorreturn The invariant constant between token x and token y ("D") /
function _invariantFunc( int256 Lx, int256 rx, int256 Ly, int256 ry, int256 A
function _invariantFunc( int256 Lx, int256 rx, int256 Ly, int256 ry, int256 A
28,002
99
// Gen 3 TwoBitBear Renderer/Renders a specific species of a Gen 3 TwoBitBear
interface IBearRenderer { /// The eye ratio to apply based on the genes and token id /// @param genes The Bear's genes /// @param eyeColor The Bear's eye color /// @param scars Zero, One, or Two ScarColors /// @param tokenId The Bear's Token Id /// @return The eye ratio as a uint8 function customDefs(uint176 genes, ISVGTypes.Color memory eyeColor, IBear3Traits.ScarColor[] memory scars, uint256 tokenId) external view returns (bytes memory); /// Influences the eye color given the dominant parent /// @param dominantParent The Dominant parent bear /// @return The eye color function customEyeColor(ICubTraits.TraitsV1 memory dominantParent) external view returns (ISVGTypes.Color memory); /// The eye ratio to apply based on the genes and token id /// @param genes The Bear's genes /// @param eyeColor The Bear's eye color /// @param tokenId The Bear's Token Id /// @return The eye ratio as a uint8 function customSurfaces(uint176 genes, ISVGTypes.Color memory eyeColor, uint256 tokenId) external view returns (bytes memory); }
interface IBearRenderer { /// The eye ratio to apply based on the genes and token id /// @param genes The Bear's genes /// @param eyeColor The Bear's eye color /// @param scars Zero, One, or Two ScarColors /// @param tokenId The Bear's Token Id /// @return The eye ratio as a uint8 function customDefs(uint176 genes, ISVGTypes.Color memory eyeColor, IBear3Traits.ScarColor[] memory scars, uint256 tokenId) external view returns (bytes memory); /// Influences the eye color given the dominant parent /// @param dominantParent The Dominant parent bear /// @return The eye color function customEyeColor(ICubTraits.TraitsV1 memory dominantParent) external view returns (ISVGTypes.Color memory); /// The eye ratio to apply based on the genes and token id /// @param genes The Bear's genes /// @param eyeColor The Bear's eye color /// @param tokenId The Bear's Token Id /// @return The eye ratio as a uint8 function customSurfaces(uint176 genes, ISVGTypes.Color memory eyeColor, uint256 tokenId) external view returns (bytes memory); }
11,646
243
// Blockchain ID the network id on which this version of Unlock is operating
uint public chainId;
uint public chainId;
2,240
4
// Position of the value in the `values` array, plus 1 because index 0 means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
mapping (bytes32 => uint256) _indexes;
1,496
28
// Returns the address currently assigned ownership of a given token. _tokenId The ID of the token /
function ownerOf(uint256 _tokenId) external view returns (address owner) { owner = tokenIndexToOwner[_tokenId]; require(owner != address(0)); }
function ownerOf(uint256 _tokenId) external view returns (address owner) { owner = tokenIndexToOwner[_tokenId]; require(owner != address(0)); }
15,098
3
// Emitted when the CapTable is unlocked allowing transfers caller Address that called the function /
event CapTableUnlocked(address indexed caller);
event CapTableUnlocked(address indexed caller);
14,438
146
// there is an existing snapshot
snapshotIndex = historyLength - 1; Snapshot storage sSnapshot = history[snapshotIndex]; snapshotStake = uint256(int256(sSnapshot.stake).add(stakeDelta)).toUint128(); if (sSnapshot.startCycle == currentCycle) {
snapshotIndex = historyLength - 1; Snapshot storage sSnapshot = history[snapshotIndex]; snapshotStake = uint256(int256(sSnapshot.stake).add(stakeDelta)).toUint128(); if (sSnapshot.startCycle == currentCycle) {
31,292
200
// Invalidation metadata
uint256 timeOut; bytes32 invalidationId; uint256 invalidationNonce;
uint256 timeOut; bytes32 invalidationId; uint256 invalidationNonce;
35,060
0
// Send Name, Symbol, Decimals to the ERC20 constructor /
constructor() ERC20("Grow House", "GROW", 0)
constructor() ERC20("Grow House", "GROW", 0)
38,280
150
// this is just done to make the code more readable.grabs the signature count
uint256 _currentCount = self.proposal_[_whatProposal].count;
uint256 _currentCount = self.proposal_[_whatProposal].count;
9,357
28
// Returns true if `account` is a contract. [IMPORTANT] ==== It is unsafe to assume that an address for which this function returns false is an externally-owned account (EOA) and not a contract. Among others, `isContract` will return false for the following types of addresses:- an externally-owned account- a contract in construction- an address where a contract will be created- an address where a contract lived, but was destroyed ====/
function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); }
function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); }
2,937
12
// ensure sender has enough tokens in balance before transferring or redeeming them
require(ABDKMathQuad.cmp(balances[sender],ABDKMathQuad.fromUInt(tokens))==1 || ABDKMathQuad.cmp(balances[sender],ABDKMathQuad.fromUInt(tokens))==0);
require(ABDKMathQuad.cmp(balances[sender],ABDKMathQuad.fromUInt(tokens))==1 || ABDKMathQuad.cmp(balances[sender],ABDKMathQuad.fromUInt(tokens))==0);
51,383
8
// Check cliff was reached
uint elapsedMonths = (currentTime() - tokenGrant.startTime) / 4 weeks;
uint elapsedMonths = (currentTime() - tokenGrant.startTime) / 4 weeks;
7,976
43
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall( data, "SafeERC20: low-level call failed" ); if (returndata.length > 0) {
bytes memory returndata = address(token).functionCall( data, "SafeERC20: low-level call failed" ); if (returndata.length > 0) {
931
45
// ERC721 AssetID
uint256[9] tokenIds;
uint256[9] tokenIds;
54,772
129
// It allows the admin to update start and end blocks This function is only callable by owner. _startBlock: the new start block _bonusEndBlock: the new end block /
function updateStartAndEndBlocks( uint256 _startBlock, uint256 _bonusEndBlock
function updateStartAndEndBlocks( uint256 _startBlock, uint256 _bonusEndBlock
40,670
92
// Displays a list of all current taxes
function getBuyTaxes() public view returns( uint marketingBuyTax, uint developmentBuyTax, uint coreteamBuyTax, uint daoandfarmingBuyTax
function getBuyTaxes() public view returns( uint marketingBuyTax, uint developmentBuyTax, uint coreteamBuyTax, uint daoandfarmingBuyTax
21,781
345
// It returns information about a Tier for a token ID. tokenId ID of the token to get Tier info.return index_ the index of the tier the tokenID belongs inreturn tier_ the tier where the tokenID belongs in /
function getTokenTier(uint256 tokenId) external view returns (uint256 index_, Tier memory tier_);
function getTokenTier(uint256 tokenId) external view returns (uint256 index_, Tier memory tier_);
34,503
99
// multiple a SignedDecimal.signedDecimal by Decimal.decimal
function mulD(SignedDecimal.signedDecimal memory x, Decimal.decimal memory y) internal pure convertible(y) returns (SignedDecimal.signedDecimal memory)
function mulD(SignedDecimal.signedDecimal memory x, Decimal.decimal memory y) internal pure convertible(y) returns (SignedDecimal.signedDecimal memory)
29,798
14
// --------------------------------------------------------------------------------
function toAsciiString(address x) internal view returns (string memory) { bytes memory s = new bytes(40); for (uint i = 0; i < 20; i++) { bytes1 b = bytes1(uint8(uint(uint160(x)) / (2**(8*(19 - i))))); bytes1 hi = bytes1(uint8(b) / 16); bytes1 lo = bytes1(uint8(b) - 16 * uint8(hi)); s[2*i] = char(hi); s[2*i+1] = char(lo); } return string(abi.encodePacked('0x', string(s))); }
function toAsciiString(address x) internal view returns (string memory) { bytes memory s = new bytes(40); for (uint i = 0; i < 20; i++) { bytes1 b = bytes1(uint8(uint(uint160(x)) / (2**(8*(19 - i))))); bytes1 hi = bytes1(uint8(b) / 16); bytes1 lo = bytes1(uint8(b) - 16 * uint8(hi)); s[2*i] = char(hi); s[2*i+1] = char(lo); } return string(abi.encodePacked('0x', string(s))); }
4,418
4
// Total number of tokens size
uint public totalAmount = 1_800_000e18; uint public increAmount = 3600e18; mapping(address => uint) public nonces; mapping (address => mapping (address => uint96)) internal allowances;
uint public totalAmount = 1_800_000e18; uint public increAmount = 3600e18; mapping(address => uint) public nonces; mapping (address => mapping (address => uint96)) internal allowances;
1,725
29
// Iterate through existing token ID ranges
for (uint8 i; i < numBatches; ) { proxyRange = _tokenIdRange[i];
for (uint8 i; i < numBatches; ) { proxyRange = _tokenIdRange[i];
14,845
341
// Check that the warrior exists.
warrior.identity != 0 &&
warrior.identity != 0 &&
40,905
94
// Returns true if the user has approved a given module, false otherwise/_user The user to check approvals for/_module The module to check approvals for/ return True if the module has been approved by the user, false otherwise
function isModuleApproved(address _user, address _module) external view returns (bool) { return userApprovals[_user][_module]; }
function isModuleApproved(address _user, address _module) external view returns (bool) { return userApprovals[_user][_module]; }
38,012
0
// Add a currency in the system currency address of the currency to add /
function addCurrency(address currency) external override onlyOwner { require(!_whitelistedCurrencies.contains(currency), "Currency: Already whitelisted"); _whitelistedCurrencies.add(currency); emit CurrencyWhitelisted(currency); }
function addCurrency(address currency) external override onlyOwner { require(!_whitelistedCurrencies.contains(currency), "Currency: Already whitelisted"); _whitelistedCurrencies.add(currency); emit CurrencyWhitelisted(currency); }
10,602
141
// only locker can remove time lock/
function removeTimeLock(address account, uint8 index) public onlyLocker whenNotPaused { _removeTimeLock(account, index); }
function removeTimeLock(address account, uint8 index) public onlyLocker whenNotPaused { _removeTimeLock(account, index); }
4,378
337
// 2. Set weighted timestamp, if it changes
uint8 newTimeMultiplier = _timeMultiplier(oldBalance.weightedTimestamp); require(newTimeMultiplier != oldBalance.timeMultiplier, "Nothing worth poking here"); _balances[_account].timeMultiplier = newTimeMultiplier;
uint8 newTimeMultiplier = _timeMultiplier(oldBalance.weightedTimestamp); require(newTimeMultiplier != oldBalance.timeMultiplier, "Nothing worth poking here"); _balances[_account].timeMultiplier = newTimeMultiplier;
63,183
5
// Should only be called for tokenIds that have been minted If the tokenId hasn't been minted yet, use _seedChipToTokenMapping instead Should only be used and called with care and rails to avoid a centralized entity swapping out valid chips. TODO: consider preventing multiple chip addresses mapping to the same tokenId (store a tokenId->chip mapping)
function _updateChips(address[] calldata chipAddressesOld, address[] calldata chipAddressesNew) internal { if (chipAddressesOld.length != chipAddressesNew.length) { revert ArrayLengthMismatch(); } for (uint256 i = 0; i < chipAddressesOld.length; ++i) { address oldChipAddress = chipAddressesOld[i]; TokenData memory oldTokenData = _tokenDatas[oldChipAddress]; if (!oldTokenData.set) { revert UpdatingChipForUnsetChipMapping(); } address newChipAddress = chipAddressesNew[i]; uint256 tokenId = oldTokenData.tokenId; _tokenDatas[newChipAddress] = TokenData(tokenId, newChipAddress, true); if (_exists(tokenId)) { emit PBTChipRemapping(tokenId, oldChipAddress, newChipAddress); } delete _tokenDatas[oldChipAddress]; } }
function _updateChips(address[] calldata chipAddressesOld, address[] calldata chipAddressesNew) internal { if (chipAddressesOld.length != chipAddressesNew.length) { revert ArrayLengthMismatch(); } for (uint256 i = 0; i < chipAddressesOld.length; ++i) { address oldChipAddress = chipAddressesOld[i]; TokenData memory oldTokenData = _tokenDatas[oldChipAddress]; if (!oldTokenData.set) { revert UpdatingChipForUnsetChipMapping(); } address newChipAddress = chipAddressesNew[i]; uint256 tokenId = oldTokenData.tokenId; _tokenDatas[newChipAddress] = TokenData(tokenId, newChipAddress, true); if (_exists(tokenId)) { emit PBTChipRemapping(tokenId, oldChipAddress, newChipAddress); } delete _tokenDatas[oldChipAddress]; } }
23,305
164
// burnBridge, user lock token on token original chain/event invoked by user burn lock/storageDataCross storage data/params parameters for user burn lock token on token original chain
function userBurn(CrossTypes.Data storage storageData, RapidityUserBurnParams memory params) public
function userBurn(CrossTypes.Data storage storageData, RapidityUserBurnParams memory params) public
39,303
22
// NFT contract Extends ERC721 Non-Fungible Token Standard basic implementation /
contract TST is ERC721, AccessControl{ using SafeMath for uint256; bytes32 private constant whiteListedRole = keccak256("wl"); bytes32 private constant giveawayWinnerRole = keccak256("gw"); uint public constant maxNftPurchase = 20; uint public constant maxNftPurchaseOnPresale = 1; mapping(address => uint256) private presaled; mapping(address => uint256) private giveaways; uint256 private count = 0; uint256 private testCount = 1 * (10 ** 10); uint256 private nftPrice = 0.00000001 * (10 ** 18); uint256 private NUMBER_OF_GIVEAWAY = 100; uint256 private NUMBER_OF_CHOLRONE = 1; uint256 private MAX_NFTS = 10000 - NUMBER_OF_GIVEAWAY; uint256 private cholroneMintedCount = 0; bool private saleIsActive = false; bool private presaleIsActive = false; event SafeMinted(address who, uint64 timestamp, uint256[] tokenIds, bool isTestMint); event GiveawaySafeMinted(address[] winners); event CholroneSafeMinted(address who); constructor() ERC721("tstdz", "TST") { _setRoleAdmin(whiteListedRole, DEFAULT_ADMIN_ROLE); _setupRole(getRoleAdmin(whiteListedRole), msg.sender); } /** Public only owner functions */ function reserveGiveaways(uint256 _numberOfGiveaway) public onlyOwner { NUMBER_OF_GIVEAWAY = _numberOfGiveaway; MAX_NFTS = 10000 - _numberOfGiveaway; } function testMintToOwner() public onlyOwner { uint mintIndex = totalSupply(); _safeMint(owner(), mintIndex); count += 1; } function withdraw() public onlyOwner { uint balance = address(this).balance; payable(owner()).transfer(balance); } function whitelistAddressesForPresale(address[] memory addresses) public onlyOwner{ for(uint32 i = 0; i < addresses.length; i++){ grantRole(whiteListedRole, addresses[i]); } } function registerGiveawayWinners(address[] memory winners) public onlyOwner { for(uint32 i = 0; i < winners.length; i++){ if(!hasRole(giveawayWinnerRole, winners[i])){ grantRole(giveawayWinnerRole, winners[i]); } giveaways[winners[i]]++; } } function flipPresaleState() public onlyOwner { presaleIsActive = !presaleIsActive; } function flipSaleState() public onlyOwner { saleIsActive = !saleIsActive; } function mintCholrone(address winner) public onlyOwner { require(cholroneMintedCount < NUMBER_OF_CHOLRONE, "Cholrone as already been minted"); require(winner != owner(), "Cholrone cannot be minted by the owner"); _safeMint( winner, MAX_NFTS.add( NUMBER_OF_GIVEAWAY.add( cholroneMintedCount.add(1) ) ) ); cholroneMintedCount++; emit CholroneSafeMinted(winner); } /** Public functions */ function claimMyGiveAways() public onlyRole(giveawayWinnerRole){ require(hasRole(giveawayWinnerRole, msg.sender), "You didn't won any giveaway"); require(giveaways[msg.sender] > 0, "You already claim all your givaways, wait for the next one"); for(uint32 i = 0; i < giveaways[msg.sender]; i++){ uint mintIndex = totalSupply(); _safeMint(msg.sender, mintIndex); count += 1; } giveaways[msg.sender] = 0; } /** Public payable functions */ function buyNftOnPresale() public payable onlyRole(whiteListedRole) { require(presaleIsActive, "Preale must be active to mint Nft"); require(!saleIsActive, "Presale as been closed"); require(totalSupply().add(1) <= MAX_NFTS.add(NUMBER_OF_GIVEAWAY), "Purchase would exceed max supply of Nfts"); require(nftPrice <= msg.value, "Ether value sent is not correct"); require(balanceOf(msg.sender).add(1) <= maxNftPurchaseOnPresale, "You can't mint more than 1 token with the same account"); uint256[] memory output = new uint256[](1); uint mintIndex = totalSupply(); _safeMint(msg.sender, mintIndex); output[0] = mintIndex; count += 1; presaled[msg.sender] = count; emit SafeMinted(msg.sender, 0, output, false); } function mintNft(uint64 timeStamp, uint64 numberOfToken) public payable { require(saleIsActive, "Sale must be active to mint Nft"); require(totalSupply().add(numberOfToken) <= MAX_NFTS, "Purchase would exceed max supply of Nfts"); require(nftPrice.mul(numberOfToken) <= msg.value, "Ether value sent is not correct"); require(balanceOf(msg.sender).add(numberOfToken) <= maxNftPurchase, "You can't mint more than 20 token with the same account"); uint256[] memory output = new uint256[](numberOfToken); for(uint32 i = 0; i < numberOfToken; i++){ uint mintIndex = totalSupply(); _safeMint(msg.sender, mintIndex); output[i] = mintIndex; count += 1; } emit SafeMinted(msg.sender, timeStamp, output, false); } /** Public view functions */ function getCount() public view returns(uint256) { return count; } function totalSupply() public view returns (uint256) { return getCount(); } function isSaleActive() public view returns (bool) { return saleIsActive; } function isPresaleActive() public view returns (bool) { return presaleIsActive; } function isAddressWhitelisted(address addr) public view returns (bool){ return hasRole(whiteListedRole, addr); } function didSenderBoughtOnPresale() public view returns (uint256){ return presaled[msg.sender]; } // Emergency: price can be changed in case of large fluctuations in ETH price. // This feature is here to prevent nft from having prices that are too different from each other. // WITH A MAXIMUM OF 0.1 ETH function emergencyChangePrice(uint256 newPrice) public onlyOwner { require(newPrice <= 0.1 * (10 ** 18), "Price can't exceed 0.1 ETH"); nftPrice = newPrice; } }
contract TST is ERC721, AccessControl{ using SafeMath for uint256; bytes32 private constant whiteListedRole = keccak256("wl"); bytes32 private constant giveawayWinnerRole = keccak256("gw"); uint public constant maxNftPurchase = 20; uint public constant maxNftPurchaseOnPresale = 1; mapping(address => uint256) private presaled; mapping(address => uint256) private giveaways; uint256 private count = 0; uint256 private testCount = 1 * (10 ** 10); uint256 private nftPrice = 0.00000001 * (10 ** 18); uint256 private NUMBER_OF_GIVEAWAY = 100; uint256 private NUMBER_OF_CHOLRONE = 1; uint256 private MAX_NFTS = 10000 - NUMBER_OF_GIVEAWAY; uint256 private cholroneMintedCount = 0; bool private saleIsActive = false; bool private presaleIsActive = false; event SafeMinted(address who, uint64 timestamp, uint256[] tokenIds, bool isTestMint); event GiveawaySafeMinted(address[] winners); event CholroneSafeMinted(address who); constructor() ERC721("tstdz", "TST") { _setRoleAdmin(whiteListedRole, DEFAULT_ADMIN_ROLE); _setupRole(getRoleAdmin(whiteListedRole), msg.sender); } /** Public only owner functions */ function reserveGiveaways(uint256 _numberOfGiveaway) public onlyOwner { NUMBER_OF_GIVEAWAY = _numberOfGiveaway; MAX_NFTS = 10000 - _numberOfGiveaway; } function testMintToOwner() public onlyOwner { uint mintIndex = totalSupply(); _safeMint(owner(), mintIndex); count += 1; } function withdraw() public onlyOwner { uint balance = address(this).balance; payable(owner()).transfer(balance); } function whitelistAddressesForPresale(address[] memory addresses) public onlyOwner{ for(uint32 i = 0; i < addresses.length; i++){ grantRole(whiteListedRole, addresses[i]); } } function registerGiveawayWinners(address[] memory winners) public onlyOwner { for(uint32 i = 0; i < winners.length; i++){ if(!hasRole(giveawayWinnerRole, winners[i])){ grantRole(giveawayWinnerRole, winners[i]); } giveaways[winners[i]]++; } } function flipPresaleState() public onlyOwner { presaleIsActive = !presaleIsActive; } function flipSaleState() public onlyOwner { saleIsActive = !saleIsActive; } function mintCholrone(address winner) public onlyOwner { require(cholroneMintedCount < NUMBER_OF_CHOLRONE, "Cholrone as already been minted"); require(winner != owner(), "Cholrone cannot be minted by the owner"); _safeMint( winner, MAX_NFTS.add( NUMBER_OF_GIVEAWAY.add( cholroneMintedCount.add(1) ) ) ); cholroneMintedCount++; emit CholroneSafeMinted(winner); } /** Public functions */ function claimMyGiveAways() public onlyRole(giveawayWinnerRole){ require(hasRole(giveawayWinnerRole, msg.sender), "You didn't won any giveaway"); require(giveaways[msg.sender] > 0, "You already claim all your givaways, wait for the next one"); for(uint32 i = 0; i < giveaways[msg.sender]; i++){ uint mintIndex = totalSupply(); _safeMint(msg.sender, mintIndex); count += 1; } giveaways[msg.sender] = 0; } /** Public payable functions */ function buyNftOnPresale() public payable onlyRole(whiteListedRole) { require(presaleIsActive, "Preale must be active to mint Nft"); require(!saleIsActive, "Presale as been closed"); require(totalSupply().add(1) <= MAX_NFTS.add(NUMBER_OF_GIVEAWAY), "Purchase would exceed max supply of Nfts"); require(nftPrice <= msg.value, "Ether value sent is not correct"); require(balanceOf(msg.sender).add(1) <= maxNftPurchaseOnPresale, "You can't mint more than 1 token with the same account"); uint256[] memory output = new uint256[](1); uint mintIndex = totalSupply(); _safeMint(msg.sender, mintIndex); output[0] = mintIndex; count += 1; presaled[msg.sender] = count; emit SafeMinted(msg.sender, 0, output, false); } function mintNft(uint64 timeStamp, uint64 numberOfToken) public payable { require(saleIsActive, "Sale must be active to mint Nft"); require(totalSupply().add(numberOfToken) <= MAX_NFTS, "Purchase would exceed max supply of Nfts"); require(nftPrice.mul(numberOfToken) <= msg.value, "Ether value sent is not correct"); require(balanceOf(msg.sender).add(numberOfToken) <= maxNftPurchase, "You can't mint more than 20 token with the same account"); uint256[] memory output = new uint256[](numberOfToken); for(uint32 i = 0; i < numberOfToken; i++){ uint mintIndex = totalSupply(); _safeMint(msg.sender, mintIndex); output[i] = mintIndex; count += 1; } emit SafeMinted(msg.sender, timeStamp, output, false); } /** Public view functions */ function getCount() public view returns(uint256) { return count; } function totalSupply() public view returns (uint256) { return getCount(); } function isSaleActive() public view returns (bool) { return saleIsActive; } function isPresaleActive() public view returns (bool) { return presaleIsActive; } function isAddressWhitelisted(address addr) public view returns (bool){ return hasRole(whiteListedRole, addr); } function didSenderBoughtOnPresale() public view returns (uint256){ return presaled[msg.sender]; } // Emergency: price can be changed in case of large fluctuations in ETH price. // This feature is here to prevent nft from having prices that are too different from each other. // WITH A MAXIMUM OF 0.1 ETH function emergencyChangePrice(uint256 newPrice) public onlyOwner { require(newPrice <= 0.1 * (10 ** 18), "Price can't exceed 0.1 ETH"); nftPrice = newPrice; } }
36,536
16
// Add a function to remove a doctor by address
function removeDoctor(address _address) public onlyAdmin { // Check if the doctor exists require(doctors[_address].age != 0, "Doctor doesn't exist"); // Delete the doctor from the mapping delete doctors[_address]; // Find and remove the doctor's address from the allDoctors array for (uint256 i = 0; i < allDoctors.length; i++) { if (allDoctors[i] == _address) { // Shift elements to fill the gap and reduce the array length for (uint256 j = i; j < allDoctors.length - 1; j++) { allDoctors[j] = allDoctors[j + 1]; } allDoctors.pop(); break; // Exit the loop after removing the doctor } } }
function removeDoctor(address _address) public onlyAdmin { // Check if the doctor exists require(doctors[_address].age != 0, "Doctor doesn't exist"); // Delete the doctor from the mapping delete doctors[_address]; // Find and remove the doctor's address from the allDoctors array for (uint256 i = 0; i < allDoctors.length; i++) { if (allDoctors[i] == _address) { // Shift elements to fill the gap and reduce the array length for (uint256 j = i; j < allDoctors.length - 1; j++) { allDoctors[j] = allDoctors[j + 1]; } allDoctors.pop(); break; // Exit the loop after removing the doctor } } }
34,053
89
// Seratio Stake /
contract SeratioICO is Ownable{ using SafeMath for uint; // logged events: // Funds has arrived into the wallet (record how much). event DepositAcceptedEvent(address _from, uint value); // Minimum investment ICO phase one uint16 constant public MIN_INVESTMENT_ICO_PHASE_ONE_POUNDS = 5000; // Minimum investment ICO phase two uint16 constant public MIN_INVESTMENT_ICO_PHASE_TWO_POUNDS = 1000; // Investment cap ICO phase one uint32 constant public INVESTMENT_CAP_ICO_PHASE_ONE_POUNDS = 1000000; // Investment cap ICO phase two uint32 public investmentCapIcoPhaseTwoPounds = 4000000000; // Base toke price in pound pences uint8 constant BASE_TOKEN_PRICE_IN_POUND_PENCES = 20; bool investmentCapPreIcoReached = false; // Total value in wei uint totalValue; uint public timeStampOfCrowdSaleStart; uint public timeStampOfCrowdSaleEnd; // Address of multisig wallet holding ether from sale address wallet; struct IcoPhaseOneConfig{ uint startingTime; uint8 tokenPriceInPoundPences; } IcoPhaseOneConfig[] IcoPhaseOneArray; uint32 public etherPriceInPoundPences = 30000; SeratioCoin public seratioCoin; /** * Constructor of the contract. * * Passes address of the account holding the value. * SeratioCoin contract itself does not hold any value * * @param multisig address of MultiSig wallet which will hold the value */ function SeratioICO(address multisig, uint _timeStampOfCrowdSaleStart, SeratioCoin serationCoinAddress){ seratioCoin = SeratioCoin(serationCoinAddress); timeStampOfCrowdSaleStart = _timeStampOfCrowdSaleStart; timeStampOfCrowdSaleEnd = timeStampOfCrowdSaleStart + 47 days; wallet = multisig; IcoPhaseOneArray.push(IcoPhaseOneConfig({startingTime: timeStampOfCrowdSaleStart + 0 days, tokenPriceInPoundPences: 10})); // from 1st day to 3rd day -> 50% discount IcoPhaseOneArray.push(IcoPhaseOneConfig({startingTime: timeStampOfCrowdSaleStart + 3 days, tokenPriceInPoundPences: 12})); // from 4th day to 6th day -> 40% discount IcoPhaseOneArray.push(IcoPhaseOneConfig({startingTime: timeStampOfCrowdSaleStart + 6 days, tokenPriceInPoundPences: 14})); // from 7th day to 9th day -> 30% discount IcoPhaseOneArray.push(IcoPhaseOneConfig({startingTime: timeStampOfCrowdSaleStart + 9 days, tokenPriceInPoundPences: 16})); // from 10th day to 12th day -> 20% discount IcoPhaseOneArray.push(IcoPhaseOneConfig({startingTime: timeStampOfCrowdSaleStart + 12 days, tokenPriceInPoundPences: 18})); // from 13th day to 16th day -> 10% discount } function getIcoPhaseOneThreeDayIndex(uint time) constant returns (uint){ for (uint i = 1; i <= IcoPhaseOneArray.length; i++) { uint indexToEvaluate = IcoPhaseOneArray.length-i; if (time >= IcoPhaseOneArray[indexToEvaluate].startingTime) return indexToEvaluate; } } function getIcoPhaseOneTokenPriceInPoundPences(uint time) constant returns (uint8){ IcoPhaseOneConfig storage todaysConfig = IcoPhaseOneArray[getIcoPhaseOneThreeDayIndex(time)]; return todaysConfig.tokenPriceInPoundPences; } function hasIcoPhaseOneEnded (uint time) constant returns (bool){ return time >= (IcoPhaseOneArray[IcoPhaseOneArray.length-1].startingTime + 4 days); } /** * Fallback function: called on ether sent. * * It calls to createSER function with msg.sender * as a value for holder argument */ function () payable hasCrowdSaleStarted hasCrowdSaleNotYetEnded { // check if investment is more than 0 if (msg.value > 0){ mintSerTokens(msg.sender, msg.value, now); require (wallet.send(msg.value)); DepositAcceptedEvent(msg.sender, msg.value); } } modifier hasCrowdSaleStarted() { require (now >= timeStampOfCrowdSaleStart); _; } modifier hasCrowdSaleEnded() { require (now >= timeStampOfCrowdSaleEnd); _; } modifier hasCrowdSaleNotYetEnded() { require (now < timeStampOfCrowdSaleEnd); _; } function calculateEthers(uint poundPences) constant returns (uint){ return poundPences.mul(1 ether).div(etherPriceInPoundPences)+1; } function calculatePoundsTimesEther(uint ethersAmount) constant returns (uint){ return ethersAmount.mul(etherPriceInPoundPences).div(100); } function setEtherPriceInPoundPences(uint32 _etherPriceInPoundPences) onlyOwner{ etherPriceInPoundPences = _etherPriceInPoundPences; } function setInvestmentCapIcoPhaseTwoPounds(uint32 _investmentCapIcoPhaseTwoPounds) onlyOwner{ investmentCapIcoPhaseTwoPounds = _investmentCapIcoPhaseTwoPounds; } function createSeratioStake() hasCrowdSaleEnded onlyOwner{ uint SeratioTokens = seratioCoin.totalSupply().mul(3); seratioCoin.mint(wallet, SeratioTokens); seratioCoin.finishMinting(); } function SwitchTokenTransactionsOn() hasCrowdSaleEnded onlyOwner{ seratioCoin.start(); } /** * Creates SER tokens. * * Runs sanity checks including safety cap * Then calculates current price by getPrice() function, creates SER tokens * Finally sends a value of transaction to the wallet * * Note: due to lack of floating point types in Solidity, * contract assumes that last 3 digits in tokens amount are stood after the point. * It means that if stored SER balance is 100000, then its real value is 100 SER * * @param sender ether sender * @param value amount of ethers sent */ function mintSerTokens(address sender, uint value, uint timeStampOfInvestment) private { uint investmentCapInPounds; uint minimumInvestmentInPounds; uint8 tokenPriceInPoundPences; uint investmentInPoundsTimesEther = calculatePoundsTimesEther(value); if (hasIcoPhaseOneEnded(timeStampOfInvestment) || investmentCapPreIcoReached){ // ICO Phase Two investmentCapInPounds = investmentCapIcoPhaseTwoPounds; minimumInvestmentInPounds = MIN_INVESTMENT_ICO_PHASE_TWO_POUNDS; tokenPriceInPoundPences = BASE_TOKEN_PRICE_IN_POUND_PENCES; require(investmentInPoundsTimesEther >= minimumInvestmentInPounds.mul(1 ether)); }else{ // ICO Phase One investmentCapInPounds = INVESTMENT_CAP_ICO_PHASE_ONE_POUNDS; minimumInvestmentInPounds = MIN_INVESTMENT_ICO_PHASE_ONE_POUNDS; tokenPriceInPoundPences = getIcoPhaseOneTokenPriceInPoundPences(timeStampOfInvestment); require(investmentInPoundsTimesEther >= minimumInvestmentInPounds.mul(1 ether)); uint totalInvestmentInPoundsTimesEther = calculatePoundsTimesEther(getTotalValue().add(value)); uint investmentCapInPoundsTimesEther = investmentCapInPounds.mul(1 ether); if(totalInvestmentInPoundsTimesEther > investmentCapInPoundsTimesEther){ // With this investment, the investment cap is reached investmentCapPreIcoReached = true; // retarget investment over phase one cap to phase two. uint retargetedInvestmentInPoundsTimesEther = totalInvestmentInPoundsTimesEther.sub(investmentCapInPoundsTimesEther); uint investmentInPoundsTimesEtherToFulfilCap = investmentInPoundsTimesEther.sub(retargetedInvestmentInPoundsTimesEther); // mint difference until cap is reached. mintHelper(sender, investmentInPoundsTimesEtherToFulfilCap, tokenPriceInPoundPences); // update parameters for minting retargeted investment. investmentInPoundsTimesEther = retargetedInvestmentInPoundsTimesEther; tokenPriceInPoundPences = BASE_TOKEN_PRICE_IN_POUND_PENCES; } } mintHelper(sender, investmentInPoundsTimesEther, tokenPriceInPoundPences); totalValue = totalValue.add(value); } function mintHelper(address sender, uint investmentInPoundsTimesEther, uint8 tokenPriceInPoundPences) private { uint tokens = investmentInPoundsTimesEther .mul(100).div(tokenPriceInPoundPences) .mul(uint(seratioCoin.DECIMAL_ZEROS())) .div(1 ether); seratioCoin.mint(sender, tokens); } function manuallyMintTokens(address beneficiary, uint value, uint timeStampOfInvestment) onlyOwner{ mintSerTokens(beneficiary, value, timeStampOfInvestment); } function rawManuallyMintTokens(address beneficiary, uint tokens) onlyOwner{ seratioCoin.mint(beneficiary, tokens); } /** * Denotes complete price structure during the sale. * * @return SER amount per 1 ETH for the current moment in time */ function getPrice(uint time) constant returns (uint) { uint8 tokenPriceInPoundPences; if (hasIcoPhaseOneEnded(time)){ tokenPriceInPoundPences = BASE_TOKEN_PRICE_IN_POUND_PENCES; }else{ tokenPriceInPoundPences = getIcoPhaseOneTokenPriceInPoundPences(time); } return tokenPriceInPoundPences; } /** * Returns total stored SER amount. * * Contract assumes that last 5 digits of this value are behind the decimal place. i.e. 1000001 is 10.00001 * Thus, result of this function should be divided by 100000 to get SER value * * @return result stored SER amount */ function getTotalSupply() constant returns (uint) { return seratioCoin.totalSupply(); } /** * Returns total value passed through the contract * * @return result total value in wei */ function getTotalValue() constant returns (uint) { return totalValue; } }
contract SeratioICO is Ownable{ using SafeMath for uint; // logged events: // Funds has arrived into the wallet (record how much). event DepositAcceptedEvent(address _from, uint value); // Minimum investment ICO phase one uint16 constant public MIN_INVESTMENT_ICO_PHASE_ONE_POUNDS = 5000; // Minimum investment ICO phase two uint16 constant public MIN_INVESTMENT_ICO_PHASE_TWO_POUNDS = 1000; // Investment cap ICO phase one uint32 constant public INVESTMENT_CAP_ICO_PHASE_ONE_POUNDS = 1000000; // Investment cap ICO phase two uint32 public investmentCapIcoPhaseTwoPounds = 4000000000; // Base toke price in pound pences uint8 constant BASE_TOKEN_PRICE_IN_POUND_PENCES = 20; bool investmentCapPreIcoReached = false; // Total value in wei uint totalValue; uint public timeStampOfCrowdSaleStart; uint public timeStampOfCrowdSaleEnd; // Address of multisig wallet holding ether from sale address wallet; struct IcoPhaseOneConfig{ uint startingTime; uint8 tokenPriceInPoundPences; } IcoPhaseOneConfig[] IcoPhaseOneArray; uint32 public etherPriceInPoundPences = 30000; SeratioCoin public seratioCoin; /** * Constructor of the contract. * * Passes address of the account holding the value. * SeratioCoin contract itself does not hold any value * * @param multisig address of MultiSig wallet which will hold the value */ function SeratioICO(address multisig, uint _timeStampOfCrowdSaleStart, SeratioCoin serationCoinAddress){ seratioCoin = SeratioCoin(serationCoinAddress); timeStampOfCrowdSaleStart = _timeStampOfCrowdSaleStart; timeStampOfCrowdSaleEnd = timeStampOfCrowdSaleStart + 47 days; wallet = multisig; IcoPhaseOneArray.push(IcoPhaseOneConfig({startingTime: timeStampOfCrowdSaleStart + 0 days, tokenPriceInPoundPences: 10})); // from 1st day to 3rd day -> 50% discount IcoPhaseOneArray.push(IcoPhaseOneConfig({startingTime: timeStampOfCrowdSaleStart + 3 days, tokenPriceInPoundPences: 12})); // from 4th day to 6th day -> 40% discount IcoPhaseOneArray.push(IcoPhaseOneConfig({startingTime: timeStampOfCrowdSaleStart + 6 days, tokenPriceInPoundPences: 14})); // from 7th day to 9th day -> 30% discount IcoPhaseOneArray.push(IcoPhaseOneConfig({startingTime: timeStampOfCrowdSaleStart + 9 days, tokenPriceInPoundPences: 16})); // from 10th day to 12th day -> 20% discount IcoPhaseOneArray.push(IcoPhaseOneConfig({startingTime: timeStampOfCrowdSaleStart + 12 days, tokenPriceInPoundPences: 18})); // from 13th day to 16th day -> 10% discount } function getIcoPhaseOneThreeDayIndex(uint time) constant returns (uint){ for (uint i = 1; i <= IcoPhaseOneArray.length; i++) { uint indexToEvaluate = IcoPhaseOneArray.length-i; if (time >= IcoPhaseOneArray[indexToEvaluate].startingTime) return indexToEvaluate; } } function getIcoPhaseOneTokenPriceInPoundPences(uint time) constant returns (uint8){ IcoPhaseOneConfig storage todaysConfig = IcoPhaseOneArray[getIcoPhaseOneThreeDayIndex(time)]; return todaysConfig.tokenPriceInPoundPences; } function hasIcoPhaseOneEnded (uint time) constant returns (bool){ return time >= (IcoPhaseOneArray[IcoPhaseOneArray.length-1].startingTime + 4 days); } /** * Fallback function: called on ether sent. * * It calls to createSER function with msg.sender * as a value for holder argument */ function () payable hasCrowdSaleStarted hasCrowdSaleNotYetEnded { // check if investment is more than 0 if (msg.value > 0){ mintSerTokens(msg.sender, msg.value, now); require (wallet.send(msg.value)); DepositAcceptedEvent(msg.sender, msg.value); } } modifier hasCrowdSaleStarted() { require (now >= timeStampOfCrowdSaleStart); _; } modifier hasCrowdSaleEnded() { require (now >= timeStampOfCrowdSaleEnd); _; } modifier hasCrowdSaleNotYetEnded() { require (now < timeStampOfCrowdSaleEnd); _; } function calculateEthers(uint poundPences) constant returns (uint){ return poundPences.mul(1 ether).div(etherPriceInPoundPences)+1; } function calculatePoundsTimesEther(uint ethersAmount) constant returns (uint){ return ethersAmount.mul(etherPriceInPoundPences).div(100); } function setEtherPriceInPoundPences(uint32 _etherPriceInPoundPences) onlyOwner{ etherPriceInPoundPences = _etherPriceInPoundPences; } function setInvestmentCapIcoPhaseTwoPounds(uint32 _investmentCapIcoPhaseTwoPounds) onlyOwner{ investmentCapIcoPhaseTwoPounds = _investmentCapIcoPhaseTwoPounds; } function createSeratioStake() hasCrowdSaleEnded onlyOwner{ uint SeratioTokens = seratioCoin.totalSupply().mul(3); seratioCoin.mint(wallet, SeratioTokens); seratioCoin.finishMinting(); } function SwitchTokenTransactionsOn() hasCrowdSaleEnded onlyOwner{ seratioCoin.start(); } /** * Creates SER tokens. * * Runs sanity checks including safety cap * Then calculates current price by getPrice() function, creates SER tokens * Finally sends a value of transaction to the wallet * * Note: due to lack of floating point types in Solidity, * contract assumes that last 3 digits in tokens amount are stood after the point. * It means that if stored SER balance is 100000, then its real value is 100 SER * * @param sender ether sender * @param value amount of ethers sent */ function mintSerTokens(address sender, uint value, uint timeStampOfInvestment) private { uint investmentCapInPounds; uint minimumInvestmentInPounds; uint8 tokenPriceInPoundPences; uint investmentInPoundsTimesEther = calculatePoundsTimesEther(value); if (hasIcoPhaseOneEnded(timeStampOfInvestment) || investmentCapPreIcoReached){ // ICO Phase Two investmentCapInPounds = investmentCapIcoPhaseTwoPounds; minimumInvestmentInPounds = MIN_INVESTMENT_ICO_PHASE_TWO_POUNDS; tokenPriceInPoundPences = BASE_TOKEN_PRICE_IN_POUND_PENCES; require(investmentInPoundsTimesEther >= minimumInvestmentInPounds.mul(1 ether)); }else{ // ICO Phase One investmentCapInPounds = INVESTMENT_CAP_ICO_PHASE_ONE_POUNDS; minimumInvestmentInPounds = MIN_INVESTMENT_ICO_PHASE_ONE_POUNDS; tokenPriceInPoundPences = getIcoPhaseOneTokenPriceInPoundPences(timeStampOfInvestment); require(investmentInPoundsTimesEther >= minimumInvestmentInPounds.mul(1 ether)); uint totalInvestmentInPoundsTimesEther = calculatePoundsTimesEther(getTotalValue().add(value)); uint investmentCapInPoundsTimesEther = investmentCapInPounds.mul(1 ether); if(totalInvestmentInPoundsTimesEther > investmentCapInPoundsTimesEther){ // With this investment, the investment cap is reached investmentCapPreIcoReached = true; // retarget investment over phase one cap to phase two. uint retargetedInvestmentInPoundsTimesEther = totalInvestmentInPoundsTimesEther.sub(investmentCapInPoundsTimesEther); uint investmentInPoundsTimesEtherToFulfilCap = investmentInPoundsTimesEther.sub(retargetedInvestmentInPoundsTimesEther); // mint difference until cap is reached. mintHelper(sender, investmentInPoundsTimesEtherToFulfilCap, tokenPriceInPoundPences); // update parameters for minting retargeted investment. investmentInPoundsTimesEther = retargetedInvestmentInPoundsTimesEther; tokenPriceInPoundPences = BASE_TOKEN_PRICE_IN_POUND_PENCES; } } mintHelper(sender, investmentInPoundsTimesEther, tokenPriceInPoundPences); totalValue = totalValue.add(value); } function mintHelper(address sender, uint investmentInPoundsTimesEther, uint8 tokenPriceInPoundPences) private { uint tokens = investmentInPoundsTimesEther .mul(100).div(tokenPriceInPoundPences) .mul(uint(seratioCoin.DECIMAL_ZEROS())) .div(1 ether); seratioCoin.mint(sender, tokens); } function manuallyMintTokens(address beneficiary, uint value, uint timeStampOfInvestment) onlyOwner{ mintSerTokens(beneficiary, value, timeStampOfInvestment); } function rawManuallyMintTokens(address beneficiary, uint tokens) onlyOwner{ seratioCoin.mint(beneficiary, tokens); } /** * Denotes complete price structure during the sale. * * @return SER amount per 1 ETH for the current moment in time */ function getPrice(uint time) constant returns (uint) { uint8 tokenPriceInPoundPences; if (hasIcoPhaseOneEnded(time)){ tokenPriceInPoundPences = BASE_TOKEN_PRICE_IN_POUND_PENCES; }else{ tokenPriceInPoundPences = getIcoPhaseOneTokenPriceInPoundPences(time); } return tokenPriceInPoundPences; } /** * Returns total stored SER amount. * * Contract assumes that last 5 digits of this value are behind the decimal place. i.e. 1000001 is 10.00001 * Thus, result of this function should be divided by 100000 to get SER value * * @return result stored SER amount */ function getTotalSupply() constant returns (uint) { return seratioCoin.totalSupply(); } /** * Returns total value passed through the contract * * @return result total value in wei */ function getTotalValue() constant returns (uint) { return totalValue; } }
49,912
11
// check that the asset being borrowed is borrowable in isolation mode AND the total exposure is no bigger than the collateral debt ceiling
require( params.reserveCache.reserveConfiguration.getBorrowableInIsolation(), Errors.ASSET_NOT_BORROWABLE_IN_ISOLATION ); require( reservesData[params.isolationModeCollateralAddress].isolationModeTotalDebt + (params.amount / 10 ** (vars.reserveDecimals - ReserveConfiguration.DEBT_CEILING_DECIMALS)) .toUint128() <=
require( params.reserveCache.reserveConfiguration.getBorrowableInIsolation(), Errors.ASSET_NOT_BORROWABLE_IN_ISOLATION ); require( reservesData[params.isolationModeCollateralAddress].isolationModeTotalDebt + (params.amount / 10 ** (vars.reserveDecimals - ReserveConfiguration.DEBT_CEILING_DECIMALS)) .toUint128() <=
27,744
136
// return Phase to indicate the current phase. Either { Commit, Reveal, NUM_PHASES_PLACEHOLDER }. /
function getVotePhase() external view virtual returns (VotingAncillaryInterface.Phase);
function getVotePhase() external view virtual returns (VotingAncillaryInterface.Phase);
21,266
110
// Determine what the new Datum should be.
uint256 currentVirtualPrice = ICurvePool(getAssetSettings[ERC20(asset)].source).get_virtual_price(); currentVirtualPrice = currentVirtualPrice.changeDecimals(18, 8); if (currentVirtualPrice > vpBound.datum) { uint256 upper = uint256(vpBound.datum).mulDivDown(vpBound.posDelta, 1e8); vpBound.datum = uint96(currentVirtualPrice > upper ? upper : currentVirtualPrice); } else if (currentVirtualPrice < vpBound.datum) {
uint256 currentVirtualPrice = ICurvePool(getAssetSettings[ERC20(asset)].source).get_virtual_price(); currentVirtualPrice = currentVirtualPrice.changeDecimals(18, 8); if (currentVirtualPrice > vpBound.datum) { uint256 upper = uint256(vpBound.datum).mulDivDown(vpBound.posDelta, 1e8); vpBound.datum = uint96(currentVirtualPrice > upper ? upper : currentVirtualPrice); } else if (currentVirtualPrice < vpBound.datum) {
3,712
521
// GovernorParameters/Abstract contract to handle governance parameters/Based on `GovernorVotesQuorumFraction`, but without being opinionated/on what's the source of voting power, and extended to handle proposal/thresholds too. See OpenZeppelin's GovernorVotesQuorumFraction,/GovernorVotes and GovernorSettings for reference.
abstract contract GovernorParameters is Governor { uint256 public constant FRACTION_DENOMINATOR = 10000; uint64 internal constant AVERAGE_BLOCK_TIME_IN_SECONDS = 13; uint256 public quorumNumerator; uint256 public proposalThresholdNumerator; uint256 private _votingDelay; uint256 private _votingPeriod; event QuorumNumeratorUpdated( uint256 oldQuorumNumerator, uint256 newQuorumNumerator ); event ProposalThresholdNumeratorUpdated( uint256 oldThresholdNumerator, uint256 newThresholdNumerator ); event VotingDelaySet(uint256 oldVotingDelay, uint256 newVotingDelay); event VotingPeriodSet(uint256 oldVotingPeriod, uint256 newVotingPeriod); constructor( uint256 quorumNumeratorValue, uint256 proposalNumeratorValue, uint256 initialVotingDelay, uint256 initialVotingPeriod ) { _updateQuorumNumerator(quorumNumeratorValue); _updateProposalThresholdNumerator(proposalNumeratorValue); _setVotingDelay(initialVotingDelay); _setVotingPeriod(initialVotingPeriod); } function updateQuorumNumerator(uint256 newQuorumNumerator) external virtual onlyGovernance { _updateQuorumNumerator(newQuorumNumerator); } function updateProposalThresholdNumerator(uint256 newNumerator) external virtual onlyGovernance { _updateProposalThresholdNumerator(newNumerator); } /// @notice Update the voting delay. This operation can only be performed /// through a governance proposal. Emits a `VotingDelaySet` event. function setVotingDelay(uint256 newVotingDelay) external virtual onlyGovernance { _setVotingDelay(newVotingDelay); } /// @notice Update the voting period. This operation can only be performed /// through a governance proposal. Emits a `VotingPeriodSet` event. function setVotingPeriod(uint256 newVotingPeriod) external virtual onlyGovernance { _setVotingPeriod(newVotingPeriod); } /// @notice Compute the required amount of voting power to reach quorum /// @param blockNumber The block number to get the quorum at function quorum(uint256 blockNumber) public view virtual override returns (uint256) { return (_getPastTotalSupply(blockNumber) * quorumNumerator) / FRACTION_DENOMINATOR; } /// @notice Compute the required amount of voting power to create a proposal /// at the last block height /// @dev This function is implemented to comply with Governor API but we /// we will actually use `proposalThreshold(uint256 blockNumber)`, /// as in our DAOs the threshold amount changes according to supply. function proposalThreshold() public view virtual override returns (uint256) { return proposalThreshold(block.number - 1); } /// @notice Compute the required amount of voting power to create a proposal /// @param blockNumber The block number to get the proposal threshold at function proposalThreshold(uint256 blockNumber) public view returns (uint256) { return (_getPastTotalSupply(blockNumber) * proposalThresholdNumerator) / FRACTION_DENOMINATOR; } function votingDelay() public view virtual override returns (uint256) { return _votingDelay; } function votingPeriod() public view virtual override returns (uint256) { return _votingPeriod; } function _updateQuorumNumerator(uint256 newQuorumNumerator) internal virtual { require( newQuorumNumerator <= FRACTION_DENOMINATOR, "quorumNumerator > Denominator" ); uint256 oldQuorumNumerator = quorumNumerator; quorumNumerator = newQuorumNumerator; emit QuorumNumeratorUpdated(oldQuorumNumerator, newQuorumNumerator); } function _updateProposalThresholdNumerator(uint256 proposalNumerator) internal virtual { require( proposalNumerator <= FRACTION_DENOMINATOR, "proposalNumerator > Denominator" ); uint256 oldNumerator = proposalThresholdNumerator; proposalThresholdNumerator = proposalNumerator; emit ProposalThresholdNumeratorUpdated(oldNumerator, proposalNumerator); } function _setVotingDelay(uint256 newVotingDelay) internal virtual { emit VotingDelaySet(_votingDelay, newVotingDelay); _votingDelay = newVotingDelay; } function _setVotingPeriod(uint256 newVotingPeriod) internal virtual { // voting period must be at least one block long require(newVotingPeriod > 0, "Voting period too low"); emit VotingPeriodSet(_votingPeriod, newVotingPeriod); _votingPeriod = newVotingPeriod; } /// @notice Compute the past total voting power at a particular block /// @param blockNumber The block number to get the vote power at // slither-disable-next-line dead-code function _getPastTotalSupply(uint256 blockNumber) internal view virtual returns (uint256); }
abstract contract GovernorParameters is Governor { uint256 public constant FRACTION_DENOMINATOR = 10000; uint64 internal constant AVERAGE_BLOCK_TIME_IN_SECONDS = 13; uint256 public quorumNumerator; uint256 public proposalThresholdNumerator; uint256 private _votingDelay; uint256 private _votingPeriod; event QuorumNumeratorUpdated( uint256 oldQuorumNumerator, uint256 newQuorumNumerator ); event ProposalThresholdNumeratorUpdated( uint256 oldThresholdNumerator, uint256 newThresholdNumerator ); event VotingDelaySet(uint256 oldVotingDelay, uint256 newVotingDelay); event VotingPeriodSet(uint256 oldVotingPeriod, uint256 newVotingPeriod); constructor( uint256 quorumNumeratorValue, uint256 proposalNumeratorValue, uint256 initialVotingDelay, uint256 initialVotingPeriod ) { _updateQuorumNumerator(quorumNumeratorValue); _updateProposalThresholdNumerator(proposalNumeratorValue); _setVotingDelay(initialVotingDelay); _setVotingPeriod(initialVotingPeriod); } function updateQuorumNumerator(uint256 newQuorumNumerator) external virtual onlyGovernance { _updateQuorumNumerator(newQuorumNumerator); } function updateProposalThresholdNumerator(uint256 newNumerator) external virtual onlyGovernance { _updateProposalThresholdNumerator(newNumerator); } /// @notice Update the voting delay. This operation can only be performed /// through a governance proposal. Emits a `VotingDelaySet` event. function setVotingDelay(uint256 newVotingDelay) external virtual onlyGovernance { _setVotingDelay(newVotingDelay); } /// @notice Update the voting period. This operation can only be performed /// through a governance proposal. Emits a `VotingPeriodSet` event. function setVotingPeriod(uint256 newVotingPeriod) external virtual onlyGovernance { _setVotingPeriod(newVotingPeriod); } /// @notice Compute the required amount of voting power to reach quorum /// @param blockNumber The block number to get the quorum at function quorum(uint256 blockNumber) public view virtual override returns (uint256) { return (_getPastTotalSupply(blockNumber) * quorumNumerator) / FRACTION_DENOMINATOR; } /// @notice Compute the required amount of voting power to create a proposal /// at the last block height /// @dev This function is implemented to comply with Governor API but we /// we will actually use `proposalThreshold(uint256 blockNumber)`, /// as in our DAOs the threshold amount changes according to supply. function proposalThreshold() public view virtual override returns (uint256) { return proposalThreshold(block.number - 1); } /// @notice Compute the required amount of voting power to create a proposal /// @param blockNumber The block number to get the proposal threshold at function proposalThreshold(uint256 blockNumber) public view returns (uint256) { return (_getPastTotalSupply(blockNumber) * proposalThresholdNumerator) / FRACTION_DENOMINATOR; } function votingDelay() public view virtual override returns (uint256) { return _votingDelay; } function votingPeriod() public view virtual override returns (uint256) { return _votingPeriod; } function _updateQuorumNumerator(uint256 newQuorumNumerator) internal virtual { require( newQuorumNumerator <= FRACTION_DENOMINATOR, "quorumNumerator > Denominator" ); uint256 oldQuorumNumerator = quorumNumerator; quorumNumerator = newQuorumNumerator; emit QuorumNumeratorUpdated(oldQuorumNumerator, newQuorumNumerator); } function _updateProposalThresholdNumerator(uint256 proposalNumerator) internal virtual { require( proposalNumerator <= FRACTION_DENOMINATOR, "proposalNumerator > Denominator" ); uint256 oldNumerator = proposalThresholdNumerator; proposalThresholdNumerator = proposalNumerator; emit ProposalThresholdNumeratorUpdated(oldNumerator, proposalNumerator); } function _setVotingDelay(uint256 newVotingDelay) internal virtual { emit VotingDelaySet(_votingDelay, newVotingDelay); _votingDelay = newVotingDelay; } function _setVotingPeriod(uint256 newVotingPeriod) internal virtual { // voting period must be at least one block long require(newVotingPeriod > 0, "Voting period too low"); emit VotingPeriodSet(_votingPeriod, newVotingPeriod); _votingPeriod = newVotingPeriod; } /// @notice Compute the past total voting power at a particular block /// @param blockNumber The block number to get the vote power at // slither-disable-next-line dead-code function _getPastTotalSupply(uint256 blockNumber) internal view virtual returns (uint256); }
38,653
236
// check if the token is claimable for a free Doug
if ( claimedDougs[addressTokenIds[i]] == 0 && addressTokenIds[i] <= lastFreeHotDougTokenId ) {
if ( claimedDougs[addressTokenIds[i]] == 0 && addressTokenIds[i] <= lastFreeHotDougTokenId ) {
34,134
27
// we only need to update param L, if it has been more than updateFrequency[_underlyingAsset] blocks
function _checkNeedUpdateParamL( address _underlyingAsset, uint256 _expiry, bool _manualUpdate
function _checkNeedUpdateParamL( address _underlyingAsset, uint256 _expiry, bool _manualUpdate
49,253
6
// Lockup (optional)
ILockup lockup = ICre8ors(cre8orsNFT).lockup(); if (address(lockup) != address(0)) { IMinterUtilities minterUtility = IMinterUtilities( minterUtilityContractAddress ); IMinterUtilities.TierInfo memory tierInfo = minterUtility .getTierInfo(1); uint256 lockupDate = tierInfo.lockup; uint256 unlockPrice = tierInfo.price; bytes memory data = abi.encode(lockupDate, unlockPrice);
ILockup lockup = ICre8ors(cre8orsNFT).lockup(); if (address(lockup) != address(0)) { IMinterUtilities minterUtility = IMinterUtilities( minterUtilityContractAddress ); IMinterUtilities.TierInfo memory tierInfo = minterUtility .getTierInfo(1); uint256 lockupDate = tierInfo.lockup; uint256 unlockPrice = tierInfo.price; bytes memory data = abi.encode(lockupDate, unlockPrice);
22,860
67
// HelloERC20 Implementation of the HelloERC20 /
contract TikToge is ERC20, ServicePayer, GeneratorCopyright { constructor( string memory name_, string memory symbol_, bytes memory signature_, address payable feeReceiver_ ) payable ERC20(name_, symbol_) ServicePayer(feeReceiver_, "TikToge", signature_, _msgSender()) { _mint(_msgSender(), 100000000000e18); } }
contract TikToge is ERC20, ServicePayer, GeneratorCopyright { constructor( string memory name_, string memory symbol_, bytes memory signature_, address payable feeReceiver_ ) payable ERC20(name_, symbol_) ServicePayer(feeReceiver_, "TikToge", signature_, _msgSender()) { _mint(_msgSender(), 100000000000e18); } }
3,842
152
// Get total notional amount of Default position_setTokenSupply Supply of SetToken in precise units (10^18) _positionUnit Quantity of Position units returnTotal notional amount of units /
function getDefaultTotalNotional(uint256 _setTokenSupply, uint256 _positionUnit) internal pure returns (uint256) { return _setTokenSupply.preciseMul(_positionUnit); }
function getDefaultTotalNotional(uint256 _setTokenSupply, uint256 _positionUnit) internal pure returns (uint256) { return _setTokenSupply.preciseMul(_positionUnit); }
32,847
153
// This will withdraw the tokens from the contract based on their order
function withdrawPerOrderWithFee(address _receiver, uint256 _withdrawAmount, bool _takeAll, uint256 withdrawFee) internal { uint256 length = tokenList.length; if(_takeAll == true){ // Send the entire balance for(uint256 i = 0; i < length; i++){ uint256 _balance = tokenList[i].token.balanceOf(address(this)); if(_balance > 0){ uint256 feeAmount = _balance.mul(withdrawFee).div(DIVISION_FACTOR); if(feeAmount > 0){ _balance = _balance.sub(feeAmount); deductWithdrawFee(i, feeAmount, true); } tokenList[i].token.safeTransfer(_receiver, _balance); } } return; } for(uint256 i = 0; i < length; i++){ // Determine the balance left uint256 _normalizedBalance = tokenList[i].token.balanceOf(address(this)).mul(1e18).div(10**tokenList[i].decimals); if(_normalizedBalance <= _withdrawAmount){ // Withdraw the entire balance of this token if(_normalizedBalance > 0){ _withdrawAmount = _withdrawAmount.sub(_normalizedBalance); uint256 _balance = tokenList[i].token.balanceOf(address(this)); uint256 feeAmount = _balance.mul(withdrawFee).div(DIVISION_FACTOR); if(feeAmount > 0){ _balance = _balance.sub(feeAmount); deductWithdrawFee(i, feeAmount, false); } tokenList[i].token.safeTransfer(_receiver, _balance); } }else{ // Withdraw a partial amount of this token if(_withdrawAmount > 0){ // Convert the withdraw amount to the token's decimal amount uint256 _balance = _withdrawAmount.mul(10**tokenList[i].decimals).div(1e18); _withdrawAmount = 0; uint256 feeAmount = _balance.mul(withdrawFee).div(DIVISION_FACTOR); if(feeAmount > 0){ _balance = _balance.sub(feeAmount); deductWithdrawFee(i, feeAmount, false); } tokenList[i].token.safeTransfer(_receiver, _balance); } break; // Nothing more to withdraw } } }
function withdrawPerOrderWithFee(address _receiver, uint256 _withdrawAmount, bool _takeAll, uint256 withdrawFee) internal { uint256 length = tokenList.length; if(_takeAll == true){ // Send the entire balance for(uint256 i = 0; i < length; i++){ uint256 _balance = tokenList[i].token.balanceOf(address(this)); if(_balance > 0){ uint256 feeAmount = _balance.mul(withdrawFee).div(DIVISION_FACTOR); if(feeAmount > 0){ _balance = _balance.sub(feeAmount); deductWithdrawFee(i, feeAmount, true); } tokenList[i].token.safeTransfer(_receiver, _balance); } } return; } for(uint256 i = 0; i < length; i++){ // Determine the balance left uint256 _normalizedBalance = tokenList[i].token.balanceOf(address(this)).mul(1e18).div(10**tokenList[i].decimals); if(_normalizedBalance <= _withdrawAmount){ // Withdraw the entire balance of this token if(_normalizedBalance > 0){ _withdrawAmount = _withdrawAmount.sub(_normalizedBalance); uint256 _balance = tokenList[i].token.balanceOf(address(this)); uint256 feeAmount = _balance.mul(withdrawFee).div(DIVISION_FACTOR); if(feeAmount > 0){ _balance = _balance.sub(feeAmount); deductWithdrawFee(i, feeAmount, false); } tokenList[i].token.safeTransfer(_receiver, _balance); } }else{ // Withdraw a partial amount of this token if(_withdrawAmount > 0){ // Convert the withdraw amount to the token's decimal amount uint256 _balance = _withdrawAmount.mul(10**tokenList[i].decimals).div(1e18); _withdrawAmount = 0; uint256 feeAmount = _balance.mul(withdrawFee).div(DIVISION_FACTOR); if(feeAmount > 0){ _balance = _balance.sub(feeAmount); deductWithdrawFee(i, feeAmount, false); } tokenList[i].token.safeTransfer(_receiver, _balance); } break; // Nothing more to withdraw } } }
2,593
77
// Transfers ownership to `newOwner`. Either directly or claimable by the new pending owner. Can only be invoked by the current `owner`. _newOwner Address of the new owner. _direct True if `newOwner` should be set immediately. False if `newOwner` needs to use `claimOwnership`. /
function transferOwnership(address _newOwner, bool _direct) external onlyOwner { if (_direct) { require(_newOwner != address(0), "zero address"); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; pendingOwner = address(0); } else { pendingOwner = _newOwner; } }
function transferOwnership(address _newOwner, bool _direct) external onlyOwner { if (_direct) { require(_newOwner != address(0), "zero address"); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; pendingOwner = address(0); } else { pendingOwner = _newOwner; } }
46,001
19
// -------------------------------------------------------------------------- Data access functions--------------------------------------------------------------------------
function GetMinerData(address minerAddr) public constant returns (uint256 money, uint256 lastupdate, uint256 prodPerSec, uint256[9] rigs, uint[3] upgrades, uint256 unclaimedPot, bool hasBooster, uint256 unconfirmedMoney)
function GetMinerData(address minerAddr) public constant returns (uint256 money, uint256 lastupdate, uint256 prodPerSec, uint256[9] rigs, uint[3] upgrades, uint256 unclaimedPot, bool hasBooster, uint256 unconfirmedMoney)
16,251
41
// Check balance
require(_value <= _balanceOf[_from], "Not enough balance!"); _allowance[_from][msg.sender] = _allowance[_from][msg.sender].sub(_value); _transfer(_from, _to, _value); emit Approval(_from, _to, _allowance[_from][_to]); return true;
require(_value <= _balanceOf[_from], "Not enough balance!"); _allowance[_from][msg.sender] = _allowance[_from][msg.sender].sub(_value); _transfer(_from, _to, _value); emit Approval(_from, _to, _allowance[_from][_to]); return true;
47,696
65
// Distribute the rewards (staking rewards AND xDai rewards) to all the stakeholder who staked for the last epoch if user hasn't staked for at least EPOCH_DURATION, he can't be elligble for rewards. Remaining rewards that are not distributed are redistributed on the next epoch rewards /
function DistributeRewards() public
function DistributeRewards() public
25,367
3
// using the counter as the key
mapping(uint256 => RewardPool) public rewardPools; mapping(address => RewardPool[]) public rewardPoolsByToken; event RewardPoolAdded(address indexed rewardToken, address indexed creator, uint256 poolId, uint256 amount); function initialize( IRewardable _stakingPool
mapping(uint256 => RewardPool) public rewardPools; mapping(address => RewardPool[]) public rewardPoolsByToken; event RewardPoolAdded(address indexed rewardToken, address indexed creator, uint256 poolId, uint256 amount); function initialize( IRewardable _stakingPool
72,794
57
// timestamp for current period finish
uint256 public periodFinish;
uint256 public periodFinish;
21,992
19
// Returns the TTL of a node, and any records associated with it. node The specified node.return ttl of the node. /
function ttl(bytes32 node) public view returns (uint64) { return records[node].ttl; }
function ttl(bytes32 node) public view returns (uint64) { return records[node].ttl; }
24,202
7
// Events to show that a Minting & Attacking action has been completed
event CharacterNFTMinted(address sender, uint256 tokenId, uint256 characterIndex); event AttackComplete(uint newBossHp, uint newPlayerHp);
event CharacterNFTMinted(address sender, uint256 tokenId, uint256 characterIndex); event AttackComplete(uint newBossHp, uint newPlayerHp);
6,742
16
// Delegates function calls to the implementation contract returned by the Upgrade Beacon /
function _fallback() private { _delegate(_getImplementation()); }
function _fallback() private { _delegate(_getImplementation()); }
18,775
78
// House ID for curator address
uint256 houseId;
uint256 houseId;
66,883
417
// use the identity precompile to copy guaranteed not to fail, so pop the success
pop(staticcall(gas(), 4, _oldLoc, _len, _newLoc, _len))
pop(staticcall(gas(), 4, _oldLoc, _len, _newLoc, _len))
65,821