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
159
// Calculate final price for bulk of tickets _discountDivisor: divisor for the discount (the smaller it is, the greater the discount is) _priceTicket: price of a ticket _numberTickets: number of tickets purchased /
function _calculateTotalPriceForBulkTickets( uint256 _discountDivisor, uint256 _priceTicket, uint256 _numberTickets
function _calculateTotalPriceForBulkTickets( uint256 _discountDivisor, uint256 _priceTicket, uint256 _numberTickets
27,773
356
// Get shared keyreturn Shared key /
function _getSharedKey() internal view override returns(bytes32) { return _sharedKey; }
function _getSharedKey() internal view override returns(bytes32) { return _sharedKey; }
65,273
16
// Dispute, settle with the disputer. Reverts if price not resolved.
int256 resolvedPrice = _oracleGetPrice(assertionId, assertion.identifier, assertion.assertionTime);
int256 resolvedPrice = _oracleGetPrice(assertionId, assertion.identifier, assertion.assertionTime);
22,424
88
// When implementing this contract don't forget to set nftName and nftSymbol. Contract constructor. /
constructor() { supportedInterfaces[0x5b5e139f] = true; // ERC721Metadata }
constructor() { supportedInterfaces[0x5b5e139f] = true; // ERC721Metadata }
52,643
265
// Get a maxCount for each mrId. It is supposed to be called once. /
function getMrMaxCount(uint8 mrId_) public view returns (uint256) { return mrInfos[mrId_].maxCount; }
function getMrMaxCount(uint8 mrId_) public view returns (uint256) { return mrInfos[mrId_].maxCount; }
61,994
18
// Returns an address of the credit account connected to the address of the vault
function getCreditAccount() external view returns (address);
function getCreditAccount() external view returns (address);
6,000
127
// Set new MinCap. _newMinCap new MinCap, /
function setMinCap(uint256 _newMinCap) public onlyOwner isTestMode { require(now < preIcoFinishTime); minCap = _newMinCap; }
function setMinCap(uint256 _newMinCap) public onlyOwner isTestMode { require(now < preIcoFinishTime); minCap = _newMinCap; }
2,836
128
// Returns the total amount of `tokenAddress` that was locked from beginning to end of epoch identified by `epochId`/
function getEpochPoolSize(uint128 epochId) public view returns (uint256) { // Premises: // 1. it's impossible to have gaps of uninitialized epochs // - any deposit or withdraw initialize the current epoch which requires the previous one to be initialized if (epochIsInitialized(epochId)) { return poolSize[epochId].size; } // epochId not initialized and epoch 0 not initialized => there was never any action on this pool if (!epochIsInitialized(0)) { return 0; } // epoch 0 is initialized => there was an action at some point but none that initialized the epochId // which means the current pool size is equal to the current balance of token held by the staking contract IERC20 token = IERC20(stakeToken); return token.balanceOf(address(this)); }
function getEpochPoolSize(uint128 epochId) public view returns (uint256) { // Premises: // 1. it's impossible to have gaps of uninitialized epochs // - any deposit or withdraw initialize the current epoch which requires the previous one to be initialized if (epochIsInitialized(epochId)) { return poolSize[epochId].size; } // epochId not initialized and epoch 0 not initialized => there was never any action on this pool if (!epochIsInitialized(0)) { return 0; } // epoch 0 is initialized => there was an action at some point but none that initialized the epochId // which means the current pool size is equal to the current balance of token held by the staking contract IERC20 token = IERC20(stakeToken); return token.balanceOf(address(this)); }
42,386
84
// EXTERNAL FUNCTIONS (ERC20 INTERFACE) /
function name() public view returns (string memory){ return _name; }
function name() public view returns (string memory){ return _name; }
17,678
111
// Randomness
uint256 timeRestriction=block.timestamp+2;
uint256 timeRestriction=block.timestamp+2;
25,130
12
// Swaps as little as possible of one token for `amountOut` of another along the specified path (reversed)/params The parameters necessary for the multi-hop swap, encoded as `ExactOutputParams` in calldata/ return amountIn The amount of the input token
function exactOutput(ExactOutputParams calldata params) external payable override nonReentrant returns (uint256 amountIn)
function exactOutput(ExactOutputParams calldata params) external payable override nonReentrant returns (uint256 amountIn)
11,320
106
// function to allow admin to claim other ERC20 tokens sent to this contract (by mistake) Admin cannot transfer out reward tokens from this smart contract
function transferAnyERC20Token(address tokenAddress, address recipient, uint amount) external onlyOwner { require (tokenAddress != TRUSTED_TOKEN_ADDRESS || now > contractStartTime.add(ADMIN_CAN_CLAIM_AFTER), "Cannot Transfer Out main tokens!"); require (Token(tokenAddress).transfer(recipient, amount), "Transfer failed!"); }
function transferAnyERC20Token(address tokenAddress, address recipient, uint amount) external onlyOwner { require (tokenAddress != TRUSTED_TOKEN_ADDRESS || now > contractStartTime.add(ADMIN_CAN_CLAIM_AFTER), "Cannot Transfer Out main tokens!"); require (Token(tokenAddress).transfer(recipient, amount), "Transfer failed!"); }
8,640
18
// Set `balance[key]` to `value`.
function setBalance(address key, uint256 value) external onlyOwner { balance[key] = value; }
function setBalance(address key, uint256 value) external onlyOwner { balance[key] = value; }
15,700
22
// stream the rewards
for (uint256 i = 0; i < rewardPoolsCount; ++i) { PoolData storage pool = rewardPools[i]; if (pool.rewardToken == address(0)) { continue; }
for (uint256 i = 0; i < rewardPoolsCount; ++i) { PoolData storage pool = rewardPools[i]; if (pool.rewardToken == address(0)) { continue; }
63,190
2
// name
string name;
string name;
25,775
20
// Cast a vote Emits a {VoteCast} event. /
function castVote(uint256 proposalId, uint8 support) public virtual returns (uint256 balance);
function castVote(uint256 proposalId, uint8 support) public virtual returns (uint256 balance);
1,250
29
// ERC223 Transfer to a contract or externally-owned account
function transfer( address to, uint value, bytes data ) public returns (bool success)
function transfer( address to, uint value, bytes data ) public returns (bool success)
41,643
23
// implementation of ERC20 approve function
function approve(address _spender, uint256 _amount) public returns (bool success) { allowed[msg.sender][_spender] = _amount; Approval(msg.sender, _spender, _amount); return true; }
function approve(address _spender, uint256 _amount) public returns (bool success) { allowed[msg.sender][_spender] = _amount; Approval(msg.sender, _spender, _amount); return true; }
16,458
12
// GToken Overrides // Transfer `tokens` tokens from `src` to `dst` by `spender` spender The address of the account performing the transfer src The address of the source account dst The address of the destination account tokens The number of tokens to transferreturn Whether or not the transfer succeeded /
function transferTokens( address spender, address src, address dst, uint256 tokens
function transferTokens( address spender, address src, address dst, uint256 tokens
3,896
1
// the recipient can close the channel at any time by presenting a/ signed amount from the sender. the recipient will be sent that amount,/ and the remainder will go back to the sender
function close(uint256 amount, bytes memory signature) public { require(msg.sender == recipient); require(isValidSignature(amount, signature)); recipient.transfer(amount); selfdestruct(sender); }
function close(uint256 amount, bytes memory signature) public { require(msg.sender == recipient); require(isValidSignature(amount, signature)); recipient.transfer(amount); selfdestruct(sender); }
27,355
388
// Hook that is called before any transfer of tokens. This includesminting and burning. Calling conditions: - when `from` and `to` are both non-zero, `amount` of ``from``'s tokenswill be to transferred to `to`.- when `from` is zero, `amount` tokens will be minted for `to`.- when `to` is zero, `amount` of ``from``'s tokens will be burned.- `from` and `to` are never both zero. To learn more about hooks, head to xref:ROOT:extending-contracts.adocusing-hooks[Using Hooks]. / Present in ERC777
function _beforeTokenTransfer( address from_, address to_, uint256 amount_
function _beforeTokenTransfer( address from_, address to_, uint256 amount_
23,156
17
// underlying
uint256 amount1In = underlyingBalance > cache1 - quote ? underlyingBalance - (cache1 - quote) : 0; require( amount0In > 0 || amount1In > 0, "PrimitiveV2: RETURNED_AMOUNT_ZERO" );
uint256 amount1In = underlyingBalance > cache1 - quote ? underlyingBalance - (cache1 - quote) : 0; require( amount0In > 0 || amount1In > 0, "PrimitiveV2: RETURNED_AMOUNT_ZERO" );
22,711
48
// Emitted when a buyer is refunded.
event Refund(address indexed buyer, uint256 amount);
event Refund(address indexed buyer, uint256 amount);
5,826
60
// Otherwise, create reinvested tree node (find referrer and create new node, transfer applies to a new referrer), recursively
address refReferrerAddress = findReferrer(3, level, referrerAddress); setTo3Matrix(referrerAddress, refReferrerAddress, level, cost); Reinvest(referrerAddress, refReferrerAddress, 3, level);
address refReferrerAddress = findReferrer(3, level, referrerAddress); setTo3Matrix(referrerAddress, refReferrerAddress, level, cost); Reinvest(referrerAddress, refReferrerAddress, 3, level);
3,394
2
// Ignore those exceptions so that we don't break tests relying on Context likea android.test.mock.MockContext or a android.content.ContextWrapper with anull base Context. /
Log.w(TAG, "Failure while trying to obtain Context class loader. " +
Log.w(TAG, "Failure while trying to obtain Context class loader. " +
39,953
10
// See {_setURI}. /
function __ERC1155Rounds_init() internal onlyInitializing { __ERC1155Rounds_init_unchained(); }
function __ERC1155Rounds_init() internal onlyInitializing { __ERC1155Rounds_init_unchained(); }
13,454
44
// verify mint limit
if(mintLimit != 0) { require(mints[msg.sender] + _amount <= mintLimit, "mint limit reached"); }
if(mintLimit != 0) { require(mints[msg.sender] + _amount <= mintLimit, "mint limit reached"); }
34,643
85
// {IERC20-approve}, and its usage is discouraged. Whenever possible, use {safeIncreaseAllowance} and{safeDecreaseAllowance} instead. /
function safeApprove(IERC20 token, address spender, uint256 value) internal {
function safeApprove(IERC20 token, address spender, uint256 value) internal {
10,184
10
// /Intiate New Package of RawMatrials by Supplier/Splr Supplier Ethereum Network Address/Des Description of RawMatrials/FN Factory Name/Loc Factory Location/Quant Number of units in a package/Rcvr Manufacturer Ethereum Network Address
constructor ( address Splr, bytes32 Des, bytes32 FN, bytes32 Loc, uint Quant, address Rcvr ) public { Owner = Splr; productid = address(this);
constructor ( address Splr, bytes32 Des, bytes32 FN, bytes32 Loc, uint Quant, address Rcvr ) public { Owner = Splr; productid = address(this);
29,460
4
// Mapping from owner to id of Profile
mapping (uint => address) public profileToOwner;
mapping (uint => address) public profileToOwner;
39,253
49
// solium-disable-next-line arg-overflow
return _createSector(x, y, beneficiary, "");
return _createSector(x, y, beneficiary, "");
5,642
113
// update order values, taken order is always first order
(isSuccess,) = list.updateWithPositionHint(orderId, orderSrcAmount, orderDstAmount, HEAD_ID); require(isSuccess);
(isSuccess,) = list.updateWithPositionHint(orderId, orderSrcAmount, orderDstAmount, HEAD_ID); require(isSuccess);
26,470
12
// Admin-only function that sets the price feed for the gas token for the given ERC20. _pricedERC20 The ERC20 that is associated to the given price feed and `_paymentERC20` _priceFeed The address of the price feed /
function setERC20PriceFeedForGasToken(address _pricedERC20, address _priceFeed) external;
function setERC20PriceFeedForGasToken(address _pricedERC20, address _priceFeed) external;
19,508
22
// The total interest owed by the borrower for the loan, reduces on loan repayments
uint256 interestOwed;
uint256 interestOwed;
47,557
240
// Start with the 0th power
uint256 realResult = REAL_ONE; while (tempExponent != 0) {
uint256 realResult = REAL_ONE; while (tempExponent != 0) {
30,218
44
// Generate two random wings on the body.
uint256 firstWingLength = (_getRandom(_id, 3002) % (_bodyLength - 2)); uint256 firstWing = _startingX + 3 * firstWingLength; uint256 secondWing = firstWing + 3 * 2 + 3 * (_getRandom(_id, 3003) % (_bodyLength - (firstWingLength + 2))); string memory wings; for (uint256 i = 0; i < wingHeight; i++) { wings = string(abi.encodePacked( wings, "<rect width=\"3%\" height=\"3%\" x=\"", (firstWing).toString(),
uint256 firstWingLength = (_getRandom(_id, 3002) % (_bodyLength - 2)); uint256 firstWing = _startingX + 3 * firstWingLength; uint256 secondWing = firstWing + 3 * 2 + 3 * (_getRandom(_id, 3003) % (_bodyLength - (firstWingLength + 2))); string memory wings; for (uint256 i = 0; i < wingHeight; i++) { wings = string(abi.encodePacked( wings, "<rect width=\"3%\" height=\"3%\" x=\"", (firstWing).toString(),
58,604
1
// uint nEntities = 0;
uint nCertificates = 0; uint nSignatures = 0;
uint nCertificates = 0; uint nSignatures = 0;
9,888
306
// returns the redirected balance of the user. The redirected balance is the balance redirected by other accounts to the user, that is accrueing interest for him._user address of the user return the total redirected balance/
function getRedirectedBalance(address _user) external view returns(uint256) { return redirectedBalances[_user]; }
function getRedirectedBalance(address _user) external view returns(uint256) { return redirectedBalances[_user]; }
81,043
448
// variable == IPriceOracle.Variable.INVARIANT
return _instLogInvariant(sample);
return _instLogInvariant(sample);
24,235
7
// Encode bytes usig hex encoding
for(uint i=0;i<20;i++){ uint8 byteValue = uint8(value[i]); strBytes[2 + (i<<1)] = encode((byteValue >> 4) & 0x0f); strBytes[3 + (i<<1)] = encode(byteValue & 0x0f); }
for(uint i=0;i<20;i++){ uint8 byteValue = uint8(value[i]); strBytes[2 + (i<<1)] = encode((byteValue >> 4) & 0x0f); strBytes[3 + (i<<1)] = encode(byteValue & 0x0f); }
10,357
1
// A map of addresses that are authorised to register domains.
mapping(address => bool) public controllers;
mapping(address => bool) public controllers;
47,364
187
// Full ERC721 Token This implementation includes all the required and some optional functionality of the ERC721 standardMoreover, it includes approve all functionality using operator terminology./
contract ERC721Full is ERC721, ERC721Enumerable, ERC721Metadata { constructor (string memory name, string memory symbol) public ERC721Metadata(name, symbol) { // solhint-disable-previous-line no-empty-blocks } }
contract ERC721Full is ERC721, ERC721Enumerable, ERC721Metadata { constructor (string memory name, string memory symbol) public ERC721Metadata(name, symbol) { // solhint-disable-previous-line no-empty-blocks } }
53,295
258
// Updates the fee contribution multiplier required for calling trainEquipment().
function setEquipmentTrainingFeeMultiplier(uint _newEquipmentTrainingFeeMultiplier) onlyOwner external { equipmentTrainingFeeMultiplier = _newEquipmentTrainingFeeMultiplier; }
function setEquipmentTrainingFeeMultiplier(uint _newEquipmentTrainingFeeMultiplier) onlyOwner external { equipmentTrainingFeeMultiplier = _newEquipmentTrainingFeeMultiplier; }
41,424
143
// Calculate receiver balance initial receive is full value
uint256 receives = _value; uint256 burn = 0; uint256 shuf = 0;
uint256 receives = _value; uint256 burn = 0; uint256 shuf = 0;
53,194
82
// Function to add Ether in the contract /
function fundContractForRefund()public payable{ }
function fundContractForRefund()public payable{ }
22,070
466
// bytes4(keccak256("isValidSignature(bytes32,bytes)")
bytes4 constant internal ERC1271_MAGICVALUE = 0x1626ba7e; function isValidSignature( bytes32 _hash, bytes memory _signature) public view virtual returns (bytes4 magicValueB32);
bytes4 constant internal ERC1271_MAGICVALUE = 0x1626ba7e; function isValidSignature( bytes32 _hash, bytes memory _signature) public view virtual returns (bytes4 magicValueB32);
32,337
11
// Determine if rewards are claimable
bool public rewardsClaimable = false;
bool public rewardsClaimable = false;
12,487
10
// ERC20 approve
function approve(address _spender, uint256 _tokens) public returns (bool) { allowances[msg.sender][_spender] = _tokens; emit Approval(msg.sender, _spender, _tokens); return true; }
function approve(address _spender, uint256 _tokens) public returns (bool) { allowances[msg.sender][_spender] = _tokens; emit Approval(msg.sender, _spender, _tokens); return true; }
18,650
10
// 提領
function withdrawal() public available payable { if(isNewUser(msg.sender)) { users[msg.sender] = User(msg.sender, 0, 0, withdrawalAmount, now, false); } else { if(now > users[msg.sender].withdrawalAt + 1 days) users[msg.sender].withdrawal += withdrawalAmount; users[msg.sender].withdrawalAt = now; } msg.sender.transfer(withdrawalAmount); emit UserWithdrawal(msg.sender, users[msg.sender], this.balance); }
function withdrawal() public available payable { if(isNewUser(msg.sender)) { users[msg.sender] = User(msg.sender, 0, 0, withdrawalAmount, now, false); } else { if(now > users[msg.sender].withdrawalAt + 1 days) users[msg.sender].withdrawal += withdrawalAmount; users[msg.sender].withdrawalAt = now; } msg.sender.transfer(withdrawalAmount); emit UserWithdrawal(msg.sender, users[msg.sender], this.balance); }
45,765
12
// Get all validators with power.
function getAllValidatorPowers() external view returns(ValidatorWithPower[] memory) { return getValidators(0, getNumberOfValidators()); }
function getAllValidatorPowers() external view returns(ValidatorWithPower[] memory) { return getValidators(0, getNumberOfValidators()); }
31,217
10
// Decode a fixed16 (half-precision) numeric value from a Witnet.Result as an `int32` value./Due to the lack of support for floating or fixed point arithmetic in the EVM, this method offsets all values./ by 5 decimal orders so as to get a fixed precision of 5 decimal positions, which should be OK for most `fixed16`./ use cases. In other words, the output of this method is 10,000 times the actual value, encoded into an `int32`./_result An instance of Witnet.Result./ return The `int128` decoded from the Witnet.Result.
function asFixed16(Witnet.Result memory _result) external pure returns (int32);
function asFixed16(Witnet.Result memory _result) external pure returns (int32);
35,853
149
// Returns the symbol of the token, usually a shorter version of the name./
function symbol() external view returns (string memory);
function symbol() external view returns (string memory);
14,122
186
// ============ Structs ============ //The base definition of a SetToken Positioncomponent Address of token in the Position moduleIf not in default state, the address of associated module unitEach unit is theof components per 10^18 of a SetToken positionState Position ENUM. Default is 0; External is 1 dataArbitrary data /
struct Position { address component; address module; int256 unit; uint8 positionState; bytes data; }
struct Position { address component; address module; int256 unit; uint8 positionState; bytes data; }
1,475
104
// extend a lock with a new unlock date, _index and _lockID ensure the correct lock is changedthis prevents errors when a user performs multiple tx per block possibly with varying gas prices /
function relock (address _lpToken, uint256 _index, uint256 _lockID, uint256 _unlock_date) external nonReentrant { require(_unlock_date < 10000000000, 'TIMESTAMP INVALID'); // prevents errors when timestamp entered in milliseconds uint256 lockID = users[msg.sender].locksForToken[_lpToken][_index]; TokenLock storage userLock = tokenLocks[_lpToken][lockID]; require(lockID == _lockID && userLock.owner == msg.sender, 'LOCK MISMATCH'); // ensures correct lock is affected require(userLock.unlockDate < _unlock_date, 'UNLOCK BEFORE'); uint256 liquidityFee = userLock.amount.mul(gFees.liquidityFee).div(1000); uint256 amountLocked = userLock.amount.sub(liquidityFee); userLock.amount = amountLocked; userLock.unlockDate = _unlock_date; // send univ2 fee to dev address TransferHelper.safeTransfer(_lpToken, devaddr, liquidityFee); }
function relock (address _lpToken, uint256 _index, uint256 _lockID, uint256 _unlock_date) external nonReentrant { require(_unlock_date < 10000000000, 'TIMESTAMP INVALID'); // prevents errors when timestamp entered in milliseconds uint256 lockID = users[msg.sender].locksForToken[_lpToken][_index]; TokenLock storage userLock = tokenLocks[_lpToken][lockID]; require(lockID == _lockID && userLock.owner == msg.sender, 'LOCK MISMATCH'); // ensures correct lock is affected require(userLock.unlockDate < _unlock_date, 'UNLOCK BEFORE'); uint256 liquidityFee = userLock.amount.mul(gFees.liquidityFee).div(1000); uint256 amountLocked = userLock.amount.sub(liquidityFee); userLock.amount = amountLocked; userLock.unlockDate = _unlock_date; // send univ2 fee to dev address TransferHelper.safeTransfer(_lpToken, devaddr, liquidityFee); }
39,979
21
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the benefit is lost if 'b' is also tested. See: https:github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) { return 0; }
if (a == 0) { return 0; }
4,567
18
// avoid an SLOAD by using the swap return data
amountIn = exactOutputInternal( params.amountOut, params.recipient, params.sqrtPriceLimitX96, SwapCallbackData({ path: abi.encodePacked( params.tokenOut, params.fee, params.tokenIn ),
amountIn = exactOutputInternal( params.amountOut, params.recipient, params.sqrtPriceLimitX96, SwapCallbackData({ path: abi.encodePacked( params.tokenOut, params.fee, params.tokenIn ),
50,236
376
// truncates it on the right.
return address(bytes20(bytes32(leaf)));
return address(bytes20(bytes32(leaf)));
5,038
50
// Converts a `uint` to its ASCII `string` decimal representation. /
function toString(uint value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint temp = value; uint digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint(value % 10))); value /= 10; } return string(buffer); }
function toString(uint value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint temp = value; uint digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint(value % 10))); value /= 10; } return string(buffer); }
33,553
13
// set old high score to new high score
highScore = playerScore;
highScore = playerScore;
11,906
8
// Remaining tokens third party spender has to send/self Stored token from token contract/_owner Address of token holder/_spender Address of authorized spender/ return remaining Number of tokens spender has left in owner&39;s account
function allowance(TokenStorage storage self, address _owner, address _spender) constant returns (uint256 remaining) { return self.allowed[_owner][_spender]; }
function allowance(TokenStorage storage self, address _owner, address _spender) constant returns (uint256 remaining) { return self.allowed[_owner][_spender]; }
43,285
79
// Hook exectued before withdrawingamount Amount to withdraw/
function beforeWithdraw(uint256 amount) internal {} /** * @dev Hook exectued after depositing * @param amount Amount deposited */ function afterDeposit(uint256 amount) internal {} /** * @dev Hook executed before each transfer * @param from Sender address * @param to Receiver address * @param amount Amount to transfer */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal isInitialized whenNotPaused override virtual { super._beforeTokenTransfer(from, to, amount); }
function beforeWithdraw(uint256 amount) internal {} /** * @dev Hook exectued after depositing * @param amount Amount deposited */ function afterDeposit(uint256 amount) internal {} /** * @dev Hook executed before each transfer * @param from Sender address * @param to Receiver address * @param amount Amount to transfer */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal isInitialized whenNotPaused override virtual { super._beforeTokenTransfer(from, to, amount); }
38,077
7,048
// 3526
entry "dickheadedly" : ENG_ADVERB
entry "dickheadedly" : ENG_ADVERB
24,362
2
// Invalid address
error InvalidAddress(); function initialize( address caller_, bytes32[] calldata commands, bytes[] calldata state ) external payable { if (initialized) revert AlreadyInit(); caller = caller_; if (commands.length != 0) {
error InvalidAddress(); function initialize( address caller_, bytes32[] calldata commands, bytes[] calldata state ) external payable { if (initialized) revert AlreadyInit(); caller = caller_; if (commands.length != 0) {
5,464
15
// if all clients ready, trigger oracle
if (readyCount == clientCount) { createRandomNumber(); }
if (readyCount == clientCount) { createRandomNumber(); }
7,442
7
// The minimum price that the auctionAsset can be sold for./ Can be set to 0.
uint256 public immutable reservePrice; address public highestBidder = address(0); uint256 public highestBid = 0; uint256 public commitPhaseEnd; uint256 public revealPhaseEnd;
uint256 public immutable reservePrice; address public highestBidder = address(0); uint256 public highestBid = 0; uint256 public commitPhaseEnd; uint256 public revealPhaseEnd;
32,700
6
// A helper modifier to check if the operator approval is allowed. /
modifier onlyAllowedOperatorApproval(address operator) virtual { _checkFilterOperator(operator); _; }
modifier onlyAllowedOperatorApproval(address operator) virtual { _checkFilterOperator(operator); _; }
18,953
2
// uint idFichero;identificacion del fichero se utiliza como index del array
address userAddress; // usuario que registra el expediente uint fecha; // fecha cuando se registra el expediente bytes32 hash; // hash del fichero
address userAddress; // usuario que registra el expediente uint fecha; // fecha cuando se registra el expediente bytes32 hash; // hash del fichero
32,378
8
// Paused tokens list, deposits are impossible to create for paused tokens
mapping(uint16 => bool) public pausedTokens;
mapping(uint16 => bool) public pausedTokens;
15,404
31
// communityCreated
event communityCreated( address indexed _leader, uint _communityID, string _name );
event communityCreated( address indexed _leader, uint _communityID, string _name );
15,764
72
// capital-related events
event CapitalAdded(uint time, address indexed sender, uint amount); event CapitalRemoved(uint time, address indexed recipient, uint amount); event CapitalRaised(uint time, uint amount);
event CapitalAdded(uint time, address indexed sender, uint amount); event CapitalRemoved(uint time, address indexed recipient, uint amount); event CapitalRaised(uint time, uint amount);
17,800
23
// nv = nfvf + nxvx(n - dn)v = nfvf + (nx - dx)vx(n - dn)v / (nfvf) = ncr =>nv - dnv = ncrnfvfnv - dxvx = ncrnfvf =>dn = (nv - ncrnfvf) / vdx = (nv - ncrnfvf) / vx
uint256 _baseVal = state.baseSupply.mul(state.baseNav).mul(PRECISION); uint256 _fVal = _newCollateralRatio.mul(state.fSupply).mul(state.fNav); if (_baseVal > _fVal) { uint256 _delta = _baseVal - _fVal; _maxXTokenRedeemable = _delta.div(state.xNav.mul(PRECISION)); _maxBaseOut = _delta.div(state.baseNav.mul(PRECISION)); }
uint256 _baseVal = state.baseSupply.mul(state.baseNav).mul(PRECISION); uint256 _fVal = _newCollateralRatio.mul(state.fSupply).mul(state.fNav); if (_baseVal > _fVal) { uint256 _delta = _baseVal - _fVal; _maxXTokenRedeemable = _delta.div(state.xNav.mul(PRECISION)); _maxBaseOut = _delta.div(state.baseNav.mul(PRECISION)); }
41,197
457
// indexFrom index in global warrior storage (aka warriorId), from this index(including), warriors data will be gatheredcount Number of warriors to include in packed data return warriorsData packed warrior data return stepSize number of fields in single warrior data /
function getWarriorsFromIndex(uint256 indexFrom, uint256 count) external view returns (uint256[] memory warriorsData, uint256 stepSize) { stepSize = 6; //check length uint256 lenght = (warriors.length - indexFrom >= count ? count : warriors.length - indexFrom); warriorsData = new uint256[](lenght * stepSize); for(uint256 i = 0; i < lenght; i ++) { _setWarriorData(warriorsData, warriors[indexFrom + i], i * stepSize); } }
function getWarriorsFromIndex(uint256 indexFrom, uint256 count) external view returns (uint256[] memory warriorsData, uint256 stepSize) { stepSize = 6; //check length uint256 lenght = (warriors.length - indexFrom >= count ? count : warriors.length - indexFrom); warriorsData = new uint256[](lenght * stepSize); for(uint256 i = 0; i < lenght; i ++) { _setWarriorData(warriorsData, warriors[indexFrom + i], i * stepSize); } }
66,402
251
// azimuth: points data storage contract.
Azimuth public azimuth;
Azimuth public azimuth;
57,695
4
// Return the number of transactions issued by the given external account or the account sequence number of the given contract
function getTransactionCount(address account) external view returns (uint256);
function getTransactionCount(address account) external view returns (uint256);
20,722
32
// function for unstaking all the tokens
function unstakeAll() external { StakeData storage stakeData = StakersData[_msgSender()]; uint256 amount = stakeData.amount; unstakeTokens(amount); }
function unstakeAll() external { StakeData storage stakeData = StakersData[_msgSender()]; uint256 amount = stakeData.amount; unstakeTokens(amount); }
58,443
26
// Checks that the call responded with a 256 bit integer.// When a call is unsuccessful the return data is expected to be error data. The data is/ rethrown to bubble up the error to the caller.// When a call is successful it is expected that the return data is exactly 32 bytes in/ length. Any other return size is treated as an error. When the return data is non-empty,/ it is expected that the return data is a unsigned 256 bit integer.//status A flag indicating if the call has reverted or not.// return value The returned 256 bit integer value./
function expectUInt256Response(bool status) private pure returns (uint256 value, bool success) { assembly { if iszero(status) { returndatacopy(0, 0, returndatasize()) revert(0, returndatasize()) } switch returndatasize() case 32 { returndatacopy(0, 0, returndatasize()) value := mload(0) success := 1 } default { success := 0 } } }
function expectUInt256Response(bool status) private pure returns (uint256 value, bool success) { assembly { if iszero(status) { returndatacopy(0, 0, returndatasize()) revert(0, returndatasize()) } switch returndatasize() case 32 { returndatacopy(0, 0, returndatasize()) value := mload(0) success := 1 } default { success := 0 } } }
20,084
0
// Withdraw asset. _assetAddress Asset to be withdrawn. /
function withdraw(address _assetAddress) public onlyOwner { uint assetBalance; if (_assetAddress == ETHER) { address self = address(this); // workaround for a possible solidity bug assetBalance = self.balance; msg.sender.transfer(assetBalance); } else { assetBalance = ERC20(_assetAddress).balanceOf(address(this)); ERC20(_assetAddress).safeTransfer(msg.sender, assetBalance); } emit LogWithdraw(msg.sender, _assetAddress, assetBalance); }
function withdraw(address _assetAddress) public onlyOwner { uint assetBalance; if (_assetAddress == ETHER) { address self = address(this); // workaround for a possible solidity bug assetBalance = self.balance; msg.sender.transfer(assetBalance); } else { assetBalance = ERC20(_assetAddress).balanceOf(address(this)); ERC20(_assetAddress).safeTransfer(msg.sender, assetBalance); } emit LogWithdraw(msg.sender, _assetAddress, assetBalance); }
9,146
176
// Minted amount does not exceed 8,5% per annum. Thus, minting does not greatly increase the total supply and does not cause significant inflation and depreciation of the starcoin.
_mintedAmount = (block.timestamp - sCVars.lastMint)*totalSupply/(12*31536000);//31536000 seconds in year sCVars.balanceOf[msg.sender] += _mintedAmount; totalSupply += _mintedAmount; sCVars.lastMint = block.timestamp; Transfer(0, this, _mintedAmount); Transfer(this, msg.sender, _mintedAmount);
_mintedAmount = (block.timestamp - sCVars.lastMint)*totalSupply/(12*31536000);//31536000 seconds in year sCVars.balanceOf[msg.sender] += _mintedAmount; totalSupply += _mintedAmount; sCVars.lastMint = block.timestamp; Transfer(0, this, _mintedAmount); Transfer(this, msg.sender, _mintedAmount);
50,891
148
// Pull aTokens from user
_pullAToken( collateralAsset, collateralReserveData.aTokenAddress, msg.sender, amounts[0], permitSignature );
_pullAToken( collateralAsset, collateralReserveData.aTokenAddress, msg.sender, amounts[0], permitSignature );
46,890
8
// Getter for the address of the payee number `index`. /
function payee(uint256 index) public view returns (address) { return _payees[index]; }
function payee(uint256 index) public view returns (address) { return _payees[index]; }
2,920
1
// Mint one token for user
uint _tokenId = totalSupply() + 1; _mint(_for, _tokenId);
uint _tokenId = totalSupply() + 1; _mint(_for, _tokenId);
35,864
90
// The tokenId of the next token to be minted.
uint256 internal _currentIndex;
uint256 internal _currentIndex;
25,907
11
// Emitted when `value` tokens are moved from one account (`from`) toanother (`to`). Note that `value` may be zero. /
event Transfer(address indexed from, address indexed to, uint256 value);
event Transfer(address indexed from, address indexed to, uint256 value);
1,101
36
// owner can transfer out any accidentally sent ERC20 tokens /
function transferAnyERC20Token(address from, uint amount) public onlyOwnerAllowed returns (bool success) { return ERC20(from).transfer(owner, amount); }
function transferAnyERC20Token(address from, uint amount) public onlyOwnerAllowed returns (bool success) { return ERC20(from).transfer(owner, amount); }
39,185
93
// It allows the admin to update start and end times This function is only callable by owner. _startTime: the new start time _endTime: the new end time /
function updateStartAndEndTimes(uint256 _startTime, uint256 _endTime) external onlyOwner { require(block.timestamp > endTime, "Pool has started"); require(_startTime < _endTime, "Invalid start and end time"); endTime = _endTime; if (_startTime > block.timestamp) { startTime = _startTime; } emit NewStartAndEndTimes(_startTime, _endTime); }
function updateStartAndEndTimes(uint256 _startTime, uint256 _endTime) external onlyOwner { require(block.timestamp > endTime, "Pool has started"); require(_startTime < _endTime, "Invalid start and end time"); endTime = _endTime; if (_startTime > block.timestamp) { startTime = _startTime; } emit NewStartAndEndTimes(_startTime, _endTime); }
35,142
25
//
if(showFundsInWei == true){ return( fundingGoal, amountRaised, amountWithdrawn , timeRemainingInMin, buyPrice_, fundingGoalReached); }
if(showFundsInWei == true){ return( fundingGoal, amountRaised, amountWithdrawn , timeRemainingInMin, buyPrice_, fundingGoalReached); }
21,258
1
// Note that the first parameter is of type "storage reference" and thus only its storage address and not its contents is passed as part of the call.This is a special feature of library functions.It is idiomatic to call the first parameter 'self', if the function can be seen as a method of that object.
function insert(Data storage self, uint value) public returns (bool) { if (self.flags[value]) return false; // already there self.flags[value] = true; return true; }
function insert(Data storage self, uint value) public returns (bool) { if (self.flags[value]) return false; // already there self.flags[value] = true; return true; }
42,680
17
// Update the address of the base task proxy contract _newTaskContract Address of the new task contract /
function updateTaskContract(address _newTaskContract) external onlyOwner { taskContractAddress = _newTaskContract; }
function updateTaskContract(address _newTaskContract) external onlyOwner { taskContractAddress = _newTaskContract; }
20,642
37
// Decrease the amount of tokens that an owner allowed to a spender.approve should be called when allowed_[_spender] == 0. To decrementallowed value is better to use this function to avoid 2 calls (and wait untilthe first transaction is mined)From MonolithDAO Token.solEmits an Approval event. spender The address which will spend the funds. subtractedValue The amount of tokens to decrease the allowance by. /
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = _allowed[msg.sender][spender].sub(subtractedValue); //injected INTEGER OVERFLOW OR UNDERFLOW emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; }
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = _allowed[msg.sender][spender].sub(subtractedValue); //injected INTEGER OVERFLOW OR UNDERFLOW emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; }
13,928
0
// string private constant _NAME = ' abiEncoderTokenIdentifier: ';void getter signatures, these signatures are always the same, so precompute them
bytes public constant SIG_NAME = abi.encodeWithSignature('name()'); bytes public constant SIG_SYMBOL = abi.encodeWithSignature('symbol()');
bytes public constant SIG_NAME = abi.encodeWithSignature('name()'); bytes public constant SIG_SYMBOL = abi.encodeWithSignature('symbol()');
15,215
2
// Configuration of purchase limits.
SellerConfig public sellerConfig;
SellerConfig public sellerConfig;
9,006
7
// The percentage of platform fees (1%) taken off of active assets over a year. /
uint256 public constant PLATFORM_FEE = 1_00;
uint256 public constant PLATFORM_FEE = 1_00;
43,650
24
// broker acts in the name of 'from' address so broker needs to have permission to transfer from/this way we may give permissions to brokering smart contracts while investors do not have permissions/to transfer. 'to' address requires standard transfer to permission
function transferFrom(address from, address to, uint256 amount) public onlyAllowedTransferFrom(msg.sender) onlyAllowedTransferTo(to) returns (bool success)
function transferFrom(address from, address to, uint256 amount) public onlyAllowedTransferFrom(msg.sender) onlyAllowedTransferTo(to) returns (bool success)
29,864
5
// Divid uint256 values, throw in case of overflow.a first value numerator b second value denominatorreturn a / b /
function safeDiv(uint256 a, uint256 b) internal returns (uint256) { assert(b != 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; }
function safeDiv(uint256 a, uint256 b) internal returns (uint256) { assert(b != 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; }
25,367
1
// Allows users with the admin role togrant/revoke the admin role from other usersParams:_admin: address of the first admin /
constructor(address _admin) ERC1155("") { _setupRole(ROLE_ADMIN, _admin); _setRoleAdmin(ROLE_ADMIN, ROLE_ADMIN); }
constructor(address _admin) ERC1155("") { _setupRole(ROLE_ADMIN, _admin); _setRoleAdmin(ROLE_ADMIN, ROLE_ADMIN); }
62,155
437
// set locked cover note amountagainst a cover Id coverId coverId of Cover amount amount of nxm to be locked /
function setDepositCNAmount(uint coverId, uint amount) public onlyInternal { depositedCN[coverId].amount = amount; }
function setDepositCNAmount(uint coverId, uint amount) public onlyInternal { depositedCN[coverId].amount = amount; }
54,650
190
// Set a new owner.
function setOwner(address newOwner) external;
function setOwner(address newOwner) external;
15,794
12
// Token -> cToken
ICToken cToken = ICToken(cTokenAddress); require(cToken.mint(sellAmount) == COMPOUND_SUCCESS_CODE, "MixinCompound/FAILED_TO_MINT_CTOKEN");
ICToken cToken = ICToken(cTokenAddress); require(cToken.mint(sellAmount) == COMPOUND_SUCCESS_CODE, "MixinCompound/FAILED_TO_MINT_CTOKEN");
41,935
35
// Returns the number of editions allowed to mint (max_uint256 when open edition)
function numberCanMint() public view override returns (uint256) { // Return max int if open edition if (editionSize == 0) { return type(uint256).max; } // atEditionId is one-indexed hence the need to remove one here return editionSize + 1 - atEditionId.current(); }
function numberCanMint() public view override returns (uint256) { // Return max int if open edition if (editionSize == 0) { return type(uint256).max; } // atEditionId is one-indexed hence the need to remove one here return editionSize + 1 - atEditionId.current(); }
42,397
70
// executes the ERC20 token's `transfer` function and reverts upon failurethe main purpose of this function is to prevent a non standard ERC20 tokenfrom failing silently_token ERC20 token address _totarget address _value transfer amount /
function safeTransfer( IERC20Token _token, address _to, uint256 _value
function safeTransfer( IERC20Token _token, address _to, uint256 _value
38,203