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
1
// ============ Shares (ERC20) ============
string public symbol; uint8 public decimals; string public name; uint256 public totalSupply; mapping(address => uint256) internal _SHARES_; mapping(address => mapping(address => uint256)) internal _ALLOWED_;
string public symbol; uint8 public decimals; string public name; uint256 public totalSupply; mapping(address => uint256) internal _SHARES_; mapping(address => mapping(address => uint256)) internal _ALLOWED_;
30,701
0
// variable Declarations
event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); event BurnEvent(address indexed burner, uint256 indexed buramount);
event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); event BurnEvent(address indexed burner, uint256 indexed buramount);
36,431
240
// Internal view function that, given an action type and arguments,will return the action ID or message hash that will need to be prefixed(according to EIP-191 0x45), hashed, and signed by the key designated bythe Dharma Key Registry in order to construct a valid signature for thecorresponding action. The current nonce will be supplied to this functionwhen reconstructing an action ID during protected function execution basedon the supplied parameters. action uint8 The type of action, designated by it's index. Validactions in V8 include Cancel (0), SetUserSigningKey (1), Generic (2),GenericAtomicBatch (3), DAIWithdrawal (10), USDCWithdrawal (5),ETHWithdrawal (6), SetEscapeHatch (7), RemoveEscapeHatch (8), andDisableEscapeHatch (9).
function _getActionID( ActionType action, bytes memory arguments, uint256 nonce, uint256 minimumActionGas, address userSigningKey, address dharmaSigningKey
function _getActionID( ActionType action, bytes memory arguments, uint256 nonce, uint256 minimumActionGas, address userSigningKey, address dharmaSigningKey
16,822
76
// uint256 balanceErc20 = balanceOf(wallet);uint256 balanceErc20 = wallet.balance;
return balanceOf(wallet);
return balanceOf(wallet);
34,520
209
// liquidity = 0 and shortFall = 0
if(liquidity == toppedUpAmtInUSD) return(0, 0, 0);
if(liquidity == toppedUpAmtInUSD) return(0, 0, 0);
28,413
64
// "_selectorCount & 7" is a gas efficient modulo by eight "_selectorCount % 8"
uint256 selectorInSlotPosition = (_selectorCount & 7) << 5;
uint256 selectorInSlotPosition = (_selectorCount & 7) << 5;
40,962
6
// Admins are able to approve proposal that someone submitted/_tokens the list of tokens in consideration during this period/_duration number of days for voting/_criteria number that determines how winner is selected/_extraData extra data for criteria parameter/_previousWinners addresses that won previous proposal
function startTokenVotes(address[] _tokens, uint _duration, uint _criteria, uint _extraData, address[] _previousWinners) public onlyAdmins { require(_tokens.length <= MAX_CANDIDATES); for (uint i=0; i < _previousWinners.length; i++) { isWinner[_previousWinners[i]] = true; } if (_criteria == 1) { // in other case all tokens would be winners require(_extraData < consideredTokens.length); } uint _proposalId = tokenBatches.length; if (_proposalId > 0) { TokenProposal memory op = tokenBatches[_proposalId - 1]; DestructibleMiniMeToken(op.votingToken).recycle(); } tokenBatches.length++; TokenProposal storage p = tokenBatches[_proposalId]; p.duration = _duration * (1 days); for (i = 0; i < _tokens.length; i++) { require(!tokenExists[_tokens[i]]); consideredTokens.push(_tokens[i]); yesVotes.push(0); lastVote[_tokens[i]] = _proposalId; tokenExists[_tokens[i]] = true; } p.votingToken = tokenFactory.createDestructibleCloneToken( nectarToken, getBlockNumber(), appendUintToString("EfxTokenVotes-", _proposalId), MiniMeToken(nectarToken).decimals(), appendUintToString("EVT-", _proposalId), true); p.startTime = now; p.startBlock = getBlockNumber(); p.criteria = _criteria; p.extraData = _extraData; emit NewTokens(_proposalId); }
function startTokenVotes(address[] _tokens, uint _duration, uint _criteria, uint _extraData, address[] _previousWinners) public onlyAdmins { require(_tokens.length <= MAX_CANDIDATES); for (uint i=0; i < _previousWinners.length; i++) { isWinner[_previousWinners[i]] = true; } if (_criteria == 1) { // in other case all tokens would be winners require(_extraData < consideredTokens.length); } uint _proposalId = tokenBatches.length; if (_proposalId > 0) { TokenProposal memory op = tokenBatches[_proposalId - 1]; DestructibleMiniMeToken(op.votingToken).recycle(); } tokenBatches.length++; TokenProposal storage p = tokenBatches[_proposalId]; p.duration = _duration * (1 days); for (i = 0; i < _tokens.length; i++) { require(!tokenExists[_tokens[i]]); consideredTokens.push(_tokens[i]); yesVotes.push(0); lastVote[_tokens[i]] = _proposalId; tokenExists[_tokens[i]] = true; } p.votingToken = tokenFactory.createDestructibleCloneToken( nectarToken, getBlockNumber(), appendUintToString("EfxTokenVotes-", _proposalId), MiniMeToken(nectarToken).decimals(), appendUintToString("EVT-", _proposalId), true); p.startTime = now; p.startBlock = getBlockNumber(); p.criteria = _criteria; p.extraData = _extraData; emit NewTokens(_proposalId); }
21,980
39
// reset after each usage _actPlayers = 0;
delete _cardToReveal; delete _playersRevealed;
delete _cardToReveal; delete _playersRevealed;
17,252
77
// Internal function to set the token URI prefix. _tokenURIPrefix string URI prefix to assign /
function _setTokenURIPrefix(string memory _tokenURIPrefix) internal { tokenURIPrefix = _tokenURIPrefix; }
function _setTokenURIPrefix(string memory _tokenURIPrefix) internal { tokenURIPrefix = _tokenURIPrefix; }
39,141
333
// Note the use of mulCeil to prevent small collateralPerPair causing rounding of collateralUsed to 0 enabling callers to mint dust LSP tokens without paying any collateral.
collateralUsed = FixedPoint.Unsigned(tokensToCreate).mulCeil(FixedPoint.Unsigned(collateralPerPair)).rawValue; collateralToken.safeTransferFrom(msg.sender, address(this), collateralUsed); require(longToken.mint(msg.sender, tokensToCreate)); require(shortToken.mint(msg.sender, tokensToCreate)); emit TokensCreated(msg.sender, collateralUsed, tokensToCreate);
collateralUsed = FixedPoint.Unsigned(tokensToCreate).mulCeil(FixedPoint.Unsigned(collateralPerPair)).rawValue; collateralToken.safeTransferFrom(msg.sender, address(this), collateralUsed); require(longToken.mint(msg.sender, tokensToCreate)); require(shortToken.mint(msg.sender, tokensToCreate)); emit TokensCreated(msg.sender, collateralUsed, tokensToCreate);
72,743
31
// Transfer all the funds to the crowdsale address.
sale.transfer(contract_eth_value);
sale.transfer(contract_eth_value);
29,002
26
// Accepts a challenge. Can only be called by the owner of the challenged entry. /
function accept(uint256 _challengeID) public existingChallenge(_challengeID) { Challenge storage challenge_ = challenges_[_challengeID]; require(challenge_.answer == Answer.PENDING, "Given challenge was already answered"); require(_canAnswer(msg.sender, challenge_), "Challenges can only be answered by the entry owner during the answer period"); challenge_.answer = Answer.ACCEPTED; challenge_.answeredAt = now; emit Accepted(_challengeID); }
function accept(uint256 _challengeID) public existingChallenge(_challengeID) { Challenge storage challenge_ = challenges_[_challengeID]; require(challenge_.answer == Answer.PENDING, "Given challenge was already answered"); require(_canAnswer(msg.sender, challenge_), "Challenges can only be answered by the entry owner during the answer period"); challenge_.answer = Answer.ACCEPTED; challenge_.answeredAt = now; emit Accepted(_challengeID); }
12,052
257
// We need to swap the leftover so were balanced, then deposit it
bool zeroForOne = _amount0 > _amount1; _checkSlippage(_swapThresholdPrice, zeroForOne); int256 swapAmount = int256( ((zeroForOne ? _amount0 : _amount1) * _swapAmountBPS) / 10000 ); (_amount0, _amount1) = _swapAndDeposit( _lowerTick, _upperTick,
bool zeroForOne = _amount0 > _amount1; _checkSlippage(_swapThresholdPrice, zeroForOne); int256 swapAmount = int256( ((zeroForOne ? _amount0 : _amount1) * _swapAmountBPS) / 10000 ); (_amount0, _amount1) = _swapAndDeposit( _lowerTick, _upperTick,
64,226
36
// newTarget = Tampered EMA-retarget on the last 6 blocks (a bit more, it's an approximation) Also, there's an adjust factor, in order to correct the delays induced by the time it takes for transactions to confirmDifficulty is adjusted to the time it takes to produce a valid hash. Here, if we set it to take 300 seconds, it will actually take 300 seconds + TxConfirmTime to validate that block. So, we wad a little % to correct that lag time.Once Ethereum scales, it will actually make block times go a tad faster. There's no perfect answer to this problem at
latestDifficultyPeriodStarted = block.number; return targetForEpoch[epoch];
latestDifficultyPeriodStarted = block.number; return targetForEpoch[epoch];
18,004
28
// fee whitelist
mapping(address => bool) public whitelistFrom; mapping(address => bool) public whitelistTo;
mapping(address => bool) public whitelistFrom; mapping(address => bool) public whitelistTo;
30,482
59
// Mint an NFT. Allowed only by the parent contract/to address to mint to/tokenId token id to mint
function __mint(address to, uint256 tokenId) external;
function __mint(address to, uint256 tokenId) external;
37,441
3
// Solidity only automatically asserts when dividing by 0
require(_b > 0); uint256 c = _a / _b;
require(_b > 0); uint256 c = _a / _b;
11,449
64
// This is similar to a `_transfer()` followed by a `_unstake()`, but optimized to avoid spurious SSTOREs on modifying _to's checkpointed balance /
function _transferAndUnstake(address _from, address _to, uint256 _amount) internal { // transferring 0 staked tokens is invalid require(_amount > 0, ERROR_AMOUNT_ZERO); // update stake uint256 newStake = _modifyStakeBalance(_from, _amount, false); // checkpoint total supply _modifyTotalStaked(_amount, false); emit Unstaked(_from, _amount, newStake, new bytes(0)); // transfer tokens require(token.safeTransfer(_to, _amount), ERROR_TOKEN_TRANSFER); }
function _transferAndUnstake(address _from, address _to, uint256 _amount) internal { // transferring 0 staked tokens is invalid require(_amount > 0, ERROR_AMOUNT_ZERO); // update stake uint256 newStake = _modifyStakeBalance(_from, _amount, false); // checkpoint total supply _modifyTotalStaked(_amount, false); emit Unstaked(_from, _amount, newStake, new bytes(0)); // transfer tokens require(token.safeTransfer(_to, _amount), ERROR_TOKEN_TRANSFER); }
34,952
43
// totalSupply Update
totalSupply += interestAmount;
totalSupply += interestAmount;
7,562
11
// When the game started (deployed timestamp)
uint256 public immutable firstSegmentStart;
uint256 public immutable firstSegmentStart;
293
19
// track msg.value actually spent
uint256 balance = msg.value;
uint256 balance = msg.value;
22,936
61
// permanently disable sniper management
function disableSniperManagement() external onlyOwner { sniperManagementEnabled = false; }
function disableSniperManagement() external onlyOwner { sniperManagementEnabled = false; }
24,185
50
// solium-disable security/no-block-members // ERC900 Simple Staking Interface basic implementation /
contract ERC900BasicStakeContract is ERC900 { // @TODO: deploy this separately so we don't have to deploy it multiple times for each contract using SafeMath for uint256; // Token used for staking ERC20 stakingToken; // The default duration of stake lock-in (in seconds) uint256 public defaultLockInDuration; // To save on gas, rather than create a separate mapping for totalStakedFor & personalStakes, // both data structures are stored in a single mapping for a given addresses. // // It's possible to have a non-existing personalStakes, but have tokens in totalStakedFor // if other users are staking on behalf of a given address. mapping (address => StakeContract) public stakeHolders; // Struct for personal stakes (i.e., stakes made by this address) // unlockedTimestamp - when the stake unlocks (in seconds since Unix epoch) // actualAmount - the amount of tokens in the stake // stakedFor - the address the stake was staked for struct Stake { uint256 unlockedTimestamp; uint256 actualAmount; address stakedFor; } // Struct for all stake metadata at a particular address // totalStakedFor - the number of tokens staked for this address // personalStakeIndex - the index in the personalStakes array. // personalStakes - append only array of stakes made by this address // exists - whether or not there are stakes that involve this address struct StakeContract { uint256 totalStakedFor; uint256 personalStakeIndex; Stake[] personalStakes; bool exists; } /** * @dev Modifier that checks that this contract can transfer tokens from the * balance in the stakingToken contract for the given address. * @dev This modifier also transfers the tokens. * @param _address address to transfer tokens from * @param _amount uint256 the number of tokens */ modifier canStake(address _address, uint256 _amount) { require( stakingToken.transferFrom(_address, this, _amount), "Stake required"); _; } /** * @dev Constructor function * @param _stakingToken ERC20 The address of the token contract used for staking */ constructor(ERC20 _stakingToken) public { stakingToken = _stakingToken; } /** * @dev Returns the timestamps for when active personal stakes for an address will unlock * @dev These accessors functions are needed until https://github.com/ethereum/web3.js/issues/1241 is solved * @param _address address that created the stakes * @return uint256[] array of timestamps */ function getPersonalStakeUnlockedTimestamps(address _address) external view returns (uint256[]) { uint256[] memory timestamps; (timestamps,,) = getPersonalStakes(_address); return timestamps; } /** * @dev Returns the stake actualAmount for active personal stakes for an address * @dev These accessors functions are needed until https://github.com/ethereum/web3.js/issues/1241 is solved * @param _address address that created the stakes * @return uint256[] array of actualAmounts */ function getPersonalStakeActualAmounts(address _address) external view returns (uint256[]) { uint256[] memory actualAmounts; (,actualAmounts,) = getPersonalStakes(_address); return actualAmounts; } /** * @dev Returns the addresses that each personal stake was created for by an address * @dev These accessors functions are needed until https://github.com/ethereum/web3.js/issues/1241 is solved * @param _address address that created the stakes * @return address[] array of amounts */ function getPersonalStakeForAddresses(address _address) external view returns (address[]) { address[] memory stakedFor; (,,stakedFor) = getPersonalStakes(_address); return stakedFor; } /** * @notice Stakes a certain amount of tokens, this MUST transfer the given amount from the user * @notice MUST trigger Staked event * @param _amount uint256 the amount of tokens to stake * @param _data bytes optional data to include in the Stake event */ function stake(uint256 _amount, bytes _data) public { createStake( msg.sender, _amount, defaultLockInDuration, _data); } /** * @notice Stakes a certain amount of tokens, this MUST transfer the given amount from the caller * @notice MUST trigger Staked event * @param _user address the address the tokens are staked for * @param _amount uint256 the amount of tokens to stake * @param _data bytes optional data to include in the Stake event */ function stakeFor(address _user, uint256 _amount, bytes _data) public { createStake( _user, _amount, defaultLockInDuration, _data); } /** * @notice Unstakes a certain amount of tokens, this SHOULD return the given amount of tokens to the user, if unstaking is currently not possible the function MUST revert * @notice MUST trigger Unstaked event * @dev Unstaking tokens is an atomic operation—either all of the tokens in a stake, or none of the tokens. * @dev Users can only unstake a single stake at a time, it is must be their oldest active stake. Upon releasing that stake, the tokens will be * transferred back to their account, and their personalStakeIndex will increment to the next active stake. * @param _amount uint256 the amount of tokens to unstake * @param _data bytes optional data to include in the Unstake event */ function unstake(uint256 _amount, bytes _data) public { withdrawStake( _amount, _data); } /** * @notice Returns the current total of tokens staked for an address * @param _address address The address to query * @return uint256 The number of tokens staked for the given address */ function totalStakedFor(address _address) public view returns (uint256) { return stakeHolders[_address].totalStakedFor; } /** * @notice Returns the current total of tokens staked * @return uint256 The number of tokens staked in the contract */ function totalStaked() public view returns (uint256) { return stakingToken.balanceOf(this); } /** * @notice Address of the token being used by the staking interface * @return address The address of the ERC20 token used for staking */ function token() public view returns (address) { return stakingToken; } /** * @notice MUST return true if the optional history functions are implemented, otherwise false * @dev Since we don't implement the optional interface, this always returns false * @return bool Whether or not the optional history functions are implemented */ function supportsHistory() public pure returns (bool) { return false; } /** * @dev Helper function to get specific properties of all of the personal stakes created by an address * @param _address address The address to query * @return (uint256[], uint256[], address[]) * timestamps array, actualAmounts array, stakedFor array */ function getPersonalStakes( address _address ) view public returns(uint256[], uint256[], address[]) { StakeContract storage stakeContract = stakeHolders[_address]; uint256 arraySize = stakeContract.personalStakes.length - stakeContract.personalStakeIndex; uint256[] memory unlockedTimestamps = new uint256[](arraySize); uint256[] memory actualAmounts = new uint256[](arraySize); address[] memory stakedFor = new address[](arraySize); for (uint256 i = stakeContract.personalStakeIndex; i < stakeContract.personalStakes.length; i++) { uint256 index = i - stakeContract.personalStakeIndex; unlockedTimestamps[index] = stakeContract.personalStakes[i].unlockedTimestamp; actualAmounts[index] = stakeContract.personalStakes[i].actualAmount; stakedFor[index] = stakeContract.personalStakes[i].stakedFor; } return ( unlockedTimestamps, actualAmounts, stakedFor ); } /** * @dev Helper function to create stakes for a given address * @param _address address The address the stake is being created for * @param _amount uint256 The number of tokens being staked * @param _lockInDuration uint256 The duration to lock the tokens for * @param _data bytes optional data to include in the Stake event */ function createStake( address _address, uint256 _amount, uint256 _lockInDuration, bytes _data ) internal canStake(msg.sender, _amount) { if (!stakeHolders[msg.sender].exists) { stakeHolders[msg.sender].exists = true; } stakeHolders[_address].totalStakedFor = stakeHolders[_address].totalStakedFor.add(_amount); stakeHolders[msg.sender].personalStakes.push( Stake( block.timestamp.add(_lockInDuration), _amount, _address) ); emit Staked( _address, _amount, totalStakedFor(_address), _data); } /** * @dev Helper function to withdraw stakes for the msg.sender * @param _amount uint256 The amount to withdraw. MUST match the stake amount for the * stake at personalStakeIndex. * @param _data bytes optional data to include in the Unstake event */ function withdrawStake( uint256 _amount, bytes _data ) internal { Stake storage personalStake = stakeHolders[msg.sender].personalStakes[stakeHolders[msg.sender].personalStakeIndex]; // Check that the current stake has unlocked & matches the unstake amount require( personalStake.unlockedTimestamp <= block.timestamp, "The current stake hasn't unlocked yet"); require( personalStake.actualAmount == _amount, "The unstake amount does not match the current stake"); // Transfer the staked tokens from this contract back to the sender // Notice that we are using transfer instead of transferFrom here, so // no approval is needed beforehand. require( stakingToken.transfer(msg.sender, _amount), "Unable to withdraw stake"); stakeHolders[personalStake.stakedFor].totalStakedFor = stakeHolders[personalStake.stakedFor] .totalStakedFor.sub(personalStake.actualAmount); personalStake.actualAmount = 0; stakeHolders[msg.sender].personalStakeIndex++; emit Unstaked( personalStake.stakedFor, _amount, totalStakedFor(personalStake.stakedFor), _data); } }
contract ERC900BasicStakeContract is ERC900 { // @TODO: deploy this separately so we don't have to deploy it multiple times for each contract using SafeMath for uint256; // Token used for staking ERC20 stakingToken; // The default duration of stake lock-in (in seconds) uint256 public defaultLockInDuration; // To save on gas, rather than create a separate mapping for totalStakedFor & personalStakes, // both data structures are stored in a single mapping for a given addresses. // // It's possible to have a non-existing personalStakes, but have tokens in totalStakedFor // if other users are staking on behalf of a given address. mapping (address => StakeContract) public stakeHolders; // Struct for personal stakes (i.e., stakes made by this address) // unlockedTimestamp - when the stake unlocks (in seconds since Unix epoch) // actualAmount - the amount of tokens in the stake // stakedFor - the address the stake was staked for struct Stake { uint256 unlockedTimestamp; uint256 actualAmount; address stakedFor; } // Struct for all stake metadata at a particular address // totalStakedFor - the number of tokens staked for this address // personalStakeIndex - the index in the personalStakes array. // personalStakes - append only array of stakes made by this address // exists - whether or not there are stakes that involve this address struct StakeContract { uint256 totalStakedFor; uint256 personalStakeIndex; Stake[] personalStakes; bool exists; } /** * @dev Modifier that checks that this contract can transfer tokens from the * balance in the stakingToken contract for the given address. * @dev This modifier also transfers the tokens. * @param _address address to transfer tokens from * @param _amount uint256 the number of tokens */ modifier canStake(address _address, uint256 _amount) { require( stakingToken.transferFrom(_address, this, _amount), "Stake required"); _; } /** * @dev Constructor function * @param _stakingToken ERC20 The address of the token contract used for staking */ constructor(ERC20 _stakingToken) public { stakingToken = _stakingToken; } /** * @dev Returns the timestamps for when active personal stakes for an address will unlock * @dev These accessors functions are needed until https://github.com/ethereum/web3.js/issues/1241 is solved * @param _address address that created the stakes * @return uint256[] array of timestamps */ function getPersonalStakeUnlockedTimestamps(address _address) external view returns (uint256[]) { uint256[] memory timestamps; (timestamps,,) = getPersonalStakes(_address); return timestamps; } /** * @dev Returns the stake actualAmount for active personal stakes for an address * @dev These accessors functions are needed until https://github.com/ethereum/web3.js/issues/1241 is solved * @param _address address that created the stakes * @return uint256[] array of actualAmounts */ function getPersonalStakeActualAmounts(address _address) external view returns (uint256[]) { uint256[] memory actualAmounts; (,actualAmounts,) = getPersonalStakes(_address); return actualAmounts; } /** * @dev Returns the addresses that each personal stake was created for by an address * @dev These accessors functions are needed until https://github.com/ethereum/web3.js/issues/1241 is solved * @param _address address that created the stakes * @return address[] array of amounts */ function getPersonalStakeForAddresses(address _address) external view returns (address[]) { address[] memory stakedFor; (,,stakedFor) = getPersonalStakes(_address); return stakedFor; } /** * @notice Stakes a certain amount of tokens, this MUST transfer the given amount from the user * @notice MUST trigger Staked event * @param _amount uint256 the amount of tokens to stake * @param _data bytes optional data to include in the Stake event */ function stake(uint256 _amount, bytes _data) public { createStake( msg.sender, _amount, defaultLockInDuration, _data); } /** * @notice Stakes a certain amount of tokens, this MUST transfer the given amount from the caller * @notice MUST trigger Staked event * @param _user address the address the tokens are staked for * @param _amount uint256 the amount of tokens to stake * @param _data bytes optional data to include in the Stake event */ function stakeFor(address _user, uint256 _amount, bytes _data) public { createStake( _user, _amount, defaultLockInDuration, _data); } /** * @notice Unstakes a certain amount of tokens, this SHOULD return the given amount of tokens to the user, if unstaking is currently not possible the function MUST revert * @notice MUST trigger Unstaked event * @dev Unstaking tokens is an atomic operation—either all of the tokens in a stake, or none of the tokens. * @dev Users can only unstake a single stake at a time, it is must be their oldest active stake. Upon releasing that stake, the tokens will be * transferred back to their account, and their personalStakeIndex will increment to the next active stake. * @param _amount uint256 the amount of tokens to unstake * @param _data bytes optional data to include in the Unstake event */ function unstake(uint256 _amount, bytes _data) public { withdrawStake( _amount, _data); } /** * @notice Returns the current total of tokens staked for an address * @param _address address The address to query * @return uint256 The number of tokens staked for the given address */ function totalStakedFor(address _address) public view returns (uint256) { return stakeHolders[_address].totalStakedFor; } /** * @notice Returns the current total of tokens staked * @return uint256 The number of tokens staked in the contract */ function totalStaked() public view returns (uint256) { return stakingToken.balanceOf(this); } /** * @notice Address of the token being used by the staking interface * @return address The address of the ERC20 token used for staking */ function token() public view returns (address) { return stakingToken; } /** * @notice MUST return true if the optional history functions are implemented, otherwise false * @dev Since we don't implement the optional interface, this always returns false * @return bool Whether or not the optional history functions are implemented */ function supportsHistory() public pure returns (bool) { return false; } /** * @dev Helper function to get specific properties of all of the personal stakes created by an address * @param _address address The address to query * @return (uint256[], uint256[], address[]) * timestamps array, actualAmounts array, stakedFor array */ function getPersonalStakes( address _address ) view public returns(uint256[], uint256[], address[]) { StakeContract storage stakeContract = stakeHolders[_address]; uint256 arraySize = stakeContract.personalStakes.length - stakeContract.personalStakeIndex; uint256[] memory unlockedTimestamps = new uint256[](arraySize); uint256[] memory actualAmounts = new uint256[](arraySize); address[] memory stakedFor = new address[](arraySize); for (uint256 i = stakeContract.personalStakeIndex; i < stakeContract.personalStakes.length; i++) { uint256 index = i - stakeContract.personalStakeIndex; unlockedTimestamps[index] = stakeContract.personalStakes[i].unlockedTimestamp; actualAmounts[index] = stakeContract.personalStakes[i].actualAmount; stakedFor[index] = stakeContract.personalStakes[i].stakedFor; } return ( unlockedTimestamps, actualAmounts, stakedFor ); } /** * @dev Helper function to create stakes for a given address * @param _address address The address the stake is being created for * @param _amount uint256 The number of tokens being staked * @param _lockInDuration uint256 The duration to lock the tokens for * @param _data bytes optional data to include in the Stake event */ function createStake( address _address, uint256 _amount, uint256 _lockInDuration, bytes _data ) internal canStake(msg.sender, _amount) { if (!stakeHolders[msg.sender].exists) { stakeHolders[msg.sender].exists = true; } stakeHolders[_address].totalStakedFor = stakeHolders[_address].totalStakedFor.add(_amount); stakeHolders[msg.sender].personalStakes.push( Stake( block.timestamp.add(_lockInDuration), _amount, _address) ); emit Staked( _address, _amount, totalStakedFor(_address), _data); } /** * @dev Helper function to withdraw stakes for the msg.sender * @param _amount uint256 The amount to withdraw. MUST match the stake amount for the * stake at personalStakeIndex. * @param _data bytes optional data to include in the Unstake event */ function withdrawStake( uint256 _amount, bytes _data ) internal { Stake storage personalStake = stakeHolders[msg.sender].personalStakes[stakeHolders[msg.sender].personalStakeIndex]; // Check that the current stake has unlocked & matches the unstake amount require( personalStake.unlockedTimestamp <= block.timestamp, "The current stake hasn't unlocked yet"); require( personalStake.actualAmount == _amount, "The unstake amount does not match the current stake"); // Transfer the staked tokens from this contract back to the sender // Notice that we are using transfer instead of transferFrom here, so // no approval is needed beforehand. require( stakingToken.transfer(msg.sender, _amount), "Unable to withdraw stake"); stakeHolders[personalStake.stakedFor].totalStakedFor = stakeHolders[personalStake.stakedFor] .totalStakedFor.sub(personalStake.actualAmount); personalStake.actualAmount = 0; stakeHolders[msg.sender].personalStakeIndex++; emit Unstaked( personalStake.stakedFor, _amount, totalStakedFor(personalStake.stakedFor), _data); } }
40
4,910
// 2457
entry "metempsychotically" : ENG_ADVERB
entry "metempsychotically" : ENG_ADVERB
23,293
187
// Max deposit fee: 4%.
uint16 public constant MAXIMUM_DEPOSIT_FEE_BP = 400;
uint16 public constant MAXIMUM_DEPOSIT_FEE_BP = 400;
12,077
21
// Events //Event to emit if a ring is successfully mined./ _amountsList is an array of:/ [_amountS, _amountB, _lrcReward, _lrcFee, splitS, splitB].
event RingMined( uint _ringIndex, bytes32 indexed _ringHash, address _miner, address _feeRecipient, bytes32[] _orderHashList, uint[6][] _amountsList ); event OrderCancelled( bytes32 indexed _orderHash,
event RingMined( uint _ringIndex, bytes32 indexed _ringHash, address _miner, address _feeRecipient, bytes32[] _orderHashList, uint[6][] _amountsList ); event OrderCancelled( bytes32 indexed _orderHash,
29,179
5
// Initialze voting array
for(uint i=0; i < u_num_voting_items; i++){ vs.votes.push(0); }
for(uint i=0; i < u_num_voting_items; i++){ vs.votes.push(0); }
46,079
47
// Function to distribute tokens to the list of addresses by the provided amount /
684
169
// Call Data registration /
function () returns (bool) { /* * Fallback to allow sending funds to this contract. * (also allows registering raw call data) */ // only scheduler can register call data. if (msg.sender != schedulerAddress) return false; // cannot write over call data if (call.callData.length > 0) return false; var _state = state(); if (_state != State.Pending && _state != State.Unclaimed && _state != State.Claimed) return false; call.callData = msg.data; return true; }
function () returns (bool) { /* * Fallback to allow sending funds to this contract. * (also allows registering raw call data) */ // only scheduler can register call data. if (msg.sender != schedulerAddress) return false; // cannot write over call data if (call.callData.length > 0) return false; var _state = state(); if (_state != State.Pending && _state != State.Unclaimed && _state != State.Claimed) return false; call.callData = msg.data; return true; }
17,618
97
// Calculates the amount of unclaimed rewards a user has earned _account user address _lp true=liquidityStake, false=tokenStakereturn Total reward amount earned /
function _earned(address _account, bool _lp) internal view returns (uint256) { Stake memory s = _lp ? liquidityStake[_account] : tokenStake[_account]; if (s.isWithdrawing) return s.rewards; // current rate per token - rate user previously received uint256 rewardPerTokenStored = currentRewardPerTokenStored(_lp); uint256 userRewardDelta = rewardPerTokenStored - s.rewardPerTokenPaid; uint256 userNewReward = s.tokens.mulTruncate(userRewardDelta); // add to previous rewards return (s.rewards + userNewReward); }
function _earned(address _account, bool _lp) internal view returns (uint256) { Stake memory s = _lp ? liquidityStake[_account] : tokenStake[_account]; if (s.isWithdrawing) return s.rewards; // current rate per token - rate user previously received uint256 rewardPerTokenStored = currentRewardPerTokenStored(_lp); uint256 userRewardDelta = rewardPerTokenStored - s.rewardPerTokenPaid; uint256 userNewReward = s.tokens.mulTruncate(userRewardDelta); // add to previous rewards return (s.rewards + userNewReward); }
11,818
6
// Executes SyndicateERC20.transferFrom(_from, _to, _value) on the bound SyndicateERC20 instanceReentrancy safe due to the SyndicateERC20 design /
function _transferSynFrom( address _from, address _to, uint256 _value
function _transferSynFrom( address _from, address _to, uint256 _value
2,166
196
// make sure all transfers occurred
require(Transfers._getBalance(token) == 0, "GRO left over");
require(Transfers._getBalance(token) == 0, "GRO left over");
23,401
282
// Calculates and returns A based on the ramp settings See the StableSwap paper for details self Swap struct to read fromreturn A parameter in its raw precision form /
function _getAPrecise(Swap storage self) internal view returns (uint256) { uint256 t1 = self.futureATime; // time when ramp is finished uint256 a1 = self.futureA; // final A value when ramp is finished if (block.timestamp < t1) { uint256 t0 = self.initialATime; // time when ramp is started uint256 a0 = self.initialA; // initial A value when ramp is started if (a1 > a0) { // a0 + (a1 - a0) * (block.timestamp - t0) / (t1 - t0) return a0.add( a1.sub(a0).mul(block.timestamp.sub(t0)).div(t1.sub(t0)) ); } else { // a0 - (a0 - a1) * (block.timestamp - t0) / (t1 - t0) return a0.sub( a0.sub(a1).mul(block.timestamp.sub(t0)).div(t1.sub(t0)) ); } } else { return a1; } }
function _getAPrecise(Swap storage self) internal view returns (uint256) { uint256 t1 = self.futureATime; // time when ramp is finished uint256 a1 = self.futureA; // final A value when ramp is finished if (block.timestamp < t1) { uint256 t0 = self.initialATime; // time when ramp is started uint256 a0 = self.initialA; // initial A value when ramp is started if (a1 > a0) { // a0 + (a1 - a0) * (block.timestamp - t0) / (t1 - t0) return a0.add( a1.sub(a0).mul(block.timestamp.sub(t0)).div(t1.sub(t0)) ); } else { // a0 - (a0 - a1) * (block.timestamp - t0) / (t1 - t0) return a0.sub( a0.sub(a1).mul(block.timestamp.sub(t0)).div(t1.sub(t0)) ); } } else { return a1; } }
8,796
232
// Initializes `GatewayRecipient` contract gateway_ `Gateway` contract address /
function _initializeGatewayRecipient( address gateway_ ) internal { gateway = gateway_; }
function _initializeGatewayRecipient( address gateway_ ) internal { gateway = gateway_; }
11,343
78
// Extend parent behavior requiring to be within contributing period beneficiary Token purchaser weiAmount Amount of wei contributed /
function _preValidatePurchase(address beneficiary, uint256 weiAmount) internal onlyWhileOpen view { super._preValidatePurchase(beneficiary, weiAmount); }
function _preValidatePurchase(address beneficiary, uint256 weiAmount) internal onlyWhileOpen view { super._preValidatePurchase(beneficiary, weiAmount); }
10,116
2
// Emitted when the implementation is upgraded. /
event Upgraded(address indexed implementation);
event Upgraded(address indexed implementation);
4,839
194
// contract Ape is ERC721Tradable, Ownable {
constructor(address _proxyRegistryAddress) public ERC721Tradable("VoxoDeus", "VXO", _proxyRegistryAddress)
constructor(address _proxyRegistryAddress) public ERC721Tradable("VoxoDeus", "VXO", _proxyRegistryAddress)
18,235
695
// uint mgasUnitCount = mgasCount.div(100);
uint256 amount = mgasCount; uint256 _prize = amount.div(10000).mul(10000 - devFeePercentage); uint256 devfee = amount - _prize; require(amount <= IERC20(manGasAddr).balanceOf(msg.sender), "low balance"); IERC20(manGasAddr).transferFrom(msg.sender, address(this), amount); transferDev(devfee); transferPrize(amount - devfee); uint256[3] memory ret;
uint256 amount = mgasCount; uint256 _prize = amount.div(10000).mul(10000 - devFeePercentage); uint256 devfee = amount - _prize; require(amount <= IERC20(manGasAddr).balanceOf(msg.sender), "low balance"); IERC20(manGasAddr).transferFrom(msg.sender, address(this), amount); transferDev(devfee); transferPrize(amount - devfee); uint256[3] memory ret;
27,005
42
// Refund the spiralBits
IERC20(SpiralBits).transfer(msg.sender, spiralBitsToReturn); emit CrystalChangeEvent(tokenId, 4, 0);
IERC20(SpiralBits).transfer(msg.sender, spiralBitsToReturn); emit CrystalChangeEvent(tokenId, 4, 0);
45,164
8
// 遍历classHashArray数组,寻找hash值
for (uint256 i = 0; i < classHashArray.length; i++) if (classHashArray[i] == aHash) return true; return false;
for (uint256 i = 0; i < classHashArray.length; i++) if (classHashArray[i] == aHash) return true; return false;
8,001
4
// YakRegistry is a list of officially supported strategies. DRAFT /
contract YakRegistry is Ownable { mapping(address => bool) public registeredStrategies; event AddStrategy(address indexed strategy); event RemoveStrategy(address indexed strategy); constructor() {} function addStrategies(address[] calldata strategies) external onlyOwner { for (uint i = 0; i < strategies.length; i++) { _addStrategy(strategies[i]); } } function removeStrategies(address[] calldata strategies) external onlyOwner { for (uint i = 0; i < strategies.length; i++) { _removeStrategy(strategies[i]); } } function _addStrategy(address strategy) private { registeredStrategies[strategy] = true; emit AddStrategy(strategy); } function _removeStrategy(address strategy) private { registeredStrategies[strategy] = false; emit RemoveStrategy(strategy); } }
contract YakRegistry is Ownable { mapping(address => bool) public registeredStrategies; event AddStrategy(address indexed strategy); event RemoveStrategy(address indexed strategy); constructor() {} function addStrategies(address[] calldata strategies) external onlyOwner { for (uint i = 0; i < strategies.length; i++) { _addStrategy(strategies[i]); } } function removeStrategies(address[] calldata strategies) external onlyOwner { for (uint i = 0; i < strategies.length; i++) { _removeStrategy(strategies[i]); } } function _addStrategy(address strategy) private { registeredStrategies[strategy] = true; emit AddStrategy(strategy); } function _removeStrategy(address strategy) private { registeredStrategies[strategy] = false; emit RemoveStrategy(strategy); } }
30,695
34
// used for interacting with uniswap
if (token0 == solariteAddress_) { isToken0 = true; } else {
if (token0 == solariteAddress_) { isToken0 = true; } else {
2,832
11
// _name = "Servica Network";_symbol = "SRV";
_name = "Servica Network"; _symbol = "SRV"; _decimals = 18; _totalSupply = 8000000000000000000000000; _balances[creator()] = _totalSupply; emit Transfer(address(0), creator(), _totalSupply);
_name = "Servica Network"; _symbol = "SRV"; _decimals = 18; _totalSupply = 8000000000000000000000000; _balances[creator()] = _totalSupply; emit Transfer(address(0), creator(), _totalSupply);
32,300
4
// Only owner/
modifier onlyOwner() { require(msg.sender == exchangable.getOwner()); _; }
modifier onlyOwner() { require(msg.sender == exchangable.getOwner()); _; }
49,337
426
// Rewards in fee period [0] are not yet available for withdrawal
for (uint i = 1; i < FEE_PERIOD_LENGTH; i++) { totalRewards = totalRewards.add(_recentFeePeriodsStorage(i).rewardsToDistribute); totalRewards = totalRewards.sub(_recentFeePeriodsStorage(i).rewardsClaimed); }
for (uint i = 1; i < FEE_PERIOD_LENGTH; i++) { totalRewards = totalRewards.add(_recentFeePeriodsStorage(i).rewardsToDistribute); totalRewards = totalRewards.sub(_recentFeePeriodsStorage(i).rewardsClaimed); }
37,457
29
// Returns the interface supported by a contract.
function _getTokenType(address _assetContract) internal view returns (TokenType tokenType) { if (IERC165(_assetContract).supportsInterface(type(IERC1155).interfaceId)) { tokenType = TokenType.ERC1155; } else if (IERC165(_assetContract).supportsInterface(type(IERC721).interfaceId)) { tokenType = TokenType.ERC721; } else { revert("Marketplace: auctioned token must be ERC1155 or ERC721."); } }
function _getTokenType(address _assetContract) internal view returns (TokenType tokenType) { if (IERC165(_assetContract).supportsInterface(type(IERC1155).interfaceId)) { tokenType = TokenType.ERC1155; } else if (IERC165(_assetContract).supportsInterface(type(IERC721).interfaceId)) { tokenType = TokenType.ERC721; } else { revert("Marketplace: auctioned token must be ERC1155 or ERC721."); } }
17,002
18
// Require une balance de tokens supérieure ou égaleà 1
require(getTokenBalance(msg.sender) >= 1 ether, "You don't have enough tokens to make a vote ");
require(getTokenBalance(msg.sender) >= 1 ether, "You don't have enough tokens to make a vote ");
10,104
37
// Adds or updates selectors and their implementation addresses _selectors The selectors to add or update _implAddress The implementation address the selectors will point to /
function addOrUpdateSelectors( bytes4[] memory _selectors, address _implAddress ) external;
function addOrUpdateSelectors( bytes4[] memory _selectors, address _implAddress ) external;
50,488
74
// Updates the new min difference of votes for PledgesUpdates the new min difference of votes for PledgesnewMinVoteDiff New minimum difference of votes/
function updateMinVoteDiff(uint256 newMinVoteDiff) external onlyOwner { // We want that value to be at minimum 1e18, to avoid any rounding issues if(newMinVoteDiff < UNIT) revert Errors.InvalidValue(); uint256 oldMinTarget = minVoteDiff; minVoteDiff = newMinVoteDiff; emit MinVoteDiffUpdated(oldMinTarget, newMinVoteDiff); }
function updateMinVoteDiff(uint256 newMinVoteDiff) external onlyOwner { // We want that value to be at minimum 1e18, to avoid any rounding issues if(newMinVoteDiff < UNIT) revert Errors.InvalidValue(); uint256 oldMinTarget = minVoteDiff; minVoteDiff = newMinVoteDiff; emit MinVoteDiffUpdated(oldMinTarget, newMinVoteDiff); }
10,672
13
// routerSend This is internal function to generate a cross chain communication request./destChainId Destination ChainID./_selector Selector to interface on destination side./_data Data to be sent on Destination side./_gasLimit Gas limit provided for cross chain send./_gasPrice Gas price provided for cross chain send.
function routerSend( uint8 destChainId, bytes4 _selector, bytes memory _data, uint256 _gasLimit, uint256 _gasPrice
function routerSend( uint8 destChainId, bytes4 _selector, bytes memory _data, uint256 _gasLimit, uint256 _gasPrice
12,071
91
// modifier to check if a participant is in the whitelist /
modifier isInWhitelist(address beneficiary) { // first check if sender is in whitelist require(whitelist.isParticipant(beneficiary)); _; }
modifier isInWhitelist(address beneficiary) { // first check if sender is in whitelist require(whitelist.isParticipant(beneficiary)); _; }
41,492
72
// require(users.getUserTier(sender) > 0, "user not certified");
require(shopAddressToShop[sender].position == bytes12(0), "caller already has shop"); require(positionToShopAddress[position] == address(0), "shop already exists at position"); require(geo.validGeohashChars12(position), "invalid geohash characters in position"); require(geo.zoneInsideCountry(country, bytes4(position)), "zone is not inside country");
require(shopAddressToShop[sender].position == bytes12(0), "caller already has shop"); require(positionToShopAddress[position] == address(0), "shop already exists at position"); require(geo.validGeohashChars12(position), "invalid geohash characters in position"); require(geo.zoneInsideCountry(country, bytes4(position)), "zone is not inside country");
22,142
56
// unclaimed reward will be trasfered to this account
address public vaultAddress;
address public vaultAddress;
59,682
37
// There is no difference whether the buyer or seller activates EscrowEscalation.
address buyerAddress; uint buyerID; //transaction ID of in buyer's history if (switcher == 0) // Buyer { buyerAddress = msg.sender; buyerID = ID; } else if (switcher == 1) //Seller
address buyerAddress; uint buyerID; //transaction ID of in buyer's history if (switcher == 0) // Buyer { buyerAddress = msg.sender; buyerID = ID; } else if (switcher == 1) //Seller
81,139
17
// insufficient balance for call
error InsufficientBalanceForCall(uint256 available, uint256 required);
error InsufficientBalanceForCall(uint256 available, uint256 required);
40,317
5
// Returns hash of a message that can be signed by owners./safe Safe to which the message is targeted/message Message that should be hashed/ return Message hash.
function getMessageHashForSafe(Safe safe, bytes memory message) public view returns (bytes32) { return keccak256(encodeMessageDataForSafe(safe, message)); }
function getMessageHashForSafe(Safe safe, bytes memory message) public view returns (bytes32) { return keccak256(encodeMessageDataForSafe(safe, message)); }
23,227
723
// initializer /
function _setPowerSwitch(address powerSwitch) internal { _powerSwitch = powerSwitch; }
function _setPowerSwitch(address powerSwitch) internal { _powerSwitch = powerSwitch; }
30,768
53
// get the size of the array self Storage array containing uint256 type variables /
function size(Uint256s storage self) internal view returns (uint256) { return self._items.length; }
function size(Uint256s storage self) internal view returns (uint256) { return self._items.length; }
51,063
57
// Check how many tokens are remaining for distribution
function getTokensRemaining() public constant returns (uint256)
function getTokensRemaining() public constant returns (uint256)
48,493
9
// Returns the information relative to a SKU. WARNING: it is the responsibility of the implementer to ensure that the number of payment tokens is bounded, so that this function does not run out of gas. Reverts if `sku` does not exist. sku The SKU identifier.return totalSupply The initial total supply for sale.return remainingSupply The remaining supply for sale.return maxQuantityPerPurchase The maximum allowed quantity for a single purchase.return notificationsReceiver The address of a contract on which to call the `onPurchaseNotificationReceived` function.return tokens The list of supported payment tokens.return prices The list of associated prices for each of the `tokens`. /
function getSkuInfo(bytes32 sku)
function getSkuInfo(bytes32 sku)
41,440
80
// no land,(0.0), has land,(x,1)
function getSummonerCoordinates(uint256 summoner)public view returns(bool,uint256 x,uint256 y){ return rls.getSummonerCoordinates(summoner); }
function getSummonerCoordinates(uint256 summoner)public view returns(bool,uint256 x,uint256 y){ return rls.getSummonerCoordinates(summoner); }
3,959
15
// View method to read 'registeredTokenIds' mapping of/ tracked registered gNFT tokens/tokenIdtokenId of gNFT token to read/ return Stored bool value of 'registeredTokenIds[tokenId]', true if registered
function registeredTokenIds(uint256 tokenId) external view returns (bool);
function registeredTokenIds(uint256 tokenId) external view returns (bool);
16,648
9
// 1 Get active phase token price
function activePhasePrice() internal returns (uint256 ) { Token tObj= Token(tokenContractAddress); uint256 currentPhaseAsPerDate = activePhase(); require(currentPhaseAsPerDate!=0,"ICO completed"); if(currentPhaseAsPerDate == defaultActivePhase){ if(soldTokenInfo(currentPhaseAsPerDate)==listOfPhases[currentPhaseAsPerDate].tokenSaleLimit){ require(tObj.balanceOf(address(this))>0,"All tokens have been sold."); defaultActivePhase = defaultActivePhase.add(1); return listOfPhases[defaultActivePhase].price; }else{ return (listOfPhases[defaultActivePhase].price); } }else if(currentPhaseAsPerDate>defaultActivePhase){ uint256 carryOverTokens; for(uint256 i=defaultActivePhase;i<currentPhaseAsPerDate;i++){ carryOverTokens+=listOfPhases[i].tokenSaleLimit.sub(soldTokenInfo(i)); } listOfPhases[currentPhaseAsPerDate].tokenSaleLimit+=carryOverTokens; defaultActivePhase = currentPhaseAsPerDate; return listOfPhases[defaultActivePhase].price; }else{ return listOfPhases[defaultActivePhase].price; } }
function activePhasePrice() internal returns (uint256 ) { Token tObj= Token(tokenContractAddress); uint256 currentPhaseAsPerDate = activePhase(); require(currentPhaseAsPerDate!=0,"ICO completed"); if(currentPhaseAsPerDate == defaultActivePhase){ if(soldTokenInfo(currentPhaseAsPerDate)==listOfPhases[currentPhaseAsPerDate].tokenSaleLimit){ require(tObj.balanceOf(address(this))>0,"All tokens have been sold."); defaultActivePhase = defaultActivePhase.add(1); return listOfPhases[defaultActivePhase].price; }else{ return (listOfPhases[defaultActivePhase].price); } }else if(currentPhaseAsPerDate>defaultActivePhase){ uint256 carryOverTokens; for(uint256 i=defaultActivePhase;i<currentPhaseAsPerDate;i++){ carryOverTokens+=listOfPhases[i].tokenSaleLimit.sub(soldTokenInfo(i)); } listOfPhases[currentPhaseAsPerDate].tokenSaleLimit+=carryOverTokens; defaultActivePhase = currentPhaseAsPerDate; return listOfPhases[defaultActivePhase].price; }else{ return listOfPhases[defaultActivePhase].price; } }
18,440
10
// Returns the eMode the user is using user The address of the userreturn The eMode id /
function getUserEMode(address user) external view returns (uint256);
function getUserEMode(address user) external view returns (uint256);
959
66
// Total amount of ether or stable withdrawn by all users
uint256 public totalWeiWithdrawn;
uint256 public totalWeiWithdrawn;
47,317
73
// Tell the Dapps a loan was created
emit LoanCreated(msg.sender, loanID, _loanAmount);
emit LoanCreated(msg.sender, loanID, _loanAmount);
43,649
12
// Do nothing
balances[msg.sender] = 100000000000000; // For testing
balances[msg.sender] = 100000000000000; // For testing
11,398
140
// Allow load refunds back on the contract for the refunding. The team can transfer the funds back on the smart contract in the case that the minimum goal was not reached. /
function loadRefund() public payable inState(State.Failure) stopInEmergency { require(msg.value >= weiRaised); require(weiRefunded == 0); uint excedent = msg.value.sub(weiRaised); loadedRefund = loadedRefund.add(msg.value.sub(excedent)); investedAmountOf[msg.sender].add(excedent); }
function loadRefund() public payable inState(State.Failure) stopInEmergency { require(msg.value >= weiRaised); require(weiRefunded == 0); uint excedent = msg.value.sub(weiRaised); loadedRefund = loadedRefund.add(msg.value.sub(excedent)); investedAmountOf[msg.sender].add(excedent); }
31,113
51
// tell the world
BuyRareCard(msg.sender, previousOwner, rareId, ethCost);
BuyRareCard(msg.sender, previousOwner, rareId, ethCost);
4,038
256
// ERC721 Burnable Token ERC721 Token that can be irreversibly burned (destroyed). /
abstract contract ERC721Burnable is Context, ERC721 { /** * @dev Burns `tokenId`. See {ERC721-_burn}. * * Requirements: * * - The caller must own `tokenId` or be an approved operator. */ function burn(uint256 tokenId) public virtual { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721Burnable: caller is not owner nor approved"); _burn(tokenId); } }
abstract contract ERC721Burnable is Context, ERC721 { /** * @dev Burns `tokenId`. See {ERC721-_burn}. * * Requirements: * * - The caller must own `tokenId` or be an approved operator. */ function burn(uint256 tokenId) public virtual { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721Burnable: caller is not owner nor approved"); _burn(tokenId); } }
9,672
80
// oraclize call back/
function __callback(bytes32 myid, string result) public { uint gaslimit = gasleft(); uint32 howmany; uint128 pot; uint gasCost; uint128 distpot; uint oraclizeFeeTmp = 0; // for event log if (msg.sender == oraclize_cbAddress() && myid == nextStealId) { howmany = numArtworks < 100 ? (numArtworks < 10 ? (numArtworks < 2 ? 0 : 1) : numArtworks / 10) : 10; //do not kill more than 10%, but at least one pot = removeArtworksByString(result,howmany); gasCost = ((oraclizeFee * etherExchangeLikeCoin) / 1 ether) * 1 ether + 1 ether/* not floor() */; if (pot > gasCost) distpot = uint128(pot - gasCost); distribute(distpot); //distribute the pot minus the oraclize gas costs oraclizeFeeTmp = oraclizeFee; oraclizeFee = 0; } emit newOraclizeCallback(myid,result,howmany,pot,distpot,oraclizeFeeTmp,gaslimit,etherExchangeLikeCoin); }
function __callback(bytes32 myid, string result) public { uint gaslimit = gasleft(); uint32 howmany; uint128 pot; uint gasCost; uint128 distpot; uint oraclizeFeeTmp = 0; // for event log if (msg.sender == oraclize_cbAddress() && myid == nextStealId) { howmany = numArtworks < 100 ? (numArtworks < 10 ? (numArtworks < 2 ? 0 : 1) : numArtworks / 10) : 10; //do not kill more than 10%, but at least one pot = removeArtworksByString(result,howmany); gasCost = ((oraclizeFee * etherExchangeLikeCoin) / 1 ether) * 1 ether + 1 ether/* not floor() */; if (pot > gasCost) distpot = uint128(pot - gasCost); distribute(distpot); //distribute the pot minus the oraclize gas costs oraclizeFeeTmp = oraclizeFee; oraclizeFee = 0; } emit newOraclizeCallback(myid,result,howmany,pot,distpot,oraclizeFeeTmp,gaslimit,etherExchangeLikeCoin); }
59,579
12
// Casts an SD59x18 number into UD60x18./Requirements:/ - x must be positive.
function intoUD60x18(SD59x18 x) pure returns (UD60x18 result) { int256 xInt = SD59x18.unwrap(x); if (xInt < 0) { revert CastingErrors.PRBMath_SD59x18_IntoUD60x18_Underflow(x); } result = UD60x18.wrap(uint256(xInt)); }
function intoUD60x18(SD59x18 x) pure returns (UD60x18 result) { int256 xInt = SD59x18.unwrap(x); if (xInt < 0) { revert CastingErrors.PRBMath_SD59x18_IntoUD60x18_Underflow(x); } result = UD60x18.wrap(uint256(xInt)); }
27,782
43
// Function to check the amount of tokens that an owner allowed to burn. owner address The address which owns the funds. burner address The address which will burn the funds.return A uint256 specifying the amount of tokens still available to burn. /
function burnAllowance(address owner, address burner) public view returns (uint256) { return _burnAllowed[owner][burner]; }
function burnAllowance(address owner, address burner) public view returns (uint256) { return _burnAllowed[owner][burner]; }
24,067
87
// produces token descriptors from inconsistent or absent ERC20 symbol implementations that can return string or bytes32 this library will always produce a string symbol to represent the token
library SafeERC20Namer { function bytes32ToString(bytes32 x) pure private returns (string memory) { bytes memory bytesString = new bytes(32); uint charCount = 0; for (uint j = 0; j < 32; j++) { byte char = x[j]; if (char != 0) { bytesString[charCount] = char; charCount++; }
library SafeERC20Namer { function bytes32ToString(bytes32 x) pure private returns (string memory) { bytes memory bytesString = new bytes(32); uint charCount = 0; for (uint j = 0; j < 32; j++) { byte char = x[j]; if (char != 0) { bytesString[charCount] = char; charCount++; }
20,448
95
// 1% profits belongs to manager
managerAssetRevenue = totalProfits.div(99); collateral = collateral.sub(totalProfits).sub(managerAssetRevenue);
managerAssetRevenue = totalProfits.div(99); collateral = collateral.sub(totalProfits).sub(managerAssetRevenue);
41,802
35
// Returns the most recent block number where a challenger verified test/This is updated whenever the verify test is activated, whether or not/ the Ante Test fails/ return Block number of last verification attempt
function lastVerifiedBlock() external view returns (uint256);
function lastVerifiedBlock() external view returns (uint256);
1,261
2
// Gets the resolver of the specified token ID. Registry related function. tokenId uint256 ID of the token to query the resolver ofreturn address currently marked as the resolver of the given token ID /
function resolverOf(uint256 tokenId) external view returns (address);
function resolverOf(uint256 tokenId) external view returns (address);
2,928
105
// Keeper disputed
event KeeperDispute(address indexed keeper, uint block);
event KeeperDispute(address indexed keeper, uint block);
42,464
28
// tips to carriers.
address carrier=clientInformation[msg.sender].carrierAddress; whoToAccessPoint[carrier].push(msg.sender); addressIndex[msg.sender]=carrierInformation[carrier].length; carrierInformation[carrier].length=uint(carrierInformation[carrier].length)+1; depositReturns[carrier]=msg.value; //will tip carrier
address carrier=clientInformation[msg.sender].carrierAddress; whoToAccessPoint[carrier].push(msg.sender); addressIndex[msg.sender]=carrierInformation[carrier].length; carrierInformation[carrier].length=uint(carrierInformation[carrier].length)+1; depositReturns[carrier]=msg.value; //will tip carrier
14,804
27
// Owner can mint new tokens, but supply cannot exceed 89 Million
function mint(uint256 amount) public onlyOwner { require(amount <= (89000000 * 10 ** decimals) - supply); _balances[msg.sender] = _balances[msg.sender].add(amount); supply = supply.add(amount); emit Transfer(address(0), msg.sender, amount); }
function mint(uint256 amount) public onlyOwner { require(amount <= (89000000 * 10 ** decimals) - supply); _balances[msg.sender] = _balances[msg.sender].add(amount); supply = supply.add(amount); emit Transfer(address(0), msg.sender, amount); }
19,868
50
// check if we have already swapped with 0x, or tried swapping but failed
if (tokensLeft > 0) { uint price; (wrapper, price) = getBestPrice(exData.srcAmount, exData.srcAddr, exData.destAddr, exData.exchangeType, ActionType.SELL); require(price > exData.minPrice || exData.price0x > exData.minPrice, "Slippage hit");
if (tokensLeft > 0) { uint price; (wrapper, price) = getBestPrice(exData.srcAmount, exData.srcAddr, exData.destAddr, exData.exchangeType, ActionType.SELL); require(price > exData.minPrice || exData.price0x > exData.minPrice, "Slippage hit");
19,271
5
// behaviour of crowdsale during privateSale
function privateSale(uint _amount, address _caller) internal { require(moneySent[_caller] + _amount >= 25 ether && moneySent[_caller] + _amount <= 600 ether, "not the right amount"); require(tokensToBeSold - _amount > 4000000, "limit reached"); uint _tokensToReceive = rate * _amount + (_amount / 10 * 40); moneySent[_caller] += _amount; tokensToReceive[_caller] += _tokensToReceive; EthersReceived += _amount; tokensToBeSold -= _tokensToReceive; emit PrivateSale(_amount, _tokensToReceive); }
function privateSale(uint _amount, address _caller) internal { require(moneySent[_caller] + _amount >= 25 ether && moneySent[_caller] + _amount <= 600 ether, "not the right amount"); require(tokensToBeSold - _amount > 4000000, "limit reached"); uint _tokensToReceive = rate * _amount + (_amount / 10 * 40); moneySent[_caller] += _amount; tokensToReceive[_caller] += _tokensToReceive; EthersReceived += _amount; tokensToBeSold -= _tokensToReceive; emit PrivateSale(_amount, _tokensToReceive); }
40,497
7
// Group lifetime in blocks. When a group reached its lifetime, it is no longer selected for new relay requests but may still be responsible for submitting relay entry if relay request assigned to that group is still pending.
uint256 groupLifetime;
uint256 groupLifetime;
21,991
75
// Fee Distribution. Purchase pUSD with ETH from Depot
require( IERC20(address(pynthpUSD())).balanceOf(address(depot())) >= depot().pynthsReceivedForEther(totalFeeETH), "The pUSD Depot does not have enough pUSD to buy for fees" ); depot().exchangeEtherForPynths.value(totalFeeETH)();
require( IERC20(address(pynthpUSD())).balanceOf(address(depot())) >= depot().pynthsReceivedForEther(totalFeeETH), "The pUSD Depot does not have enough pUSD to buy for fees" ); depot().exchangeEtherForPynths.value(totalFeeETH)();
36,271
74
// keccak256("Manager"); 1.2
bytes32 internal constant KEY_MANAGER = 0x6d439300980e333f0256d64be2c9f67e86f4493ce25f82498d6db7f4be3d9e6f;
bytes32 internal constant KEY_MANAGER = 0x6d439300980e333f0256d64be2c9f67e86f4493ce25f82498d6db7f4be3d9e6f;
11,342
88
// Work on the given position. Must be called by the operator./id The position ID to work on./user The original user that is interacting with the operator./borrowToken The token user borrow from bank./borrow The amount user borrow form bank./debt The user's debt amount./data The encoded data, consisting of strategy address and bytes to strategy.
function work(uint256 id, address user, address borrowToken, uint256 borrow, uint256 debt, bytes calldata data) override external payable onlyOperator nonReentrant
function work(uint256 id, address user, address borrowToken, uint256 borrow, uint256 debt, bytes calldata data) override external payable onlyOperator nonReentrant
2,901
3
// Returns the index of the Pool's BPT in the Pool tokens array (as returned by IVault.getPoolTokens). /
function getBptIndex() external view returns (uint256);
function getBptIndex() external view returns (uint256);
20,843
61
// Get token ID of the specified creator and index.// Throw owner is not valid./ Throw overflow index./_creator creator of the token./_index index of the creator tokens./ return uint256 token id.
function tokenOfCreatorByIndex(address _creator, uint256 _index) external view returns (uint256) { require(_creator != address(0)); uint256 count = 0; for (uint256 i = 0; i < tokens.length; i++) { if (tokens[i].creator == _creator) { if (count == _index) { return tokens[i].id; } count++; } } revert(); }
function tokenOfCreatorByIndex(address _creator, uint256 _index) external view returns (uint256) { require(_creator != address(0)); uint256 count = 0; for (uint256 i = 0; i < tokens.length; i++) { if (tokens[i].creator == _creator) { if (count == _index) { return tokens[i].id; } count++; } } revert(); }
23,988
119
// Contract initialization parameters _openingTime Public crowdsale opening time _closingTime Public crowdsale closing time _rate Initial rate (Maybe remove, put as constant) _cap RTE token issue cap (Should be the same amount as approved allowance from issueWallet) _wallet Multisig wallet to send ether raised to _issueWallet Wallet that approves allowance of tokens to be issued _token RTE token address deployed seperately /
function RTECrowdsale( uint256 _openingTime, uint256 _closingTime, uint256 _rate, uint256 _cap, address _wallet, address _issueWallet, RTEToken _token ) AllowanceCrowdsale(_issueWallet)
function RTECrowdsale( uint256 _openingTime, uint256 _closingTime, uint256 _rate, uint256 _cap, address _wallet, address _issueWallet, RTEToken _token ) AllowanceCrowdsale(_issueWallet)
45,874
40
// Withdraw the user balance in the contract to the user address.
function withdraw() external returns (bool) { uint amount = balances[msg.sender]; require(amount > 0); balances[msg.sender] = 0; if(!msg.sender.send(amount)) { balances[msg.sender] = amount; return false; } return true; }
function withdraw() external returns (bool) { uint amount = balances[msg.sender]; require(amount > 0); balances[msg.sender] = 0; if(!msg.sender.send(amount)) { balances[msg.sender] = amount; return false; } return true; }
46,718
40
// Pool - withdraw all stake and forfeit rewards, skips pool update
function emergencyWithdraw(uint256 pid) external NoReentrant(pid, msg.sender) { PoolInfo storage pool = poolInfo[pid]; UserInfo storage user = userInfo[pid][msg.sender]; require(user.amount > 0, "EmergencyWithdraw: user amount insufficient"); uint256 stakingFeeAmount = user.amount.mul(pool.stakingFee).div(1000); uint256 remainingUserAmount = user.amount.sub(stakingFeeAmount); pool.totalStaked = pool.totalStaked.sub(user.amount); user.amount = 0; user.rewardDebt = 0; user.lastRewardBlock = block.number; if (pool.totalStaked == 0) { totalEligiblePools = totalEligiblePools.sub(1); } safeTokenTransfer(vault, pool.stakedToken, stakingFeeAmount); safeTokenTransfer(msg.sender, pool.stakedToken, remainingUserAmount); emit EmergencyWithdraw(msg.sender, pid, remainingUserAmount); }
function emergencyWithdraw(uint256 pid) external NoReentrant(pid, msg.sender) { PoolInfo storage pool = poolInfo[pid]; UserInfo storage user = userInfo[pid][msg.sender]; require(user.amount > 0, "EmergencyWithdraw: user amount insufficient"); uint256 stakingFeeAmount = user.amount.mul(pool.stakingFee).div(1000); uint256 remainingUserAmount = user.amount.sub(stakingFeeAmount); pool.totalStaked = pool.totalStaked.sub(user.amount); user.amount = 0; user.rewardDebt = 0; user.lastRewardBlock = block.number; if (pool.totalStaked == 0) { totalEligiblePools = totalEligiblePools.sub(1); } safeTokenTransfer(vault, pool.stakedToken, stakingFeeAmount); safeTokenTransfer(msg.sender, pool.stakedToken, remainingUserAmount); emit EmergencyWithdraw(msg.sender, pid, remainingUserAmount); }
44,890
289
// updating collateral factor note 1: one should settle the loan first before calling this note 2: collateralFactorDenominator is 1000, therefore, for 20%, you need 200
function setCollateralFactorNumerator(uint256 numerator) public onlyGovernance { require(numerator <= 740, "Collateral factor cannot be this high"); collateralFactorNumerator = numerator; }
function setCollateralFactorNumerator(uint256 numerator) public onlyGovernance { require(numerator <= 740, "Collateral factor cannot be this high"); collateralFactorNumerator = numerator; }
12,801
17
// unwraps gas tokens./
function unwrap(uint256 value) external;
function unwrap(uint256 value) external;
38,670
139
// Get the outgoing limit of tokens return The outgoing limit of tokens/
function getLimitOfAction() external view returns (uint256)
function getLimitOfAction() external view returns (uint256)
21,852
6
// returns the total fees of `classId` /
function classFees(uint256 classId) public view override returns(uint256) { return _fees[classId]; }
function classFees(uint256 classId) public view override returns(uint256) { return _fees[classId]; }
52,867
231
// See {ERC20-_burn}./
function _burn(address _userAddress, uint256 _amount) internal virtual { require(_userAddress != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(_userAddress, address(0), _amount); _balances[_userAddress] = _balances[_userAddress].sub(_amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(_amount); emit Transfer(_userAddress, address(0), _amount); }
function _burn(address _userAddress, uint256 _amount) internal virtual { require(_userAddress != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(_userAddress, address(0), _amount); _balances[_userAddress] = _balances[_userAddress].sub(_amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(_amount); emit Transfer(_userAddress, address(0), _amount); }
15,237
42
// Atomically increases the allowance granted to `spender` by the caller.
* This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; }
* This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; }
2,879
1
// Emitted when an Organization contract is registered
event OrganisationCreated(address organisation, uint now);
event OrganisationCreated(address organisation, uint now);
36,255
3
// keep track of token pricing when purchased
mapping(uint256 => address) internal _originalTokens; mapping(address => uint) public referrerFees; error TransferFailed();
mapping(uint256 => address) internal _originalTokens; mapping(address => uint) public referrerFees; error TransferFailed();
2,072
10
// 销毁合约
function close() external onlyOwner { selfdestruct(owner); }
function close() external onlyOwner { selfdestruct(owner); }
10,123