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
9
// Returns the downcasted uint176 from uint256, reverting onoverflow (when the input is greater than largest uint176). Counterpart to Solidity's `uint176` operator. Requirements: - input must fit into 176 bits /
function toUint176(uint256 value) internal pure returns (uint176) { require(value < 2**176, "SafeCast: value doesn\'t fit in 176 bits"); return uint176(value); }
function toUint176(uint256 value) internal pure returns (uint176) { require(value < 2**176, "SafeCast: value doesn\'t fit in 176 bits"); return uint176(value); }
12,225
119
// if any account belongs to _isExcludedFromFee account then remove the fee
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; }
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; }
590
42
// Redeem a specific collateral type using an amount of internal system coins from your bag collateralType The collateral type to redeem coinsAmount The amount of internal coins to use from your bag /
function redeemCollateral(bytes32 collateralType, uint256 coinsAmount) external { require(collateralCashPrice[collateralType] != 0, "GlobalSettlement/collateral-cash-price-not-defined"); uint256 collateralAmount = rmultiply(coinsAmount, collateralCashPrice[collateralType]); safeEngine.transferCollateral( collateralType, address(this), msg.sender, collateralAmount ); coinsUsedToRedeem[collateralType][msg.sender] = addition(coinsUsedToRedeem[collateralType][msg.sender], coinsAmount); require(coinsUsedToRedeem[collateralType][msg.sender] <= coinBag[msg.sender], "GlobalSettlement/insufficient-bag-balance"); emit RedeemCollateral(collateralType, msg.sender, coinsAmount, collateralAmount); }
function redeemCollateral(bytes32 collateralType, uint256 coinsAmount) external { require(collateralCashPrice[collateralType] != 0, "GlobalSettlement/collateral-cash-price-not-defined"); uint256 collateralAmount = rmultiply(coinsAmount, collateralCashPrice[collateralType]); safeEngine.transferCollateral( collateralType, address(this), msg.sender, collateralAmount ); coinsUsedToRedeem[collateralType][msg.sender] = addition(coinsUsedToRedeem[collateralType][msg.sender], coinsAmount); require(coinsUsedToRedeem[collateralType][msg.sender] <= coinBag[msg.sender], "GlobalSettlement/insufficient-bag-balance"); emit RedeemCollateral(collateralType, msg.sender, coinsAmount, collateralAmount); }
38,080
3
// called when user wants to withdraw tokens back to root chain Should burn user's tokens. This transaction will be verified when exiting on root chain amount amount of tokens to withdraw /
function withdraw(uint256 amount) external { _burn(_msgSender(), amount); }
function withdraw(uint256 amount) external { _burn(_msgSender(), amount); }
6,219
10
// ERC 20 /
function balanceOf(address _owner) public constant returns (uint256 balance); function transfer(address _to, uint256 _value) public returns (bool success); function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); function approve(address _spender, uint256 _value) public returns (bool success); function allowance(address _owner, address _spender) public constant returns (uint256 remaining); function burn(uint num) public;
function balanceOf(address _owner) public constant returns (uint256 balance); function transfer(address _to, uint256 _value) public returns (bool success); function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); function approve(address _spender, uint256 _value) public returns (bool success); function allowance(address _owner, address _spender) public constant returns (uint256 remaining); function burn(uint num) public;
17,702
0
// Calculator of pool owner commission for each block reward/Danilo Tuler/This provides flexibility for different commission models
interface Fee { /// @notice calculates the total amount of the reward that will be directed to the pool owner /// @return amount of tokens taken by the pool owner as commission function getCommission(uint256 posIndex, uint256 rewardAmount) external view returns (uint256); }
interface Fee { /// @notice calculates the total amount of the reward that will be directed to the pool owner /// @return amount of tokens taken by the pool owner as commission function getCommission(uint256 posIndex, uint256 rewardAmount) external view returns (uint256); }
24,425
12
// Utility function to convert string to bytes32 /
function stringToBytes32(string memory source) private pure returns (bytes32 result) { bytes memory tempEmptyStringTest = bytes(source); if (tempEmptyStringTest.length == 0) { return 0x0; } assembly { result := mload(add(source, 32)) } }
function stringToBytes32(string memory source) private pure returns (bytes32 result) { bytes memory tempEmptyStringTest = bytes(source); if (tempEmptyStringTest.length == 0) { return 0x0; } assembly { result := mload(add(source, 32)) } }
27,018
23
// Event emitted when the DAO contract is changed/daoContract The address of the new DAO contract/admin The admin account that made the change
event DAOContractChanged(address daoContract, address admin);
event DAOContractChanged(address daoContract, address admin);
21,333
0
// _airnode Address of the Airnode contract
constructor (address _airnode) public
constructor (address _airnode) public
1,707
34
// The Ownable constructor sets the original `owner` of the contract to the senderaccount. /
function initialize(address sender) public initializer { _owner = sender; }
function initialize(address sender) public initializer { _owner = sender; }
39,773
8
// TODO: extract the correct part of the block header for this
bytes32 signedmsg = keccak256(""); address signer = ecrecover(signedmsg, v, r, s); console.log(signer, miner);
bytes32 signedmsg = keccak256(""); address signer = ecrecover(signedmsg, v, r, s); console.log(signer, miner);
1,735
16
// Manage Holders List
_addHolder(from); _addHolder(to); if (balanceOf(from) == 0) _removeHolder(from); return;
_addHolder(from); _addHolder(to); if (balanceOf(from) == 0) _removeHolder(from); return;
15,016
7
// Transfers `amount` tokens from `sender` to `recipient` up to the allowance given to the `msg.sender`/sender The account from which the transfer will be initiated/recipient The recipient of the transfer/amount The amount of the transfer/ return Returns true for a successful transfer, false for unsuccessful
function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool);
function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool);
7,636
9
// Add a new version of the logic contract _version The version to be associated with the new contract. _logic New logic contract.return Success of the transaction. /
function addLogicVersion ( uint256 _version, address _logic ) external returns(bool)
function addLogicVersion ( uint256 _version, address _logic ) external returns(bool)
13,957
16
// Reverts if the proposer didn't specify a target address
error PROPOSAL_TARGET_MISSING();
error PROPOSAL_TARGET_MISSING();
32,282
53
// Restart the process of vendor minting with vendorMint().
function unpause() public isManager virtual
function unpause() public isManager virtual
43,618
7
// NFT Token Metadata Provides common functions for various NFT metadata standards. This extension supports base URI, per-token URI, and a fallback URI. You can also freeze URIs until a certain token ID. @custom:type eip-2535-facet@custom:category NFTs@custom:provides-interfaces ITokenMetadata /
contract TokenMetadata is ITokenMetadata { function baseURI() external view virtual returns (string memory) { return TokenMetadataStorage.layout().baseURI; } function fallbackURI() external view virtual returns (string memory) { return TokenMetadataStorage.layout().fallbackURI; } function uriSuffix() external view virtual returns (string memory) { return TokenMetadataStorage.layout().uriSuffix; } function baseURILocked() external view virtual returns (bool) { return TokenMetadataStorage.layout().baseURILocked; } function fallbackURILocked() external view virtual returns (bool) { return TokenMetadataStorage.layout().fallbackURILocked; } function uriSuffixLocked() external view virtual returns (bool) { return TokenMetadataStorage.layout().uriSuffixLocked; } function lastUnlockedTokenId() external view virtual returns (uint256) { return TokenMetadataStorage.layout().lastUnlockedTokenId; } }
contract TokenMetadata is ITokenMetadata { function baseURI() external view virtual returns (string memory) { return TokenMetadataStorage.layout().baseURI; } function fallbackURI() external view virtual returns (string memory) { return TokenMetadataStorage.layout().fallbackURI; } function uriSuffix() external view virtual returns (string memory) { return TokenMetadataStorage.layout().uriSuffix; } function baseURILocked() external view virtual returns (bool) { return TokenMetadataStorage.layout().baseURILocked; } function fallbackURILocked() external view virtual returns (bool) { return TokenMetadataStorage.layout().fallbackURILocked; } function uriSuffixLocked() external view virtual returns (bool) { return TokenMetadataStorage.layout().uriSuffixLocked; } function lastUnlockedTokenId() external view virtual returns (uint256) { return TokenMetadataStorage.layout().lastUnlockedTokenId; } }
8,412
11
// Make sure this is not a duplicate pool
mapping(IERC20 => bool) public supportedToken; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw( address indexed user, uint256 indexed pid, uint256 amount );
mapping(IERC20 => bool) public supportedToken; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw( address indexed user, uint256 indexed pid, uint256 amount );
70,903
4,066
// 2034
entry "untasked" : ENG_ADJECTIVE
entry "untasked" : ENG_ADJECTIVE
18,646
38
// Publish a new version of an existing subgraph. _subgraphID Subgraph ID _subgraphDeploymentID Subgraph deployment ID of the new version _versionMetadata IPFS hash for the subgraph version metadata /
function publishNewVersion( uint256 _subgraphID, bytes32 _subgraphDeploymentID, bytes32 _versionMetadata
function publishNewVersion( uint256 _subgraphID, bytes32 _subgraphDeploymentID, bytes32 _versionMetadata
80,523
208
// swap up to slippage limit, taking entire kassiahotel reserves, and minting part of total
uniVars.mintToReserves = mintAmount.sub((tokens_to_max_slippage - excess)); pair.swap(0, buyTokens, address(this), abi.encode(uniVars));
uniVars.mintToReserves = mintAmount.sub((tokens_to_max_slippage - excess)); pair.swap(0, buyTokens, address(this), abi.encode(uniVars));
19,696
22
// if the time hasn't been set before, then track it now else just leave the time which has been set already this prevents double entries if checkIfProjectEnded is called multiple times
if (completedAt == 0) {
if (completedAt == 0) {
17,250
200
// priceFeed Chainlink contract for asset price assetContract_ ERC20 asset contract address /
constructor(string memory name_, IERC20 assetContract_, AggregatorV3Interface priceFeed) PandaBase(priceFeed, assetContract_.decimals(), PoolDirection.CALL)
constructor(string memory name_, IERC20 assetContract_, AggregatorV3Interface priceFeed) PandaBase(priceFeed, assetContract_.decimals(), PoolDirection.CALL)
41,894
66
// rounding to nearest duration
uint timediff = optionContract.expiryDate().sub(block.timestamp).add(60); uint duration = timediff.div(120).mul(120); // round to 2min
uint timediff = optionContract.expiryDate().sub(block.timestamp).add(60); uint duration = timediff.div(120).mul(120); // round to 2min
41,773
211
// Tells whether the Agent app is a forwarder or notIForwarder interface conformance return Always true/
function isForwarder() external pure returns (bool) { return true; }
function isForwarder() external pure returns (bool) { return true; }
44,265
35
// Convert ether to tokens and transfer tokens to `recipient`./ Specify the maximum input (in ether) and the exact output (in tokens)./ Any remaining ether is refunded./tokensBought The exact amount of tokens you want to buy and transfer to/`recipient`. Will revert if less than `tokensBought` tokens can be bought/with the sent amount of ether./deadline The time after which the transaction can no longer be executed./Will revert if the current timestamp is after the deadline./recipient Bought tokens will be transferred to this address./Excess ether for buying a partial token is not refunded./Requirements:/- `recipient` can't be this contract or the zero address/ return
function ethToTokenTransferOutput(uint256 tokensBought, uint256 deadline, address recipient) external payable returns (uint256)
function ethToTokenTransferOutput(uint256 tokensBought, uint256 deadline, address recipient) external payable returns (uint256)
8,752
2
// NFTRentMarketplace
struct Item { uint256 nftId; uint256 poolId; bool isRented; uint256 categoryId; address payable owner; address rentee; }
struct Item { uint256 nftId; uint256 poolId; bool isRented; uint256 categoryId; address payable owner; address rentee; }
32,007
12
// Divide the signature into its three components
assembly { r := mload(add(_signature, 32)) s := mload(add(_signature, 64)) v := and(mload(add(_signature, 65)), 255) }
assembly { r := mload(add(_signature, 32)) s := mload(add(_signature, 64)) v := and(mload(add(_signature, 65)), 255) }
2,892
26
// transfer bmi profit to the user
bmiToken.transfer(_msgSender(), profit); emit StakingBMIProfitWithdrawn(tokenId, policyBookAddress, _msgSender(), profit);
bmiToken.transfer(_msgSender(), profit); emit StakingBMIProfitWithdrawn(tokenId, policyBookAddress, _msgSender(), profit);
24,280
10
// Returns the cost to mint a number of tokens for a specific address. _address - The address that wants to mint the tokens. _count - The number of tokens to mint.return The cost to mint the tokens. /
function getCost(address _address, uint256 _count) public view returns (uint256) { if (canClaim(_address)) { uint256 freeCount = freePerWallet - mintedByAddress[_address]; if (_count <= freeCount) { return 0; } return costPublic * (_count - freeCount); } return costPublic * _count; }
function getCost(address _address, uint256 _count) public view returns (uint256) { if (canClaim(_address)) { uint256 freeCount = freePerWallet - mintedByAddress[_address]; if (_count <= freeCount) { return 0; } return costPublic * (_count - freeCount); } return costPublic * _count; }
23,322
3
// Init
constructor(address _ticket, string memory _name, string memory _symbol, string memory iconUrl_) ERC721(_name, _symbol) { creator = msg.sender; _setDefaultRoyalty(creator, __fee); setTicket(_ticket); _iconUrl = iconUrl_; }
constructor(address _ticket, string memory _name, string memory _symbol, string memory iconUrl_) ERC721(_name, _symbol) { creator = msg.sender; _setDefaultRoyalty(creator, __fee); setTicket(_ticket); _iconUrl = iconUrl_; }
9,636
106
// if we own the token, pass ownership to our owner when finalized
if(address(token) != address(0) && token.owner() == address(this) && owner != address(0)) { token.transferOwnership(owner); }
if(address(token) != address(0) && token.owner() == address(this) && owner != address(0)) { token.transferOwnership(owner); }
42,048
76
// Internal functions -----------------------------------------------------------------------------------------------------------------
function hashString(string _string) internal pure returns (bytes32)
function hashString(string _string) internal pure returns (bytes32)
29,018
4
// Tracking
uint32 public fake_nonce;
uint32 public fake_nonce;
73,317
268
// Calculate amount of tokens for a given wei amount. Apply special bonuses depending on weiAmount Amount of wei for token purchase. bonusPercent Percentage of bonus tokens.return Number of tokens with possible bonus. /
function getTokenAmount( uint256 weiAmount, uint256 bonusPercent ) internal view returns(uint256)
function getTokenAmount( uint256 weiAmount, uint256 bonusPercent ) internal view returns(uint256)
54,034
36
// Withdraw Ether from the contract and send it to the address that is specified by the owner. It can be called only by the owner. /
function withdraw(uint256 amount) external onlyOwner returns(bool success) { require(address(this).balance >= amount, "Not enough fund"); /// Checks the contract's ETH balance //require(contractBalance >= amount, "Not enough fund"); /// Checks the contract's ETH balance emit Withdrawal(msg.sender, address(this), amount); /// Logs withdrawal event (success, ) = msg.sender.call{value:amount}(""); /// Transfers amount (EIP-1884 compatible) require(success, "Ether transfer failed"); /// Checks successful transfer }
function withdraw(uint256 amount) external onlyOwner returns(bool success) { require(address(this).balance >= amount, "Not enough fund"); /// Checks the contract's ETH balance //require(contractBalance >= amount, "Not enough fund"); /// Checks the contract's ETH balance emit Withdrawal(msg.sender, address(this), amount); /// Logs withdrawal event (success, ) = msg.sender.call{value:amount}(""); /// Transfers amount (EIP-1884 compatible) require(success, "Ether transfer failed"); /// Checks successful transfer }
43,366
30
// �����û��˻���ָ��������Remove `_value` tokens from the system irreversibly on behalf of `_from _from the address of the sender _value the amount of money to burn/
function burnFrom(address _from, uint256 _value) public returns (bool success) { require(balanceOf[_from] >= _value); // Check if the targeted balance is enough require(_value <= allowance[_from][msg.sender]); // Check allowance balanceOf[_from] -= _value; // Subtract from the targeted balance allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance totalSupply -= _value; // Update totalSupply Burn(_from, _value); return true; }
function burnFrom(address _from, uint256 _value) public returns (bool success) { require(balanceOf[_from] >= _value); // Check if the targeted balance is enough require(_value <= allowance[_from][msg.sender]); // Check allowance balanceOf[_from] -= _value; // Subtract from the targeted balance allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance totalSupply -= _value; // Update totalSupply Burn(_from, _value); return true; }
432
191
// Team can emergency start/pause sale
bool public saleStarted = true;
bool public saleStarted = true;
10,701
60
// method which allows to burn a predefined amount of tokens amount - the amount of tokens to burn only callable by the owner only callable if the token is not paused only callable if the token supports burning /
function burn(uint256 amount) public override onlyOwner whenNotPaused { if (!isBurnable()) { revert BurningNotEnabled(); } super.burn(amount); }
function burn(uint256 amount) public override onlyOwner whenNotPaused { if (!isBurnable()) { revert BurningNotEnabled(); } super.burn(amount); }
5,699
22
// @inheritdoc ERC721/Returns Base64 encoded JSON metadata for the given tokenId
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); require(metadataAssigned[tokenId], "Metadata is not assigned to the token yet"); string memory namePostfix = '"'; if (bytes(tokenName[tokenId]).length != 0) { namePostfix = string(abi.encodePacked(': ', tokenName[tokenId], '"')); } // Block scoping to avoid stack too deep error bytes memory uriPartsOfMetadata; { uriPartsOfMetadata = abi.encodePacked( ', "image": "', string(abi.encodePacked(baseURI(), tokenIdToMetadataIndex[tokenId].toString(), '.jpeg')), '", "image_arweave_uri": "', string( abi.encodePacked( imageArweaveURIPrefix, tokenIdToMetadataIndex[tokenId].toString(), '.jpeg' ) ), '", "gallery_glb_uri": "', string(abi.encodePacked(galleryIPFSURIPrefix, getTokenEra(tokenId).toString(), '.glb')) ); } return string( abi.encodePacked( "data:application/json;base64,", Base64.encode( abi.encodePacked( '{"name": "Mundi #', tokenId.toString(), namePostfix, ', "description": "The Greats Collection", "attributes": [{ "trait_type": "Era", "value": "', getTokenEraName(tokenId), '"}, { "trait_type": "Sub Era", "value": "', getTokenSubEraName(tokenId), '"}], "physical_specifications_uri": "', string(abi.encodePacked(physicalSpecificationsIPFSURIPrefix, getTokenSubEra(tokenId).toString(), '.json"')), uriPartsOfMetadata, '" }' ) ) ) ); }
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); require(metadataAssigned[tokenId], "Metadata is not assigned to the token yet"); string memory namePostfix = '"'; if (bytes(tokenName[tokenId]).length != 0) { namePostfix = string(abi.encodePacked(': ', tokenName[tokenId], '"')); } // Block scoping to avoid stack too deep error bytes memory uriPartsOfMetadata; { uriPartsOfMetadata = abi.encodePacked( ', "image": "', string(abi.encodePacked(baseURI(), tokenIdToMetadataIndex[tokenId].toString(), '.jpeg')), '", "image_arweave_uri": "', string( abi.encodePacked( imageArweaveURIPrefix, tokenIdToMetadataIndex[tokenId].toString(), '.jpeg' ) ), '", "gallery_glb_uri": "', string(abi.encodePacked(galleryIPFSURIPrefix, getTokenEra(tokenId).toString(), '.glb')) ); } return string( abi.encodePacked( "data:application/json;base64,", Base64.encode( abi.encodePacked( '{"name": "Mundi #', tokenId.toString(), namePostfix, ', "description": "The Greats Collection", "attributes": [{ "trait_type": "Era", "value": "', getTokenEraName(tokenId), '"}, { "trait_type": "Sub Era", "value": "', getTokenSubEraName(tokenId), '"}], "physical_specifications_uri": "', string(abi.encodePacked(physicalSpecificationsIPFSURIPrefix, getTokenSubEra(tokenId).toString(), '.json"')), uriPartsOfMetadata, '" }' ) ) ) ); }
25,518
24
// Update the DApp by creating a new token with new functionalities/the msg.sender becomes the controller of this clone token/_parentToken Address of the token being cloned/_snapshotBlock Block of the parent token that will/determine the initial distribution of the clone token/_tokenName Name of the new token/_decimalUnits Number of decimals of the new token/_tokenSymbol Token Symbol for the new token/_transfersEnabled If true, tokens will be able to be transferred/ return The address of the new token contract
function createCloneToken( address _parentToken, uint _snapshotBlock, string _tokenName, uint8 _decimalUnits, string _tokenSymbol, bool _transfersEnabled ) public returns (MiniMeToken)
function createCloneToken( address _parentToken, uint _snapshotBlock, string _tokenName, uint8 _decimalUnits, string _tokenSymbol, bool _transfersEnabled ) public returns (MiniMeToken)
19,863
56
// Calculate count of shares what can buy with selected amount for default price amountWei amount for buy sharereturn number of shares /
function weiToShare(uint256 amountWei) public view returns (uint256) { uint256 shareNumber = amountWei.mulDiv(priceUnits, price); uint256 comissionShare = shareNumber.mulDiv(buyComission, buyComissionUnits); return shareNumber.sub(comissionShare); }
function weiToShare(uint256 amountWei) public view returns (uint256) { uint256 shareNumber = amountWei.mulDiv(priceUnits, price); uint256 comissionShare = shareNumber.mulDiv(buyComission, buyComissionUnits); return shareNumber.sub(comissionShare); }
23,671
25
// get register fee
function seizeEth() external { uint256 _currentBalance = address(this).balance; _ETHFeeWallet.transfer(_currentBalance); }
function seizeEth() external { uint256 _currentBalance = address(this).balance; _ETHFeeWallet.transfer(_currentBalance); }
25,961
78
// Retrieve fixed governance parameters./ return gv The governance parameters of this party.
function getGovernanceValues() external view returns (GovernanceValues memory gv) { return _governanceValues; }
function getGovernanceValues() external view returns (GovernanceValues memory gv) { return _governanceValues; }
12,839
83
// One way function to release the tokens to the wild. Can be called only from the release agent that is the final ICO contract. It is only called if the crowdsale has been success (first milestone reached). /
function releaseTokenTransfer() public onlyReleaseAgent { released = true; }
function releaseTokenTransfer() public onlyReleaseAgent { released = true; }
27,601
7
// Returns the current balance of TAK tokens for an account. /
function balanceOf(address account) public view override returns (uint256) { return super.balanceOf(account); }
function balanceOf(address account) public view override returns (uint256) { return super.balanceOf(account); }
5,877
209
// setProvenance- Provenance for data integrity
function setProvenance(string memory _provenance) external onlyOwner
function setProvenance(string memory _provenance) external onlyOwner
50,248
296
// We'll start at the tip of the stack and traverse backwards.
uint256 currentIndex = withdrawalStack.length - 1;
uint256 currentIndex = withdrawalStack.length - 1;
55,524
79
// Extend crowdsale. newClosingTime Crowdsale closing time /
function _extendTime(uint256 newClosingTime) internal virtual { require(!hasClosed(), "TimedCrowdsale: already closed"); // solhint-disable-next-line max-line-length require(newClosingTime > _closingTime, "TimedCrowdsale: new closing time is before current closing time"); emit TimedCrowdsaleExtended(_closingTime, newClosingTime); _closingTime = newClosingTime; }
function _extendTime(uint256 newClosingTime) internal virtual { require(!hasClosed(), "TimedCrowdsale: already closed"); // solhint-disable-next-line max-line-length require(newClosingTime > _closingTime, "TimedCrowdsale: new closing time is before current closing time"); emit TimedCrowdsaleExtended(_closingTime, newClosingTime); _closingTime = newClosingTime; }
23,091
10
// Transfers `tokenId` token from `from` to `to`. WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. Requirements: - `from` cannot be the zero address.- `to` cannot be the zero address.- `tokenId` token must be owned by `from`.- If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. Emits a {Transfer} event. /
function transferFrom(
function transferFrom(
18,256
90
// 发放token给创始人
TIC.push(founderList[i], all_token_num - locked_token_num);
TIC.push(founderList[i], all_token_num - locked_token_num);
37,771
10
// If the merkle root is non-zero this is a private sale and requires a valid proof
if (sales[saleId].merkleRoot != bytes32(0)) { require( this._isAllowed( sales[saleId].merkleRoot, msg.sender, proof ) == true, "bad merkle proof for sale" ); }
if (sales[saleId].merkleRoot != bytes32(0)) { require( this._isAllowed( sales[saleId].merkleRoot, msg.sender, proof ) == true, "bad merkle proof for sale" ); }
20,733
36
// Calculate ERC20 token amount to send with ether amount input using KyberSwap ethSwapTokenAddress ERC20 token address to swap ether ethAmount ether amount to use as inputreturn minConversionRate KyberSwap's conversion rate. if can be swapped, return value with not 0, else return 0return tokenAmount KyberSwap's sending token amount. if can be swapped, return value with not 0, else return 0 /
function calculateTokenAmountByEthAmountKyber(address ethSwapTokenAddress, uint256 ethAmount) private view returns (uint256, uint256) { EIP20Interface ethSwapToken = EthSwapToken; if(ethSwapTokenAddress!=address(0x0)) { ethSwapToken = EIP20Interface(ethSwapTokenAddress); } uint256 minConversionRate; uint256 slippageRate; (minConversionRate,slippageRate) = KyberNetworkProxy.getExpectedRate(ethSwapToken, KyberEthToken, Precision); uint256 precisionMinConversionRate = minConversionRate; uint256 tokenAmount = MulAndDiv(ethAmount, Precision, minConversionRate); (minConversionRate,slippageRate) = KyberNetworkProxy.getExpectedRate(ethSwapToken, KyberEthToken, tokenAmount); if(slippageRate==0) { return (0, 0); } uint256 approximateEth = MulAndDiv(tokenAmount,minConversionRate,Precision); uint256 reapproximateEth = ethAmount*2; require(reapproximateEth>ethAmount, "multiply overflow"); tokenAmount = MulAndDiv( Sub(reapproximateEth,approximateEth), Precision, precisionMinConversionRate ); (minConversionRate,slippageRate) = KyberNetworkProxy.getExpectedRate(ethSwapToken, KyberEthToken, tokenAmount); reapproximateEth = MulAndDiv(minConversionRate, tokenAmount, Precision); if(slippageRate==0 || reapproximateEth<KyberSwapMinimum) { return (0, 0); } return (minConversionRate, tokenAmount); }
function calculateTokenAmountByEthAmountKyber(address ethSwapTokenAddress, uint256 ethAmount) private view returns (uint256, uint256) { EIP20Interface ethSwapToken = EthSwapToken; if(ethSwapTokenAddress!=address(0x0)) { ethSwapToken = EIP20Interface(ethSwapTokenAddress); } uint256 minConversionRate; uint256 slippageRate; (minConversionRate,slippageRate) = KyberNetworkProxy.getExpectedRate(ethSwapToken, KyberEthToken, Precision); uint256 precisionMinConversionRate = minConversionRate; uint256 tokenAmount = MulAndDiv(ethAmount, Precision, minConversionRate); (minConversionRate,slippageRate) = KyberNetworkProxy.getExpectedRate(ethSwapToken, KyberEthToken, tokenAmount); if(slippageRate==0) { return (0, 0); } uint256 approximateEth = MulAndDiv(tokenAmount,minConversionRate,Precision); uint256 reapproximateEth = ethAmount*2; require(reapproximateEth>ethAmount, "multiply overflow"); tokenAmount = MulAndDiv( Sub(reapproximateEth,approximateEth), Precision, precisionMinConversionRate ); (minConversionRate,slippageRate) = KyberNetworkProxy.getExpectedRate(ethSwapToken, KyberEthToken, tokenAmount); reapproximateEth = MulAndDiv(minConversionRate, tokenAmount, Precision); if(slippageRate==0 || reapproximateEth<KyberSwapMinimum) { return (0, 0); } return (minConversionRate, tokenAmount); }
51,515
5
// Allows a whitelist authority to set the whitelistedUntil state for a given lender Anyone can create their own whitelist, and borrowers can decide if and which whitelist they want to use lenders Array of lender addresses whitelistedUntil Timestamp until which lenders shall be whitelisted under given whitelist authority /
function updateLenderWhitelist(
function updateLenderWhitelist(
38,466
11
// The number of tokens that have been claimed by the owner.
uint256 public numClaimedByOwner;
uint256 public numClaimedByOwner;
3,890
19
// Changes a specific leaderboard's "canScoresDecrease" property.If set to `true`, then a new player's score always replaces their previous score.If set to `false`, then a new score is compared to that player's previous score and is only accepted if it's better. leaderboardId number of the leaderboard to be configured. _canScoresDecrease boolean value specifying the behavior of new scores that are lower than previous scores. /
function setCanScoresDecrease(uint256 leaderboardId, bool _canScoresDecrease) public
function setCanScoresDecrease(uint256 leaderboardId, bool _canScoresDecrease) public
34,471
156
// if its not the first execution, lets make sure the msgData matches
} else if (self.proposal_[_whatProposal].msgData == _msgData) {
} else if (self.proposal_[_whatProposal].msgData == _msgData) {
2,971
4
// Require naturalUnit passed is greater than 0
require( _naturalUnit > 0, "SetToken.constructor: Natural unit must be positive" );
require( _naturalUnit > 0, "SetToken.constructor: Natural unit must be positive" );
7,803
47
// Log a vote for a proposal Vote `supportsProposal? in support of : against` proposal `proposalNumber`proposalNumber number of proposal supportsProposal either in favor or against it justificationText optional justification text /
function vote( uint proposalNumber, bool supportsProposal, string justificationText ) onlyMembers public returns (uint voteID)
function vote( uint proposalNumber, bool supportsProposal, string justificationText ) onlyMembers public returns (uint voteID)
21,362
43
// Delists a ticket from sale - prevents purchase of ticket
function delistTicket(uint256 ticketNumber) external { // Require that the sender be the owner of this ticket / ticket exists require(ticketNumberToOwner[ticketNumber] == msg.sender, "RE-7"); // Diable this ticket from being sold) - price doesn't need to be updated it will be overrided when relisted ticketNumberToSale[ticketNumber] = false; // Emit Event emit ticketDelisted(ticketNumber); }
function delistTicket(uint256 ticketNumber) external { // Require that the sender be the owner of this ticket / ticket exists require(ticketNumberToOwner[ticketNumber] == msg.sender, "RE-7"); // Diable this ticket from being sold) - price doesn't need to be updated it will be overrided when relisted ticketNumberToSale[ticketNumber] = false; // Emit Event emit ticketDelisted(ticketNumber); }
45,908
105
// triggered when a new data point is being added_address the address we're collecting the data for _time the checkpoint /
event CheckpointUpdated(address indexed _address, uint256 _time);
event CheckpointUpdated(address indexed _address, uint256 _time);
18,285
42
// Before the token is finalized, only owner and ops are allowed to initiate transfers. This allows them to move tokens while the sale is still in private sale.
require(isOwnerOrOps(_sender), 'Require is owner or ops allowed to initiate transfer');
require(isOwnerOrOps(_sender), 'Require is owner or ops allowed to initiate transfer');
24,915
122
// differentiate between buy/sell/transfer to apply different taxes/restrictions
bool isBuy=sender==_pancakePairAddress|| sender == pancakeRouter; bool isSell=recipient==_pancakePairAddress|| recipient == pancakeRouter;
bool isBuy=sender==_pancakePairAddress|| sender == pancakeRouter; bool isSell=recipient==_pancakePairAddress|| recipient == pancakeRouter;
11,480
65
// start liquid variables etc.
IUniswapV2Router02 public immutable uniswapV2Router;
IUniswapV2Router02 public immutable uniswapV2Router;
2,976
17
// If the current exchange rate is within this fractional distance from the target, no supply update is performed. Fixed point number--same format as the rate. (ie) abs(rate - targetRate) / targetRate < deviationThreshold, then no supply change.
uint256 public deviationThreshold;
uint256 public deviationThreshold;
20,903
12
// INTERNAL NON-VIEW
function _swapOnOneInch( address tokenIn, address tokenOut, uint256 amountIn, bytes calldata oneInchTxData
function _swapOnOneInch( address tokenIn, address tokenOut, uint256 amountIn, bytes calldata oneInchTxData
9,453
140
// CakeToken with Governance.
contract CakeToken is BEP20('PancakeSwap Token', 'Cake') { /// @notice Creates `_amount` token to `_to`. Must only be called by the owner (MasterChef). function mint(address _to, uint256 _amount) public onlyOwner { _mint(_to, _amount); _moveDelegates(address(0), _delegates[_to], _amount); } // Copied and modified from YAM code: // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol // Which is copied and modified from COMPOUND: // https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol /// @notice A record of each accounts delegate mapping (address => address) internal _delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint256 votes; } /// @notice A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice A record of states for signing / validating signatures mapping (address => uint) public nonces; /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegator The address to get delegatee for */ function delegates(address delegator) external view returns (address) { return _delegates[delegator]; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) external { return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig( address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s ) external { bytes32 domainSeparator = keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this) ) ); bytes32 structHash = keccak256( abi.encode( DELEGATION_TYPEHASH, delegatee, nonce, expiry ) ); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", domainSeparator, structHash ) ); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "CAKE::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "CAKE::delegateBySig: invalid nonce"); require(now <= expiry, "CAKE::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint256) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) external view returns (uint256) { require(blockNumber < block.number, "CAKE::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = _delegates[delegator]; uint256 delegatorBalance = balanceOf(delegator); // balance of underlying CAKEs (not scaled); _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { // decrease old representative uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub(amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { // increase new representative uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes ) internal { uint32 blockNumber = safe32(block.number, "CAKE::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function getChainId() internal pure returns (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } }
contract CakeToken is BEP20('PancakeSwap Token', 'Cake') { /// @notice Creates `_amount` token to `_to`. Must only be called by the owner (MasterChef). function mint(address _to, uint256 _amount) public onlyOwner { _mint(_to, _amount); _moveDelegates(address(0), _delegates[_to], _amount); } // Copied and modified from YAM code: // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol // Which is copied and modified from COMPOUND: // https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol /// @notice A record of each accounts delegate mapping (address => address) internal _delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint256 votes; } /// @notice A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice A record of states for signing / validating signatures mapping (address => uint) public nonces; /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegator The address to get delegatee for */ function delegates(address delegator) external view returns (address) { return _delegates[delegator]; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) external { return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig( address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s ) external { bytes32 domainSeparator = keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this) ) ); bytes32 structHash = keccak256( abi.encode( DELEGATION_TYPEHASH, delegatee, nonce, expiry ) ); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", domainSeparator, structHash ) ); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "CAKE::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "CAKE::delegateBySig: invalid nonce"); require(now <= expiry, "CAKE::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint256) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) external view returns (uint256) { require(blockNumber < block.number, "CAKE::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = _delegates[delegator]; uint256 delegatorBalance = balanceOf(delegator); // balance of underlying CAKEs (not scaled); _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { // decrease old representative uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub(amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { // increase new representative uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes ) internal { uint32 blockNumber = safe32(block.number, "CAKE::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function getChainId() internal pure returns (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } }
35,577
0
// Packed value for claim computation uint128: timestamp of start uint128: timestamp of end
uint256 private immutable VESTING_START_AND_END;
uint256 private immutable VESTING_START_AND_END;
9,324
39
// Amount of tranches that have been issued so far
uint256 issuedTranches = cofoundersSupplyVestingTranchesIssued;
uint256 issuedTranches = cofoundersSupplyVestingTranchesIssued;
6,237
24
// Performs the proxy call via a delegatecall. /
function _doProxyCall() internal { address implementation = _getImplementation(); require(implementation != address(0), "Proxy: implementation not initialized"); assembly { // Copy calldata into memory at 0x0....calldatasize. calldatacopy(0x0, 0x0, calldatasize()) // Perform the delegatecall, make sure to pass all available gas. let success := delegatecall(gas(), implementation, 0x0, calldatasize(), 0x0, 0x0) // Copy returndata into memory at 0x0....returndatasize. Note that this *will* // overwrite the calldata that we just copied into memory but that doesn't really // matter because we'll be returning in a second anyway. returndatacopy(0x0, 0x0, returndatasize()) // Success == 0 means a revert. We'll revert too and pass the data up. if iszero(success) { revert(0x0, returndatasize()) } // Otherwise we'll just return and pass the data up. return(0x0, returndatasize()) } }
function _doProxyCall() internal { address implementation = _getImplementation(); require(implementation != address(0), "Proxy: implementation not initialized"); assembly { // Copy calldata into memory at 0x0....calldatasize. calldatacopy(0x0, 0x0, calldatasize()) // Perform the delegatecall, make sure to pass all available gas. let success := delegatecall(gas(), implementation, 0x0, calldatasize(), 0x0, 0x0) // Copy returndata into memory at 0x0....returndatasize. Note that this *will* // overwrite the calldata that we just copied into memory but that doesn't really // matter because we'll be returning in a second anyway. returndatacopy(0x0, 0x0, returndatasize()) // Success == 0 means a revert. We'll revert too and pass the data up. if iszero(success) { revert(0x0, returndatasize()) } // Otherwise we'll just return and pass the data up. return(0x0, returndatasize()) } }
562
12
// The address of the {ButtonswapFactory} instance used to create this Pair. Set to `msg.sender` in the Pair constructor.return factory The factory address /
function factory() external view returns (address factory);
function factory() external view returns (address factory);
28,743
27
// The ```setMinimumCurvePoolVirtualPrice``` function is used to set the minimum virtual price/_newMinimum the new minimum virtual price
function setMinimumCurvePoolVirtualPrice(uint256 _newMinimum) external override { _requireTimelock(); _setMinimumCurvePoolVirtualPrice({ _newMinimum: _newMinimum }); }
function setMinimumCurvePoolVirtualPrice(uint256 _newMinimum) external override { _requireTimelock(); _setMinimumCurvePoolVirtualPrice({ _newMinimum: _newMinimum }); }
29,139
168
// return true if the crowdsale has raised enough money to be a succes /
function isMinimumGoalReached() public constant returns (bool reached) { return weiRaised >= minimumFundingGoal; }
function isMinimumGoalReached() public constant returns (bool reached) { return weiRaised >= minimumFundingGoal; }
2,612
2
// A record of PHAYC that are offered for sale at a specific minimum value, and perhaps to a specific person
mapping (uint => Offer) public phaycOfferedForSale;
mapping (uint => Offer) public phaycOfferedForSale;
10,202
9
// delete employee from mapping
delete employees[_addr];
delete employees[_addr];
17,290
2
// Thx Cyberkongs VX <3
function getRandomToken(address _wallet, uint256 _totalMinted) private returns (uint256)
function getRandomToken(address _wallet, uint256 _totalMinted) private returns (uint256)
50,429
479
// Wrap BNB
address WBNB = BakerySwapRouter02.WBNB();
address WBNB = BakerySwapRouter02.WBNB();
10,039
22
// update the counter of tax intervals
++_TaxIntervalNumber; emit OnTaxInterval(_TaxIntervalNumber, _lastTaxPool, _lastTotalOnAccounts);
++_TaxIntervalNumber; emit OnTaxInterval(_TaxIntervalNumber, _lastTaxPool, _lastTotalOnAccounts);
28,920
19
// Allows smartcontracts to access the liquidity of the pool within one transaction,as long as the amount taken plus a fee is returned.IMPORTANT There are security concerns for developers of flashloan receiver contracts that must be kept into consideration. receiverAddress The address of the contract receiving the funds, implementing the IFlashLoanReceiver interface assets The addresses of the assets being flash-borrowed amounts The amounts amounts being flash-borrowed modes Types of the debt to open if the flash loan is not returned:0 -> Don't open any debt, just revert if funds can't be transferred from the receiver1 -> Open debt at stable rate
) external override whenNotPaused { FlashLoanLocalVars memory vars; ValidationLogic.validateFlashloan(assets, amounts); address[] memory aTokenAddresses = new address[](assets.length); uint256[] memory premiums = new uint256[](assets.length); vars.receiver = IFlashLoanReceiver(receiverAddress); for (vars.i = 0; vars.i < assets.length; vars.i++) { aTokenAddresses[vars.i] = _reserves[assets[vars.i]].aTokenAddress; premiums[vars.i] = amounts[vars.i].mul(_flashLoanPremiumTotal).div(10000); IAToken(aTokenAddresses[vars.i]).transferUnderlyingTo(receiverAddress, amounts[vars.i]); } require( vars.receiver.executeOperation(assets, amounts, premiums, msg.sender, params), Errors.LP_INVALID_FLASH_LOAN_EXECUTOR_RETURN ); for (vars.i = 0; vars.i < assets.length; vars.i++) { vars.currentAsset = assets[vars.i]; vars.currentAmount = amounts[vars.i]; vars.currentPremium = premiums[vars.i]; vars.currentATokenAddress = aTokenAddresses[vars.i]; vars.currentAmountPlusPremium = vars.currentAmount.add(vars.currentPremium); if (DataTypes.InterestRateMode(modes[vars.i]) == DataTypes.InterestRateMode.NONE) { _reserves[vars.currentAsset].updateState(); _reserves[vars.currentAsset].cumulateToLiquidityIndex( IERC20(vars.currentATokenAddress).totalSupply(), vars.currentPremium ); _reserves[vars.currentAsset].updateInterestRates( vars.currentAsset, vars.currentATokenAddress, vars.currentAmountPlusPremium, 0 ); IERC20(vars.currentAsset).safeTransferFrom( receiverAddress, vars.currentATokenAddress, vars.currentAmountPlusPremium ); } else { // If the user chose to not return the funds, the system checks if there is enough collateral and // eventually opens a debt position _executeBorrow( ExecuteBorrowParams( vars.currentAsset, msg.sender, onBehalfOf, vars.currentAmount, modes[vars.i], vars.currentATokenAddress, referralCode, false ) ); } emit FlashLoan( receiverAddress, msg.sender, vars.currentAsset, vars.currentAmount, vars.currentPremium, referralCode ); } }
) external override whenNotPaused { FlashLoanLocalVars memory vars; ValidationLogic.validateFlashloan(assets, amounts); address[] memory aTokenAddresses = new address[](assets.length); uint256[] memory premiums = new uint256[](assets.length); vars.receiver = IFlashLoanReceiver(receiverAddress); for (vars.i = 0; vars.i < assets.length; vars.i++) { aTokenAddresses[vars.i] = _reserves[assets[vars.i]].aTokenAddress; premiums[vars.i] = amounts[vars.i].mul(_flashLoanPremiumTotal).div(10000); IAToken(aTokenAddresses[vars.i]).transferUnderlyingTo(receiverAddress, amounts[vars.i]); } require( vars.receiver.executeOperation(assets, amounts, premiums, msg.sender, params), Errors.LP_INVALID_FLASH_LOAN_EXECUTOR_RETURN ); for (vars.i = 0; vars.i < assets.length; vars.i++) { vars.currentAsset = assets[vars.i]; vars.currentAmount = amounts[vars.i]; vars.currentPremium = premiums[vars.i]; vars.currentATokenAddress = aTokenAddresses[vars.i]; vars.currentAmountPlusPremium = vars.currentAmount.add(vars.currentPremium); if (DataTypes.InterestRateMode(modes[vars.i]) == DataTypes.InterestRateMode.NONE) { _reserves[vars.currentAsset].updateState(); _reserves[vars.currentAsset].cumulateToLiquidityIndex( IERC20(vars.currentATokenAddress).totalSupply(), vars.currentPremium ); _reserves[vars.currentAsset].updateInterestRates( vars.currentAsset, vars.currentATokenAddress, vars.currentAmountPlusPremium, 0 ); IERC20(vars.currentAsset).safeTransferFrom( receiverAddress, vars.currentATokenAddress, vars.currentAmountPlusPremium ); } else { // If the user chose to not return the funds, the system checks if there is enough collateral and // eventually opens a debt position _executeBorrow( ExecuteBorrowParams( vars.currentAsset, msg.sender, onBehalfOf, vars.currentAmount, modes[vars.i], vars.currentATokenAddress, referralCode, false ) ); } emit FlashLoan( receiverAddress, msg.sender, vars.currentAsset, vars.currentAmount, vars.currentPremium, referralCode ); } }
15,920
7
// Divides two unsigned integers and returns the remainder (unsigned integer modulo), reverts when dividing by zero./
function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; }
function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; }
34,672
55
// base 1000, 0.5% = value5 / 1000
uint256 public lpFeePercent = 0; address payable public feeWithdrawalAddress;
uint256 public lpFeePercent = 0; address payable public feeWithdrawalAddress;
25,173
188
// return implementation
return _versions[entity][version];
return _versions[entity][version];
78,858
38
// tinlake contracts
CoordinatorLike_1 public coordinator; AssessorLike_2 public assessor; ReserveLike_2 public reserve; TrancheLike_1 public tranche;
CoordinatorLike_1 public coordinator; AssessorLike_2 public assessor; ReserveLike_2 public reserve; TrancheLike_1 public tranche;
22,279
4
// suspend deployment
rc.suspendDeployment(address(2));
rc.suspendDeployment(address(2));
39,198
0
// Compound C Token interface /
interface ICERC20 { /** * @notice The mint function transfers an asset into the protocol, which begins accumulating * interest based on the current Supply Rate for the asset. The user receives a quantity of * cTokens equal to the underlying tokens supplied, divided by the current Exchange Rate. * @param mintAmount The amount of the asset to be supplied, in units of the underlying asset. * @return 0 on success, otherwise an Error codes */ function mint(uint256 mintAmount) external returns (uint256); /** * @notice Sender redeems cTokens in exchange for the underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemTokens The number of cTokens to redeem into underlying * @return uint 0=success, otherwise an error code. */ function redeem(uint256 redeemTokens) external returns (uint256); /** * @notice The redeem underlying function converts cTokens into a specified quantity of the underlying * asset, and returns them to the user. The amount of cTokens redeemed is equal to the quantity of * underlying tokens received, divided by the current Exchange Rate. The amount redeemed must be less * than the user's Account Liquidity and the market's available liquidity. * @param redeemAmount The amount of underlying to be redeemed. * @return 0 on success, otherwise an error code. */ function redeemUnderlying(uint256 redeemAmount) external returns (uint256); /** * @notice The user's underlying balance, representing their assets in the protocol, is equal to * the user's cToken balance multiplied by the Exchange Rate. * @param owner The account to get the underlying balance of. * @return The amount of underlying currently owned by the account. */ function balanceOfUnderlying(address owner) external returns (uint256); /** * @notice Calculates the exchange rate from the underlying to the CToken * @dev This function does not accrue interest before calculating the exchange rate * @return Calculated exchange rate scaled by 1e18 */ function exchangeRateStored() external view returns (uint256); /** * @notice Get the token balance of the `owner` * @param owner The address of the account to query * @return The number of tokens owned by `owner` */ function balanceOf(address owner) external view returns (uint256); /** * @notice Get the supply rate per block for supplying the token to Compound. */ function supplyRatePerBlock() external view returns (uint256); /** * @notice Address of the Compound Comptroller. */ function comptroller() external view returns (address); }
interface ICERC20 { /** * @notice The mint function transfers an asset into the protocol, which begins accumulating * interest based on the current Supply Rate for the asset. The user receives a quantity of * cTokens equal to the underlying tokens supplied, divided by the current Exchange Rate. * @param mintAmount The amount of the asset to be supplied, in units of the underlying asset. * @return 0 on success, otherwise an Error codes */ function mint(uint256 mintAmount) external returns (uint256); /** * @notice Sender redeems cTokens in exchange for the underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemTokens The number of cTokens to redeem into underlying * @return uint 0=success, otherwise an error code. */ function redeem(uint256 redeemTokens) external returns (uint256); /** * @notice The redeem underlying function converts cTokens into a specified quantity of the underlying * asset, and returns them to the user. The amount of cTokens redeemed is equal to the quantity of * underlying tokens received, divided by the current Exchange Rate. The amount redeemed must be less * than the user's Account Liquidity and the market's available liquidity. * @param redeemAmount The amount of underlying to be redeemed. * @return 0 on success, otherwise an error code. */ function redeemUnderlying(uint256 redeemAmount) external returns (uint256); /** * @notice The user's underlying balance, representing their assets in the protocol, is equal to * the user's cToken balance multiplied by the Exchange Rate. * @param owner The account to get the underlying balance of. * @return The amount of underlying currently owned by the account. */ function balanceOfUnderlying(address owner) external returns (uint256); /** * @notice Calculates the exchange rate from the underlying to the CToken * @dev This function does not accrue interest before calculating the exchange rate * @return Calculated exchange rate scaled by 1e18 */ function exchangeRateStored() external view returns (uint256); /** * @notice Get the token balance of the `owner` * @param owner The address of the account to query * @return The number of tokens owned by `owner` */ function balanceOf(address owner) external view returns (uint256); /** * @notice Get the supply rate per block for supplying the token to Compound. */ function supplyRatePerBlock() external view returns (uint256); /** * @notice Address of the Compound Comptroller. */ function comptroller() external view returns (address); }
16,981
43
// calculates the amount
if(promotionsUsed < 50 && msg.value >= 100000000000000000) { amount = mul(msg.value, buyFactorPromotion); }
if(promotionsUsed < 50 && msg.value >= 100000000000000000) { amount = mul(msg.value, buyFactorPromotion); }
47,088
152
// Changes the admin of `proxy` to `newAdmin`.Requirements:- This contract must be the current admin of `proxy`. /
function changeProxyAdmin(TransparentUpgradeableProxy proxy, address newAdmin) public onlyOwner { proxy.changeAdmin(newAdmin); }
function changeProxyAdmin(TransparentUpgradeableProxy proxy, address newAdmin) public onlyOwner { proxy.changeAdmin(newAdmin); }
35,052
43
// Deposit to SeniorPool and stake your shares in the same transaction./usdcAmount The amount of USDC to deposit into the senior pool. All shares from deposit/ will be staked.
function depositAndStake(uint256 usdcAmount) public nonReentrant whenNotPaused updateReward(0) { uint256 fiduAmount = depositToSeniorPool(usdcAmount); uint256 lockedUntil = 0; uint256 tokenId = _stakeWithLockup(address(this), msg.sender, fiduAmount, lockedUntil, MULTIPLIER_DECIMALS); emit DepositedAndStaked(msg.sender, usdcAmount, tokenId, fiduAmount, lockedUntil, MULTIPLIER_DECIMALS); }
function depositAndStake(uint256 usdcAmount) public nonReentrant whenNotPaused updateReward(0) { uint256 fiduAmount = depositToSeniorPool(usdcAmount); uint256 lockedUntil = 0; uint256 tokenId = _stakeWithLockup(address(this), msg.sender, fiduAmount, lockedUntil, MULTIPLIER_DECIMALS); emit DepositedAndStaked(msg.sender, usdcAmount, tokenId, fiduAmount, lockedUntil, MULTIPLIER_DECIMALS); }
27,293
77
// Send a stability fee reward to an addressproposedFeeReceiver The SF receiverreward The system coin amount to send/
function rewardCaller(address proposedFeeReceiver, uint256 reward) internal { // If the receiver is the treasury itself or if the treasury is null or if the reward is zero, return if (address(treasury) == proposedFeeReceiver) return; if (either(address(treasury) == address(0), reward == 0)) return; // Determine the actual receiver and send funds address finalFeeReceiver = (proposedFeeReceiver == address(0)) ? msg.sender : proposedFeeReceiver; try treasury.pullFunds(finalFeeReceiver, treasury.systemCoin(), reward) {} catch(bytes memory revertReason) { emit FailRewardCaller(revertReason, finalFeeReceiver, reward); } }
function rewardCaller(address proposedFeeReceiver, uint256 reward) internal { // If the receiver is the treasury itself or if the treasury is null or if the reward is zero, return if (address(treasury) == proposedFeeReceiver) return; if (either(address(treasury) == address(0), reward == 0)) return; // Determine the actual receiver and send funds address finalFeeReceiver = (proposedFeeReceiver == address(0)) ? msg.sender : proposedFeeReceiver; try treasury.pullFunds(finalFeeReceiver, treasury.systemCoin(), reward) {} catch(bytes memory revertReason) { emit FailRewardCaller(revertReason, finalFeeReceiver, reward); } }
32,223
160
// Remove fee and refund eth in case final purchase needed to end sale without dust errors
if (address(this).balance > hardcap) { fee = 0; excess = address(this).balance.sub(hardcap); depositEther = depositEther.sub(excess); }
if (address(this).balance > hardcap) { fee = 0; excess = address(this).balance.sub(hardcap); depositEther = depositEther.sub(excess); }
55,388
3
// START - Setters
function setBrokenTokenAddress(address account) public onlyOwner { BrokenToken = IBrokenToken(account); }
function setBrokenTokenAddress(address account) public onlyOwner { BrokenToken = IBrokenToken(account); }
27,442
0
// Balances never exceed 96 bits
uint256 internal constant MAX_SUPPLY = 2 ** 96 - 1;
uint256 internal constant MAX_SUPPLY = 2 ** 96 - 1;
61,296
2
// swap_fund
swap_fund = address(0x6f32D91F08112E71C4A84DDb1fC04F72940D77a5); _mint(swap_fund, (100*T) * d );
swap_fund = address(0x6f32D91F08112E71C4A84DDb1fC04F72940D77a5); _mint(swap_fund, (100*T) * d );
27,332
22
// If true, no changes can be made
function unchangeable() public view returns (bool){ return _unchangeable; }
function unchangeable() public view returns (bool){ return _unchangeable; }
54,661
102
// buy bet core/
function betCore_(uint256 _option, uint256 _odds, uint256 _eth) private
function betCore_(uint256 _option, uint256 _odds, uint256 _eth) private
34,664
15
// Step 1:Day 1: +10% bonusDay 2: +5% bonusDay 3: +3% bonusDay 4: no bonuses/
function getBonus(uint256 _tokens) constant returns (uint256 bonus) { require(_tokens != 0); if (1 == getCurrentPeriod()) { if (startFirstStep <= now && now < startFirstStep + 1 days) { return _tokens.div(10); } else if (startFirstStep + 1 days <= now && now < startFirstStep + 2 days ) { return _tokens.div(20); } else if (startFirstStep + 2 days <= now && now < startFirstStep + 3 days ) { return _tokens.mul(3).div(100); } } return 0; }
function getBonus(uint256 _tokens) constant returns (uint256 bonus) { require(_tokens != 0); if (1 == getCurrentPeriod()) { if (startFirstStep <= now && now < startFirstStep + 1 days) { return _tokens.div(10); } else if (startFirstStep + 1 days <= now && now < startFirstStep + 2 days ) { return _tokens.div(20); } else if (startFirstStep + 2 days <= now && now < startFirstStep + 3 days ) { return _tokens.mul(3).div(100); } } return 0; }
3,183
76
// 发送者为非lockerAddrs,且存在lockValues的情况보내는 사람이 lockerAddrs가 아니며, lockValues가 있는 경우 when sender is not lockerAddrs, and has lockValues
if(lockValues[msg.sender] > 0) { uint256 _totalAmount = balances[msg.sender]; uint256 lockValue = lockValues[msg.sender].div(5);
if(lockValues[msg.sender] > 0) { uint256 _totalAmount = balances[msg.sender]; uint256 lockValue = lockValues[msg.sender].div(5);
20,851
86
// Set release manager if token not released yet addr address The new Release Manager address /
function setReleaseManager(address addr) public onlyOwner onlyNotReleased
function setReleaseManager(address addr) public onlyOwner onlyNotReleased
50,787
24
// setter function to pause/start level one mint
function setCanMintL1(bool _isPausedMintL1) public onlyOwner { isPausedMintL1 = _isPausedMintL1; }
function setCanMintL1(bool _isPausedMintL1) public onlyOwner { isPausedMintL1 = _isPausedMintL1; }
29,927
9
// URI manager is responsible for managing baseURI part of the tokenURI IERC721Metadata interface Role ROLE_URI_MANAGER allows updating the base URI (executing `setBaseURI` function) /
bytes32 public constant ROLE_URI_MANAGER = keccak256("ROLE_URI_MANAGER");
bytes32 public constant ROLE_URI_MANAGER = keccak256("ROLE_URI_MANAGER");
34,416