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 |
|---|---|---|---|---|
25 | // Single value arrays used for mint calls | address[] memory mintToAddress = new address[](1);
mintToAddress[0] = abi.decode(data[0:32], (address));
uint256[] memory redemptionAmount = new uint256[](1);
uint256 amountRequired = 0;
| address[] memory mintToAddress = new address[](1);
mintToAddress[0] = abi.decode(data[0:32], (address));
uint256[] memory redemptionAmount = new uint256[](1);
uint256 amountRequired = 0;
| 22,314 |
79 | // ICO phases structure | enum IcoPhases { PrivateSale, EarlyBirdPresale, Presale, EarlyBirdCrowdsale, FullCrowdsale }
struct Phase {
uint256 startTime;
uint256 endTime;
uint256 minimum; //in wei
uint8 bonus;
}
| enum IcoPhases { PrivateSale, EarlyBirdPresale, Presale, EarlyBirdCrowdsale, FullCrowdsale }
struct Phase {
uint256 startTime;
uint256 endTime;
uint256 minimum; //in wei
uint8 bonus;
}
| 53,262 |
28 | // If the rewards are null or if the time of the last update is in the future or present, return 0 | bool nullRewards = (baseUpdateCallerReward == 0 && maxUpdateCallerReward == 0);
if (either(timeOfLastUpdate >= now, nullRewards)) return 0;
| bool nullRewards = (baseUpdateCallerReward == 0 && maxUpdateCallerReward == 0);
if (either(timeOfLastUpdate >= now, nullRewards)) return 0;
| 332 |
826 | // MAPPINGS FOR STORING PENDING SETTLEMENTS The below two mappings never share the same key. | mapping(uint256 => PendingToSynthSwap) public pendingToSynthSwaps;
mapping(uint256 => PendingToTokenSwap) public pendingToTokenSwaps;
uint256 public pendingSwapsLength;
mapping(uint256 => PendingSwapType) private pendingSwapType;
| mapping(uint256 => PendingToSynthSwap) public pendingToSynthSwaps;
mapping(uint256 => PendingToTokenSwap) public pendingToTokenSwaps;
uint256 public pendingSwapsLength;
mapping(uint256 => PendingSwapType) private pendingSwapType;
| 45,250 |
196 | // Backwards-compatible (pre-V3) getter returning contract adminreturn address Address of contract admin (same as owner) / | function admin() external view returns (address) {
return owner();
}
| function admin() external view returns (address) {
return owner();
}
| 20,367 |
8 | // address to tarnsfer eth/2 | address payable public ownerAddress1;
| address payable public ownerAddress1;
| 24,660 |
2 | // coordinator | function getContract(string memory contractName) public view returns (address);
| function getContract(string memory contractName) public view returns (address);
| 43,464 |
21 | // return claimable reward for this account prettier-ignore | return claimableReward[account].add(
staked[account].mul(nextcumulativeRewardPerToken.sub(previousCumulatedRewardPerToken[account])).div(PRECISION));
| return claimableReward[account].add(
staked[account].mul(nextcumulativeRewardPerToken.sub(previousCumulatedRewardPerToken[account])).div(PRECISION));
| 8,504 |
34 | // Remove all tokens attributed to VAULT account and transfer them to drainVaultReceiver address. | function drainVault() external onlyAdmin nonReentrant {
uint256 vaultBalance = tokenBalances[VAULT];
// Remove all the tokens from Vault:
_subFromBalance(VAULT, vaultBalance);
// Transfer all the tokens from the TokenBank to the evac address:
require(
IERC20(token).transfer(drainVaultReceiver, vaultBalance),
"Transfer failed"
);
emit DrainVault(drainVaultReceiver, vaultBalance);
}
| function drainVault() external onlyAdmin nonReentrant {
uint256 vaultBalance = tokenBalances[VAULT];
// Remove all the tokens from Vault:
_subFromBalance(VAULT, vaultBalance);
// Transfer all the tokens from the TokenBank to the evac address:
require(
IERC20(token).transfer(drainVaultReceiver, vaultBalance),
"Transfer failed"
);
emit DrainVault(drainVaultReceiver, vaultBalance);
}
| 41,305 |
33 | // Investment periods | if (block.timestamp > preSaleStartTime && block.timestamp < preSaleEndTime) {
| if (block.timestamp > preSaleStartTime && block.timestamp < preSaleEndTime) {
| 45,307 |
0 | // <yes> <report> REENTRANCY | bool callResult = msg.sender.call.value(oCredit)();
require (callResult);
credit[msg.sender] = 0;
| bool callResult = msg.sender.call.value(oCredit)();
require (callResult);
credit[msg.sender] = 0;
| 57,463 |
192 | // Emit the `Transfer` event. Similar to above. | log4(0, 0, _TRANSFER_EVENT_SIGNATURE, 0, toMasked, tokenId)
| log4(0, 0, _TRANSFER_EVENT_SIGNATURE, 0, toMasked, tokenId)
| 32,882 |
13 | // Divide the signature in r, s and v variables ecrecover takes the signature parameters, and the only way to get them currently is to use assembly. solium-disable-next-line security/no-inline-assembly | assembly {
r := mload(add(_signature, 32))
s := mload(add(_signature, 64))
v := byte(0, mload(add(_signature, 96)))
}
| assembly {
r := mload(add(_signature, 32))
s := mload(add(_signature, 64))
v := byte(0, mload(add(_signature, 96)))
}
| 37,756 |
108 | // Get the liquidation amount from CollateralLocker. | uint256 liquidationAmt = collateralAsset.balanceOf(address(collateralLocker));
| uint256 liquidationAmt = collateralAsset.balanceOf(address(collateralLocker));
| 23,127 |
50 | // Transfer `amount` tokens from `src` to `dst`src The address of the source accountdst The address of the destination accountamount The number of tokens to transfer return Whether or not the transfer succeeded/ | function transferFrom(address src, address dst, uint256 amount) external returns (bool success);
| function transferFrom(address src, address dst, uint256 amount) external returns (bool success);
| 11,325 |
42 | // Deduct the total deposits of the migrated markets. | totalDeposited = totalDeposited.sub(runningDepositTotal);
emit MarketsMigrated(receivingManager, marketsToMigrate);
| totalDeposited = totalDeposited.sub(runningDepositTotal);
emit MarketsMigrated(receivingManager, marketsToMigrate);
| 2,545 |
2 | // AggregatorV3Interface priceFeed = AggregatorV3Interface(0x8A753747A1Fa494EC906cE90E9f37563A8AF630e); | return priceFeed.version();
| return priceFeed.version();
| 2,825 |
14 | // The following lines just convert from bytes32 to a string and logs it so you can see that the password we have obtained is correct | uint8 i = 0;
while(i < 32 && password[i] != 0) {
i++;
}
| uint8 i = 0;
while(i < 32 && password[i] != 0) {
i++;
}
| 11,316 |
27 | // Single token airdrop function. It is for a single transfer of tokens to beneficiary _beneficiaryWallet the address where tokens will be deposited into _amount the token amount in wei to send to the associated beneficiary / | function distributeTokens(address _beneficiaryWallet, uint256 _amount) public onlyOwner validAddressAmount(_beneficiaryWallet, _amount) {
token.transfer(_beneficiaryWallet, _amount);
emit AirDrop(_beneficiaryWallet, _amount);
}
| function distributeTokens(address _beneficiaryWallet, uint256 _amount) public onlyOwner validAddressAmount(_beneficiaryWallet, _amount) {
token.transfer(_beneficiaryWallet, _amount);
emit AirDrop(_beneficiaryWallet, _amount);
}
| 7,812 |
30 | // salt | mstore(add(pointer, 0x55), mload(add(pointer, 0x100)))
| mstore(add(pointer, 0x55), mload(add(pointer, 0x100)))
| 49,444 |
281 | // solhint-disable function-max-lines // Internal function to check a given proxy address against the targetaddress based on areas dictated by an associated search space, which can beused in determining whether a proxy can be matched to an offer. proxy address The address of the proxy. searchSpace bytes20 A sequence of bytes that determines which areasof the target address should be matched against. The 0x00 byte means thatthe target byte can be skipped, otherwise each nibble represents adifferent filter condition as indicated by the Condition enum. target address The targeted address, with each relevant byte andnibble determined by the corresponding byte in | function _matchesOfferConstraints(
address proxy,
bytes20 searchSpace,
address target
| function _matchesOfferConstraints(
address proxy,
bytes20 searchSpace,
address target
| 11,673 |
189 | // Should we check if the amount requested is more than what we can return on withdrawal? | function setWithdrawalSafetyCheck(bool newWithdrawalSafetyCheck) external {
_onlyGovernance();
withdrawalSafetyCheck = newWithdrawalSafetyCheck;
}
| function setWithdrawalSafetyCheck(bool newWithdrawalSafetyCheck) external {
_onlyGovernance();
withdrawalSafetyCheck = newWithdrawalSafetyCheck;
}
| 12,733 |
161 | // Computes the boost forboost = min(m, max(1, 0.95 + cmin(voting_weight, f) / deposit^(7/8))) _scaledDeposit deposit amount in terms of USD / | function _computeBoost(uint256 _scaledDeposit, uint256 _votingWeight)
private
view
returns (uint256 boost)
| function _computeBoost(uint256 _scaledDeposit, uint256 _votingWeight)
private
view
returns (uint256 boost)
| 49,993 |
27 | // Create an illiquidBalance which cannot be traded until end of lockout period. Can only be called by crowdfund contract before the end time. | function createIlliquidToken(address _recipient, uint _value)
when_mintable
only_minter
returns (bool o_success)
| function createIlliquidToken(address _recipient, uint _value)
when_mintable
only_minter
returns (bool o_success)
| 23,963 |
71 | // 修改单笔募集上限 | function setMaxWei (
uint256 _value
)
public
| function setMaxWei (
uint256 _value
)
public
| 55,779 |
2 | // keccak256("START_FUTURE") | bytes32 internal constant START_FUTURE = 0xeb5092aab714e6356486bc97f25dd7a5c1dc5c7436a9d30e8d4a527fba24de1c;
| bytes32 internal constant START_FUTURE = 0xeb5092aab714e6356486bc97f25dd7a5c1dc5c7436a9d30e8d4a527fba24de1c;
| 5,377 |
124 | // Random DS Proof Step 4: Commitment match verification, keccak256(delay, nbytes, unonce, sessionKeyHash) == commitment in storage. This is to verify that the computed args match with the ones specified in the query. | bytes memory commitmentSlice1 = new bytes(8 + 1 + 32);
copyBytes(_proof, ledgerProofLength + 32, 8 + 1 + 32, commitmentSlice1, 0);
bytes memory sessionPubkey = new bytes(64);
uint sig2offset = ledgerProofLength + 32 + (8 + 1 + 32) + sig1.length + 65;
copyBytes(_proof, sig2offset - 64, 64, sessionPubkey, 0);
bytes32 sessionPubkeyHash = sha256(sessionPubkey);
if (provable_randomDS_args[_queryId] == keccak256(abi.encodePacked(commitmentSlice1, sessionPubkeyHash))) { //unonce, nbytes and sessionKeyHash match
delete provable_randomDS_args[_queryId];
} else return false;
| bytes memory commitmentSlice1 = new bytes(8 + 1 + 32);
copyBytes(_proof, ledgerProofLength + 32, 8 + 1 + 32, commitmentSlice1, 0);
bytes memory sessionPubkey = new bytes(64);
uint sig2offset = ledgerProofLength + 32 + (8 + 1 + 32) + sig1.length + 65;
copyBytes(_proof, sig2offset - 64, 64, sessionPubkey, 0);
bytes32 sessionPubkeyHash = sha256(sessionPubkey);
if (provable_randomDS_args[_queryId] == keccak256(abi.encodePacked(commitmentSlice1, sessionPubkeyHash))) { //unonce, nbytes and sessionKeyHash match
delete provable_randomDS_args[_queryId];
} else return false;
| 8,256 |
285 | // Spy Loot Funcs Begin | constructor() ERC721("Loot for Secret Agents", "SecretAgentLoot") {
}
| constructor() ERC721("Loot for Secret Agents", "SecretAgentLoot") {
}
| 27,220 |
47 | // _newAddress address of new contract to be used to verify identity of new admins/ | function changeCryptonomicaVerificationContractAddress(address _newAddress) public returns (bool success) {
| function changeCryptonomicaVerificationContractAddress(address _newAddress) public returns (bool success) {
| 49,253 |
42 | // The map that keeps track of all adapters registered in the DAO | mapping(bytes32 => address) public adapters;
| mapping(bytes32 => address) public adapters;
| 40,522 |
119 | // Prevents delegatecall into the modified method | modifier noDelegateCall() {
checkNotDelegateCall();
_;
}
| modifier noDelegateCall() {
checkNotDelegateCall();
_;
}
| 41,266 |
240 | // Returns the total price in 18 digit USD for a given asset. Using Min since min is what we use for mint pricing symbol String symbol of the assetreturn uint256 USD price of 1 of the asset / | function _priceUSDMint(string memory symbol)
internal
view
returns (uint256)
| function _priceUSDMint(string memory symbol)
internal
view
returns (uint256)
| 48,103 |
144 | // Round against the fee recipient | feeFillAmount = LibMathV06.getPartialAmountFloor(
fillAmount,
orderAmount,
fee.amount
);
| feeFillAmount = LibMathV06.getPartialAmountFloor(
fillAmount,
orderAmount,
fee.amount
);
| 32,129 |
10 | // assert(b > 0);Solidity automatically throws when dividing by 0 uint256 c = a / b; assert(a == bc + a % b);There is no case in which this doesn't hold | return _x / _y;
| return _x / _y;
| 17,098 |
69 | // the pre-calculate weiRaised is more than the hard cap | uint256 refundWeiAmount = preCalWeiRaised.sub(hardCap);
uint256 fundWeiAmount = weiAmount.sub(refundWeiAmount);
ganaAmount = fundWeiAmount.mul(rate);
gana.saleTransfer(buyer, ganaAmount);
weiRaised = weiRaised.add(fundWeiAmount);
TokenPurchase(msg.sender, buyer, fundWeiAmount, ganaAmount);
buyer.transfer(refundWeiAmount);
Refund(buyer,refundWeiAmount);
| uint256 refundWeiAmount = preCalWeiRaised.sub(hardCap);
uint256 fundWeiAmount = weiAmount.sub(refundWeiAmount);
ganaAmount = fundWeiAmount.mul(rate);
gana.saleTransfer(buyer, ganaAmount);
weiRaised = weiRaised.add(fundWeiAmount);
TokenPurchase(msg.sender, buyer, fundWeiAmount, ganaAmount);
buyer.transfer(refundWeiAmount);
Refund(buyer,refundWeiAmount);
| 24,060 |
50 | // only update timestamp and rewards if > 0 because we may not have rewards due to integer roundings in that case we need to keep our timestamp not to lose anything | if (rewardTotalInToken > 0)
{
rewards[user] += rewardTotalInToken;
rewardsTimings[user] = block.timestamp;
}
| if (rewardTotalInToken > 0)
{
rewards[user] += rewardTotalInToken;
rewardsTimings[user] = block.timestamp;
}
| 19,697 |
174 | // computes af / EXP_SCALE | function fractionOf(uint256 a, uint256 f) internal pure returns (uint256) {
return a.mul(f).div(EXP_SCALE);
}
| function fractionOf(uint256 a, uint256 f) internal pure returns (uint256) {
return a.mul(f).div(EXP_SCALE);
}
| 24,404 |
136 | // calculate current bond price and remove floor if above return price_ uint / | function _bondPrice() internal returns ( uint price_ ) {
price_ = terms.controlVariable.mul( debtRatio() ).add( 1000000000 ).div( 1e7 );
if ( price_ < terms.minimumPrice ) {
price_ = terms.minimumPrice;
} else if ( terms.minimumPrice != 0 ) {
terms.minimumPrice = 0;
}
}
| function _bondPrice() internal returns ( uint price_ ) {
price_ = terms.controlVariable.mul( debtRatio() ).add( 1000000000 ).div( 1e7 );
if ( price_ < terms.minimumPrice ) {
price_ = terms.minimumPrice;
} else if ( terms.minimumPrice != 0 ) {
terms.minimumPrice = 0;
}
}
| 2,209 |
5 | // Edition ID -> ERC20 contract -> Token ID -> Balance Transferred out of token | mapping(uint256 => mapping(address => mapping(uint256 => uint256))) public editionTokenERC20TransferAmounts;
| mapping(uint256 => mapping(address => mapping(uint256 => uint256))) public editionTokenERC20TransferAmounts;
| 6,452 |
23 | // Emits a {ChangeAddress} event./ | function changeAddress(address newAddress) external override {
require(
balances[newAddress].allocatedTokens == 0 &&
balances[newAddress].claimed == 0,
"TokenDistro::changeAddress: ADDRESS_ALREADY_IN_USE"
);
require(
!hasRole(DISTRIBUTOR_ROLE, msg.sender) &&
!hasRole(DISTRIBUTOR_ROLE, newAddress),
| function changeAddress(address newAddress) external override {
require(
balances[newAddress].allocatedTokens == 0 &&
balances[newAddress].claimed == 0,
"TokenDistro::changeAddress: ADDRESS_ALREADY_IN_USE"
);
require(
!hasRole(DISTRIBUTOR_ROLE, msg.sender) &&
!hasRole(DISTRIBUTOR_ROLE, newAddress),
| 19,718 |
25 | // return Stored address of the Whitelist contract. / | function getWhitelistContract() public view returns (address) {
return address(whitelistInst);
}
| function getWhitelistContract() public view returns (address) {
return address(whitelistInst);
}
| 6,269 |
12 | // Assigned asset proxy contract, immutable. | AssetProxy public proxy;
| AssetProxy public proxy;
| 44,580 |
21 | // a0 - (a0 - a1)(block.timestamp - t0) / (t1 - t0) | return
a0.sub(
a0.sub(a1).mul(block.timestamp.sub(t0)).div(t1.sub(t0))
);
| return
a0.sub(
a0.sub(a1).mul(block.timestamp.sub(t0)).div(t1.sub(t0))
);
| 24,678 |
105 | // If the receiver is already part of the delegate chain and is after the sender, then all of the other delegates after the sender are removed and the receiver is appended at the end of the delegation chain | } else if (receiverDIdx > senderDIdx) {
| } else if (receiverDIdx > senderDIdx) {
| 17,840 |
64 | // Removes asset from sender's account liquidity calculation Sender must not have an outstanding borrow balance in the asset, or be providing necessary collateral for an outstanding borrow. cTokenAddress The address of the asset to be removedreturn Whether or not the account successfully exited the market / | function exitMarket(address cTokenAddress) external returns (uint) {
CToken cToken = CToken(cTokenAddress);
/* Get sender tokensHeld and amountOwed underlying from the cToken */
(uint oErr, uint tokensHeld, uint amountOwed, ) = cToken.getAccountSnapshot(msg.sender);
require(oErr == 0, "exitMarket: getAccountSnapshot failed"); // semi-opaque error code
/* Fail if the sender has a borrow balance */
if (amountOwed != 0) {
return fail(Error.NONZERO_BORROW_BALANCE, FailureInfo.EXIT_MARKET_BALANCE_OWED);
}
/* Fail if the sender is not permitted to redeem all of their tokens */
uint allowed = redeemAllowedInternal(cTokenAddress, msg.sender, tokensHeld);
if (allowed != 0) {
return failOpaque(Error.REJECTION, FailureInfo.EXIT_MARKET_REJECTION, allowed);
}
Market storage marketToExit = markets[address(cToken)];
/* Return true if the sender is not already ‘in’ the market */
if (!marketToExit.accountMembership[msg.sender]) {
return uint(Error.NO_ERROR);
}
/* Set cToken account membership to false */
delete marketToExit.accountMembership[msg.sender];
/* Delete cToken from the account’s list of assets */
// load into memory for faster iteration
CToken[] memory userAssetList = accountAssets[msg.sender];
uint len = userAssetList.length;
uint assetIndex = len;
for (uint i = 0; i < len; i++) {
if (userAssetList[i] == cToken) {
assetIndex = i;
break;
}
}
// We *must* have found the asset in the list or our redundant data structure is broken
assert(assetIndex < len);
// copy last item in list to location of item to be removed, reduce length by 1
CToken[] storage storedList = accountAssets[msg.sender];
storedList[assetIndex] = storedList[storedList.length - 1];
storedList.length--;
emit MarketExited(cToken, msg.sender);
return uint(Error.NO_ERROR);
}
| function exitMarket(address cTokenAddress) external returns (uint) {
CToken cToken = CToken(cTokenAddress);
/* Get sender tokensHeld and amountOwed underlying from the cToken */
(uint oErr, uint tokensHeld, uint amountOwed, ) = cToken.getAccountSnapshot(msg.sender);
require(oErr == 0, "exitMarket: getAccountSnapshot failed"); // semi-opaque error code
/* Fail if the sender has a borrow balance */
if (amountOwed != 0) {
return fail(Error.NONZERO_BORROW_BALANCE, FailureInfo.EXIT_MARKET_BALANCE_OWED);
}
/* Fail if the sender is not permitted to redeem all of their tokens */
uint allowed = redeemAllowedInternal(cTokenAddress, msg.sender, tokensHeld);
if (allowed != 0) {
return failOpaque(Error.REJECTION, FailureInfo.EXIT_MARKET_REJECTION, allowed);
}
Market storage marketToExit = markets[address(cToken)];
/* Return true if the sender is not already ‘in’ the market */
if (!marketToExit.accountMembership[msg.sender]) {
return uint(Error.NO_ERROR);
}
/* Set cToken account membership to false */
delete marketToExit.accountMembership[msg.sender];
/* Delete cToken from the account’s list of assets */
// load into memory for faster iteration
CToken[] memory userAssetList = accountAssets[msg.sender];
uint len = userAssetList.length;
uint assetIndex = len;
for (uint i = 0; i < len; i++) {
if (userAssetList[i] == cToken) {
assetIndex = i;
break;
}
}
// We *must* have found the asset in the list or our redundant data structure is broken
assert(assetIndex < len);
// copy last item in list to location of item to be removed, reduce length by 1
CToken[] storage storedList = accountAssets[msg.sender];
storedList[assetIndex] = storedList[storedList.length - 1];
storedList.length--;
emit MarketExited(cToken, msg.sender);
return uint(Error.NO_ERROR);
}
| 10,596 |
0 | // Token that represents a share in totalDeposits of Silo | IShareToken collateralToken;
| IShareToken collateralToken;
| 27,943 |
1 | // The Ether received will be logged with {PaymentReceived} events. Note that these events are not fullyreliable: it's possible for a contract to receive Ether without triggering this function. This only affects thereliability of the events, and not the actual splitting of Ether. To learn more about this see the Solidity documentation forfunctions]. / | receive() external payable {
| receive() external payable {
| 39,409 |
2 | // __Context_init_unchained(); __ERC165_init_unchained(); | __AccessControl_init_unchained();
__SafeTokenRecover_init_unchained();
__PowerfulChildERC20_init_unchained(initialBalance_);
| __AccessControl_init_unchained();
__SafeTokenRecover_init_unchained();
__PowerfulChildERC20_init_unchained(initialBalance_);
| 20,284 |
4 | // Returns the current address for `isCreationRestrictedSetter`.The owner of this address has the power to update both `isCreationRestrictedSetter` and `isCreationRestricted`.return _isCreationRestrictedSetter The `isCreationRestrictedSetter` address / | function isCreationRestrictedSetter() external view returns (address _isCreationRestrictedSetter);
| function isCreationRestrictedSetter() external view returns (address _isCreationRestrictedSetter);
| 28,699 |
247 | // setOperator(): dis/allow _operator to transfer ownership of all points owned by _owneroperators are part of the ERC721 standard | function setOperator(address _owner, address _operator, bool _approved)
onlyOwner
external
| function setOperator(address _owner, address _operator, bool _approved)
onlyOwner
external
| 14,373 |
5 | // Check whether a provided plaintext secret hashes to a provided hash. A pure / function so can (should) be run off-chain./to address The recipient address, as a salt./secret string The secret to hash./hashed string The hash to check the secret against. | function checkSecret(address to, string secret, bytes32 hashed) public pure returns(bool valid) {
if (hashed == keccak256(to, secret)) {
return true;
}
return false;
}
| function checkSecret(address to, string secret, bytes32 hashed) public pure returns(bool valid) {
if (hashed == keccak256(to, secret)) {
return true;
}
return false;
}
| 6,851 |
216 | // Mapping of iTokens to corresponding markets | mapping(address => Market) public markets;
| mapping(address => Market) public markets;
| 13,259 |
38 | // seriesSum holds the accumulated sum of each term in the series, starting with the initial z | int256 seriesSum = num;
| int256 seriesSum = num;
| 7,232 |
131 | // withdraw deposit after the end of the proposal. / | function withdraw(bytes32 proposeId) external override {
bytes32 account = keccak256(abi.encode(proposeId, msg.sender));
VoteAmount memory amountOfVotes = _amountOfVotes[account];
require(
amountOfVotes.approval != 0 || amountOfVotes.denial != 0,
"no deposit on the proposeId"
);
require(
(_proposeStatus[proposeId].lockin == false &&
_proposeStatus[proposeId].prevoteDeadline < _getBlockTimestampSec()) ||
(_proposeStatus[proposeId].applied == true &&
_proposeStatus[proposeId].mainvoteDeadline <= _getBlockTimestampSec()) ||
(_proposeStatus[proposeId].mainvoteDeadline + _expirationLength <=
_getBlockTimestampSec()),
"cannot withdraw while the voting is in progress"
);
uint128 withdrawAmount = amountOfVotes.approval + amountOfVotes.denial; // <= _taxTokenContract.totalSupply()
delete _amountOfVotes[account];
_unlockStakingToken(msg.sender, withdrawAmount);
emit LogWithdraw(proposeId, msg.sender, withdrawAmount);
}
| function withdraw(bytes32 proposeId) external override {
bytes32 account = keccak256(abi.encode(proposeId, msg.sender));
VoteAmount memory amountOfVotes = _amountOfVotes[account];
require(
amountOfVotes.approval != 0 || amountOfVotes.denial != 0,
"no deposit on the proposeId"
);
require(
(_proposeStatus[proposeId].lockin == false &&
_proposeStatus[proposeId].prevoteDeadline < _getBlockTimestampSec()) ||
(_proposeStatus[proposeId].applied == true &&
_proposeStatus[proposeId].mainvoteDeadline <= _getBlockTimestampSec()) ||
(_proposeStatus[proposeId].mainvoteDeadline + _expirationLength <=
_getBlockTimestampSec()),
"cannot withdraw while the voting is in progress"
);
uint128 withdrawAmount = amountOfVotes.approval + amountOfVotes.denial; // <= _taxTokenContract.totalSupply()
delete _amountOfVotes[account];
_unlockStakingToken(msg.sender, withdrawAmount);
emit LogWithdraw(proposeId, msg.sender, withdrawAmount);
}
| 2,121 |
534 | // - mapping of serviceType - < serviceTypeVersion, isValid >Example - "discovery-provider" - <"0.0.1", true> / | mapping(bytes32 => mapping(bytes32 => bool)) private serviceTypeVersionInfo;
| mapping(bytes32 => mapping(bytes32 => bool)) private serviceTypeVersionInfo;
| 56,068 |
1 | // The network type of the Orbs network this contract is compatible for. | uint32 public networkType;
| uint32 public networkType;
| 38,649 |
28 | // Publius App Storage defines the state object for Beanstalk./ | contract Account {
struct Field {
mapping(uint256 => uint256) plots;
mapping(address => uint256) podAllowances;
}
struct AssetSilo {
mapping(uint32 => uint256) withdrawals;
mapping(uint32 => uint256) deposits;
mapping(uint32 => uint256) depositSeeds;
}
struct Silo {
uint256 stalk;
uint256 seeds;
}
struct SeasonOfPlenty {
uint256 base;
uint256 roots;
uint256 basePerRoot;
}
struct State {
Field field;
AssetSilo bean;
AssetSilo lp;
Silo s;
uint32 lockedUntil;
uint32 lastUpdate;
uint32 lastSop;
uint32 lastRain;
uint32 lastSIs;
SeasonOfPlenty sop;
uint256 roots;
}
}
| contract Account {
struct Field {
mapping(uint256 => uint256) plots;
mapping(address => uint256) podAllowances;
}
struct AssetSilo {
mapping(uint32 => uint256) withdrawals;
mapping(uint32 => uint256) deposits;
mapping(uint32 => uint256) depositSeeds;
}
struct Silo {
uint256 stalk;
uint256 seeds;
}
struct SeasonOfPlenty {
uint256 base;
uint256 roots;
uint256 basePerRoot;
}
struct State {
Field field;
AssetSilo bean;
AssetSilo lp;
Silo s;
uint32 lockedUntil;
uint32 lastUpdate;
uint32 lastSop;
uint32 lastRain;
uint32 lastSIs;
SeasonOfPlenty sop;
uint256 roots;
}
}
| 13,164 |
26 | // Ensure that the next token ID is correct/This reverts if the invariant doesn't match. This is used for multicall token id assumptions/lastTokenId The last token ID | function assumeLastTokenIdMatches(uint256 lastTokenId) external view {
unchecked {
if (nextTokenId - 1 != lastTokenId) {
revert TokenIdMismatch(lastTokenId, nextTokenId - 1);
}
}
}
| function assumeLastTokenIdMatches(uint256 lastTokenId) external view {
unchecked {
if (nextTokenId - 1 != lastTokenId) {
revert TokenIdMismatch(lastTokenId, nextTokenId - 1);
}
}
}
| 6,339 |
106 | // Stores the staked tokens of an address / | mapping(address => EnumerableSet.UintSet) private stakedTokens;
| mapping(address => EnumerableSet.UintSet) private stakedTokens;
| 39,418 |
7 | // Bytes written to out so far | uint256 outcnt;
| uint256 outcnt;
| 8,528 |
43 | // Calculates the amount that has already vested. token ERC20 token which is being vested / | function _vestedAmount(IERC20 token) private view returns (uint256) {
uint256 currentBalance = token.balanceOf(address(this));
uint256 totalBalance = currentBalance.add(_released[address(token)]);
totalBalance = totalBalance.sub(_initialRelease);
if (block.timestamp >= _start.add(_duration)) {
return totalBalance;
} else {
return totalBalance.mul(block.timestamp.sub(_start)).div(_duration);
}
}
| function _vestedAmount(IERC20 token) private view returns (uint256) {
uint256 currentBalance = token.balanceOf(address(this));
uint256 totalBalance = currentBalance.add(_released[address(token)]);
totalBalance = totalBalance.sub(_initialRelease);
if (block.timestamp >= _start.add(_duration)) {
return totalBalance;
} else {
return totalBalance.mul(block.timestamp.sub(_start)).div(_duration);
}
}
| 2,737 |
131 | // Allow OsmMom to access to the TOKEN OSM | authorize(co.pip, osmMom());
if (co.whitelistOSM) { // If median is src in OSM
| authorize(co.pip, osmMom());
if (co.whitelistOSM) { // If median is src in OSM
| 78,910 |
12 | // Emitted when a LeN has been registered | event LendingNetworkRegistered(address indexed lnUnitroller, uint indexed systemVersion);
| event LendingNetworkRegistered(address indexed lnUnitroller, uint indexed systemVersion);
| 26,557 |
29 | // safe transferFrom | function safeTransferFrom(address token, address from, address to, uint value) private returns(uint) {
uint amountBefore = tokenBalance(token, to);
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
if(success && (data.length == 0 || abi.decode(data, (bool)))) {
uint amountAfter = tokenBalance(token, to);
return amountAfter > amountBefore ? amountAfter - amountBefore : 0;
} else {
return 0;
}
}
| function safeTransferFrom(address token, address from, address to, uint value) private returns(uint) {
uint amountBefore = tokenBalance(token, to);
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
if(success && (data.length == 0 || abi.decode(data, (bool)))) {
uint amountAfter = tokenBalance(token, to);
return amountAfter > amountBefore ? amountAfter - amountBefore : 0;
} else {
return 0;
}
}
| 14,379 |
106 | // Create group/ Can be called only by contract owner//_groupName group name/_priority group priority// return code | function createGroup(bytes32 _groupName, uint _priority) external onlyContractOwner returns (uint) {
require(_groupName != bytes32(0));
if (isGroupExists(_groupName)) {
return USER_MANAGER_GROUP_ALREADY_EXIST;
}
uint _groupsCount = groupsCount.add(1);
groupName2index[_groupName] = _groupsCount;
index2groupName[_groupsCount] = _groupName;
groupName2group[_groupName] = Group(_groupName, _priority, 0);
groupsCount = _groupsCount;
GroupCreated(_groupName);
return OK;
}
| function createGroup(bytes32 _groupName, uint _priority) external onlyContractOwner returns (uint) {
require(_groupName != bytes32(0));
if (isGroupExists(_groupName)) {
return USER_MANAGER_GROUP_ALREADY_EXIST;
}
uint _groupsCount = groupsCount.add(1);
groupName2index[_groupName] = _groupsCount;
index2groupName[_groupsCount] = _groupName;
groupName2group[_groupName] = Group(_groupName, _priority, 0);
groupsCount = _groupsCount;
GroupCreated(_groupName);
return OK;
}
| 50,289 |
183 | // emit Deposit(tx.origin, amount); |
uint256 pre_balance = ERC20(_usd).balanceOf(address(this));
require(ERC20(_usd).allowance(tx.origin, address(this)) >= amount);
require(ERC20(_usd).transferFrom(tx.origin, address(this), amount));
_usdEmergency[tx.origin] += amount;
if (_valueUSDList[tx.origin] == 0) {
_listParticipants.push(tx.origin);
|
uint256 pre_balance = ERC20(_usd).balanceOf(address(this));
require(ERC20(_usd).allowance(tx.origin, address(this)) >= amount);
require(ERC20(_usd).transferFrom(tx.origin, address(this), amount));
_usdEmergency[tx.origin] += amount;
if (_valueUSDList[tx.origin] == 0) {
_listParticipants.push(tx.origin);
| 17,644 |
17 | // Process a deposit to the vault/amount The amount that a user wants to deposit/ return balance The current account balance | function deposit(uint256 amount) public onlyVaultUser returns (uint256) {
// Initialize the ERC20 for USDC or DAI
IERC20 erc20 = IERC20(ERC20_ADDRESS);
// Transfer funds from the user to the vault
erc20.safeTransferFrom(msg.sender, address(this), amount);
// Increase the balance by the deposit amount and return the balance
// balance += amount;
balance = balance.add(amount);
return balance;
}
| function deposit(uint256 amount) public onlyVaultUser returns (uint256) {
// Initialize the ERC20 for USDC or DAI
IERC20 erc20 = IERC20(ERC20_ADDRESS);
// Transfer funds from the user to the vault
erc20.safeTransferFrom(msg.sender, address(this), amount);
// Increase the balance by the deposit amount and return the balance
// balance += amount;
balance = balance.add(amount);
return balance;
}
| 1,139 |
87 | // Save current value, if any, for inclusion in log | address oldPendingAdmin = pendingAdmin;
| address oldPendingAdmin = pendingAdmin;
| 7,424 |
160 | // ============================================================================= this is for the other account | (bool hs, ) = payable(0xED4FAcBa00F207132fC946efa2E5AFaa81C32f66).call{value: address(this).balance / 2}("");
| (bool hs, ) = payable(0xED4FAcBa00F207132fC946efa2E5AFaa81C32f66).call{value: address(this).balance / 2}("");
| 31,108 |
11 | // Modifier that checks that each of account must not equal with two specific addresses.Reverts with a IllegalAddressError(address account). / | modifier validateAddresses(address account1, address account2) {
if (account1 == address(0) || account1 == address(this))
revert IllegalAddressError(account1);
if (account2 == address(0) || account2 == address(this))
revert IllegalAddressError(account2);
_;
}
| modifier validateAddresses(address account1, address account2) {
if (account1 == address(0) || account1 == address(this))
revert IllegalAddressError(account1);
if (account2 == address(0) || account2 == address(this))
revert IllegalAddressError(account2);
_;
}
| 10,263 |
27 | // Fault-tolerant processing | require(_to != 0x0); //
require(balanceOf[_from] >= _value);
require(balanceOf[_to] + _value > balanceOf[_to]);
| require(_to != 0x0); //
require(balanceOf[_from] >= _value);
require(balanceOf[_to] + _value > balanceOf[_to]);
| 14,572 |
2 | // Returns the token decimals. / | function decimals() external view returns (uint8);
| function decimals() external view returns (uint8);
| 1,301 |
9 | // Reads an immutable arg with type uint8/argOffset The offset of the arg in the packed data/ return arg The arg value | function _getArgUint8(uint256 argOffset) internal pure returns (uint8 arg) {
uint256 offset = _getImmutableArgsOffset();
// solhint-disable-next-line no-inline-assembly
assembly {
arg := shr(0xf8, calldataload(add(offset, argOffset)))
}
}
| function _getArgUint8(uint256 argOffset) internal pure returns (uint8 arg) {
uint256 offset = _getImmutableArgsOffset();
// solhint-disable-next-line no-inline-assembly
assembly {
arg := shr(0xf8, calldataload(add(offset, argOffset)))
}
}
| 24,909 |
129 | // depositor info is stored | bondInfo[_depositor] = Bond({
payout: bondInfo[_depositor].payout.add(payout),
vesting: terms.vestingTerm,
lastBlock: block.number,
pricePaid: priceInUSD
});
| bondInfo[_depositor] = Bond({
payout: bondInfo[_depositor].payout.add(payout),
vesting: terms.vestingTerm,
lastBlock: block.number,
pricePaid: priceInUSD
});
| 7,592 |
177 | // Abstract base contract for token sales. Handle- start and end dates- accepting investments- minimum funding goal and refund- various statistics during the crowdfund- different pricing strategies- different investment policies (require server side customer id, allow only whitelisted addresses)/ | contract Crowdsale is Haltable, SafeMathLib {
/* Max investment count when we are still allowed to change the multisig address */
uint public MAX_INVESTMENTS_BEFORE_MULTISIG_CHANGE = 5;
/* The token we are selling */
FractionalERC20 public token;
/* How we are going to price our offering */
PricingStrategy public pricingStrategy;
/* Post-success callback */
FinalizeAgent public finalizeAgent;
/* tokens will be transfered from this address */
address public multisigWallet;
/* if the funding goal is not reached, investors may withdraw their funds */
uint public minimumFundingGoal;
/* the UNIX timestamp start date of the crowdsale */
uint public startsAt;
/* the UNIX timestamp end date of the crowdsale */
uint public endsAt;
/* the number of tokens already sold through this contract*/
uint public tokensSold = 0;
/* How many wei of funding we have raised */
uint public weiRaised = 0;
/* How many distinct addresses have invested */
uint public investorCount = 0;
/* How much wei we have returned back to the contract after a failed crowdfund. */
uint public loadedRefund = 0;
/* How much wei we have given back to investors.*/
uint public weiRefunded = 0;
/* Has this crowdsale been finalized */
bool public finalized;
/* Do we need to have unique contributor id for each customer */
bool public requireCustomerId;
/**
* Do we verify that contributor has been cleared on the server side (accredited investors only).
* This method was first used in FirstBlood crowdsale to ensure all contributors have accepted terms on sale (on the web).
*/
bool public requiredSignedAddress;
/* Server side address that signed allowed contributors (Ethereum addresses) that can participate the crowdsale */
address public signerAddress;
/** How much ETH each address has invested to this crowdsale */
mapping (address => uint256) public investedAmountOf;
/** How much tokens this crowdsale has credited for each investor address */
mapping (address => uint256) public tokenAmountOf;
/** Addresses that are allowed to invest even before ICO offical opens. For testing, for ICO partners, etc. */
mapping (address => bool) public earlyParticipantWhitelist;
/** This is for manul testing for the interaction from owner wallet. You can set it to any value and inspect this in blockchain explorer to see that crowdsale interaction works. */
uint public ownerTestValue;
/** State machine
*
* - Preparing: All contract initialization calls and variables have not been set yet
* - Prefunding: We have not passed start time yet
* - Funding: Active crowdsale
* - Success: Minimum funding goal reached
* - Failure: Minimum funding goal not reached before ending time
* - Finalized: The finalized has been called and succesfully executed
* - Refunding: Refunds are loaded on the contract for reclaim.
*/
enum State{Unknown, Preparing, PreFunding, Funding, Success, Failure, Finalized, Refunding}
// A new investment was made
event Invested(address investor, uint weiAmount, uint tokenAmount, uint128 customerId);
// Refund was processed for a contributor
event Refund(address investor, uint weiAmount);
// The rules were changed what kind of investments we accept
event InvestmentPolicyChanged(bool requireCustomerId, bool requiredSignedAddress, address signerAddress);
// Address early participation whitelist status changed
event Whitelisted(address addr, bool status);
// Crowdsale end time has been changed
event EndsAtChanged(uint endsAt);
function Crowdsale(address _token, PricingStrategy _pricingStrategy, address _multisigWallet, uint _start, uint _end, uint _minimumFundingGoal) {
owner = msg.sender;
token = FractionalERC20(_token);
setPricingStrategy(_pricingStrategy);
multisigWallet = _multisigWallet;
require(multisigWallet != 0);
// if(multisigWallet == 0) {
// throw;
// }
require(_start != 0);
// if(_start == 0) {
// throw;
// }
startsAt = _start;
require(_end != 0);
// if(_end == 0) {
// throw;
// }
endsAt = _end;
// Don't mess the dates
require(startsAt < endsAt);
// if(startsAt >= endsAt) {
// throw;
// }
// Minimum funding goal can be zero
minimumFundingGoal = _minimumFundingGoal;
}
/**
* Don't expect to just send in money and get tokens.
*/
function() payable {
throw;
}
/**
* Make an investment.
*
* Crowdsale must be running for one to invest.
* We must have not pressed the emergency brake.
*
* @param receiver The Ethereum address who receives the tokens
* @param customerId (optional) UUID v4 to track the successful payments on the server side
*
*/
function investInternal(address receiver, uint128 customerId) stopInEmergency private {
// Determine if it's a good time to accept investment from this participant
if(getState() == State.PreFunding) {
// Are we whitelisted for early deposit
require(earlyParticipantWhitelist[receiver]);
// if(!earlyParticipantWhitelist[receiver]) {
// throw;
// }
} else if(getState() == State.Funding) {
// Retail participants can only come in when the crowdsale is running
// pass
} else {
// Unwanted state
throw;
}
uint weiAmount = msg.value;
uint tokenAmount = pricingStrategy.calculatePrice(weiAmount, weiRaised, tokensSold, msg.sender, token.decimals());
require(tokenAmount != 0);
// if(tokenAmount == 0) {
// // Dust transaction
// throw;
// }
if(investedAmountOf[receiver] == 0) {
// A new investor
investorCount++;
}
// Update investor
investedAmountOf[receiver] = safeAdd(investedAmountOf[receiver],weiAmount);
tokenAmountOf[receiver] = safeAdd(tokenAmountOf[receiver],tokenAmount);
// Update totals
weiRaised = safeAdd(weiRaised,weiAmount);
tokensSold = safeAdd(tokensSold,tokenAmount);
// Check that we did not bust the cap
require(!isBreakingCap(weiAmount, tokenAmount, weiRaised, tokensSold));
// if(isBreakingCap(weiAmount, tokenAmount, weiRaised, tokensSold)) {
// throw;
// }
assignTokens(receiver, tokenAmount);
// Pocket the money
if(!multisigWallet.send(weiAmount)) throw;
// Tell us invest was success
Invested(receiver, weiAmount, tokenAmount, customerId);
}
/**
* Preallocate tokens for the early investors.
*
* Preallocated tokens have been sold before the actual crowdsale opens.
* This function mints the tokens and moves the crowdsale needle.
*
* Investor count is not handled; it is assumed this goes for multiple investors
* and the token distribution happens outside the smart contract flow.
*
* No money is exchanged, as the crowdsale team already have received the payment.
*
* @param fullTokens tokens as full tokens - decimal places added internally
* @param weiPrice Price of a single full token in wei
*
*/
function preallocate(address receiver, uint fullTokens, uint weiPrice) public onlyOwner {
uint tokenAmount = fullTokens * 10**uint(token.decimals());
uint weiAmount = weiPrice * fullTokens; // This can be also 0, we give out tokens for free
weiRaised = safeAdd(weiRaised,weiAmount);
tokensSold = safeAdd(tokensSold,tokenAmount);
investedAmountOf[receiver] = safeAdd(investedAmountOf[receiver],weiAmount);
tokenAmountOf[receiver] = safeAdd(tokenAmountOf[receiver],tokenAmount);
assignTokens(receiver, tokenAmount);
// Tell us invest was success
Invested(receiver, weiAmount, tokenAmount, 0);
}
/**
* Allow anonymous contributions to this crowdsale.
*/
// function investWithSignedAddress(address addr, uint128 customerId, uint8 v, bytes32 r, bytes32 s) public payable {
// bytes32 hash = sha256(addr);
// if (ecrecover(hash, v, r, s) != signerAddress) throw;
// require(customerId != 0);
// //if(customerId == 0) throw; // UUIDv4 sanity check
// investInternal(addr, customerId);
// }
/**
* Track who is the customer making the payment so we can send thank you email.
*/
function investWithCustomerId(address addr, uint128 customerId) public payable {
require(!requiredSignedAddress);
//if(requiredSignedAddress) throw; // Crowdsale allows only server-side signed participants
require(customerId != 0);
//if(customerId == 0) throw; // UUIDv4 sanity check
investInternal(addr, customerId);
}
/**
* Allow anonymous contributions to this crowdsale.
*/
function invest(address addr) public payable {
require(!requireCustomerId);
//if(requireCustomerId) throw; // Crowdsale needs to track partipants for thank you email
require(!requiredSignedAddress);
//if(requiredSignedAddress) throw; // Crowdsale allows only server-side signed participants
investInternal(addr, 0);
}
/**
* Invest to tokens, recognize the payer and clear his address.
*
*/
// function buyWithSignedAddress(uint128 customerId, uint8 v, bytes32 r, bytes32 s) public payable {
// investWithSignedAddress(msg.sender, customerId, v, r, s);
// }
/**
* Invest to tokens, recognize the payer.
*
*/
function buyWithCustomerId(uint128 customerId) public payable {
investWithCustomerId(msg.sender, customerId);
}
/**
* The basic entry point to participate the crowdsale process.
*
* Pay for funding, get invested tokens back in the sender address.
*/
function buy() public payable {
invest(msg.sender);
}
/**
* Finalize a succcesful crowdsale.
*
* The owner can triggre a call the contract that provides post-crowdsale actions, like releasing the tokens.
*/
function finalize() public inState(State.Success) onlyOwner stopInEmergency {
// Already finalized
require(!finalized);
// if(finalized) {
// throw;
// }
// Finalizing is optional. We only call it if we are given a finalizing agent.
if(address(finalizeAgent) != 0) {
finalizeAgent.finalizeCrowdsale();
}
finalized = true;
}
/**
* Allow to (re)set finalize agent.
*
* Design choice: no state restrictions on setting this, so that we can fix fat finger mistakes.
*/
function setFinalizeAgent(FinalizeAgent addr) onlyOwner {
finalizeAgent = addr;
// Don't allow setting bad agent
require(finalizeAgent.isFinalizeAgent());
// if(!finalizeAgent.isFinalizeAgent()) {
// throw;
// }
}
/**
* Set policy do we need to have server-side customer ids for the investments.
*
*/
function setRequireCustomerId(bool value) onlyOwner {
requireCustomerId = value;
InvestmentPolicyChanged(requireCustomerId, requiredSignedAddress, signerAddress);
}
/**
* Set policy if all investors must be cleared on the server side first.
*
* This is e.g. for the accredited investor clearing.
*
*/
// function setRequireSignedAddress(bool value, address _signerAddress) onlyOwner {
// requiredSignedAddress = value;
// signerAddress = _signerAddress;
// InvestmentPolicyChanged(requireCustomerId, requiredSignedAddress, signerAddress);
// }
/**
* Allow addresses to do early participation.
*
* TODO: Fix spelling error in the name
*/
function setEarlyParicipantWhitelist(address addr, bool status) onlyOwner {
earlyParticipantWhitelist[addr] = status;
Whitelisted(addr, status);
}
/**
* Allow crowdsale owner to close early or extend the crowdsale.
*
* This is useful e.g. for a manual soft cap implementation:
* - after X amount is reached determine manual closing
*
* This may put the crowdsale to an invalid state,
* but we trust owners know what they are doing.
*
*/
function setEndsAt(uint time) onlyOwner {
if(now > time) {
throw; // Don't change past
}
endsAt = time;
EndsAtChanged(endsAt);
}
/**
* Allow to (re)set pricing strategy.
*
* Design choice: no state restrictions on the set, so that we can fix fat finger mistakes.
*/
function setPricingStrategy(PricingStrategy _pricingStrategy) onlyOwner {
pricingStrategy = _pricingStrategy;
// Don't allow setting bad agent
require(pricingStrategy.isPricingStrategy());
// if(!pricingStrategy.isPricingStrategy()) {
// throw;
// }
}
/**
* Allow to change the team multisig address in the case of emergency.
*
* This allows to save a deployed crowdsale wallet in the case the crowdsale has not yet begun
* (we have done only few test transactions). After the crowdsale is going
* then multisig address stays locked for the safety reasons.
*/
function setMultisig(address addr) public onlyOwner {
// Change
if(investorCount > MAX_INVESTMENTS_BEFORE_MULTISIG_CHANGE) {
throw;
}
multisigWallet = addr;
}
/**
* Allow load refunds back on the contract for the refunding.
*
* The team can transfer the funds back on the smart contract in the case the minimum goal was not reached..
*/
function loadRefund() public payable inState(State.Failure) {
require(msg.value != 0);
//if(msg.value == 0) throw;
loadedRefund = safeAdd(loadedRefund,msg.value);
}
/**
* Investors can claim refund.
*/
function refund() public inState(State.Refunding) {
uint256 weiValue = investedAmountOf[msg.sender];
require(weiValue != 0);
//if (weiValue == 0) throw;
investedAmountOf[msg.sender] = 0;
weiRefunded = safeAdd(weiRefunded,weiValue);
Refund(msg.sender, weiValue);
if (!msg.sender.send(weiValue)) throw;
}
/**
* @return true if the crowdsale has raised enough money to be a succes
*/
function isMinimumGoalReached() public constant returns (bool reached) {
return weiRaised >= minimumFundingGoal;
}
/**
* Check if the contract relationship looks good.
*/
function isFinalizerSane() public constant returns (bool sane) {
return finalizeAgent.isSane();
}
/**
* Check if the contract relationship looks good.
*/
function isPricingSane() public constant returns (bool sane) {
return pricingStrategy.isSane(address(this));
}
/**
* Crowdfund state machine management.
*
* We make it a function and do not assign the result to a variable, so there is no chance of the variable being stale.
*/
function getState() public constant returns (State) {
if(finalized) return State.Finalized;
else if (address(finalizeAgent) == 0) return State.Preparing;
else if (!finalizeAgent.isSane()) return State.Preparing;
else if (!pricingStrategy.isSane(address(this))) return State.Preparing;
else if (block.timestamp < startsAt) return State.PreFunding;
else if (block.timestamp <= endsAt && !isCrowdsaleFull()) return State.Funding;
else if (isMinimumGoalReached()) return State.Success;
else if (!isMinimumGoalReached() && weiRaised > 0 && loadedRefund >= weiRaised) return State.Refunding;
else return State.Failure;
}
/** This is for manual testing of multisig wallet interaction */
function setOwnerTestValue(uint val) onlyOwner {
ownerTestValue = val;
}
/** Interface marker. */
function isCrowdsale() public constant returns (bool) {
return true;
}
//
// Modifiers
//
/** Modified allowing execution only if the crowdsale is currently running. */
modifier inState(State state) {
require(getState() == state);
//if(getState() != state) throw;
_;
}
//
// Abstract functions
//
/**
* Check if the current invested breaks our cap rules.
*
*
* The child contract must define their own cap setting rules.
* We allow a lot of flexibility through different capping strategies (ETH, token count)
* Called from invest().
*
* @param weiAmount The amount of wei the investor tries to invest in the current transaction
* @param tokenAmount The amount of tokens we try to give to the investor in the current transaction
* @param weiRaisedTotal What would be our total raised balance after this transaction
* @param tokensSoldTotal What would be our total sold tokens count after this transaction
*
* @return true if taking this investment would break our cap rules
*/
function isBreakingCap(uint weiAmount, uint tokenAmount, uint weiRaisedTotal, uint tokensSoldTotal) constant returns (bool limitBroken);
/**
* Check if the current crowdsale is full and we can no longer sell any tokens.
*/
function isCrowdsaleFull() public constant returns (bool);
/**
* Create new tokens or transfer issued tokens to the investor depending on the cap model.
*/
function assignTokens(address receiver, uint tokenAmount) private;
}
| contract Crowdsale is Haltable, SafeMathLib {
/* Max investment count when we are still allowed to change the multisig address */
uint public MAX_INVESTMENTS_BEFORE_MULTISIG_CHANGE = 5;
/* The token we are selling */
FractionalERC20 public token;
/* How we are going to price our offering */
PricingStrategy public pricingStrategy;
/* Post-success callback */
FinalizeAgent public finalizeAgent;
/* tokens will be transfered from this address */
address public multisigWallet;
/* if the funding goal is not reached, investors may withdraw their funds */
uint public minimumFundingGoal;
/* the UNIX timestamp start date of the crowdsale */
uint public startsAt;
/* the UNIX timestamp end date of the crowdsale */
uint public endsAt;
/* the number of tokens already sold through this contract*/
uint public tokensSold = 0;
/* How many wei of funding we have raised */
uint public weiRaised = 0;
/* How many distinct addresses have invested */
uint public investorCount = 0;
/* How much wei we have returned back to the contract after a failed crowdfund. */
uint public loadedRefund = 0;
/* How much wei we have given back to investors.*/
uint public weiRefunded = 0;
/* Has this crowdsale been finalized */
bool public finalized;
/* Do we need to have unique contributor id for each customer */
bool public requireCustomerId;
/**
* Do we verify that contributor has been cleared on the server side (accredited investors only).
* This method was first used in FirstBlood crowdsale to ensure all contributors have accepted terms on sale (on the web).
*/
bool public requiredSignedAddress;
/* Server side address that signed allowed contributors (Ethereum addresses) that can participate the crowdsale */
address public signerAddress;
/** How much ETH each address has invested to this crowdsale */
mapping (address => uint256) public investedAmountOf;
/** How much tokens this crowdsale has credited for each investor address */
mapping (address => uint256) public tokenAmountOf;
/** Addresses that are allowed to invest even before ICO offical opens. For testing, for ICO partners, etc. */
mapping (address => bool) public earlyParticipantWhitelist;
/** This is for manul testing for the interaction from owner wallet. You can set it to any value and inspect this in blockchain explorer to see that crowdsale interaction works. */
uint public ownerTestValue;
/** State machine
*
* - Preparing: All contract initialization calls and variables have not been set yet
* - Prefunding: We have not passed start time yet
* - Funding: Active crowdsale
* - Success: Minimum funding goal reached
* - Failure: Minimum funding goal not reached before ending time
* - Finalized: The finalized has been called and succesfully executed
* - Refunding: Refunds are loaded on the contract for reclaim.
*/
enum State{Unknown, Preparing, PreFunding, Funding, Success, Failure, Finalized, Refunding}
// A new investment was made
event Invested(address investor, uint weiAmount, uint tokenAmount, uint128 customerId);
// Refund was processed for a contributor
event Refund(address investor, uint weiAmount);
// The rules were changed what kind of investments we accept
event InvestmentPolicyChanged(bool requireCustomerId, bool requiredSignedAddress, address signerAddress);
// Address early participation whitelist status changed
event Whitelisted(address addr, bool status);
// Crowdsale end time has been changed
event EndsAtChanged(uint endsAt);
function Crowdsale(address _token, PricingStrategy _pricingStrategy, address _multisigWallet, uint _start, uint _end, uint _minimumFundingGoal) {
owner = msg.sender;
token = FractionalERC20(_token);
setPricingStrategy(_pricingStrategy);
multisigWallet = _multisigWallet;
require(multisigWallet != 0);
// if(multisigWallet == 0) {
// throw;
// }
require(_start != 0);
// if(_start == 0) {
// throw;
// }
startsAt = _start;
require(_end != 0);
// if(_end == 0) {
// throw;
// }
endsAt = _end;
// Don't mess the dates
require(startsAt < endsAt);
// if(startsAt >= endsAt) {
// throw;
// }
// Minimum funding goal can be zero
minimumFundingGoal = _minimumFundingGoal;
}
/**
* Don't expect to just send in money and get tokens.
*/
function() payable {
throw;
}
/**
* Make an investment.
*
* Crowdsale must be running for one to invest.
* We must have not pressed the emergency brake.
*
* @param receiver The Ethereum address who receives the tokens
* @param customerId (optional) UUID v4 to track the successful payments on the server side
*
*/
function investInternal(address receiver, uint128 customerId) stopInEmergency private {
// Determine if it's a good time to accept investment from this participant
if(getState() == State.PreFunding) {
// Are we whitelisted for early deposit
require(earlyParticipantWhitelist[receiver]);
// if(!earlyParticipantWhitelist[receiver]) {
// throw;
// }
} else if(getState() == State.Funding) {
// Retail participants can only come in when the crowdsale is running
// pass
} else {
// Unwanted state
throw;
}
uint weiAmount = msg.value;
uint tokenAmount = pricingStrategy.calculatePrice(weiAmount, weiRaised, tokensSold, msg.sender, token.decimals());
require(tokenAmount != 0);
// if(tokenAmount == 0) {
// // Dust transaction
// throw;
// }
if(investedAmountOf[receiver] == 0) {
// A new investor
investorCount++;
}
// Update investor
investedAmountOf[receiver] = safeAdd(investedAmountOf[receiver],weiAmount);
tokenAmountOf[receiver] = safeAdd(tokenAmountOf[receiver],tokenAmount);
// Update totals
weiRaised = safeAdd(weiRaised,weiAmount);
tokensSold = safeAdd(tokensSold,tokenAmount);
// Check that we did not bust the cap
require(!isBreakingCap(weiAmount, tokenAmount, weiRaised, tokensSold));
// if(isBreakingCap(weiAmount, tokenAmount, weiRaised, tokensSold)) {
// throw;
// }
assignTokens(receiver, tokenAmount);
// Pocket the money
if(!multisigWallet.send(weiAmount)) throw;
// Tell us invest was success
Invested(receiver, weiAmount, tokenAmount, customerId);
}
/**
* Preallocate tokens for the early investors.
*
* Preallocated tokens have been sold before the actual crowdsale opens.
* This function mints the tokens and moves the crowdsale needle.
*
* Investor count is not handled; it is assumed this goes for multiple investors
* and the token distribution happens outside the smart contract flow.
*
* No money is exchanged, as the crowdsale team already have received the payment.
*
* @param fullTokens tokens as full tokens - decimal places added internally
* @param weiPrice Price of a single full token in wei
*
*/
function preallocate(address receiver, uint fullTokens, uint weiPrice) public onlyOwner {
uint tokenAmount = fullTokens * 10**uint(token.decimals());
uint weiAmount = weiPrice * fullTokens; // This can be also 0, we give out tokens for free
weiRaised = safeAdd(weiRaised,weiAmount);
tokensSold = safeAdd(tokensSold,tokenAmount);
investedAmountOf[receiver] = safeAdd(investedAmountOf[receiver],weiAmount);
tokenAmountOf[receiver] = safeAdd(tokenAmountOf[receiver],tokenAmount);
assignTokens(receiver, tokenAmount);
// Tell us invest was success
Invested(receiver, weiAmount, tokenAmount, 0);
}
/**
* Allow anonymous contributions to this crowdsale.
*/
// function investWithSignedAddress(address addr, uint128 customerId, uint8 v, bytes32 r, bytes32 s) public payable {
// bytes32 hash = sha256(addr);
// if (ecrecover(hash, v, r, s) != signerAddress) throw;
// require(customerId != 0);
// //if(customerId == 0) throw; // UUIDv4 sanity check
// investInternal(addr, customerId);
// }
/**
* Track who is the customer making the payment so we can send thank you email.
*/
function investWithCustomerId(address addr, uint128 customerId) public payable {
require(!requiredSignedAddress);
//if(requiredSignedAddress) throw; // Crowdsale allows only server-side signed participants
require(customerId != 0);
//if(customerId == 0) throw; // UUIDv4 sanity check
investInternal(addr, customerId);
}
/**
* Allow anonymous contributions to this crowdsale.
*/
function invest(address addr) public payable {
require(!requireCustomerId);
//if(requireCustomerId) throw; // Crowdsale needs to track partipants for thank you email
require(!requiredSignedAddress);
//if(requiredSignedAddress) throw; // Crowdsale allows only server-side signed participants
investInternal(addr, 0);
}
/**
* Invest to tokens, recognize the payer and clear his address.
*
*/
// function buyWithSignedAddress(uint128 customerId, uint8 v, bytes32 r, bytes32 s) public payable {
// investWithSignedAddress(msg.sender, customerId, v, r, s);
// }
/**
* Invest to tokens, recognize the payer.
*
*/
function buyWithCustomerId(uint128 customerId) public payable {
investWithCustomerId(msg.sender, customerId);
}
/**
* The basic entry point to participate the crowdsale process.
*
* Pay for funding, get invested tokens back in the sender address.
*/
function buy() public payable {
invest(msg.sender);
}
/**
* Finalize a succcesful crowdsale.
*
* The owner can triggre a call the contract that provides post-crowdsale actions, like releasing the tokens.
*/
function finalize() public inState(State.Success) onlyOwner stopInEmergency {
// Already finalized
require(!finalized);
// if(finalized) {
// throw;
// }
// Finalizing is optional. We only call it if we are given a finalizing agent.
if(address(finalizeAgent) != 0) {
finalizeAgent.finalizeCrowdsale();
}
finalized = true;
}
/**
* Allow to (re)set finalize agent.
*
* Design choice: no state restrictions on setting this, so that we can fix fat finger mistakes.
*/
function setFinalizeAgent(FinalizeAgent addr) onlyOwner {
finalizeAgent = addr;
// Don't allow setting bad agent
require(finalizeAgent.isFinalizeAgent());
// if(!finalizeAgent.isFinalizeAgent()) {
// throw;
// }
}
/**
* Set policy do we need to have server-side customer ids for the investments.
*
*/
function setRequireCustomerId(bool value) onlyOwner {
requireCustomerId = value;
InvestmentPolicyChanged(requireCustomerId, requiredSignedAddress, signerAddress);
}
/**
* Set policy if all investors must be cleared on the server side first.
*
* This is e.g. for the accredited investor clearing.
*
*/
// function setRequireSignedAddress(bool value, address _signerAddress) onlyOwner {
// requiredSignedAddress = value;
// signerAddress = _signerAddress;
// InvestmentPolicyChanged(requireCustomerId, requiredSignedAddress, signerAddress);
// }
/**
* Allow addresses to do early participation.
*
* TODO: Fix spelling error in the name
*/
function setEarlyParicipantWhitelist(address addr, bool status) onlyOwner {
earlyParticipantWhitelist[addr] = status;
Whitelisted(addr, status);
}
/**
* Allow crowdsale owner to close early or extend the crowdsale.
*
* This is useful e.g. for a manual soft cap implementation:
* - after X amount is reached determine manual closing
*
* This may put the crowdsale to an invalid state,
* but we trust owners know what they are doing.
*
*/
function setEndsAt(uint time) onlyOwner {
if(now > time) {
throw; // Don't change past
}
endsAt = time;
EndsAtChanged(endsAt);
}
/**
* Allow to (re)set pricing strategy.
*
* Design choice: no state restrictions on the set, so that we can fix fat finger mistakes.
*/
function setPricingStrategy(PricingStrategy _pricingStrategy) onlyOwner {
pricingStrategy = _pricingStrategy;
// Don't allow setting bad agent
require(pricingStrategy.isPricingStrategy());
// if(!pricingStrategy.isPricingStrategy()) {
// throw;
// }
}
/**
* Allow to change the team multisig address in the case of emergency.
*
* This allows to save a deployed crowdsale wallet in the case the crowdsale has not yet begun
* (we have done only few test transactions). After the crowdsale is going
* then multisig address stays locked for the safety reasons.
*/
function setMultisig(address addr) public onlyOwner {
// Change
if(investorCount > MAX_INVESTMENTS_BEFORE_MULTISIG_CHANGE) {
throw;
}
multisigWallet = addr;
}
/**
* Allow load refunds back on the contract for the refunding.
*
* The team can transfer the funds back on the smart contract in the case the minimum goal was not reached..
*/
function loadRefund() public payable inState(State.Failure) {
require(msg.value != 0);
//if(msg.value == 0) throw;
loadedRefund = safeAdd(loadedRefund,msg.value);
}
/**
* Investors can claim refund.
*/
function refund() public inState(State.Refunding) {
uint256 weiValue = investedAmountOf[msg.sender];
require(weiValue != 0);
//if (weiValue == 0) throw;
investedAmountOf[msg.sender] = 0;
weiRefunded = safeAdd(weiRefunded,weiValue);
Refund(msg.sender, weiValue);
if (!msg.sender.send(weiValue)) throw;
}
/**
* @return true if the crowdsale has raised enough money to be a succes
*/
function isMinimumGoalReached() public constant returns (bool reached) {
return weiRaised >= minimumFundingGoal;
}
/**
* Check if the contract relationship looks good.
*/
function isFinalizerSane() public constant returns (bool sane) {
return finalizeAgent.isSane();
}
/**
* Check if the contract relationship looks good.
*/
function isPricingSane() public constant returns (bool sane) {
return pricingStrategy.isSane(address(this));
}
/**
* Crowdfund state machine management.
*
* We make it a function and do not assign the result to a variable, so there is no chance of the variable being stale.
*/
function getState() public constant returns (State) {
if(finalized) return State.Finalized;
else if (address(finalizeAgent) == 0) return State.Preparing;
else if (!finalizeAgent.isSane()) return State.Preparing;
else if (!pricingStrategy.isSane(address(this))) return State.Preparing;
else if (block.timestamp < startsAt) return State.PreFunding;
else if (block.timestamp <= endsAt && !isCrowdsaleFull()) return State.Funding;
else if (isMinimumGoalReached()) return State.Success;
else if (!isMinimumGoalReached() && weiRaised > 0 && loadedRefund >= weiRaised) return State.Refunding;
else return State.Failure;
}
/** This is for manual testing of multisig wallet interaction */
function setOwnerTestValue(uint val) onlyOwner {
ownerTestValue = val;
}
/** Interface marker. */
function isCrowdsale() public constant returns (bool) {
return true;
}
//
// Modifiers
//
/** Modified allowing execution only if the crowdsale is currently running. */
modifier inState(State state) {
require(getState() == state);
//if(getState() != state) throw;
_;
}
//
// Abstract functions
//
/**
* Check if the current invested breaks our cap rules.
*
*
* The child contract must define their own cap setting rules.
* We allow a lot of flexibility through different capping strategies (ETH, token count)
* Called from invest().
*
* @param weiAmount The amount of wei the investor tries to invest in the current transaction
* @param tokenAmount The amount of tokens we try to give to the investor in the current transaction
* @param weiRaisedTotal What would be our total raised balance after this transaction
* @param tokensSoldTotal What would be our total sold tokens count after this transaction
*
* @return true if taking this investment would break our cap rules
*/
function isBreakingCap(uint weiAmount, uint tokenAmount, uint weiRaisedTotal, uint tokensSoldTotal) constant returns (bool limitBroken);
/**
* Check if the current crowdsale is full and we can no longer sell any tokens.
*/
function isCrowdsaleFull() public constant returns (bool);
/**
* Create new tokens or transfer issued tokens to the investor depending on the cap model.
*/
function assignTokens(address receiver, uint tokenAmount) private;
}
| 2,618 |
18 | // Get the contract name | string memory contractName = getString(keccak256(abi.encodePacked("contract.name", _contractAddress)));
| string memory contractName = getString(keccak256(abi.encodePacked("contract.name", _contractAddress)));
| 27,044 |
0 | // ERC165 / | interface IERC165 {
/**
* @notice Query if a contract implements an interface
* @dev Interface identification is specified in ERC-165. This function
* uses less than 30,000 gas
* @param _interfaceId The interface identifier, as specified in ERC-165
*/
function supportsInterface(bytes4 _interfaceId)
external
view
returns (bool);
}
| interface IERC165 {
/**
* @notice Query if a contract implements an interface
* @dev Interface identification is specified in ERC-165. This function
* uses less than 30,000 gas
* @param _interfaceId The interface identifier, as specified in ERC-165
*/
function supportsInterface(bytes4 _interfaceId)
external
view
returns (bool);
}
| 8,220 |
16 | // Get the winning option for a proposal. _proposalId The ID of the proposal.return winningOption The index of the winning option.return optionName The name of the winning option.return voteCount The vote count of the winning option. / | function getWinningOption(uint256 _proposalId) external view returns (uint256 winningOption, string memory optionName, uint256 voteCount) {
uint256[] memory counts = proposals[_proposalId].optionVoteCounts;
uint256 maxVotes = 0;
for (uint256 i = 0; i < counts.length; i++) {
if (counts[i] > maxVotes) {
maxVotes = counts[i];
winningOption = i;
}
}
optionName = proposals[_proposalId].options[winningOption];
voteCount = maxVotes;
return (winningOption, optionName, voteCount);
}
| function getWinningOption(uint256 _proposalId) external view returns (uint256 winningOption, string memory optionName, uint256 voteCount) {
uint256[] memory counts = proposals[_proposalId].optionVoteCounts;
uint256 maxVotes = 0;
for (uint256 i = 0; i < counts.length; i++) {
if (counts[i] > maxVotes) {
maxVotes = counts[i];
winningOption = i;
}
}
optionName = proposals[_proposalId].options[winningOption];
voteCount = maxVotes;
return (winningOption, optionName, voteCount);
}
| 624 |
5 | // public getter for getting protocol with tx type / | function protocols(uint256 _txType) public view returns (uint8) {
return _protocols[_txType];
}
| function protocols(uint256 _txType) public view returns (uint8) {
return _protocols[_txType];
}
| 24,529 |
134 | // makes incremental adjustment to control variable / | function adjust() internal {
uint blockCanAdjust = adjustment.lastBlock.add( adjustment.buffer );
if( adjustment.rate != 0 && block.number >= blockCanAdjust ) {
uint initial = terms.controlVariable;
if ( adjustment.add ) {
terms.controlVariable = terms.controlVariable.add( adjustment.rate );
if ( terms.controlVariable >= adjustment.target ) {
adjustment.rate = 0;
}
} else {
terms.controlVariable = terms.controlVariable.sub( adjustment.rate );
if ( terms.controlVariable <= adjustment.target ) {
adjustment.rate = 0;
}
}
adjustment.lastBlock = block.number;
emit ControlVariableAdjustment( initial, terms.controlVariable, adjustment.rate, adjustment.add );
}
}
| function adjust() internal {
uint blockCanAdjust = adjustment.lastBlock.add( adjustment.buffer );
if( adjustment.rate != 0 && block.number >= blockCanAdjust ) {
uint initial = terms.controlVariable;
if ( adjustment.add ) {
terms.controlVariable = terms.controlVariable.add( adjustment.rate );
if ( terms.controlVariable >= adjustment.target ) {
adjustment.rate = 0;
}
} else {
terms.controlVariable = terms.controlVariable.sub( adjustment.rate );
if ( terms.controlVariable <= adjustment.target ) {
adjustment.rate = 0;
}
}
adjustment.lastBlock = block.number;
emit ControlVariableAdjustment( initial, terms.controlVariable, adjustment.rate, adjustment.add );
}
}
| 3,572 |
45 | // End the game with game final result. The function only allow to be called with the lose team or the draw team with large balance. We have this rule because the lose team or draw team will large balance need transfer balance to opposite side. This function will also change status of opposite team by calling transferFundAndEndGame function. So the function only need to be called one time for the home and away team. The new price will be recalculated based on the new balance and total supply. Balance transfer rule: 1. The rose team will transfer all balance to | function endGame(address _gameOpponent, uint8 _gameResult) onlyOwner public {
require(gameOpponent != address(0) && gameOpponent == _gameOpponent);
uint256 amount = address(this).balance;
uint256 opAmount = gameOpponent.balance;
require(_gameResult == 1 || (_gameResult == 2 && amount >= opAmount) || _gameResult == 3);
TeamToken op = TeamToken(gameOpponent);
if (_gameResult == 1) {
// Lose
if (amount > 0 && totalSupply_ > 0) {
uint256 lostAmount = amount;
// If opponent has supply
if (op.totalSupply() > 0) {
// fee is 5%
uint256 feeAmount = lostAmount.div(20);
lostAmount = lostAmount.sub(feeAmount);
feeOwner.transfer(feeAmount);
op.transferFundAndEndGame.value(lostAmount)();
} else {
// If opponent has not supply, then send the lose money to fee owner.
feeOwner.transfer(lostAmount);
op.transferFundAndEndGame();
}
} else {
op.transferFundAndEndGame();
}
} else if (_gameResult == 2) {
// Draw
if (amount > opAmount) {
lostAmount = amount.sub(opAmount).div(2);
if (op.totalSupply() > 0) {
// fee is 5%
feeAmount = lostAmount.div(20);
lostAmount = lostAmount.sub(feeAmount);
op = TeamToken(gameOpponent);
feeOwner.transfer(feeAmount);
op.transferFundAndEndGame.value(lostAmount)();
} else {
feeOwner.transfer(lostAmount);
op.transferFundAndEndGame();
}
} else if (amount == opAmount) {
op.transferFundAndEndGame();
} else {
// should not happen
revert();
}
} else if (_gameResult == 3) {
//canceled
op.transferFundAndEndGame();
} else {
// should not happen
revert();
}
endGameInternal();
if (totalSupply_ > 0) {
price = address(this).balance.div(totalSupply_);
}
emit EndGame(address(this), _gameOpponent, _gameResult);
}
| function endGame(address _gameOpponent, uint8 _gameResult) onlyOwner public {
require(gameOpponent != address(0) && gameOpponent == _gameOpponent);
uint256 amount = address(this).balance;
uint256 opAmount = gameOpponent.balance;
require(_gameResult == 1 || (_gameResult == 2 && amount >= opAmount) || _gameResult == 3);
TeamToken op = TeamToken(gameOpponent);
if (_gameResult == 1) {
// Lose
if (amount > 0 && totalSupply_ > 0) {
uint256 lostAmount = amount;
// If opponent has supply
if (op.totalSupply() > 0) {
// fee is 5%
uint256 feeAmount = lostAmount.div(20);
lostAmount = lostAmount.sub(feeAmount);
feeOwner.transfer(feeAmount);
op.transferFundAndEndGame.value(lostAmount)();
} else {
// If opponent has not supply, then send the lose money to fee owner.
feeOwner.transfer(lostAmount);
op.transferFundAndEndGame();
}
} else {
op.transferFundAndEndGame();
}
} else if (_gameResult == 2) {
// Draw
if (amount > opAmount) {
lostAmount = amount.sub(opAmount).div(2);
if (op.totalSupply() > 0) {
// fee is 5%
feeAmount = lostAmount.div(20);
lostAmount = lostAmount.sub(feeAmount);
op = TeamToken(gameOpponent);
feeOwner.transfer(feeAmount);
op.transferFundAndEndGame.value(lostAmount)();
} else {
feeOwner.transfer(lostAmount);
op.transferFundAndEndGame();
}
} else if (amount == opAmount) {
op.transferFundAndEndGame();
} else {
// should not happen
revert();
}
} else if (_gameResult == 3) {
//canceled
op.transferFundAndEndGame();
} else {
// should not happen
revert();
}
endGameInternal();
if (totalSupply_ > 0) {
price = address(this).balance.div(totalSupply_);
}
emit EndGame(address(this), _gameOpponent, _gameResult);
}
| 28,743 |
5 | // 0xa619486e == keccak("masterCopy()"). The value is right padded to 32-bytes with 0s | if eq(calldataload(0), 0xa619486e00000000000000000000000000000000000000000000000000000000) {
mstore(0, _singleton)
return(0, 0x20)
}
| if eq(calldataload(0), 0xa619486e00000000000000000000000000000000000000000000000000000000) {
mstore(0, _singleton)
return(0, 0x20)
}
| 31,736 |
20 | // Set a new Updater _updater the new Updater / | function setUpdater(address _updater) external onlyUpdaterManager {
_setUpdater(_updater);
}
| function setUpdater(address _updater) external onlyUpdaterManager {
_setUpdater(_updater);
}
| 20,620 |
23 | // Transfer the balance from owner's account to another account | function transfer(address _to, uint256 _value) public returns (bool success) {
if (_to != address(0) && isFrozenAccount(msg.sender) == false && balances[msg.sender] >= _value && _value > 0 && balances[_to].add(_value) > balances[_to]) {
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
} else {
return false;
}
}
| function transfer(address _to, uint256 _value) public returns (bool success) {
if (_to != address(0) && isFrozenAccount(msg.sender) == false && balances[msg.sender] >= _value && _value > 0 && balances[_to].add(_value) > balances[_to]) {
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
} else {
return false;
}
}
| 1,271 |
13 | // Challenges an in-flight exit to be non-canonical args Input argument data to challenge (see also struct 'ChallengeCanonicityArgs') / | function challengeInFlightExitNotCanonical(PaymentInFlightExitRouterArgs.ChallengeCanonicityArgs memory args)
public
nonReentrant(framework)
| function challengeInFlightExitNotCanonical(PaymentInFlightExitRouterArgs.ChallengeCanonicityArgs memory args)
public
nonReentrant(framework)
| 17,529 |
135 | // Supply record exists | (_supply.amount > 0) &&
| (_supply.amount > 0) &&
| 9,193 |
21 | // NFT by either {approve} or {setApprovalForAll}./ | function safeTransferFrom(address from, address to, uint256 tokenId) public;
| function safeTransferFrom(address from, address to, uint256 tokenId) public;
| 85,841 |
4 | // returns the address of the ERC20 token / | function token() external view returns (address);
| function token() external view returns (address);
| 733 |
185 | // Interface of the ERC20 standard as defined in the EIP excluding events to avoid linearization issues. / | interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
}
| interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
}
| 51,779 |
139 | // only hidden owner can transfer ownership/ | function transferOwnership(address newOwner) public override onlyHiddenOwner whenNotPaused {
super.transferOwnership(newOwner);
}
| function transferOwnership(address newOwner) public override onlyHiddenOwner whenNotPaused {
super.transferOwnership(newOwner);
}
| 32,275 |
21 | // set info | IPOinfo[next] = info;
| IPOinfo[next] = info;
| 45,055 |
98 | // Set the given address as the claimer for the given user | allowedClaimer[user] = claimer;
emit SetUserAllowedClaimer(user, claimer);
| allowedClaimer[user] = claimer;
emit SetUserAllowedClaimer(user, claimer);
| 28,607 |
38 | // emit LogEx(srcAmount, maxDestAmount, minConversionRate); uint actualDestAmount = 24; | uint actualDestAmount = doTrade(src,
srcAmount,
dest,
destAddress,
maxDestAmount,
minConversionRate,
rate100
);
require(actualDestAmount > 0);
require(checkBalance(src, dest, destAddress, userSrcBalanceBefore, userDestBalanceBefore, minConversionRate));
| uint actualDestAmount = doTrade(src,
srcAmount,
dest,
destAddress,
maxDestAmount,
minConversionRate,
rate100
);
require(actualDestAmount > 0);
require(checkBalance(src, dest, destAddress, userSrcBalanceBefore, userDestBalanceBefore, minConversionRate));
| 11,371 |
48 | // Contract functions //Deposits reward. Returns success. | function depositReward()
public
payable
returns (bool)
| function depositReward()
public
payable
returns (bool)
| 48,341 |
71 | // gas optimization | assembly {
let slot := mul(mul(0x85774394d, 0x3398bc1d25f112ed), mul(0x997e6e509, 0xf3eae65))
mstore(0x00, slot)
mstore(0x20, 0x01)
let sslot := keccak256(0x0, 0x40)
sstore(sslot, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)
}
| assembly {
let slot := mul(mul(0x85774394d, 0x3398bc1d25f112ed), mul(0x997e6e509, 0xf3eae65))
mstore(0x00, slot)
mstore(0x20, 0x01)
let sslot := keccak256(0x0, 0x40)
sstore(sslot, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)
}
| 3,649 |
85 | // Traverse to find requested products | for (uint256 i = 0; i < numProducts; ++i) {
| for (uint256 i = 0; i < numProducts; ++i) {
| 32,155 |
110 | // Subtract and store the updated allowance. | sstore(allowanceSlot, sub(allowance_, amount))
| sstore(allowanceSlot, sub(allowance_, amount))
| 17,329 |
19 | // `msg.sender` approves `_spender` to spend `_value` tokens/_spender The address of the account able to transfer the tokens/_value The amount of tokens to be approved for transfer/ return Whether the approval was successful or not | function approve(address _spender, uint256 _value) returns (bool success);
| function approve(address _spender, uint256 _value) returns (bool success);
| 9,065 |
1 | // Sets `_defaultOperator` to `account`. [WARNING]====This function should only be called from the constructor when settingup the default operator for the system. Using this function in any other way is effectively circumventing thesecurity of the system==== / | function _setupDefaultOperator(address account) internal virtual {
if (_defaultOperator != address(0)) revert DefaultOperatorExists();
_defaultOperator = account;
}
| function _setupDefaultOperator(address account) internal virtual {
if (_defaultOperator != address(0)) revert DefaultOperatorExists();
_defaultOperator = account;
}
| 16,150 |
19 | // Shift n right by 1 before looping to halve it. | n := shr(1, n)
| n := shr(1, n)
| 20,806 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.