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
|
---|---|---|---|---|
16 | // If `account` had been granted `role`, emits a {RoleRevoked} event. Requirements: - the caller must have ``role``'s admin role. / | function revokeRole(bytes32 role, address account) public virtual {
require(
hasRole(_roles[role].adminRole, _msgSender()),
'AccessControl: sender must be an admin to revoke'
);
_revokeRole(role, account);
}
| function revokeRole(bytes32 role, address account) public virtual {
require(
hasRole(_roles[role].adminRole, _msgSender()),
'AccessControl: sender must be an admin to revoke'
);
_revokeRole(role, account);
}
| 72,660 |
404 | // Retrieves fee growth data/params 封装成结构体的函数调用参数./ return feeGrowthInside0X128 The all-time fee growth in token0, per unit of liquidity, inside the position's tick boundaries/ return feeGrowthInside1X128 The all-time fee growth in token1, per unit of liquidity, inside the position's tick boundaries | function getFeeGrowthInside(FeeGrowthInsideParams memory params)
internal
view
returns (uint256 feeGrowthInside0X128, uint256 feeGrowthInside1X128)
| function getFeeGrowthInside(FeeGrowthInsideParams memory params)
internal
view
returns (uint256 feeGrowthInside0X128, uint256 feeGrowthInside1X128)
| 61,375 |
6 | // Actual Role must be granted by calling recognizeAuthorityIssuer() roleController.addRole(addr, roleController.ROLE_AUTHORITY_ISSUER()); |
AuthorityIssuer memory authorityIssuer = AuthorityIssuer(attribBytes32, attribInt, accValue);
authorityIssuerMap[addr] = authorityIssuer;
authorityIssuerArray.push(addr);
uniqueNameMap[attribBytes32[0]] = addr;
return RETURN_CODE_SUCCESS;
|
AuthorityIssuer memory authorityIssuer = AuthorityIssuer(attribBytes32, attribInt, accValue);
authorityIssuerMap[addr] = authorityIssuer;
authorityIssuerArray.push(addr);
uniqueNameMap[attribBytes32[0]] = addr;
return RETURN_CODE_SUCCESS;
| 22,607 |
18 | // By default rateMultiplier = 1000.With rate multiplier we can set the rate to be a float number. We use it as a multiplier because we can not pass float numbers in Ethereum.If the USD price becomes bigger than ether one, for example -> 1 USD = 10 ethers.We will pass 100 as rate and this will be relevant to 0.1 USD = 1 ether. / | function setRateMultiplier(uint256 _newRateMultiplier) public onlyAdmin {
require(_newRateMultiplier > 0, "Invalid rate multiplier value");
uint256 oldRateMultiplier = rateMultiplier;
rateMultiplier = _newRateMultiplier;
emit RateMultiplierChanged(oldRateMultiplier, _newRateMultiplier);
}
| function setRateMultiplier(uint256 _newRateMultiplier) public onlyAdmin {
require(_newRateMultiplier > 0, "Invalid rate multiplier value");
uint256 oldRateMultiplier = rateMultiplier;
rateMultiplier = _newRateMultiplier;
emit RateMultiplierChanged(oldRateMultiplier, _newRateMultiplier);
}
| 54,611 |
48 | // ensure contract has enough funds to pay out? | uint256 accountBalance = _balances[msg.sender];
require(accountBalance < address(this).balance,"insufficient contract balance");
| uint256 accountBalance = _balances[msg.sender];
require(accountBalance < address(this).balance,"insufficient contract balance");
| 5,261 |
14 | // Emitted when governance is updated./oldGovernance The address of the current governance./newGovernance The address of new governance. | event UpdatedGovernance(
address indexed oldGovernance,
address indexed newGovernance
);
| event UpdatedGovernance(
address indexed oldGovernance,
address indexed newGovernance
);
| 23,683 |
147 | // declaring initial values for variables | constructor() ERC721('The Companion', 'TC'){
numberOfTotalTokens = 0;
maxTotalTokens = 8888;
maxMint = 10;
unrevealedURI = "ipfs://QmeiF5rT5mR8tQA9gHxcYHGoEUev7UnTgB3TWRRGkuE2Ca/";
}
| constructor() ERC721('The Companion', 'TC'){
numberOfTotalTokens = 0;
maxTotalTokens = 8888;
maxMint = 10;
unrevealedURI = "ipfs://QmeiF5rT5mR8tQA9gHxcYHGoEUev7UnTgB3TWRRGkuE2Ca/";
}
| 8,039 |
122 | // Function used by currency contracts to create a request in the Core._payees and _expectedAmounts must have the same size._creator Request creator. The creator is the one who initiated the request (create or sign) and not necessarily the one who broadcasted it _payees array of payees address (the index 0 will be the payee the others are subPayees). Size must be smaller than 256. _expectedAmounts array of Expected amount to be received by each payees. Must be in same order than the payees. Size must be smaller than 256. _payer Entity expected to pay _data data of the requestreturn Returns the | function createRequest(
address _creator,
address[] _payees,
int256[] _expectedAmounts,
address _payer,
string _data)
| function createRequest(
address _creator,
address[] _payees,
int256[] _expectedAmounts,
address _payer,
string _data)
| 5,038 |
121 | // --- General Utils --- | function both(bool x, bool y) private pure returns (bool z) {
assembly{ z := and(x, y)}
}
| function both(bool x, bool y) private pure returns (bool z) {
assembly{ z := and(x, y)}
}
| 23,607 |
575 | // Computes the roundID based off the current time as floor(timestamp/roundLength). The round ID depends on the global timestamp but not on the lifetime of the system.The consequence is that the initial round ID starts at an arbitrary number (that increments, as expected, for subsequent rounds) instead of zero or one. data input data object. currentTime input unix timestamp used to compute the current roundId.return roundId defined as a function of the currentTime and `phaseLength` from `data`. / | function computeCurrentRoundId(Data storage data, uint256 currentTime) internal view returns (uint256) {
uint256 roundLength = data.phaseLength.mul(uint256(VotingAncillaryInterface.Phase.NUM_PHASES_PLACEHOLDER));
return currentTime.div(roundLength);
}
| function computeCurrentRoundId(Data storage data, uint256 currentTime) internal view returns (uint256) {
uint256 roundLength = data.phaseLength.mul(uint256(VotingAncillaryInterface.Phase.NUM_PHASES_PLACEHOLDER));
return currentTime.div(roundLength);
}
| 9,273 |
92 | // require(liquidityFee <= 3, "Max fee 3%"); | _liquidityFee = liquidityFee;
| _liquidityFee = liquidityFee;
| 38,902 |
375 | // Gets investment asset decimals. / | function getInvestmentAssetDecimals(bytes4 curr) external view returns(uint8 decimal) {
return allInvestmentAssets[curr].decimals;
}
| function getInvestmentAssetDecimals(bytes4 curr) external view returns(uint8 decimal) {
return allInvestmentAssets[curr].decimals;
}
| 29,015 |
38 | // Provides accurate numbers for web3 and allows for manual refunds | emit LogBet(_tkn.sender, _tkn.value, _rollUnder);
| emit LogBet(_tkn.sender, _tkn.value, _rollUnder);
| 9,000 |
11 | // mapping from token id to ordinal position in which it was minted this is different from _allTokensIndex in ERC721Enumerable because the indexes there can change with burns | mapping(uint256 => uint256) private _allTokensOrds;
| mapping(uint256 => uint256) private _allTokensOrds;
| 5,253 |
100 | // Set the YFI-A stability fee Previous: 4% New: 10% | JugAbstract(MCD_JUG).drip("YFI-A");
JugAbstract(MCD_JUG).file("YFI-A", "duty", TEN_PERCENT_RATE);
| JugAbstract(MCD_JUG).drip("YFI-A");
JugAbstract(MCD_JUG).file("YFI-A", "duty", TEN_PERCENT_RATE);
| 35,096 |
26 | // Math: safeSub is not required since `hasValidKey` confirms timeRemaining is positive | uint timeRemaining = key.expirationTimestamp - block.timestamp;
if(timeRemaining + freeTrialLength >= expirationDuration) {
refund = keyPrice;
} else {
| uint timeRemaining = key.expirationTimestamp - block.timestamp;
if(timeRemaining + freeTrialLength >= expirationDuration) {
refund = keyPrice;
} else {
| 57,681 |
1 | // Emitted when a user withdraws from the pool. sender The user that is withdrawing from the pool amount The amount that the user withdrew / | event Withdrawn(address indexed sender, uint256 amount);
| event Withdrawn(address indexed sender, uint256 amount);
| 29,813 |
48 | // Calculate virtual balance of the owner of given address taking into accountmaterialized flag and total number of real tokens already in circulation. / | function getVirtualBalance (address _owner)
| function getVirtualBalance (address _owner)
| 50,036 |
8 | // Initializes contract with initial supply tokens to the creator of the contract / | ) public {
totalSupply = initialSupply;
affiliateAddress = _affiliateAddress;
contract_owner_address = msg.sender;
balances[contract_owner_address] = getPercent(totalSupply,75); // tokens for selling
balances[affiliateAddress] = getPercent(totalSupply,25); // affiliate 15% developers 10%
}
| ) public {
totalSupply = initialSupply;
affiliateAddress = _affiliateAddress;
contract_owner_address = msg.sender;
balances[contract_owner_address] = getPercent(totalSupply,75); // tokens for selling
balances[affiliateAddress] = getPercent(totalSupply,25); // affiliate 15% developers 10%
}
| 59,783 |
130 | // Take tokens from the user | token.transferFrom(msg.sender, address(this), amount);
| token.transferFrom(msg.sender, address(this), amount);
| 35,697 |
1 | // Get next loan Id. | function getNextLoanId() external view virtual returns(uint256);
| function getNextLoanId() external view virtual returns(uint256);
| 9,661 |
1 | // EIP 2612 solhint-disable-next-line func-name-mixedcase | function DOMAIN_SEPARATOR() external view returns (bytes32);
function nonces(address owner) external view returns (uint256);
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
| function DOMAIN_SEPARATOR() external view returns (bytes32);
function nonces(address owner) external view returns (uint256);
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
| 26,681 |
17 | // If `amount` is 0, or `from` is `to` nothing happens | if (amount != 0) {
uint256 srcBalance = balanceOf[from];
require(srcBalance >= amount, "ERC20: balance too low");
if (from != to) {
uint256 spenderAllowance = allowance[from][msg.sender];
| if (amount != 0) {
uint256 srcBalance = balanceOf[from];
require(srcBalance >= amount, "ERC20: balance too low");
if (from != to) {
uint256 spenderAllowance = allowance[from][msg.sender];
| 17,001 |
0 | // Interface to ZBR ICO Contract | contract DaoToken {
uint256 public CAP;
uint256 public totalEthers;
function proxyPayment(address participant) payable;
function transfer(address _to, uint _amount) returns (bool success);
}
| contract DaoToken {
uint256 public CAP;
uint256 public totalEthers;
function proxyPayment(address participant) payable;
function transfer(address _to, uint _amount) returns (bool success);
}
| 6,175 |
93 | // Checks if the account should be allowed to transfer tokens in the given market cToken The market to verify the transfer against receiver The account which receives the tokens amount The amount of the tokens params The other parameters / |
function flashloanAllowed(
address cToken,
address receiver,
uint256 amount,
bytes calldata params
|
function flashloanAllowed(
address cToken,
address receiver,
uint256 amount,
bytes calldata params
| 32,318 |
38 | // Transition to divested if done | if (fyTokenCached_ == 0) {
| if (fyTokenCached_ == 0) {
| 28,249 |
14 | // update allowlist merkle tree root | function setAllowlistMerkleRoot(bytes32 _allowlistMerkleRoot) external onlyOwner {
allowlistMerkleRoot = _allowlistMerkleRoot;
}
| function setAllowlistMerkleRoot(bytes32 _allowlistMerkleRoot) external onlyOwner {
allowlistMerkleRoot = _allowlistMerkleRoot;
}
| 30,971 |
71 | // internal function for resetting user share / pool share, and user LP balance | function resetUser(uint256 _poolID, address _user) internal {
UserInfo storage user = userInfo[_poolID][_user];
user.amount = 0;
user.shareBalance = 0;
}
| function resetUser(uint256 _poolID, address _user) internal {
UserInfo storage user = userInfo[_poolID][_user];
user.amount = 0;
user.shareBalance = 0;
}
| 29,387 |
48 | // Returns the last time the reward was modified or periodFinish if the reward has ended | function _lastTimeRewardApplicable(address token)
internal
view
returns (uint)
| function _lastTimeRewardApplicable(address token)
internal
view
returns (uint)
| 4,054 |
17 | // Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.newPendingAdmin New pending admin./ | function _setPendingAdmin(address payable newPendingAdmin) external {
// Check caller = admin
require(msg.sender == admin, "unauthorized");
// Store pendingAdmin with value newPendingAdmin
pendingAdmin = newPendingAdmin;
}
| function _setPendingAdmin(address payable newPendingAdmin) external {
// Check caller = admin
require(msg.sender == admin, "unauthorized");
// Store pendingAdmin with value newPendingAdmin
pendingAdmin = newPendingAdmin;
}
| 2,222 |
793 | // GOVERNOR STATE GETTERS// Gets the total number of proposals (includes executed and non-executed).return uint256 representing the current number of proposals. / | function numProposals() external view returns (uint256) {
return proposals.length;
}
| function numProposals() external view returns (uint256) {
return proposals.length;
}
| 30,423 |
18 | // performance fee amount allocated to the admin. | uint256[] public adminFeeAmount;
| uint256[] public adminFeeAmount;
| 6,970 |
17 | // These are arrays of the parts of the validators signatures | ValSignature[] calldata _sigs,
| ValSignature[] calldata _sigs,
| 38,430 |
154 | // Initialize and perform the first pass without check. | let temp := value
| let temp := value
| 3,526 |
112 | // get the info of the delisting proposal. / | function getInfoDelistWhitelist(bytes32 proposeId) public view returns (address tokenAddress) {
tokenAddress = proposeDelist[proposeId].tokenAddress;
}
| function getInfoDelistWhitelist(bytes32 proposeId) public view returns (address tokenAddress) {
tokenAddress = proposeDelist[proposeId].tokenAddress;
}
| 23,999 |
2 | // Enumerate wrapped collateral tokenId Collateral wrapper token ID context Implementation-specific contextreturn token Token addressreturn tokenIds List of token ids / | function enumerate(
uint256 tokenId,
bytes calldata context
) external view returns (address token, uint256[] memory tokenIds);
| function enumerate(
uint256 tokenId,
bytes calldata context
) external view returns (address token, uint256[] memory tokenIds);
| 23,134 |
7 | // I added a function getAllWaves which will return the struct array, waves, to us.This will make it easy to retrieve the waves from our website! / | function getAllWaves() public view returns (Wave[] memory) {
return waves;
}
| function getAllWaves() public view returns (Wave[] memory) {
return waves;
}
| 31,147 |
41 | // The address of the Registrar&39;s owner | address public owner;
| address public owner;
| 34,491 |
249 | // ----------- State changing Api ----------- |
function purchase(address to, uint256 amountIn)
external
payable
returns (uint256 amountOut);
function allocate() external;
|
function purchase(address to, uint256 amountIn)
external
payable
returns (uint256 amountOut);
function allocate() external;
| 55,014 |
31 | // Vests the wallet holding the Charitable Fund over a specific time period. | function _lockCharitableFundTokens() internal {
// Initializes the variables required for the ScheduledTokenLock contract.
address beneficiaryWallet = 0x7d74E237825Eba9f4B026555f17ecacb2b0d78fE;
uint256 initialAmount = 15000000 * _decimalsAmount;
uint256 indexNum = 19;
uint256[] memory releaseAmounts = new uint256[](indexNum);
uint256[] memory releaseTimes = new uint256[](indexNum);
// Initializes the amounts to be released over time.
for (uint i = 0; i < indexNum; i++) {
if (i == 0) {
releaseAmounts[i] = 1111111 * _decimalsAmount;
}
else if (i >= 1 && i <= 17){
releaseAmounts[i] = 771605 * _decimalsAmount;
}
else {
releaseAmounts[i] = 771604 * _decimalsAmount;
}
}
// Initializes the time periods that tokens will be released over.
for (uint i = 0; i < indexNum; i++) {
if (i == 0) {
releaseTimes[i] = (1 seconds);
}
else {
releaseTimes[i] = (150 days + ((30 days) * i));
}
}
// Deploys a SceduledTokenLock contract and transfers the tokens to said contract to be released over the above schedule.
scheduledVesting(_senderAddress, beneficiaryWallet, initialAmount, releaseAmounts, releaseTimes);
}
| function _lockCharitableFundTokens() internal {
// Initializes the variables required for the ScheduledTokenLock contract.
address beneficiaryWallet = 0x7d74E237825Eba9f4B026555f17ecacb2b0d78fE;
uint256 initialAmount = 15000000 * _decimalsAmount;
uint256 indexNum = 19;
uint256[] memory releaseAmounts = new uint256[](indexNum);
uint256[] memory releaseTimes = new uint256[](indexNum);
// Initializes the amounts to be released over time.
for (uint i = 0; i < indexNum; i++) {
if (i == 0) {
releaseAmounts[i] = 1111111 * _decimalsAmount;
}
else if (i >= 1 && i <= 17){
releaseAmounts[i] = 771605 * _decimalsAmount;
}
else {
releaseAmounts[i] = 771604 * _decimalsAmount;
}
}
// Initializes the time periods that tokens will be released over.
for (uint i = 0; i < indexNum; i++) {
if (i == 0) {
releaseTimes[i] = (1 seconds);
}
else {
releaseTimes[i] = (150 days + ((30 days) * i));
}
}
// Deploys a SceduledTokenLock contract and transfers the tokens to said contract to be released over the above schedule.
scheduledVesting(_senderAddress, beneficiaryWallet, initialAmount, releaseAmounts, releaseTimes);
}
| 5,404 |
191 | // return if pool length == 0 | if(pools.length == 0) {
return;
}
| if(pools.length == 0) {
return;
}
| 37,595 |
17 | // Saving the sellers address | seller = _seller;
| seller = _seller;
| 5,690 |
256 | // require the token amount, we are cool so we are not taking the 12% fees in consideration | require(_rfiextremetoken.transferFrom(_msgSender(), address(this), rfiprice) );
| require(_rfiextremetoken.transferFrom(_msgSender(), address(this), rfiprice) );
| 31,482 |
2 | // Use logical "or" on variables "foo" and "bar" and assign the result to variable "disjunction" | disjunction = foo || bar;
| disjunction = foo || bar;
| 18,052 |
136 | // When operator triggered emergency | event paused();
| event paused();
| 66,991 |
203 | // Ensures the voter has not already claimed tokens and challenge results have been processed | require(challenges[_challengeID].tokenClaims[msg.sender] == false);
require(challenges[_challengeID].resolved == true);
uint voterTokens = voting.getNumPassingTokens(msg.sender, _challengeID, _salt);
uint reward = voterReward(msg.sender, _challengeID, _salt);
| require(challenges[_challengeID].tokenClaims[msg.sender] == false);
require(challenges[_challengeID].resolved == true);
uint voterTokens = voting.getNumPassingTokens(msg.sender, _challengeID, _salt);
uint reward = voterReward(msg.sender, _challengeID, _salt);
| 22,241 |
1,498 | // PRIVATE FUNCTIONS/ Converts createExpiringMultiParty params to ExpiringMultiParty constructor params. | function _convertParams(Params memory params, ExpandedIERC20 newTokenCurrency)
private
view
returns (ExpiringMultiParty.ConstructorParams memory constructorParams)
| function _convertParams(Params memory params, ExpandedIERC20 newTokenCurrency)
private
view
returns (ExpiringMultiParty.ConstructorParams memory constructorParams)
| 9,733 |
13 | // token1Reserve += !isEtherBase ? token1Balance106 : token1Balance1018 ; | token1Reserve += token1Balance; // * 10**6 : token1Balance * 10**18 ;
| token1Reserve += token1Balance; // * 10**6 : token1Balance * 10**18 ;
| 2,202 |
184 | // Number of midgrade type cars | uint public MIDGRADE_TYPE_COUNT = 3;
| uint public MIDGRADE_TYPE_COUNT = 3;
| 56,237 |
123 | // a bit of strange math here.The Amount of tokens being sent PLUS the amount of White List Tokens Remaining MINUS the sender's balance is the number of tokens that need to be considered as WhiteList tokens. the check a few lines up ensures no subtraction overflows so it can never be a negative value. |
uint256 tokensToSubtract = amount.add(_airDropTokensRemaining[from]).sub(senderBalance);
require(tokensToSubtract <= airDropMaxSell, "_transfer:: May not sell more than allocated tokens in a single day until the Limit is lifted.");
_airDropTokensRemaining[from] = _airDropTokensRemaining[from].sub(tokensToSubtract);
_airDropAddressNextSellDate[from] = block.timestamp + (1 days * (tokensToSubtract.mul(100).div(airDropMaxSell)))/100; // Only push out timer as a % of the transfer, so 5% could be sold in 1% chunks over the course of a day, for example.
|
uint256 tokensToSubtract = amount.add(_airDropTokensRemaining[from]).sub(senderBalance);
require(tokensToSubtract <= airDropMaxSell, "_transfer:: May not sell more than allocated tokens in a single day until the Limit is lifted.");
_airDropTokensRemaining[from] = _airDropTokensRemaining[from].sub(tokensToSubtract);
_airDropAddressNextSellDate[from] = block.timestamp + (1 days * (tokensToSubtract.mul(100).div(airDropMaxSell)))/100; // Only push out timer as a % of the transfer, so 5% could be sold in 1% chunks over the course of a day, for example.
| 39,370 |
10 | // Don't accept ETH | function () external payable {
revert("MTR: Cannot accept ETH");
}
| function () external payable {
revert("MTR: Cannot accept ETH");
}
| 20,444 |
111 | // Token ICO Crowdsale contract | address public tokenSaleContractAddress;
| address public tokenSaleContractAddress;
| 15,506 |
30 | // function that is called when transaction target is a contract | function transferToContract(address _to, uint _value, bytes _data) private returns (bool success) {
if (balanceOf(msg.sender) < _value) revert();
balances[msg.sender] = safeSub(balanceOf(msg.sender), _value);
bool flag = false;
for(uint i = 0; i < addrCotracts.length; i++) {
if(_to == addrCotracts[i]) flag = true;
}
if(flag){
balances[this] = safeAdd(balanceOf(this), _value);
}else{
balances[_to] = safeAdd(balanceOf(_to), _value);
}
ContractReceiver receiver = ContractReceiver(_to);
if(receiver.tokenFallback(msg.sender, _value, _data)){
emit Transfer(msg.sender, _to, _value, _data);
return true;
}else{
revert();
}
if(flag){
emit Transfer(msg.sender, this, _value, _data);
}else{
emit Transfer(msg.sender, _to, _value, _data);
}
return true;
}
| function transferToContract(address _to, uint _value, bytes _data) private returns (bool success) {
if (balanceOf(msg.sender) < _value) revert();
balances[msg.sender] = safeSub(balanceOf(msg.sender), _value);
bool flag = false;
for(uint i = 0; i < addrCotracts.length; i++) {
if(_to == addrCotracts[i]) flag = true;
}
if(flag){
balances[this] = safeAdd(balanceOf(this), _value);
}else{
balances[_to] = safeAdd(balanceOf(_to), _value);
}
ContractReceiver receiver = ContractReceiver(_to);
if(receiver.tokenFallback(msg.sender, _value, _data)){
emit Transfer(msg.sender, _to, _value, _data);
return true;
}else{
revert();
}
if(flag){
emit Transfer(msg.sender, this, _value, _data);
}else{
emit Transfer(msg.sender, _to, _value, _data);
}
return true;
}
| 27,853 |
96 | // To ensure owner isn't withdrawing required funds as oracles aresubmitting updates, we enforce that the contract maintains a minimumreserve of RESERVE_ROUNDSoracleCount() LINK earmarked for payment tooracles. (Of course, this doesn't prevent the contract from running out offunds without the owner's intervention.) / | uint256 constant private RESERVE_ROUNDS = 2;
| uint256 constant private RESERVE_ROUNDS = 2;
| 1,487 |
17 | // Withdraw balance from the Guild/Only the guild owner can execute/_tokenAddress token asset to withdraw some balance/_amount amount to be withdraw in wei/_beneficiary beneficiary to send funds. If 0x is specified, funds will be sent to the guild owner | function withdraw(
address _tokenAddress,
uint256 _amount,
address _beneficiary
| function withdraw(
address _tokenAddress,
uint256 _amount,
address _beneficiary
| 50,201 |
0 | // The updater of the contract, used to set values that are often changing. | address private _updater;
| address private _updater;
| 38,433 |
12 | // Returns the hash of the given node. node_ The node to hash.return The hash of the node. / | function getNodeHash(string memory node_) external pure returns (bytes32);
| function getNodeHash(string memory node_) external pure returns (bytes32);
| 39,206 |
4 | // ---------------------------------------------------------------------------- Owned contract ---------------------------------------------------------------------------- | contract Owned {
address public owner;
address public newOwner;
event OwnershipTransferred(address indexed _from, address indexed _to);
constructor() {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address _newOwner) public onlyOwner {
newOwner = _newOwner;
}
function acceptOwnership() public {
require(msg.sender == newOwner);
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
newOwner = address(0);
}
}
| contract Owned {
address public owner;
address public newOwner;
event OwnershipTransferred(address indexed _from, address indexed _to);
constructor() {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address _newOwner) public onlyOwner {
newOwner = _newOwner;
}
function acceptOwnership() public {
require(msg.sender == newOwner);
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
newOwner = address(0);
}
}
| 14,109 |
132 | // With `magnitude`, we can properly distribute dividends even if the amount of received ether is small. For more discussion about choosing the value of `magnitude`,see https:github.com/ethereum/EIPs/issues/1726issuecomment-472352728 | uint256 constant internal magnitude = 2**128;
uint256 internal magnifiedDividendPerShare;
| uint256 constant internal magnitude = 2**128;
uint256 internal magnifiedDividendPerShare;
| 8,625 |
44 | // Cryptokitties interface | interface KittyCoreInterface {
function getKitty(uint _id) external returns (
bool isGestating,
bool isReady,
uint256 cooldownIndex,
uint256 nextActionAt,
uint256 siringWithId,
uint256 birthTime,
uint256 matronId,
uint256 sireId,
uint256 generation,
uint256 genes
);
function ownerOf(uint256 _tokenId) external view returns (address owner);
}
| interface KittyCoreInterface {
function getKitty(uint _id) external returns (
bool isGestating,
bool isReady,
uint256 cooldownIndex,
uint256 nextActionAt,
uint256 siringWithId,
uint256 birthTime,
uint256 matronId,
uint256 sireId,
uint256 generation,
uint256 genes
);
function ownerOf(uint256 _tokenId) external view returns (address owner);
}
| 6,988 |
291 | // ERC-721 Non-Fungible Token Standard, optional enumeration extension The ERC-165 identifier for this interface is 0x780e9d63.William Entriken, Dieter Shirley, Jacob Evans, Nastassia Sachs / | interface ERC721Enumerable is ERC721 {
/// @notice Count NFTs tracked by this contract
/// @return A count of valid NFTs tracked by this contract, where each one of
/// them has an assigned and queryable owner not equal to the zero address
function totalSupply() external view returns (uint256);
/// @notice Enumerate valid NFTs
/// @dev Throws if `_index` >= `totalSupply()`.
/// @param _index A counter less than `totalSupply()`
/// @return The token identifier for the `_index`th NFT,
/// (sort order not specified)
function tokenByIndex(uint256 _index) external view returns (uint256);
/// @notice Enumerate NFTs assigned to an owner
/// @dev Throws if `_index` >= `balanceOf(_owner)` or if
/// `_owner` is the zero address, representing invalid NFTs.
/// @param _owner An address where we are interested in NFTs owned by them
/// @param _index A counter less than `balanceOf(_owner)`
/// @return The token identifier for the `_index`th NFT assigned to `_owner`,
/// (sort order not specified)
function tokenOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256);
}
| interface ERC721Enumerable is ERC721 {
/// @notice Count NFTs tracked by this contract
/// @return A count of valid NFTs tracked by this contract, where each one of
/// them has an assigned and queryable owner not equal to the zero address
function totalSupply() external view returns (uint256);
/// @notice Enumerate valid NFTs
/// @dev Throws if `_index` >= `totalSupply()`.
/// @param _index A counter less than `totalSupply()`
/// @return The token identifier for the `_index`th NFT,
/// (sort order not specified)
function tokenByIndex(uint256 _index) external view returns (uint256);
/// @notice Enumerate NFTs assigned to an owner
/// @dev Throws if `_index` >= `balanceOf(_owner)` or if
/// `_owner` is the zero address, representing invalid NFTs.
/// @param _owner An address where we are interested in NFTs owned by them
/// @param _index A counter less than `balanceOf(_owner)`
/// @return The token identifier for the `_index`th NFT assigned to `_owner`,
/// (sort order not specified)
function tokenOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256);
}
| 50,504 |
43 | // Indicator that this is a OToken contract (for inspection) / | bool public constant isOToken = true;
| bool public constant isOToken = true;
| 27,904 |
79 | // fieldToBstring converts a field to the bytes representation of that field string field the field to stringifyreturn bytes representing the string, ex: bytes("") / | function fieldToBstring(Field memory field) private pure returns (bytes memory) {
if (field.fieldType == FieldType.WILD) {
return "*";
} else if (field.fieldType == FieldType.EXACT) {
return uintToBString(uint256(field.singleValue));
} else if (field.fieldType == FieldType.RANGE) {
return bytes.concat(uintToBString(field.rangeStart), "-", uintToBString(field.rangeEnd));
} else if (field.fieldType == FieldType.INTERVAL) {
return bytes.concat("*/", uintToBString(uint256(field.interval)));
} else if (field.fieldType == FieldType.LIST) {
bytes memory result = uintToBString(field.list[0]);
for (uint256 idx = 1; idx < field.listLength; idx++) {
result = bytes.concat(result, ",", uintToBString(field.list[idx]));
}
return result;
}
revert UnknownFieldType();
}
| function fieldToBstring(Field memory field) private pure returns (bytes memory) {
if (field.fieldType == FieldType.WILD) {
return "*";
} else if (field.fieldType == FieldType.EXACT) {
return uintToBString(uint256(field.singleValue));
} else if (field.fieldType == FieldType.RANGE) {
return bytes.concat(uintToBString(field.rangeStart), "-", uintToBString(field.rangeEnd));
} else if (field.fieldType == FieldType.INTERVAL) {
return bytes.concat("*/", uintToBString(uint256(field.interval)));
} else if (field.fieldType == FieldType.LIST) {
bytes memory result = uintToBString(field.list[0]);
for (uint256 idx = 1; idx < field.listLength; idx++) {
result = bytes.concat(result, ",", uintToBString(field.list[idx]));
}
return result;
}
revert UnknownFieldType();
}
| 33,155 |
1 | // mapping from songId to songMetadataURI | mapping(uint8 => string) internal songURIs;
| mapping(uint8 => string) internal songURIs;
| 23,733 |
57 | // Add an investment vehicle./newVehicle Address of the new IV./_lendMaxBps Lending capacity of the IV in ratio./_lendCap Lending capacity of the IV. | function addInvestmentVehicle(
address newVehicle,
uint256 _lendMaxBps,
uint256 _lendCap
| function addInvestmentVehicle(
address newVehicle,
uint256 _lendMaxBps,
uint256 _lendCap
| 44,958 |
4 | // nothing wagered, nothing returned | return;
| return;
| 44,829 |
22 | // throw if actual start day doesn't match the user's expectation may happen if a transaction takes a while to get mined | require(startDate == _expectedStartDate);
for (uint32 i = 0; i < NUM_REGISTER_DAYS; i++) {
uint32 date = startDate.add(i.mul(DAY));
| require(startDate == _expectedStartDate);
for (uint32 i = 0; i < NUM_REGISTER_DAYS; i++) {
uint32 date = startDate.add(i.mul(DAY));
| 37,736 |
89 | // участник уже на аренеtodo излишне, такого быть не должно, проанализировать | require(fr.exists);
| require(fr.exists);
| 31,727 |
13 | // _settlement The GPv2 settlement contract / | constructor(address _settlement) {
domainSeparator = CoWSettlement(_settlement).domainSeparator();
}
| constructor(address _settlement) {
domainSeparator = CoWSettlement(_settlement).domainSeparator();
}
| 20,110 |
30 | // Allows writer to retrieve funds from an unsold, non-exercised and non-canceled option | function retrieveFunds(uint ID) public payable {
require(msg.sender == Opts[ID].writer, "You did not write this option");
//Must be unsold, not exercised and not canceled
require(Opts[ID].buyer == address(0) && !Opts[ID].exercised && !Opts[ID].canceled, "This option is not eligible for withdraw");
//Repurposing canceled flag to prevent more than one withdraw
Opts[ID].canceled = true;
Opts[ID].writer.transfer(Opts[ID].amount);
}
| function retrieveFunds(uint ID) public payable {
require(msg.sender == Opts[ID].writer, "You did not write this option");
//Must be unsold, not exercised and not canceled
require(Opts[ID].buyer == address(0) && !Opts[ID].exercised && !Opts[ID].canceled, "This option is not eligible for withdraw");
//Repurposing canceled flag to prevent more than one withdraw
Opts[ID].canceled = true;
Opts[ID].writer.transfer(Opts[ID].amount);
}
| 12,338 |
13 | // The value mint expects for a token. / | function mintPrice() external view returns(uint256) {
return _mintPrice;
}
| function mintPrice() external view returns(uint256) {
return _mintPrice;
}
| 44,388 |
196 | // Destroys `amount` token from the caller without giving collateral back/amount Amount to burn/poolManager Reference to the `PoolManager` contract for which the `stocksUsers` will need to be updated | function burnNoRedeem(uint256 amount, address poolManager) external;
| function burnNoRedeem(uint256 amount, address poolManager) external;
| 13,153 |
101 | // amount to decay total debt by return decay_ uint / | function debtDecay() public view returns ( uint decay_ ) {
uint blocksSinceLast = block.number.sub( lastDecay );
decay_ = totalDebt.mul( blocksSinceLast ).div( terms.vestingTerm );
if ( decay_ > totalDebt ) {
decay_ = totalDebt;
}
}
| function debtDecay() public view returns ( uint decay_ ) {
uint blocksSinceLast = block.number.sub( lastDecay );
decay_ = totalDebt.mul( blocksSinceLast ).div( terms.vestingTerm );
if ( decay_ > totalDebt ) {
decay_ = totalDebt;
}
}
| 10,707 |
95 | // Sends the weekly BABL reward to the garden (if any) / | function _sendWeeklyReward() private {
if (bablRewardLeft > 0) {
uint256 bablToSend = bablRewardLeft < weeklyRewardAmount ? bablRewardLeft : weeklyRewardAmount;
uint256 currentBalance = IERC20(BABL).balanceOf(address(this));
bablToSend = currentBalance < bablToSend ? currentBalance : bablToSend;
IERC20(BABL).safeTransfer(address(heartGarden), bablToSend);
bablRewardLeft = bablRewardLeft.sub(bablToSend);
emit BABLRewardSent(block.timestamp, bablToSend);
totalStats[6] = totalStats[6].add(bablToSend);
}
}
| function _sendWeeklyReward() private {
if (bablRewardLeft > 0) {
uint256 bablToSend = bablRewardLeft < weeklyRewardAmount ? bablRewardLeft : weeklyRewardAmount;
uint256 currentBalance = IERC20(BABL).balanceOf(address(this));
bablToSend = currentBalance < bablToSend ? currentBalance : bablToSend;
IERC20(BABL).safeTransfer(address(heartGarden), bablToSend);
bablRewardLeft = bablRewardLeft.sub(bablToSend);
emit BABLRewardSent(block.timestamp, bablToSend);
totalStats[6] = totalStats[6].add(bablToSend);
}
}
| 38,009 |
152 | // Maps NFT ID to protocol config. / | mapping (uint256 => bytes32[]) internal config;
| mapping (uint256 => bytes32[]) internal config;
| 63,980 |
11 | // Update free memory pointer - | mstore(0x40, 0x180)
| mstore(0x40, 0x180)
| 28,129 |
13 | // Mint tokens in random | uint256 _tokenId;
for (uint256 i = 0; i < _numTokens; i++) {
| uint256 _tokenId;
for (uint256 i = 0; i < _numTokens; i++) {
| 15,107 |
121 | // Called by the Chainlink node to fulfill requests with multi-word support Given params must hash back to the commitment stored from `oracleRequest`.Will call the callback address' callback function without bubbling up errorchecking in a `require` so that the node can get paid. requestId The fulfillment request ID that must match the requester's payment The payment amount that will be released for the oracle (specified in wei) callbackAddress The callback address to call for fulfillment callbackFunctionId The callback function ID to use for fulfillment expiration The expiration that the node should respond by before the requester can cancel data The data | function fulfillOracleRequest2(
bytes32 requestId,
uint256 payment,
address callbackAddress,
bytes4 callbackFunctionId,
uint256 expiration,
bytes calldata data
)
external
override
| function fulfillOracleRequest2(
bytes32 requestId,
uint256 payment,
address callbackAddress,
bytes4 callbackFunctionId,
uint256 expiration,
bytes calldata data
)
external
override
| 30,853 |
99 | // refund vault used to hold funds while crowdsale is running | RefundVault public vault;
| RefundVault public vault;
| 11,066 |
105 | // Return the buy price of 1 individual token.Start Price + (7-day Average Dividend Payout) x BEP x HARD_TOTAL_SUPPLY / (Total No. of Circulating Tokens) / (HARD_TOTAL_SUPPLY - Total No. of Circulating Tokens + 1) / | function getBuyPrice()
public
view
returns(uint256)
| function getBuyPrice()
public
view
returns(uint256)
| 15,885 |
95 | // Mainly used for addresses such as CEX, presale, etc | function setStakingExclusionStatus(address addr, bool exclude) external authorized {
if(exclude)
excludeFromStaking(addr);
else
includeToStaking(addr);
emit ExcludeFromStaking(addr, exclude);
}
| function setStakingExclusionStatus(address addr, bool exclude) external authorized {
if(exclude)
excludeFromStaking(addr);
else
includeToStaking(addr);
emit ExcludeFromStaking(addr, exclude);
}
| 24,043 |
4 | // ============ Internal Functions ============ //Checks if the Compound oracles should be updated before executing any rebalance action. Updates must occur if the resulting trade would end up outside theslippage bounds as calculated against the Compound oracle. Aligning the oracle more closely with market prices should allow rebalances to go through._maxTradeSize Max trade size of rebalance action (varies whether its ripcord or normal rebalance) _slippageToleranceSlippage tolerance of rebalance action (varies whether its ripcord or normal rebalance) return boolBoolean indicating whether oracle needs to be updated / | function _shouldOracleBeUpdated(
uint256 _maxTradeSize,
uint256 _slippageTolerance
)
internal
view
returns (bool)
| function _shouldOracleBeUpdated(
uint256 _maxTradeSize,
uint256 _slippageTolerance
)
internal
view
returns (bool)
| 34,723 |
72 | // OWNER-ONLY FUNCTIONSadjust the last time at which penguins can deposit | function adjustDepositEnd(uint256 newDepositEnd) external onlyOwner {
depositEnd = newDepositEnd;
}
| function adjustDepositEnd(uint256 newDepositEnd) external onlyOwner {
depositEnd = newDepositEnd;
}
| 6,617 |
123 | // if the admin fee is set a check is made to check whether the admin has withdrawn or not | if (adminWithdraw) {
| if (adminWithdraw) {
| 21,725 |
0 | // uint8 public decimals; | uint256 public totalSupply;
event Transfer(
address indexed _from,
address indexed _to,
uint256 _value
);
event Approval(
address indexed _owner,
| uint256 public totalSupply;
event Transfer(
address indexed _from,
address indexed _to,
uint256 _value
);
event Approval(
address indexed _owner,
| 36,229 |
7 | // get storeDetails using storeHash | mapping(bytes32=>Store) store;
| mapping(bytes32=>Store) store;
| 48,775 |
194 | // mint | _updateAccountSnapshot(to);
_updateTotalSupplySnapshot();
| _updateAccountSnapshot(to);
_updateTotalSupplySnapshot();
| 13,059 |
188 | // Transfers punk to the smart contract owner / | function transfer(address punkContract, uint256 punkIndex)
external
returns (bool)
| function transfer(address punkContract, uint256 punkIndex)
external
returns (bool)
| 37,948 |
23 | // Opens the ICO for buying tokens._icoDurationInMinutes The duration of the ICO in minutes.Only the contract owner can open the ICO./ | function openIco(uint256 _icoDurationInMinutes) external onlyOwner {
require(_icoDurationInMinutes > 0, "ICO: Invalid ico Duration");
require(!isOpen(), "ICO: has been already opened");
require(_icoTokenAmount > 0, "ICO: No tokens to buy");
_icoOpeningTime = block.timestamp;
_icoDurationInSeconds = _icoDurationInMinutes * 60;
_icoClosingTime = _icoOpeningTime + _icoDurationInSeconds;
}
| function openIco(uint256 _icoDurationInMinutes) external onlyOwner {
require(_icoDurationInMinutes > 0, "ICO: Invalid ico Duration");
require(!isOpen(), "ICO: has been already opened");
require(_icoTokenAmount > 0, "ICO: No tokens to buy");
_icoOpeningTime = block.timestamp;
_icoDurationInSeconds = _icoDurationInMinutes * 60;
_icoClosingTime = _icoOpeningTime + _icoDurationInSeconds;
}
| 1,957 |
16 | // _totalStakes = _totalStakes.sub(amount); | amount2Deduct = amount;
amount = 0;
| amount2Deduct = amount;
amount = 0;
| 13,309 |
4 | // solhint-disable-next-line not-rely-on-time | uint256 expiration = now.add(EXPIRY_TIME);
commitments[requestId] = Request(
_callbackAddress,
_callbackFunctionId
);
emit OracleRequest(
_specId,
_sender,
| uint256 expiration = now.add(EXPIRY_TIME);
commitments[requestId] = Request(
_callbackAddress,
_callbackFunctionId
);
emit OracleRequest(
_specId,
_sender,
| 7,835 |
182 | // The value of unclaimedFees measured in shares of this fund at current value | feesShareQuantity = (gav == 0) ? 0 : mul(_totalSupply, unclaimedFees) / gav;
| feesShareQuantity = (gav == 0) ? 0 : mul(_totalSupply, unclaimedFees) / gav;
| 8,595 |
40 | // Unset the locator on the index. | indexes[signerToken][senderToken][protocol].unsetLocator(user);
if (score > 0) {
| indexes[signerToken][senderToken][protocol].unsetLocator(user);
if (score > 0) {
| 26,412 |
4 | // Allows to allocate currency for the sale. / | function allocate() public payable {
require(wasStarted(), "PresalePublic: Cannot allocate yet");
require(areAllocationsAccepted(), "PresalePublic: Cannot allocate anymore");
require((msg.value >= _minimumAllocation), "PresalePublic: Allocation is too small");
require(((msg.value + _allocations[msg.sender]) <= _maximumAllocation), "PresalePublic: Allocation is too big");
require(canAllocate(msg.sender), "PresalePublic: Not allowed to participate");
_totalAllocated += msg.value;
if (_allocations[msg.sender] == 0) {
_participants.push(msg.sender);
}
_allocations[msg.sender] += msg.value;
emit Allocated(msg.sender, msg.value);
}
| function allocate() public payable {
require(wasStarted(), "PresalePublic: Cannot allocate yet");
require(areAllocationsAccepted(), "PresalePublic: Cannot allocate anymore");
require((msg.value >= _minimumAllocation), "PresalePublic: Allocation is too small");
require(((msg.value + _allocations[msg.sender]) <= _maximumAllocation), "PresalePublic: Allocation is too big");
require(canAllocate(msg.sender), "PresalePublic: Not allowed to participate");
_totalAllocated += msg.value;
if (_allocations[msg.sender] == 0) {
_participants.push(msg.sender);
}
_allocations[msg.sender] += msg.value;
emit Allocated(msg.sender, msg.value);
}
| 51,480 |
322 | // Ensure the SNX proxy has the correct Synthetix target set; | proxyerc20_i.setTarget(Proxyable(new_Synthetix_contract));
| proxyerc20_i.setTarget(Proxyable(new_Synthetix_contract));
| 71,340 |
165 | // gib muni | uint256 _prize;
if (_eth >= 10000000000000000000)
{
| uint256 _prize;
if (_eth >= 10000000000000000000)
{
| 3,496 |
19 | // cutFor returns the affiliate cut for a sale cutFor returns the cut (amount in wei) to give in comission to the affiliate_affiliate - the address of the affiliate to check for _productId - the productId in the sale _purchaseId - the purchaseId in the sale _purchaseAmount - the purchaseAmount / | function cutFor(
address _affiliate,
uint256 _productId,
uint256 _purchaseId,
uint256 _purchaseAmount)
public
view
returns (uint256)
| function cutFor(
address _affiliate,
uint256 _productId,
uint256 _purchaseId,
uint256 _purchaseAmount)
public
view
returns (uint256)
| 26,383 |
12 | // Return the minimum of how many vested can transfer and other value in case there are other limiting transferability factors (default is balanceOf) | return _vestedTransferable;
| return _vestedTransferable;
| 15,849 |
75 | // Chubbies Governance Token | contract Chubbies is IERC20, Ownable {
using SafeMath for uint256;
mapping (address => uint256) private balances;
mapping (address => mapping (address => uint256)) private allowed;
address public governance;
string public constant name = "Chubbies.io";
string public constant symbol = "CHUB";
uint8 public constant decimals = 18;
uint256 _totalSupply = 420000000 * (10 ** 18); // 420 million supply
mapping (address => bool) public initContracts;
modifier isInitContract() {
require(initContracts[msg.sender],"calling address is not owner");
_;
}
constructor() public Ownable(){
balances[msg.sender] = _totalSupply;
emit Transfer(address(0), msg.sender, _totalSupply);
}
function setInitAccess(address account, bool Init) public onlyOwner {
initContracts[account]=Init;
}
function setGovernance(address _governance) public onlyOwner {
governance = _governance;
}
function _init(address account, uint256 amount) public isInitContract {
require(account != address(0), "ERC20: zero address");
_totalSupply = _totalSupply.add(amount);
balances[account] = balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
function balanceOf(address user) public view override returns (uint256) {
return balances[user];
}
function allowance(address user, address spender) public view override returns (uint256) {
return allowed[user][spender];
}
function transfer(address to, uint256 value) public override returns (bool) {
require(value <= balances[msg.sender],"insufficient balance");
require(to != address(0),"cannot send to zero address");
balances[msg.sender] = balances[msg.sender].sub(value);
balances[to] = balances[to].add(value);
emit Transfer(msg.sender, to, value);
return true;
}
function approve(address spender, uint256 value) public override returns (bool) {
require(spender != address(0),"cannot approve the zero address");
allowed[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
function approveAndCall(address spender, uint256 tokens, bytes calldata data) external returns (bool) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, address(this), data);
return true;
}
function transferFrom(address from, address to, uint256 value) public override returns (bool) {
require(value <= balances[from],"insufficient balance");
require(value <= allowed[from][msg.sender],"insufficient allowance");
require(to != address(0),"cannot send to the zero address");
balances[from] = balances[from].sub(value);
balances[to] = balances[to].add(value);
allowed[from][msg.sender] = allowed[from][msg.sender].sub(value);
emit Transfer(from, to, value);
return true;
}
function burn(uint256 amount) external {
require(amount != 0,"must burn more than zero");
require(amount <= balances[msg.sender],"insufficient balance");
_totalSupply = _totalSupply.sub(amount);
balances[msg.sender] = balances[msg.sender].sub(amount);
emit Transfer(msg.sender, address(0), 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
/// @dev 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)");
/// @dev 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 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, "YAX::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 YAXs (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, "YAX::_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 Chubbies is IERC20, Ownable {
using SafeMath for uint256;
mapping (address => uint256) private balances;
mapping (address => mapping (address => uint256)) private allowed;
address public governance;
string public constant name = "Chubbies.io";
string public constant symbol = "CHUB";
uint8 public constant decimals = 18;
uint256 _totalSupply = 420000000 * (10 ** 18); // 420 million supply
mapping (address => bool) public initContracts;
modifier isInitContract() {
require(initContracts[msg.sender],"calling address is not owner");
_;
}
constructor() public Ownable(){
balances[msg.sender] = _totalSupply;
emit Transfer(address(0), msg.sender, _totalSupply);
}
function setInitAccess(address account, bool Init) public onlyOwner {
initContracts[account]=Init;
}
function setGovernance(address _governance) public onlyOwner {
governance = _governance;
}
function _init(address account, uint256 amount) public isInitContract {
require(account != address(0), "ERC20: zero address");
_totalSupply = _totalSupply.add(amount);
balances[account] = balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
function balanceOf(address user) public view override returns (uint256) {
return balances[user];
}
function allowance(address user, address spender) public view override returns (uint256) {
return allowed[user][spender];
}
function transfer(address to, uint256 value) public override returns (bool) {
require(value <= balances[msg.sender],"insufficient balance");
require(to != address(0),"cannot send to zero address");
balances[msg.sender] = balances[msg.sender].sub(value);
balances[to] = balances[to].add(value);
emit Transfer(msg.sender, to, value);
return true;
}
function approve(address spender, uint256 value) public override returns (bool) {
require(spender != address(0),"cannot approve the zero address");
allowed[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
function approveAndCall(address spender, uint256 tokens, bytes calldata data) external returns (bool) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, address(this), data);
return true;
}
function transferFrom(address from, address to, uint256 value) public override returns (bool) {
require(value <= balances[from],"insufficient balance");
require(value <= allowed[from][msg.sender],"insufficient allowance");
require(to != address(0),"cannot send to the zero address");
balances[from] = balances[from].sub(value);
balances[to] = balances[to].add(value);
allowed[from][msg.sender] = allowed[from][msg.sender].sub(value);
emit Transfer(from, to, value);
return true;
}
function burn(uint256 amount) external {
require(amount != 0,"must burn more than zero");
require(amount <= balances[msg.sender],"insufficient balance");
_totalSupply = _totalSupply.sub(amount);
balances[msg.sender] = balances[msg.sender].sub(amount);
emit Transfer(msg.sender, address(0), 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
/// @dev 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)");
/// @dev 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 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, "YAX::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 YAXs (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, "YAX::_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;
}
} | 34,320 |
23 | // Reverts if `msg.value` is not zero. It can be used to avoid `msg.value` stuck in the contractif an upgrade doesn't perform an initialization call. / | function _checkNonPayable() private {
if (msg.value > 0) {
revert ERC1967NonPayable();
}
}
| function _checkNonPayable() private {
if (msg.value > 0) {
revert ERC1967NonPayable();
}
}
| 20,605 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.