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
18
// Calculate tokens to sell
uint256 weiAmount = msg.value; uint256 tokens = weiAmount.mul(RATE); BoughtTokens(msg.sender, tokens);
uint256 weiAmount = msg.value; uint256 tokens = weiAmount.mul(RATE); BoughtTokens(msg.sender, tokens);
66,609
10
// Requests a new price. identifier price identifier being requested. timestamp timestamp of the price being requested. ancillaryData ancillary data representing additional args being passed with the price request. currency ERC20 token used for payment of rewards and fees. Must be approved for use with the DVM. reward reward offered to a successful proposer. Will be pulled from the caller. Note: this can be 0,which could make sense if the contract requests and proposes the value in the same call orprovides its own reward system.return totalBond default bond (final fee) + final fee that the proposer and disputer will be required
function requestPrice( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, IERC20 currency, uint256 reward
function requestPrice( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, IERC20 currency, uint256 reward
22,482
33
// NOTE: Only the admin can call this function. See {ProxyAdmin-getProxyAdmin}.TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the`0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103` /
function admin() external override ifAdmin returns (address) { return _admin(); }
function admin() external override ifAdmin returns (address) { return _admin(); }
78,724
327
// Ensure that the sender is the user to act on behalf of or someone with the required permission_user Address of the user to act on behalf of/
function _authenticateSender(address _user) internal view { require(_isSenderAllowed(_user), ERROR_SENDER_NOT_ALLOWED); }
function _authenticateSender(address _user) internal view { require(_isSenderAllowed(_user), ERROR_SENDER_NOT_ALLOWED); }
39,820
80
// retrieve stable coins total staked in epoch
uint valueUsdc = _staking.getEpochPoolSize(_usdc, epochId).mul(10 ** 12); // for usdc which has 6 decimals add a 10**12 to get to a common ground uint valueSusd = _staking.getEpochPoolSize(_susd, epochId); uint valueDai = _staking.getEpochPoolSize(_dai, epochId); uint valueUsdt = _staking.getEpochPoolSize(_usdt, epochId).mul(10 ** 12); // for usdt which has 6 decimals add a 10**12 to get to a common ground return valueUsdc.add(valueSusd).add(valueDai).add(valueUsdt);
uint valueUsdc = _staking.getEpochPoolSize(_usdc, epochId).mul(10 ** 12); // for usdc which has 6 decimals add a 10**12 to get to a common ground uint valueSusd = _staking.getEpochPoolSize(_susd, epochId); uint valueDai = _staking.getEpochPoolSize(_dai, epochId); uint valueUsdt = _staking.getEpochPoolSize(_usdt, epochId).mul(10 ** 12); // for usdt which has 6 decimals add a 10**12 to get to a common ground return valueUsdc.add(valueSusd).add(valueDai).add(valueUsdt);
26,389
13
// ------------------------------------------------------------/ CHECKS/ ------------------------------------------------------------
if (syDesired == 0 || ptDesired == 0) revert Errors.MarketZeroAmountsInput(); if (MiniHelpers.isExpired(market.expiry, blockTime)) revert Errors.MarketExpired();
if (syDesired == 0 || ptDesired == 0) revert Errors.MarketZeroAmountsInput(); if (MiniHelpers.isExpired(market.expiry, blockTime)) revert Errors.MarketExpired();
22,463
131
// External functions // Funds `_amount` of tokens from ClaimsManager to target account _amount - amount of rewards toadd to stake _stakerAccount - address of staker /
function stakeRewards(uint256 _amount, address _stakerAccount) external { _requireIsInitialized(); _requireClaimsManagerAddressIsSet(); require( msg.sender == claimsManagerAddress, "Staking: Only callable from ClaimsManager" ); _stakeFor(_stakerAccount, msg.sender, _amount); this.updateClaimHistory(_amount, _stakerAccount); }
function stakeRewards(uint256 _amount, address _stakerAccount) external { _requireIsInitialized(); _requireClaimsManagerAddressIsSet(); require( msg.sender == claimsManagerAddress, "Staking: Only callable from ClaimsManager" ); _stakeFor(_stakerAccount, msg.sender, _amount); this.updateClaimHistory(_amount, _stakerAccount); }
7,376
32
// Modular function to set Wrapped to Karma path
function setWrappedToKarmaPath(address[] memory _path) external onlyAdmin { require (_path[0] == wrapped && _path[_path.length - 1] == karma, "!path"); wrappedToKarmaPath = _path; emit SetWrappedToKarmaPath(_path); }
function setWrappedToKarmaPath(address[] memory _path) external onlyAdmin { require (_path[0] == wrapped && _path[_path.length - 1] == karma, "!path"); wrappedToKarmaPath = _path; emit SetWrappedToKarmaPath(_path); }
25,030
45
// We don't provide an error message here, as we use it to return the estimate solium-disable-next-line error-reason
require(execute(to, value, data, operation, gasleft())); uint256 requiredGas = startGas - gasleft();
require(execute(to, value, data, operation, gasleft())); uint256 requiredGas = startGas - gasleft();
29,073
37
// Wrap ether
weth.deposit{value: amountIn}();
weth.deposit{value: amountIn}();
4,246
117
// Deposit LP tokens to MasterChef for VEMP allocation.
function deposit(address _user, uint256 _amount) public { PoolInfo storage pool = poolInfo; UserInfo storage user = userInfo[_user]; updatePool(); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accVEMPPerShare).div(1e12).sub(user.rewardDebt); safeVEMPTransfer(_user, pending); uint256 LPReward = user.amount.mul(pool.accLPPerShare).div(1e12).sub(user.rewardLPDebt); pool.lpToken.safeTransfer(_user, LPReward); pool.lastLPRewardBalance = pool.lpToken.balanceOf(address(this)).sub(totalLPStaked.sub(totalLPUsedForPurchase)); } pool.lpToken.safeTransferFrom(msg.sender, address(this), _amount); totalLPStaked = totalLPStaked.add(_amount); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accVEMPPerShare).div(1e12); user.rewardLPDebt = user.amount.mul(pool.accLPPerShare).div(1e12); emit Deposit(_user, _amount); }
function deposit(address _user, uint256 _amount) public { PoolInfo storage pool = poolInfo; UserInfo storage user = userInfo[_user]; updatePool(); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accVEMPPerShare).div(1e12).sub(user.rewardDebt); safeVEMPTransfer(_user, pending); uint256 LPReward = user.amount.mul(pool.accLPPerShare).div(1e12).sub(user.rewardLPDebt); pool.lpToken.safeTransfer(_user, LPReward); pool.lastLPRewardBalance = pool.lpToken.balanceOf(address(this)).sub(totalLPStaked.sub(totalLPUsedForPurchase)); } pool.lpToken.safeTransferFrom(msg.sender, address(this), _amount); totalLPStaked = totalLPStaked.add(_amount); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accVEMPPerShare).div(1e12); user.rewardLPDebt = user.amount.mul(pool.accLPPerShare).div(1e12); emit Deposit(_user, _amount); }
64,498
98
// 查询:上一局信息 返回:局ID,状态,奖池金额,获胜队伍ID,队伍名字,队伍人数,总队伍数 如果不存在上一局,会返回一堆0
function getLastRoundInfo() public view returns (uint256, uint256, uint256, uint256, bytes32, uint256, uint256)
function getLastRoundInfo() public view returns (uint256, uint256, uint256, uint256, bytes32, uint256, uint256)
7,911
48
// Transfer `amount` tokens from `msg.sender` to `dst` This function is expected to ALWAYS return true, or else it should throw dst The address of the destination account rawAmount The number of tokens to transferreturn Whether or not the transfer succeeded /
function transfer(address dst, uint256 rawAmount) external returns (bool) { uint96 amount = safe96(rawAmount, 'Ptp::transfer: amount exceeds 96 bits'); _transferTokens(msg.sender, dst, amount); return true; }
function transfer(address dst, uint256 rawAmount) external returns (bool) { uint96 amount = safe96(rawAmount, 'Ptp::transfer: amount exceeds 96 bits'); _transferTokens(msg.sender, dst, amount); return true; }
6,191
12
// To change the approve amount you first have to reduce the addresses`allowance to zero by calling `approve(_spender, 0)` if it is notalready 0 to mitigate the race condition described here:https:github.com/ethereum/EIPs/issues/20issuecomment-263524729
require((_value == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true;
require((_value == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true;
3,533
6,988
// 3496
entry "nosologically" : ENG_ADVERB
entry "nosologically" : ENG_ADVERB
24,332
4
// ========================= ERRORS ==========================
error UpshotOracleInvalidPriceTime(); error UpshotOracleInvalidSigner();
error UpshotOracleInvalidPriceTime(); error UpshotOracleInvalidSigner();
1,021
71
// Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation. /
function toHexString(address addr) internal pure returns (string memory) { return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH); }
function toHexString(address addr) internal pure returns (string memory) { return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH); }
8,811
30
// x to the power of y/
function pwr(uint256 x, uint256 y) internal pure returns (uint256)
function pwr(uint256 x, uint256 y) internal pure returns (uint256)
11,930
35
// SafeMath Unsigned math operations with safety checks that revert on error /
library SafeMath { /** * @dev Multiplies two unsigned integers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // 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-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } }
library SafeMath { /** * @dev Multiplies two unsigned integers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // 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-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } }
29,280
54
// Triggers an approval from owner to spends owner The address to approve from spender The address to be approved rawAmount The number of tokens that are approved (2^256-1 means infinite) deadline The time at which to expire the signature v The recovery byte of the signature r Half of the ECDSA signature pair s Half of the ECDSA signature pair /
function permit( address owner, address spender, uint256 rawAmount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external;
function permit( address owner, address spender, uint256 rawAmount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external;
6,201
17
// Calculate tokens amount.rateP rate of tokenrateMultiplierP rate multiplierweiAmountP wei weiAmountMultiplierP wei multiplier return The number of tokens _weiAmount wei will buy at present time/
function calculateTokens(uint256 rateP, uint256 rateMultiplierP, uint weiAmountP, uint weiAmountMultiplierP) public view returns (uint256) { uint256 currentRate = getCurrentRate(); uint256 rateLocal = rateP; uint256 rateMultiplier = rateMultiplierP; uint256 weiAmount = weiAmountP; uint256 weiAmountMultiplier = weiAmountMultiplierP; if(rateLocal == 0){ rateLocal = currentRate; } if(rateMultiplier != 0){ rateLocal = rateLocal.mul(10**rateMultiplier); } if(weiAmountMultiplier != 0){ weiAmount = weiAmount.mul(10**weiAmountMultiplier); } return weiAmount.div(rateLocal); }
function calculateTokens(uint256 rateP, uint256 rateMultiplierP, uint weiAmountP, uint weiAmountMultiplierP) public view returns (uint256) { uint256 currentRate = getCurrentRate(); uint256 rateLocal = rateP; uint256 rateMultiplier = rateMultiplierP; uint256 weiAmount = weiAmountP; uint256 weiAmountMultiplier = weiAmountMultiplierP; if(rateLocal == 0){ rateLocal = currentRate; } if(rateMultiplier != 0){ rateLocal = rateLocal.mul(10**rateMultiplier); } if(weiAmountMultiplier != 0){ weiAmount = weiAmount.mul(10**weiAmountMultiplier); } return weiAmount.div(rateLocal); }
21,338
53
// Compute Ratio of transfer before payback
uint256 ratio = _flashLoanAmount.mul(1e18).div( IProvider(activeProvider).getBorrowBalance(vAssets.borrowAsset) );
uint256 ratio = _flashLoanAmount.mul(1e18).div( IProvider(activeProvider).getBorrowBalance(vAssets.borrowAsset) );
78,980
90
// Generate the feComposite elements.
string memory feCompositeElements; string memory feCompositeAttributes; ( feCompositeElements, feCompositeAttributes, nonce ) = generateFeCompositeElements(seed, nonce);
string memory feCompositeElements; string memory feCompositeAttributes; ( feCompositeElements, feCompositeAttributes, nonce ) = generateFeCompositeElements(seed, nonce);
35,665
0
// Constants / Minimum amount of Ether that can be sent in a bid
uint constant public MIN_BID = 1 ether;
uint constant public MIN_BID = 1 ether;
38,540
7
// Updates the swapping path for the router. The first element of the path must be the input token. The last element of the path must be the output token. This method is only callable by an exchanger. newPath The new router path. /
function updatePath(address[] memory newPath) onlyExchanger external { require(newPath[0]==address(FeeExchanger._inputToken), "FE: PATH INPUT"); require(newPath[newPath.length-1]==address(FeeExchanger._outputToken), "FE: PATH OUTPUT"); _path = newPath; }
function updatePath(address[] memory newPath) onlyExchanger external { require(newPath[0]==address(FeeExchanger._inputToken), "FE: PATH INPUT"); require(newPath[newPath.length-1]==address(FeeExchanger._outputToken), "FE: PATH OUTPUT"); _path = newPath; }
40,517
11
// Throws if bounty status is not completed._bountyID The ID of the bounty./
modifier bountyStatusCompleted(uint256 _bountyID) { require(bountyList[_bountyID].status == BountyStatus.Completed); _; }
modifier bountyStatusCompleted(uint256 _bountyID) { require(bountyList[_bountyID].status == BountyStatus.Completed); _; }
17,992
21
// @inheritdoc PendleForgeBase/ different from AaveForge, here there is no compound interest occurred because the amount/
function _updateForgeFee( address _underlyingAsset, uint256 _expiry, uint256 _feeAmount
function _updateForgeFee( address _underlyingAsset, uint256 _expiry, uint256 _feeAmount
4,414
0
// Adventurer contract interface
interface iAdv { function walletOfOwner(address address_) external view returns (uint256[] memory); }
interface iAdv { function walletOfOwner(address address_) external view returns (uint256[] memory); }
49,104
17
// Get the difference between the newIndex and oldIndex.
SignedMath.Int memory signedIndexDiff = SignedMath.Int({ isPositive: newIndex.isPositive, value: newIndex.value });
SignedMath.Int memory signedIndexDiff = SignedMath.Int({ isPositive: newIndex.isPositive, value: newIndex.value });
20,859
4
// This stores the validator id of the last withdraw request sent to
uint256 private lastWithdrawnValidatorId;
uint256 private lastWithdrawnValidatorId;
40,590
1
// Emitted when borrow cap for a cToken is changed
event NewBorrowCap(address indexed cToken, uint256 newBorrowCap);
event NewBorrowCap(address indexed cToken, uint256 newBorrowCap);
27,310
2
// Exception codes:
uint constant MESSAGE_SENDER_IS_NOT_THE_OWNER = 101; uint constant MAPPING_REPLACE_ERROR = 102; uint constant PLAIN_TRANSFERS_ARE_FORBIDDEN = 103; uint constant NO_PUBKEY = 104;
uint constant MESSAGE_SENDER_IS_NOT_THE_OWNER = 101; uint constant MAPPING_REPLACE_ERROR = 102; uint constant PLAIN_TRANSFERS_ARE_FORBIDDEN = 103; uint constant NO_PUBKEY = 104;
24,230
142
// checks if_daoAddress _daoAddress - address of the unique user IDreturn recordExists bool /
function exists(address _daoAddress) external view returns (bool recordExists) { return _exists(_daoAddress); }
function exists(address _daoAddress) external view returns (bool recordExists) { return _exists(_daoAddress); }
84,132
44
// What is their percentage (as a high precision int) of the total debt?
uint debtPercentage = amount.divideDecimalRoundPrecise(newTotalDebtIssued);
uint debtPercentage = amount.divideDecimalRoundPrecise(newTotalDebtIssued);
10,545
96
// Contracts that should not own Tokens Remco Bloemen <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e5978088868aa5d7">[email&160;protected]</a>π.com> This blocks incoming ERC223 tokens to prevent accidental loss of tokens.Should tokens (any ERC20Basic compatible) end up in the contract, it allows theowner to reclaim the tokens. /
contract HasNoTokens is CanReclaimToken { /** * @dev Reject all ERC223 compatible tokens * @param from_ address The address that is transferring the tokens * @param value_ uint256 the amount of the specified token * @param data_ Bytes The data passed from the caller. */ function tokenFallback(address from_, uint256 value_, bytes data_) external { from_; value_; data_; revert(); } }
contract HasNoTokens is CanReclaimToken { /** * @dev Reject all ERC223 compatible tokens * @param from_ address The address that is transferring the tokens * @param value_ uint256 the amount of the specified token * @param data_ Bytes The data passed from the caller. */ function tokenFallback(address from_, uint256 value_, bytes data_) external { from_; value_; data_; revert(); } }
15,299
6
// Library for managing uint256 to bool mapping in a compact and efficient way, providing the keys are sequential. /
library BitMaps { struct BitMap { mapping(uint256 => uint256) _data; } /** * @dev Returns whether the bit at `index` is set. */ function get(BitMap storage bitmap, uint256 index) internal view returns (bool) { uint256 bucket = index >> 8; uint256 mask = 1 << (index & 0xff); return bitmap._data[bucket] & mask != 0; } /** * @dev Sets the bit at `index` to the boolean `value`. */ function setTo( BitMap storage bitmap, uint256 index, bool value ) internal { if (value) { set(bitmap, index); } else { unset(bitmap, index); } } /** * @dev Sets the bit at `index`. */ function set(BitMap storage bitmap, uint256 index) internal { uint256 bucket = index >> 8; uint256 mask = 1 << (index & 0xff); bitmap._data[bucket] |= mask; } /** * @dev Unsets the bit at `index`. */ function unset(BitMap storage bitmap, uint256 index) internal { uint256 bucket = index >> 8; uint256 mask = 1 << (index & 0xff); bitmap._data[bucket] &= ~mask; } }
library BitMaps { struct BitMap { mapping(uint256 => uint256) _data; } /** * @dev Returns whether the bit at `index` is set. */ function get(BitMap storage bitmap, uint256 index) internal view returns (bool) { uint256 bucket = index >> 8; uint256 mask = 1 << (index & 0xff); return bitmap._data[bucket] & mask != 0; } /** * @dev Sets the bit at `index` to the boolean `value`. */ function setTo( BitMap storage bitmap, uint256 index, bool value ) internal { if (value) { set(bitmap, index); } else { unset(bitmap, index); } } /** * @dev Sets the bit at `index`. */ function set(BitMap storage bitmap, uint256 index) internal { uint256 bucket = index >> 8; uint256 mask = 1 << (index & 0xff); bitmap._data[bucket] |= mask; } /** * @dev Unsets the bit at `index`. */ function unset(BitMap storage bitmap, uint256 index) internal { uint256 bucket = index >> 8; uint256 mask = 1 << (index & 0xff); bitmap._data[bucket] &= ~mask; } }
22,537
167
// Parameters of the auction. Times are either absolute unix timestamps (seconds since 1970-01-01) or time periods in seconds.
address payable beneficiary; uint auctionEnd;
address payable beneficiary; uint auctionEnd;
34,642
96
// 0: DAI, 1: USDC, 2: USDT
interface IStableSwap3Pool { function get_virtual_price() external view returns (uint); function balances(uint) external view returns (uint); function calc_token_amount(uint[3] calldata amounts, bool deposit) external view returns (uint); function calc_withdraw_one_coin(uint _token_amount, int128 i) external view returns (uint); function get_dy(int128 i, int128 j, uint dx) external view returns (uint); function add_liquidity(uint[3] calldata amounts, uint min_mint_amount) external; function remove_liquidity_one_coin(uint _token_amount, int128 i, uint min_amount) external; function exchange(int128 i, int128 j, uint dx, uint min_dy) external; }
interface IStableSwap3Pool { function get_virtual_price() external view returns (uint); function balances(uint) external view returns (uint); function calc_token_amount(uint[3] calldata amounts, bool deposit) external view returns (uint); function calc_withdraw_one_coin(uint _token_amount, int128 i) external view returns (uint); function get_dy(int128 i, int128 j, uint dx) external view returns (uint); function add_liquidity(uint[3] calldata amounts, uint min_mint_amount) external; function remove_liquidity_one_coin(uint _token_amount, int128 i, uint min_amount) external; function exchange(int128 i, int128 j, uint dx, uint min_dy) external; }
18,036
42
// Storage slot with the admin of the contract.This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and isvalidated in the constructor. /
bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
4,588
10
// Sets the recipient of the vested distributions. In the initial Pangolin scheme, thisshould be the address of the LiquidityPoolManager. Can only be called by the contractowner. /
function setRecipient(address recipient_) external onlyOwner { require( recipient_ != address(0), "TreasuryVester::setRecipient: Recipient can't be the zero address" ); recipient = recipient_; emit RecipientChanged(recipient); }
function setRecipient(address recipient_) external onlyOwner { require( recipient_ != address(0), "TreasuryVester::setRecipient: Recipient can't be the zero address" ); recipient = recipient_; emit RecipientChanged(recipient); }
2,096
41
// Update the winning bid and listing's end time before external contract calls.
winningBid[_targetListing.listingId] = _incomingBid; if (_targetListing.endTime - block.timestamp <= timeBuffer) { _targetListing.endTime += timeBuffer; listings[_targetListing.listingId] = _targetListing; }
winningBid[_targetListing.listingId] = _incomingBid; if (_targetListing.endTime - block.timestamp <= timeBuffer) { _targetListing.endTime += timeBuffer; listings[_targetListing.listingId] = _targetListing; }
20,506
99
// Track claimed tokens within a season IMPORTANT: The format of the mapping is: claimedForSeason[season][tokenId][claimed]
mapping(uint256 => mapping(uint256 => bool)) public seasonClaimedByTokenId;
mapping(uint256 => mapping(uint256 => bool)) public seasonClaimedByTokenId;
4,964
11
// transfer an amount of tokens to another address.The transfer needs to be >0 does the msg.sender have enough tokens to forfill the transferdecrease the balance of the sender and increase the balance of the to address
function transfer(address _to, uint _value) public override returns (bool success) { require(_value <= __balanceOf[msg.sender], 'This wallet does not have enough money'); __balanceOf[msg.sender] -= _value; __balanceOf[_to] += _value; emit Transfer(msg.sender, _to, _value); return true; }
function transfer(address _to, uint _value) public override returns (bool success) { require(_value <= __balanceOf[msg.sender], 'This wallet does not have enough money'); __balanceOf[msg.sender] -= _value; __balanceOf[_to] += _value; emit Transfer(msg.sender, _to, _value); return true; }
15,005
23
// function to check whether passed address is a contract address/
function isContract(address _address) private view returns (bool is_contract) { uint256 length; assembly { //retrieve the size of the code on target address, this needs assembly length := extcodesize(_address) } return (length > 0); }
function isContract(address _address) private view returns (bool is_contract) { uint256 length; assembly { //retrieve the size of the code on target address, this needs assembly length := extcodesize(_address) } return (length > 0); }
46,001
114
// return the time after which a player can close the game. _gameId 32 byte game identifier. /
function timeUntilCancel( bytes32 _gameId ) public view isOpen(_gameId) returns (uint256 remainingTime)
function timeUntilCancel( bytes32 _gameId ) public view isOpen(_gameId) returns (uint256 remainingTime)
32,067
15
// Returns true if `account` is a contract. [IMPORTANT]====It is unsafe to assume that an address for which this function returnsfalse is an externally-owned account (EOA) and not a contract. Among others, `isContract` will return false for the followingtypes of addresses:- an externally-owned account - a contract in construction - an address where a contract will be created - an address where a contract lived, but was destroyed Furthermore, `isContract` will also return true if the target contract withinthe same transaction is already scheduled for destruction by `SELFDESTRUCT`,which only has an effect at the end of a transaction.==== [IMPORTANT]====You shouldn't rely
function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; }
function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; }
23,283
268
// Vesting A token holder contract that can release its token balance gradually like atypical vesting scheme, with a cliff and vesting period. Owner has the powerto change the beneficiary who receives the vested tokens. /
contract Vesting is Initializable, Context { using SafeERC20 for IERC20; event Released(uint256 amount); event VestingInitialized( address indexed beneficiary, uint256 startTimestamp, uint256 cliff, uint256 duration ); event SetBeneficiary(address indexed beneficiary); // beneficiary of tokens after they are released address public beneficiary; IERC20 public token; uint256 public cliffInSeconds; uint256 public durationInSeconds; uint256 public startTimestamp; uint256 public released; /** * @dev Sets the beneficiary to _msgSender() on deploying this contract. This prevents others from * initializing the logic contract. */ constructor() public { beneficiary = _msgSender(); } /** * @dev Limits certain functions to be called by governance */ modifier onlyGovernance() { require( _msgSender() == governance(), "only governance can perform this action" ); _; } /** * @dev Initializes a vesting contract that vests its balance of any ERC20 token to the * _beneficiary, monthly in a linear fashion until duration has passed. By then all * of the balance will have vested. * @param _token address of the token that is subject to vesting * @param _beneficiary address of the beneficiary to whom vested tokens are transferred * @param _cliffInSeconds duration in months of the cliff in which tokens will begin to vest * @param _durationInSeconds duration in months of the period in which the tokens will vest * @param _startTimestamp start timestamp when the cliff and vesting should start to count */ function initialize( address _token, address _beneficiary, uint256 _startTimestamp, uint256 _cliffInSeconds, uint256 _durationInSeconds ) external initializer { require(_token != address(0), "_token cannot be empty"); // dev: beneficiary is set to msg.sender on logic contracts during deployment require(beneficiary == address(0), "cannot initialize logic contract"); require(_beneficiary != address(0), "_beneficiary cannot be empty"); require(_startTimestamp != 0, "startTimestamp cannot be 0"); require( _startTimestamp <= block.timestamp, "startTimestamp cannot be from the future" ); require(_durationInSeconds != 0, "duration cannot be 0"); require( _cliffInSeconds <= _durationInSeconds, "cliff is greater than duration" ); token = IERC20(_token); beneficiary = _beneficiary; startTimestamp = _startTimestamp; durationInSeconds = _durationInSeconds; cliffInSeconds = _cliffInSeconds; emit VestingInitialized( _beneficiary, _startTimestamp, _cliffInSeconds, _durationInSeconds ); } /** * @notice Transfers vested tokens to beneficiary. */ function release() external { uint256 vested = vestedAmount(); require(vested > 0, "No tokens to release"); released = released + vested; emit Released(vested); token.safeTransfer(beneficiary, vested); } /** * @notice Calculates the amount that has already vested but hasn't been released yet. */ function vestedAmount() public view returns (uint256) { uint256 blockTimestamp = block.timestamp; uint256 _durationInSeconds = durationInSeconds; uint256 elapsedTime = blockTimestamp - startTimestamp; // @dev startTimestamp is always less than blockTimestamp if (elapsedTime < cliffInSeconds) { return 0; } // If over vesting duration, all tokens vested if (elapsedTime >= _durationInSeconds) { return token.balanceOf(address(this)); } else { uint256 currentBalance = token.balanceOf(address(this)); // If there are no tokens in this contract yet, return 0. if (currentBalance == 0) { return 0; } uint256 totalBalance = currentBalance + released; uint256 vested = (totalBalance * elapsedTime) / _durationInSeconds; uint256 unreleased = vested - released; return unreleased; } } /** * @notice Changes beneficiary who receives the vested token. * @dev Only governance can call this function. This is to be used in case the target address * needs to be updated. If the previous beneficiary has any unclaimed tokens, the new beneficiary * will be able to claim them and the rest of the vested tokens. * @param newBeneficiary new address to become the beneficiary */ function changeBeneficiary(address newBeneficiary) external onlyGovernance { require( newBeneficiary != beneficiary, "beneficiary must be different from current one" ); require(newBeneficiary != address(0), "beneficiary cannot be empty"); beneficiary = newBeneficiary; emit SetBeneficiary(newBeneficiary); } /** * @notice Governance who owns this contract. * @dev Governance of the token contract also owns this vesting contract. */ function governance() public view returns (address) { return SimpleGovernance(address(token)).governance(); } }
contract Vesting is Initializable, Context { using SafeERC20 for IERC20; event Released(uint256 amount); event VestingInitialized( address indexed beneficiary, uint256 startTimestamp, uint256 cliff, uint256 duration ); event SetBeneficiary(address indexed beneficiary); // beneficiary of tokens after they are released address public beneficiary; IERC20 public token; uint256 public cliffInSeconds; uint256 public durationInSeconds; uint256 public startTimestamp; uint256 public released; /** * @dev Sets the beneficiary to _msgSender() on deploying this contract. This prevents others from * initializing the logic contract. */ constructor() public { beneficiary = _msgSender(); } /** * @dev Limits certain functions to be called by governance */ modifier onlyGovernance() { require( _msgSender() == governance(), "only governance can perform this action" ); _; } /** * @dev Initializes a vesting contract that vests its balance of any ERC20 token to the * _beneficiary, monthly in a linear fashion until duration has passed. By then all * of the balance will have vested. * @param _token address of the token that is subject to vesting * @param _beneficiary address of the beneficiary to whom vested tokens are transferred * @param _cliffInSeconds duration in months of the cliff in which tokens will begin to vest * @param _durationInSeconds duration in months of the period in which the tokens will vest * @param _startTimestamp start timestamp when the cliff and vesting should start to count */ function initialize( address _token, address _beneficiary, uint256 _startTimestamp, uint256 _cliffInSeconds, uint256 _durationInSeconds ) external initializer { require(_token != address(0), "_token cannot be empty"); // dev: beneficiary is set to msg.sender on logic contracts during deployment require(beneficiary == address(0), "cannot initialize logic contract"); require(_beneficiary != address(0), "_beneficiary cannot be empty"); require(_startTimestamp != 0, "startTimestamp cannot be 0"); require( _startTimestamp <= block.timestamp, "startTimestamp cannot be from the future" ); require(_durationInSeconds != 0, "duration cannot be 0"); require( _cliffInSeconds <= _durationInSeconds, "cliff is greater than duration" ); token = IERC20(_token); beneficiary = _beneficiary; startTimestamp = _startTimestamp; durationInSeconds = _durationInSeconds; cliffInSeconds = _cliffInSeconds; emit VestingInitialized( _beneficiary, _startTimestamp, _cliffInSeconds, _durationInSeconds ); } /** * @notice Transfers vested tokens to beneficiary. */ function release() external { uint256 vested = vestedAmount(); require(vested > 0, "No tokens to release"); released = released + vested; emit Released(vested); token.safeTransfer(beneficiary, vested); } /** * @notice Calculates the amount that has already vested but hasn't been released yet. */ function vestedAmount() public view returns (uint256) { uint256 blockTimestamp = block.timestamp; uint256 _durationInSeconds = durationInSeconds; uint256 elapsedTime = blockTimestamp - startTimestamp; // @dev startTimestamp is always less than blockTimestamp if (elapsedTime < cliffInSeconds) { return 0; } // If over vesting duration, all tokens vested if (elapsedTime >= _durationInSeconds) { return token.balanceOf(address(this)); } else { uint256 currentBalance = token.balanceOf(address(this)); // If there are no tokens in this contract yet, return 0. if (currentBalance == 0) { return 0; } uint256 totalBalance = currentBalance + released; uint256 vested = (totalBalance * elapsedTime) / _durationInSeconds; uint256 unreleased = vested - released; return unreleased; } } /** * @notice Changes beneficiary who receives the vested token. * @dev Only governance can call this function. This is to be used in case the target address * needs to be updated. If the previous beneficiary has any unclaimed tokens, the new beneficiary * will be able to claim them and the rest of the vested tokens. * @param newBeneficiary new address to become the beneficiary */ function changeBeneficiary(address newBeneficiary) external onlyGovernance { require( newBeneficiary != beneficiary, "beneficiary must be different from current one" ); require(newBeneficiary != address(0), "beneficiary cannot be empty"); beneficiary = newBeneficiary; emit SetBeneficiary(newBeneficiary); } /** * @notice Governance who owns this contract. * @dev Governance of the token contract also owns this vesting contract. */ function governance() public view returns (address) { return SimpleGovernance(address(token)).governance(); } }
23,418
80
// Determines how ETH is stored/forwarded on purchases. /
function _forwardFunds() internal { _wallet.transfer(msg.value); }
function _forwardFunds() internal { _wallet.transfer(msg.value); }
1,116
24
// Handle after ETH withdrawal from the SGRToken contract operation. _sender The address of the account which has issued the operation. _wallet The address of the withdrawal wallet. _amount The ETH withdraw amount. _priorWithdrawEthBalance The amount of ETH in the SGRToken contract prior the withdrawal. _afterWithdrawEthBalance The amount of ETH in the SGRToken contract after the withdrawal. /
function afterWithdraw(address _sender, address _wallet, uint256 _amount, uint256 _priorWithdrawEthBalance, uint256 _afterWithdrawEthBalance) external;
function afterWithdraw(address _sender, address _wallet, uint256 _amount, uint256 _priorWithdrawEthBalance, uint256 _afterWithdrawEthBalance) external;
11,255
21
// Set limits for mystery boxes/
_mysteryBoxesLimits[COMMON] = 2000;
_mysteryBoxesLimits[COMMON] = 2000;
13,745
1
// Constant to indicate precision
uint256 private constant INTEGRATOR_FEE_PRECISION = 1000;
uint256 private constant INTEGRATOR_FEE_PRECISION = 1000;
25,914
241
// kashiPair must not already be attached
require(_newKashiPair != address(kashiPairs[i].kashiPair));
require(_newKashiPair != address(kashiPairs[i].kashiPair));
69,663
1
// Sets the amount of gas used for a transaction on a given chain. chainId The ID of the chain. gasAmount The amount of gas used on the chain. /
function setGasUsage(uint chainId, uint gasAmount) external onlyOwner { gasUsage[chainId] = gasAmount; }
function setGasUsage(uint chainId, uint gasAmount) external onlyOwner { gasUsage[chainId] = gasAmount; }
36,877
433
// Set the price for any given category in USD. /
function setPrice(uint8 category, uint256 price, bool inWei) public onlyOwner { uint256 multiply = 1e18; if (inWei) { multiply = 1; } categoryPrice[category] = price * multiply; }
function setPrice(uint8 category, uint256 price, bool inWei) public onlyOwner { uint256 multiply = 1e18; if (inWei) { multiply = 1; } categoryPrice[category] = price * multiply; }
35,203
1
// ================================= VARIABLES =================================
IEulerStakingRewards public eulerStakingContract; AggregatorV3Interface public chainlinkOracle; uint8 public isUniMultiplied;
IEulerStakingRewards public eulerStakingContract; AggregatorV3Interface public chainlinkOracle; uint8 public isUniMultiplied;
32,577
114
// Updates base uri. /
function _updateBaseURI(string memory _baseURI) internal { _setBaseURI(_baseURI); emit BaseURIUpdated(_baseURI); }
function _updateBaseURI(string memory _baseURI) internal { _setBaseURI(_baseURI); emit BaseURIUpdated(_baseURI); }
80,545
89
// Revokes `role` from the calling account.
* Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); }
* Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); }
1,334
79
// update user's context list?
if (!assignments[_context].hasUser(_addr)) { userContexts[_addr].remove(_context); }
if (!assignments[_context].hasUser(_addr)) { userContexts[_addr].remove(_context); }
41,770
7
// console.log('getBalanceFromLastEpoch who %s', who); console.log('getBalanceFromLastEpoch currentEpoch %s', currentEpoch);
if (currentEpoch == 1) return 0;
if (currentEpoch == 1) return 0;
21,704
15
// If a primary terminal for the token was specifically set, return it.
if (_primaryTerminalOf[_projectId][_token] != IJBTerminal(address(0))) return _primaryTerminalOf[_projectId][_token];
if (_primaryTerminalOf[_projectId][_token] != IJBTerminal(address(0))) return _primaryTerminalOf[_projectId][_token];
29,420
11
// probability of phishing
uint256 internal NFTRUITE_CHANCE = 1000; uint256 internal NFT_BIG_TRUITE_CHANCE = 1000; uint256 internal NFT_PA_SQUALE_CHANCE = 1000;
uint256 internal NFTRUITE_CHANCE = 1000; uint256 internal NFT_BIG_TRUITE_CHANCE = 1000; uint256 internal NFT_PA_SQUALE_CHANCE = 1000;
19,090
46
// else {notApprovedReviwer.push(_reviewer[tokenId][i]); return true; }
}
}
12,494
6
// get the left and right headers for a user, left header is the index counter till which we have already iterated, right header is basically the length of user's lockInfo array
function getLeftRightCounters(address _user) external view returns(uint256, uint256){ return(latestCounterByUser[_user], lockInfoByUser[_user].length); }
function getLeftRightCounters(address _user) external view returns(uint256, uint256){ return(latestCounterByUser[_user], lockInfoByUser[_user].length); }
8,073
1
// register a validator and provide registration data./ the new validator entry will be owned and identified by msg.sender./ if msg.sender is already registered as a validator in this registry the/ transaction will fail./name string The name of the validator/ipAddress bytes4 The validator node ip address. If another validator previously registered this ipAddress the transaction will fail/website string The website of the validator/orbsAddress bytes20 The validator node orbs public address. If another validator previously registered this orbsAddress the transaction will fail
function register( string name, bytes4 ipAddress, string website, bytes20 orbsAddress ) external;
function register( string name, bytes4 ipAddress, string website, bytes20 orbsAddress ) external;
44,578
32
// ERC20 compliant token intermediary contract holding core logic. This contract serves as an intermediary between the exposed ERC20 interface in ERC20Proxy and the store of balances in ERC20Store. This contract contains core logic that the proxy can delegate to and that the store is called by. This contract contains the core logic to implement the ERC20 specification as well as several extensions. 1. Changes to the token supply. 2. Batched transfers. 3. Relative changes to spending approvals. 4. Delegated transfer control ('sweeping'). Gemini Trust Company, LLC/
contract ERC20Impl is CustodianUpgradeable { // TYPES /// @dev The struct type for pending increases to the token supply (print). struct PendingPrint { address receiver; uint256 value; } // MEMBERS /// @dev The reference to the proxy. ERC20Proxy public erc20Proxy; /// @dev The reference to the store. ERC20Store public erc20Store; /// @dev The sole authorized caller of delegated transfer control ('sweeping'). address public sweeper; /** @dev The static message to be signed by an external account that * signifies their permission to forward their balance to any arbitrary * address. This is used to consolidate the control of all accounts * backed by a shared keychain into the control of a single key. * Initialized as the concatenation of the address of this contract * and the word "sweep". This concatenation is done to prevent a replay * attack in a subsequent contract, where the sweep message could * potentially be replayed to re-enable sweeping ability. */ bytes32 public sweepMsg; /** @dev The mapping that stores whether the address in question has * enabled sweeping its contents to another account or not. * If an address maps to "true", it has already enabled sweeping, * and thus does not need to re-sign the `sweepMsg` to enact the sweep. */ mapping (address => bool) public sweptSet; /// @dev The map of lock ids to pending token increases. mapping (bytes32 => PendingPrint) public pendingPrintMap; // CONSTRUCTOR function ERC20Impl( address _erc20Proxy, address _erc20Store, address _custodian, address _sweeper ) CustodianUpgradeable(_custodian) public { require(_sweeper != 0); erc20Proxy = ERC20Proxy(_erc20Proxy); erc20Store = ERC20Store(_erc20Store); sweeper = _sweeper; sweepMsg = keccak256(address(this), "sweep"); } // MODIFIERS modifier onlyProxy { require(msg.sender == address(erc20Proxy)); _; } modifier onlySweeper { require(msg.sender == sweeper); _; } /** @notice Core logic of the ERC20 `approve` function. * * @dev This function can only be called by the referenced proxy, * which has an `approve` function. * Every argument passed to that function as well as the original * `msg.sender` gets passed to this function. * NOTE: approvals for the zero address (unspendable) are disallowed. * * @param _sender The address initiating the approval in proxy. */ function approveWithSender( address _sender, address _spender, uint256 _value ) public onlyProxy returns (bool success) { require(_spender != address(0)); // disallow unspendable approvals erc20Store.setAllowance(_sender, _spender, _value); erc20Proxy.emitApproval(_sender, _spender, _value); return true; } /** @notice Core logic of the `increaseApproval` function. * * @dev This function can only be called by the referenced proxy, * which has an `increaseApproval` function. * Every argument passed to that function as well as the original * `msg.sender` gets passed to this function. * NOTE: approvals for the zero address (unspendable) are disallowed. * * @param _sender The address initiating the approval. */ function increaseApprovalWithSender( address _sender, address _spender, uint256 _addedValue ) public onlyProxy returns (bool success) { require(_spender != address(0)); // disallow unspendable approvals uint256 currentAllowance = erc20Store.allowed(_sender, _spender); uint256 newAllowance = currentAllowance + _addedValue; require(newAllowance >= currentAllowance); erc20Store.setAllowance(_sender, _spender, newAllowance); erc20Proxy.emitApproval(_sender, _spender, newAllowance); return true; } /** @notice Core logic of the `decreaseApproval` function. * * @dev This function can only be called by the referenced proxy, * which has a `decreaseApproval` function. * Every argument passed to that function as well as the original * `msg.sender` gets passed to this function. * NOTE: approvals for the zero address (unspendable) are disallowed. * * @param _sender The address initiating the approval. */ function decreaseApprovalWithSender( address _sender, address _spender, uint256 _subtractedValue ) public onlyProxy returns (bool success) { require(_spender != address(0)); // disallow unspendable approvals uint256 currentAllowance = erc20Store.allowed(_sender, _spender); uint256 newAllowance = currentAllowance - _subtractedValue; require(newAllowance <= currentAllowance); erc20Store.setAllowance(_sender, _spender, newAllowance); erc20Proxy.emitApproval(_sender, _spender, newAllowance); return true; } /** @notice Requests an increase in the token supply, with the newly created * tokens to be added to the balance of the specified account. * * @dev Returns a unique lock id associated with the request. * Anyone can call this function, but confirming the request is authorized * by the custodian. * NOTE: printing to the zero address is disallowed. * * @param _receiver The receiving address of the print, if confirmed. * @param _value The number of tokens to add to the total supply and the * balance of the receiving address, if confirmed. * * @return lockId A unique identifier for this request. */ function requestPrint(address _receiver, uint256 _value) public returns (bytes32 lockId) { require(_receiver != address(0)); lockId = generateLockId(); pendingPrintMap[lockId] = PendingPrint({ receiver: _receiver, value: _value }); emit PrintingLocked(lockId, _receiver, _value); } /** @notice Confirms a pending increase in the token supply. * * @dev When called by the custodian with a lock id associated with a * pending increase, the amount requested to be printed in the print request * is printed to the receiving address specified in that same request. * NOTE: this function will not execute any print that would overflow the * total supply, but it will not revert either. * * @param _lockId The identifier of a pending print request. */ function confirmPrint(bytes32 _lockId) public onlyCustodian { PendingPrint storage print = pendingPrintMap[_lockId]; // reject ‘null’ results from the map lookup // this can only be the case if an unknown `_lockId` is received address receiver = print.receiver; require (receiver != address(0)); uint256 value = print.value; delete pendingPrintMap[_lockId]; uint256 supply = erc20Store.totalSupply(); uint256 newSupply = supply + value; if (newSupply >= supply) { erc20Store.setTotalSupply(newSupply); erc20Store.addBalance(receiver, value); emit PrintingConfirmed(_lockId, receiver, value); erc20Proxy.emitTransfer(address(0), receiver, value); } } /** @notice Burns the specified value from the sender's balance. * * @dev Sender's balanced is subtracted by the amount they wish to burn. * * @param _value The amount to burn. * * @return success true if the burn succeeded. */ function burn(uint256 _value) public returns (bool success) { uint256 balanceOfSender = erc20Store.balances(msg.sender); require(_value <= balanceOfSender); erc20Store.setBalance(msg.sender, balanceOfSender - _value); erc20Store.setTotalSupply(erc20Store.totalSupply() - _value); erc20Proxy.emitTransfer(msg.sender, address(0), _value); return true; } /** @notice A function for a sender to issue multiple transfers to multiple * different addresses at once. This function is implemented for gas * considerations when someone wishes to transfer, as one transaction is * cheaper than issuing several distinct individual `transfer` transactions. * * @dev By specifying a set of destination addresses and values, the * sender can issue one transaction to transfer multiple amounts to * distinct addresses, rather than issuing each as a separate * transaction. The `_tos` and `_values` arrays must be equal length, and * an index in one array corresponds to the same index in the other array * (e.g. `_tos[0]` will receive `_values[0]`, `_tos[1]` will receive * `_values[1]`, and so on.) * NOTE: transfers to the zero address are disallowed. * * @param _tos The destination addresses to receive the transfers. * @param _values The values for each destination address. * @return success If transfers succeeded. */ function batchTransfer(address[] _tos, uint256[] _values) public returns (bool success) { require(_tos.length == _values.length); uint256 numTransfers = _tos.length; uint256 senderBalance = erc20Store.balances(msg.sender); for (uint256 i = 0; i < numTransfers; i++) { address to = _tos[i]; require(to != address(0)); uint256 v = _values[i]; require(senderBalance >= v); if (msg.sender != to) { senderBalance -= v; erc20Store.addBalance(to, v); } erc20Proxy.emitTransfer(msg.sender, to, v); } erc20Store.setBalance(msg.sender, senderBalance); return true; } /** @notice Enables the delegation of transfer control for many * accounts to the sweeper account, transferring any balances * as well to the given destination. * * @dev An account delegates transfer control by signing the * value of `sweepMsg`. The sweeper account is the only authorized * caller of this function, so it must relay signatures on behalf * of accounts that delegate transfer control to it. Enabling * delegation is idempotent and permanent. If the account has a * balance at the time of enabling delegation, its balance is * also transfered to the given destination account `_to`. * NOTE: transfers to the zero address are disallowed. * * @param _vs The array of recovery byte components of the ECDSA signatures. * @param _rs The array of 'R' components of the ECDSA signatures. * @param _ss The array of 'S' components of the ECDSA signatures. * @param _to The destination for swept balances. */ function enableSweep(uint8[] _vs, bytes32[] _rs, bytes32[] _ss, address _to) public onlySweeper { require(_to != address(0)); require((_vs.length == _rs.length) && (_vs.length == _ss.length)); uint256 numSignatures = _vs.length; uint256 sweptBalance = 0; for (uint256 i=0; i<numSignatures; ++i) { address from = ecrecover(sweepMsg, _vs[i], _rs[i], _ss[i]); // ecrecover returns 0 on malformed input if (from != address(0)) { sweptSet[from] = true; uint256 fromBalance = erc20Store.balances(from); if (fromBalance > 0) { sweptBalance += fromBalance; erc20Store.setBalance(from, 0); erc20Proxy.emitTransfer(from, _to, fromBalance); } } } if (sweptBalance > 0) { erc20Store.addBalance(_to, sweptBalance); } } /** @notice For accounts that have delegated, transfer control * to the sweeper, this function transfers their balances to the given * destination. * * @dev The sweeper account is the only authorized caller of * this function. This function accepts an array of addresses to have their * balances transferred for gas efficiency purposes. * NOTE: any address for an account that has not been previously enabled * will be ignored. * NOTE: transfers to the zero address are disallowed. * * @param _froms The addresses to have their balances swept. * @param _to The destination address of all these transfers. */ function replaySweep(address[] _froms, address _to) public onlySweeper { require(_to != address(0)); uint256 lenFroms = _froms.length; uint256 sweptBalance = 0; for (uint256 i=0; i<lenFroms; ++i) { address from = _froms[i]; if (sweptSet[from]) { uint256 fromBalance = erc20Store.balances(from); if (fromBalance > 0) { sweptBalance += fromBalance; erc20Store.setBalance(from, 0); erc20Proxy.emitTransfer(from, _to, fromBalance); } } } if (sweptBalance > 0) { erc20Store.addBalance(_to, sweptBalance); } } /** @notice Core logic of the ERC20 `transferFrom` function. * * @dev This function can only be called by the referenced proxy, * which has a `transferFrom` function. * Every argument passed to that function as well as the original * `msg.sender` gets passed to this function. * NOTE: transfers to the zero address are disallowed. * * @param _sender The address initiating the transfer in proxy. */ function transferFromWithSender( address _sender, address _from, address _to, uint256 _value ) public onlyProxy returns (bool success) { require(_to != address(0)); // ensure burn is the cannonical transfer to 0x0 uint256 balanceOfFrom = erc20Store.balances(_from); require(_value <= balanceOfFrom); uint256 senderAllowance = erc20Store.allowed(_from, _sender); require(_value <= senderAllowance); erc20Store.setBalance(_from, balanceOfFrom - _value); erc20Store.addBalance(_to, _value); erc20Store.setAllowance(_from, _sender, senderAllowance - _value); erc20Proxy.emitTransfer(_from, _to, _value); return true; } /** @notice Core logic of the ERC20 `transfer` function. * * @dev This function can only be called by the referenced proxy, * which has a `transfer` function. * Every argument passed to that function as well as the original * `msg.sender` gets passed to this function. * NOTE: transfers to the zero address are disallowed. * * @param _sender The address initiating the transfer in proxy. */ function transferWithSender( address _sender, address _to, uint256 _value ) public onlyProxy returns (bool success) { require(_to != address(0)); // ensure burn is the cannonical transfer to 0x0 uint256 balanceOfSender = erc20Store.balances(_sender); require(_value <= balanceOfSender); erc20Store.setBalance(_sender, balanceOfSender - _value); erc20Store.addBalance(_to, _value); erc20Proxy.emitTransfer(_sender, _to, _value); return true; } // METHODS (ERC20 sub interface impl.) /// @notice Core logic of the ERC20 `totalSupply` function. function totalSupply() public view returns (uint256) { return erc20Store.totalSupply(); } /// @notice Core logic of the ERC20 `balanceOf` function. function balanceOf(address _owner) public view returns (uint256 balance) { return erc20Store.balances(_owner); } /// @notice Core logic of the ERC20 `allowance` function. function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return erc20Store.allowed(_owner, _spender); } // EVENTS /// @dev Emitted by successful `requestPrint` calls. event PrintingLocked(bytes32 _lockId, address _receiver, uint256 _value); /// @dev Emitted by successful `confirmPrint` calls. event PrintingConfirmed(bytes32 _lockId, address _receiver, uint256 _value); }
contract ERC20Impl is CustodianUpgradeable { // TYPES /// @dev The struct type for pending increases to the token supply (print). struct PendingPrint { address receiver; uint256 value; } // MEMBERS /// @dev The reference to the proxy. ERC20Proxy public erc20Proxy; /// @dev The reference to the store. ERC20Store public erc20Store; /// @dev The sole authorized caller of delegated transfer control ('sweeping'). address public sweeper; /** @dev The static message to be signed by an external account that * signifies their permission to forward their balance to any arbitrary * address. This is used to consolidate the control of all accounts * backed by a shared keychain into the control of a single key. * Initialized as the concatenation of the address of this contract * and the word "sweep". This concatenation is done to prevent a replay * attack in a subsequent contract, where the sweep message could * potentially be replayed to re-enable sweeping ability. */ bytes32 public sweepMsg; /** @dev The mapping that stores whether the address in question has * enabled sweeping its contents to another account or not. * If an address maps to "true", it has already enabled sweeping, * and thus does not need to re-sign the `sweepMsg` to enact the sweep. */ mapping (address => bool) public sweptSet; /// @dev The map of lock ids to pending token increases. mapping (bytes32 => PendingPrint) public pendingPrintMap; // CONSTRUCTOR function ERC20Impl( address _erc20Proxy, address _erc20Store, address _custodian, address _sweeper ) CustodianUpgradeable(_custodian) public { require(_sweeper != 0); erc20Proxy = ERC20Proxy(_erc20Proxy); erc20Store = ERC20Store(_erc20Store); sweeper = _sweeper; sweepMsg = keccak256(address(this), "sweep"); } // MODIFIERS modifier onlyProxy { require(msg.sender == address(erc20Proxy)); _; } modifier onlySweeper { require(msg.sender == sweeper); _; } /** @notice Core logic of the ERC20 `approve` function. * * @dev This function can only be called by the referenced proxy, * which has an `approve` function. * Every argument passed to that function as well as the original * `msg.sender` gets passed to this function. * NOTE: approvals for the zero address (unspendable) are disallowed. * * @param _sender The address initiating the approval in proxy. */ function approveWithSender( address _sender, address _spender, uint256 _value ) public onlyProxy returns (bool success) { require(_spender != address(0)); // disallow unspendable approvals erc20Store.setAllowance(_sender, _spender, _value); erc20Proxy.emitApproval(_sender, _spender, _value); return true; } /** @notice Core logic of the `increaseApproval` function. * * @dev This function can only be called by the referenced proxy, * which has an `increaseApproval` function. * Every argument passed to that function as well as the original * `msg.sender` gets passed to this function. * NOTE: approvals for the zero address (unspendable) are disallowed. * * @param _sender The address initiating the approval. */ function increaseApprovalWithSender( address _sender, address _spender, uint256 _addedValue ) public onlyProxy returns (bool success) { require(_spender != address(0)); // disallow unspendable approvals uint256 currentAllowance = erc20Store.allowed(_sender, _spender); uint256 newAllowance = currentAllowance + _addedValue; require(newAllowance >= currentAllowance); erc20Store.setAllowance(_sender, _spender, newAllowance); erc20Proxy.emitApproval(_sender, _spender, newAllowance); return true; } /** @notice Core logic of the `decreaseApproval` function. * * @dev This function can only be called by the referenced proxy, * which has a `decreaseApproval` function. * Every argument passed to that function as well as the original * `msg.sender` gets passed to this function. * NOTE: approvals for the zero address (unspendable) are disallowed. * * @param _sender The address initiating the approval. */ function decreaseApprovalWithSender( address _sender, address _spender, uint256 _subtractedValue ) public onlyProxy returns (bool success) { require(_spender != address(0)); // disallow unspendable approvals uint256 currentAllowance = erc20Store.allowed(_sender, _spender); uint256 newAllowance = currentAllowance - _subtractedValue; require(newAllowance <= currentAllowance); erc20Store.setAllowance(_sender, _spender, newAllowance); erc20Proxy.emitApproval(_sender, _spender, newAllowance); return true; } /** @notice Requests an increase in the token supply, with the newly created * tokens to be added to the balance of the specified account. * * @dev Returns a unique lock id associated with the request. * Anyone can call this function, but confirming the request is authorized * by the custodian. * NOTE: printing to the zero address is disallowed. * * @param _receiver The receiving address of the print, if confirmed. * @param _value The number of tokens to add to the total supply and the * balance of the receiving address, if confirmed. * * @return lockId A unique identifier for this request. */ function requestPrint(address _receiver, uint256 _value) public returns (bytes32 lockId) { require(_receiver != address(0)); lockId = generateLockId(); pendingPrintMap[lockId] = PendingPrint({ receiver: _receiver, value: _value }); emit PrintingLocked(lockId, _receiver, _value); } /** @notice Confirms a pending increase in the token supply. * * @dev When called by the custodian with a lock id associated with a * pending increase, the amount requested to be printed in the print request * is printed to the receiving address specified in that same request. * NOTE: this function will not execute any print that would overflow the * total supply, but it will not revert either. * * @param _lockId The identifier of a pending print request. */ function confirmPrint(bytes32 _lockId) public onlyCustodian { PendingPrint storage print = pendingPrintMap[_lockId]; // reject ‘null’ results from the map lookup // this can only be the case if an unknown `_lockId` is received address receiver = print.receiver; require (receiver != address(0)); uint256 value = print.value; delete pendingPrintMap[_lockId]; uint256 supply = erc20Store.totalSupply(); uint256 newSupply = supply + value; if (newSupply >= supply) { erc20Store.setTotalSupply(newSupply); erc20Store.addBalance(receiver, value); emit PrintingConfirmed(_lockId, receiver, value); erc20Proxy.emitTransfer(address(0), receiver, value); } } /** @notice Burns the specified value from the sender's balance. * * @dev Sender's balanced is subtracted by the amount they wish to burn. * * @param _value The amount to burn. * * @return success true if the burn succeeded. */ function burn(uint256 _value) public returns (bool success) { uint256 balanceOfSender = erc20Store.balances(msg.sender); require(_value <= balanceOfSender); erc20Store.setBalance(msg.sender, balanceOfSender - _value); erc20Store.setTotalSupply(erc20Store.totalSupply() - _value); erc20Proxy.emitTransfer(msg.sender, address(0), _value); return true; } /** @notice A function for a sender to issue multiple transfers to multiple * different addresses at once. This function is implemented for gas * considerations when someone wishes to transfer, as one transaction is * cheaper than issuing several distinct individual `transfer` transactions. * * @dev By specifying a set of destination addresses and values, the * sender can issue one transaction to transfer multiple amounts to * distinct addresses, rather than issuing each as a separate * transaction. The `_tos` and `_values` arrays must be equal length, and * an index in one array corresponds to the same index in the other array * (e.g. `_tos[0]` will receive `_values[0]`, `_tos[1]` will receive * `_values[1]`, and so on.) * NOTE: transfers to the zero address are disallowed. * * @param _tos The destination addresses to receive the transfers. * @param _values The values for each destination address. * @return success If transfers succeeded. */ function batchTransfer(address[] _tos, uint256[] _values) public returns (bool success) { require(_tos.length == _values.length); uint256 numTransfers = _tos.length; uint256 senderBalance = erc20Store.balances(msg.sender); for (uint256 i = 0; i < numTransfers; i++) { address to = _tos[i]; require(to != address(0)); uint256 v = _values[i]; require(senderBalance >= v); if (msg.sender != to) { senderBalance -= v; erc20Store.addBalance(to, v); } erc20Proxy.emitTransfer(msg.sender, to, v); } erc20Store.setBalance(msg.sender, senderBalance); return true; } /** @notice Enables the delegation of transfer control for many * accounts to the sweeper account, transferring any balances * as well to the given destination. * * @dev An account delegates transfer control by signing the * value of `sweepMsg`. The sweeper account is the only authorized * caller of this function, so it must relay signatures on behalf * of accounts that delegate transfer control to it. Enabling * delegation is idempotent and permanent. If the account has a * balance at the time of enabling delegation, its balance is * also transfered to the given destination account `_to`. * NOTE: transfers to the zero address are disallowed. * * @param _vs The array of recovery byte components of the ECDSA signatures. * @param _rs The array of 'R' components of the ECDSA signatures. * @param _ss The array of 'S' components of the ECDSA signatures. * @param _to The destination for swept balances. */ function enableSweep(uint8[] _vs, bytes32[] _rs, bytes32[] _ss, address _to) public onlySweeper { require(_to != address(0)); require((_vs.length == _rs.length) && (_vs.length == _ss.length)); uint256 numSignatures = _vs.length; uint256 sweptBalance = 0; for (uint256 i=0; i<numSignatures; ++i) { address from = ecrecover(sweepMsg, _vs[i], _rs[i], _ss[i]); // ecrecover returns 0 on malformed input if (from != address(0)) { sweptSet[from] = true; uint256 fromBalance = erc20Store.balances(from); if (fromBalance > 0) { sweptBalance += fromBalance; erc20Store.setBalance(from, 0); erc20Proxy.emitTransfer(from, _to, fromBalance); } } } if (sweptBalance > 0) { erc20Store.addBalance(_to, sweptBalance); } } /** @notice For accounts that have delegated, transfer control * to the sweeper, this function transfers their balances to the given * destination. * * @dev The sweeper account is the only authorized caller of * this function. This function accepts an array of addresses to have their * balances transferred for gas efficiency purposes. * NOTE: any address for an account that has not been previously enabled * will be ignored. * NOTE: transfers to the zero address are disallowed. * * @param _froms The addresses to have their balances swept. * @param _to The destination address of all these transfers. */ function replaySweep(address[] _froms, address _to) public onlySweeper { require(_to != address(0)); uint256 lenFroms = _froms.length; uint256 sweptBalance = 0; for (uint256 i=0; i<lenFroms; ++i) { address from = _froms[i]; if (sweptSet[from]) { uint256 fromBalance = erc20Store.balances(from); if (fromBalance > 0) { sweptBalance += fromBalance; erc20Store.setBalance(from, 0); erc20Proxy.emitTransfer(from, _to, fromBalance); } } } if (sweptBalance > 0) { erc20Store.addBalance(_to, sweptBalance); } } /** @notice Core logic of the ERC20 `transferFrom` function. * * @dev This function can only be called by the referenced proxy, * which has a `transferFrom` function. * Every argument passed to that function as well as the original * `msg.sender` gets passed to this function. * NOTE: transfers to the zero address are disallowed. * * @param _sender The address initiating the transfer in proxy. */ function transferFromWithSender( address _sender, address _from, address _to, uint256 _value ) public onlyProxy returns (bool success) { require(_to != address(0)); // ensure burn is the cannonical transfer to 0x0 uint256 balanceOfFrom = erc20Store.balances(_from); require(_value <= balanceOfFrom); uint256 senderAllowance = erc20Store.allowed(_from, _sender); require(_value <= senderAllowance); erc20Store.setBalance(_from, balanceOfFrom - _value); erc20Store.addBalance(_to, _value); erc20Store.setAllowance(_from, _sender, senderAllowance - _value); erc20Proxy.emitTransfer(_from, _to, _value); return true; } /** @notice Core logic of the ERC20 `transfer` function. * * @dev This function can only be called by the referenced proxy, * which has a `transfer` function. * Every argument passed to that function as well as the original * `msg.sender` gets passed to this function. * NOTE: transfers to the zero address are disallowed. * * @param _sender The address initiating the transfer in proxy. */ function transferWithSender( address _sender, address _to, uint256 _value ) public onlyProxy returns (bool success) { require(_to != address(0)); // ensure burn is the cannonical transfer to 0x0 uint256 balanceOfSender = erc20Store.balances(_sender); require(_value <= balanceOfSender); erc20Store.setBalance(_sender, balanceOfSender - _value); erc20Store.addBalance(_to, _value); erc20Proxy.emitTransfer(_sender, _to, _value); return true; } // METHODS (ERC20 sub interface impl.) /// @notice Core logic of the ERC20 `totalSupply` function. function totalSupply() public view returns (uint256) { return erc20Store.totalSupply(); } /// @notice Core logic of the ERC20 `balanceOf` function. function balanceOf(address _owner) public view returns (uint256 balance) { return erc20Store.balances(_owner); } /// @notice Core logic of the ERC20 `allowance` function. function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return erc20Store.allowed(_owner, _spender); } // EVENTS /// @dev Emitted by successful `requestPrint` calls. event PrintingLocked(bytes32 _lockId, address _receiver, uint256 _value); /// @dev Emitted by successful `confirmPrint` calls. event PrintingConfirmed(bytes32 _lockId, address _receiver, uint256 _value); }
5,213
91
// Now, memPtr is a cursor pointing to the beginning of the current sub-operation
memPtr := add(memPtr, 1)
memPtr := add(memPtr, 1)
22,697
112
// ========== STRUCTS ========== /
struct TokenInfoConstructorArgs { address token_address; address agg_addr_for_underlying; uint256 agg_other_side; // 0: USD, 1: ETH address underlying_tkn_address; // Will be address(0) for simple tokens. Otherwise, the aUSDC, yvUSDC address, etc address pps_override_address; bytes4 pps_call_selector; // eg bytes4(keccak256("pricePerShare()")); uint256 pps_decimals; }
struct TokenInfoConstructorArgs { address token_address; address agg_addr_for_underlying; uint256 agg_other_side; // 0: USD, 1: ETH address underlying_tkn_address; // Will be address(0) for simple tokens. Otherwise, the aUSDC, yvUSDC address, etc address pps_override_address; bytes4 pps_call_selector; // eg bytes4(keccak256("pricePerShare()")); uint256 pps_decimals; }
9,444
22
// send ether to the fund collection walletoverride to create custom fund forwarding mechanisms /
function forwardFunds() internal { wallet.transfer(msg.value); }
function forwardFunds() internal { wallet.transfer(msg.value); }
22,349
36
// `msg.sender` approves `_spender` to send `_amount` tokens on/its behalf, and then a function is triggered in the contract that is/being approved, `_spender`. This allows users to use their tokens to/interact with contracts in one function call instead of two/_spender The address of the contract able to transfer the tokens/_amount The amount of tokens to be approved for transfer/ return True if the function call was successful
function approveAndCall(address _spender, uint256 _amount, bytes _extraData
function approveAndCall(address _spender, uint256 _amount, bytes _extraData
16,394
147
// The address of the auction's curator. The curator can reject or approve an auction
address payable curator;
address payable curator;
25,828
0
// date struct for easy coding
struct VacationDay { uint8 day; // Day of vacation 0 - 6 uint8 month; // Month of year uint16 year; // Year uint256 amount; // amount in Hours (mod 4) and max is 8 (1 day) }
struct VacationDay { uint8 day; // Day of vacation 0 - 6 uint8 month; // Month of year uint16 year; // Year uint256 amount; // amount in Hours (mod 4) and max is 8 (1 day) }
21,390
12
// EIP 2612
function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external;
function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external;
12,922
0
// Does nothing, accepts ETH value (payable) /
fallback() external payable { }
fallback() external payable { }
11,511
0
// Reading the implementation of the AxelarDepositService and delegating the call back to it solhint-disable-next-line avoid-low-level-calls
(bool success, ) = IAxelarDepositService(msg.sender).receiverImplementation().delegatecall(delegateData);
(bool success, ) = IAxelarDepositService(msg.sender).receiverImplementation().delegatecall(delegateData);
9,947
27
// '_selectorCount & 7' is a gas efficient modulo by eight '_selectorCount % 8'
uint256 selectorInSlotPosition = (_selectorCount & 7) << 5;
uint256 selectorInSlotPosition = (_selectorCount & 7) << 5;
3,023
24
// Revert and pass along revert message if call to upgrade beacon reverts.
require(_ok, string(_returnData));
require(_ok, string(_returnData));
6,195
1,240
// Calculates the net value of a currency within a portfolio, this is a bit/ convoluted to fit into the stack frame
function _calculateLiquidationAssetValue( FreeCollateralFactors memory factors, LiquidationFactors memory liquidationFactors, bytes2 currencyBytes, bool setLiquidationFactors, uint256 blockTime
function _calculateLiquidationAssetValue( FreeCollateralFactors memory factors, LiquidationFactors memory liquidationFactors, bytes2 currencyBytes, bool setLiquidationFactors, uint256 blockTime
63,550
31
// mint new token
uint256 changedPetTokenId = _tokenIdCounter.current() + 1; _safeMint(msg.sender, changedPetTokenId); _tokenIdCounter.increment();
uint256 changedPetTokenId = _tokenIdCounter.current() + 1; _safeMint(msg.sender, changedPetTokenId); _tokenIdCounter.increment();
4,807
65
// Atomically increases the allowance granted to `spender` by the caller.
* This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; }
* This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; }
34,750
1
// Getters
function getRegisterPrice() external view returns(uint256)
function getRegisterPrice() external view returns(uint256)
32,805
29
// If the Stability Pool was emptied, increment the epoch, and reset the scale and product P
if (newProductFactor == 0) { currentEpoch += 1; emit EpochUpdated(currentEpoch); currentScale = 0; emit ScaleUpdated(0); newP = DECIMAL_PRECISION;
if (newProductFactor == 0) { currentEpoch += 1; emit EpochUpdated(currentEpoch); currentScale = 0; emit ScaleUpdated(0); newP = DECIMAL_PRECISION;
31,031
59
// bonusSum = bonusSum - bonusPart + bonus
bonusSum = bonusSum.sub(bonusPart).add(bonus); return adjustedAmount;
bonusSum = bonusSum.sub(bonusPart).add(bonus); return adjustedAmount;
20,616
57
// Add tokens for specified beneficiary (referral system tokens, for example). _beneficiary Token purchaser _tokenAmount Amount of tokens added /
function addTokens(address _beneficiary, uint256 _tokenAmount) public onlyOwner { balances[_beneficiary] = balances[_beneficiary].add(_tokenAmount); tokensIssued = tokensIssued.add(_tokenAmount); emit TokenAdded(_beneficiary, _tokenAmount); }
function addTokens(address _beneficiary, uint256 _tokenAmount) public onlyOwner { balances[_beneficiary] = balances[_beneficiary].add(_tokenAmount); tokensIssued = tokensIssued.add(_tokenAmount); emit TokenAdded(_beneficiary, _tokenAmount); }
67,336
197
// PaymentSplitter This contract allows to split Ether payments among a group of accounts. The sender does not need to be awarethat the Ether will be split in this way, since it is handled transparently by the contract. The split can be in equal parts or in any other arbitrary proportion. The way this is specified is by assigning eachaccount to a number of shares. Of all the Ether that this contract receives, each account will then be able to claiman amount proportional to the percentage of total shares they were assigned. `PaymentSplitter` follows a _pull payment_ model. This means that
* accounts but kept in this contract, and the actual transfer is triggered as a separate step by calling the {release} * function. */ contract PaymentSplitter is Context { event PayeeAdded(address account, uint256 shares); event PaymentReleased(address to, uint256 amount); event PaymentReceived(address from, uint256 amount); uint256 private _totalShares; uint256 private _totalReleased; mapping(address => uint256) private _shares; mapping(address => uint256) private _released; address[] private _payees; /** * @dev Creates an instance of `PaymentSplitter` where each account in `payees` is assigned the number of shares at * the matching position in the `shares` array. * * All addresses in `payees` must be non-zero. Both arrays must have the same non-zero length, and there must be no * duplicates in `payees`. */ constructor(address[] memory payees, uint256[] memory shares_) payable { require(payees.length == shares_.length, "PaymentSplitter: payees and shares length mismatch"); require(payees.length > 0, "PaymentSplitter: no payees"); for (uint256 i = 0; i < payees.length; i++) { _addPayee(payees[i], shares_[i]); } } /** * @dev The Ether received will be logged with {PaymentReceived} events. Note that these events are not fully * reliable: it's possible for a contract to receive Ether without triggering this function. This only affects the * reliability of the events, and not the actual splitting of Ether. * * To learn more about this see the Solidity documentation for * https://solidity.readthedocs.io/en/latest/contracts.html#fallback-function[fallback * functions]. */ receive() external payable virtual { emit PaymentReceived(_msgSender(), msg.value); } /** * @dev Getter for the total shares held by payees. */ function totalShares() public view returns (uint256) { return _totalShares; } /** * @dev Getter for the total amount of Ether already released. */ function totalReleased() public view returns (uint256) { return _totalReleased; } /** * @dev Getter for the amount of shares held by an account. */ function shares(address account) public view returns (uint256) { return _shares[account]; } /** * @dev Getter for the amount of Ether already released to a payee. */ function released(address account) public view returns (uint256) { return _released[account]; } /** * @dev Getter for the address of the payee number `index`. */ function payee(uint256 index) public view returns (address) { return _payees[index]; } /** * @dev Triggers a transfer to `account` of the amount of Ether they are owed, according to their percentage of the * total shares and their previous withdrawals. */ function release(address payable account) public virtual { require(_shares[account] > 0, "PaymentSplitter: account has no shares"); uint256 totalReceived = address(this).balance + _totalReleased; uint256 payment = (totalReceived * _shares[account]) / _totalShares - _released[account]; require(payment != 0, "PaymentSplitter: account is not due payment"); _released[account] = _released[account] + payment; _totalReleased = _totalReleased + payment; Address.sendValue(account, payment); emit PaymentReleased(account, payment); } /** * @dev Add a new payee to the contract. * @param account The address of the payee to add. * @param shares_ The number of shares owned by the payee. */ function _addPayee(address account, uint256 shares_) private { require(account != address(0), "PaymentSplitter: account is the zero address"); require(shares_ > 0, "PaymentSplitter: shares are 0"); require(_shares[account] == 0, "PaymentSplitter: account already has shares"); _payees.push(account); _shares[account] = shares_; _totalShares = _totalShares + shares_; emit PayeeAdded(account, shares_); } }
* accounts but kept in this contract, and the actual transfer is triggered as a separate step by calling the {release} * function. */ contract PaymentSplitter is Context { event PayeeAdded(address account, uint256 shares); event PaymentReleased(address to, uint256 amount); event PaymentReceived(address from, uint256 amount); uint256 private _totalShares; uint256 private _totalReleased; mapping(address => uint256) private _shares; mapping(address => uint256) private _released; address[] private _payees; /** * @dev Creates an instance of `PaymentSplitter` where each account in `payees` is assigned the number of shares at * the matching position in the `shares` array. * * All addresses in `payees` must be non-zero. Both arrays must have the same non-zero length, and there must be no * duplicates in `payees`. */ constructor(address[] memory payees, uint256[] memory shares_) payable { require(payees.length == shares_.length, "PaymentSplitter: payees and shares length mismatch"); require(payees.length > 0, "PaymentSplitter: no payees"); for (uint256 i = 0; i < payees.length; i++) { _addPayee(payees[i], shares_[i]); } } /** * @dev The Ether received will be logged with {PaymentReceived} events. Note that these events are not fully * reliable: it's possible for a contract to receive Ether without triggering this function. This only affects the * reliability of the events, and not the actual splitting of Ether. * * To learn more about this see the Solidity documentation for * https://solidity.readthedocs.io/en/latest/contracts.html#fallback-function[fallback * functions]. */ receive() external payable virtual { emit PaymentReceived(_msgSender(), msg.value); } /** * @dev Getter for the total shares held by payees. */ function totalShares() public view returns (uint256) { return _totalShares; } /** * @dev Getter for the total amount of Ether already released. */ function totalReleased() public view returns (uint256) { return _totalReleased; } /** * @dev Getter for the amount of shares held by an account. */ function shares(address account) public view returns (uint256) { return _shares[account]; } /** * @dev Getter for the amount of Ether already released to a payee. */ function released(address account) public view returns (uint256) { return _released[account]; } /** * @dev Getter for the address of the payee number `index`. */ function payee(uint256 index) public view returns (address) { return _payees[index]; } /** * @dev Triggers a transfer to `account` of the amount of Ether they are owed, according to their percentage of the * total shares and their previous withdrawals. */ function release(address payable account) public virtual { require(_shares[account] > 0, "PaymentSplitter: account has no shares"); uint256 totalReceived = address(this).balance + _totalReleased; uint256 payment = (totalReceived * _shares[account]) / _totalShares - _released[account]; require(payment != 0, "PaymentSplitter: account is not due payment"); _released[account] = _released[account] + payment; _totalReleased = _totalReleased + payment; Address.sendValue(account, payment); emit PaymentReleased(account, payment); } /** * @dev Add a new payee to the contract. * @param account The address of the payee to add. * @param shares_ The number of shares owned by the payee. */ function _addPayee(address account, uint256 shares_) private { require(account != address(0), "PaymentSplitter: account is the zero address"); require(shares_ > 0, "PaymentSplitter: shares are 0"); require(_shares[account] == 0, "PaymentSplitter: account already has shares"); _payees.push(account); _shares[account] = shares_; _totalShares = _totalShares + shares_; emit PayeeAdded(account, shares_); } }
1,233
645
// receives tokens and shares them among holders
contract CropJoin { VatLike public immutable vat; // cdp engine bytes32 public immutable ilk; // collateral type ERC20 public immutable gem; // collateral token uint256 public immutable dec; // gem decimals ERC20 public immutable bonus; // rewards token uint256 public share; // crops per gem [ray] uint256 public total; // total gems [wad] uint256 public stock; // crop balance [wad] mapping (address => uint256) public crops; // crops per user [wad] mapping (address => uint256) public stake; // gems per user [wad] uint256 immutable internal to18ConversionFactor; uint256 immutable internal toGemConversionFactor; // --- Events --- event Join(uint256 val); event Exit(uint256 val); event Flee(); event Tack(address indexed src, address indexed dst, uint256 wad); constructor(address vat_, bytes32 ilk_, address gem_, address bonus_) public { vat = VatLike(vat_); ilk = ilk_; gem = ERC20(gem_); uint256 dec_ = ERC20(gem_).decimals(); require(dec_ <= 18); dec = dec_; to18ConversionFactor = 10 ** (18 - dec_); toGemConversionFactor = 10 ** dec_; bonus = ERC20(bonus_); } function add(uint256 x, uint256 y) public pure returns (uint256 z) { require((z = x + y) >= x, "ds-math-add-overflow"); } function sub(uint256 x, uint256 y) public pure returns (uint256 z) { require((z = x - y) <= x, "ds-math-sub-underflow"); } function mul(uint256 x, uint256 y) public pure returns (uint256 z) { require(y == 0 || (z = x * y) / y == x, "ds-math-mul-overflow"); } function divup(uint256 x, uint256 y) internal pure returns (uint256 z) { z = add(x, sub(y, 1)) / y; } uint256 constant WAD = 10 ** 18; function wmul(uint256 x, uint256 y) public pure returns (uint256 z) { z = mul(x, y) / WAD; } function wdiv(uint256 x, uint256 y) public pure returns (uint256 z) { z = mul(x, WAD) / y; } function wdivup(uint256 x, uint256 y) public pure returns (uint256 z) { z = divup(mul(x, WAD), y); } uint256 constant RAY = 10 ** 27; function rmul(uint256 x, uint256 y) public pure returns (uint256 z) { z = mul(x, y) / RAY; } function rmulup(uint256 x, uint256 y) public pure returns (uint256 z) { z = divup(mul(x, y), RAY); } function rdiv(uint256 x, uint256 y) public pure returns (uint256 z) { z = mul(x, RAY) / y; } // Net Asset Valuation [wad] function nav() public virtual returns (uint256) { uint256 _nav = gem.balanceOf(address(this)); return mul(_nav, to18ConversionFactor); } // Net Assets per Share [wad] function nps() public returns (uint256) { if (total == 0) return WAD; else return wdiv(nav(), total); } function crop() internal virtual returns (uint256) { return sub(bonus.balanceOf(address(this)), stock); } function harvest(address from, address to) internal { if (total > 0) share = add(share, rdiv(crop(), total)); uint256 last = crops[from]; uint256 curr = rmul(stake[from], share); if (curr > last) require(bonus.transfer(to, curr - last)); stock = bonus.balanceOf(address(this)); } function join(address urn, uint256 val) internal virtual { harvest(urn, urn); if (val > 0) { uint256 wad = wdiv(mul(val, to18ConversionFactor), nps()); // Overflow check for int256(wad) cast below // Also enforces a non-zero wad require(int256(wad) > 0); require(gem.transferFrom(msg.sender, address(this), val)); vat.slip(ilk, urn, int256(wad)); total = add(total, wad); stake[urn] = add(stake[urn], wad); } crops[urn] = rmulup(stake[urn], share); emit Join(val); } function exit(address guy, uint256 val) internal virtual { harvest(msg.sender, guy); if (val > 0) { uint256 wad = wdivup(mul(val, to18ConversionFactor), nps()); // Overflow check for int256(wad) cast below // Also enforces a non-zero wad require(int256(wad) > 0); require(gem.transfer(guy, val)); vat.slip(ilk, msg.sender, -int256(wad)); total = sub(total, wad); stake[msg.sender] = sub(stake[msg.sender], wad); } crops[msg.sender] = rmulup(stake[msg.sender], share); emit Exit(val); } }
contract CropJoin { VatLike public immutable vat; // cdp engine bytes32 public immutable ilk; // collateral type ERC20 public immutable gem; // collateral token uint256 public immutable dec; // gem decimals ERC20 public immutable bonus; // rewards token uint256 public share; // crops per gem [ray] uint256 public total; // total gems [wad] uint256 public stock; // crop balance [wad] mapping (address => uint256) public crops; // crops per user [wad] mapping (address => uint256) public stake; // gems per user [wad] uint256 immutable internal to18ConversionFactor; uint256 immutable internal toGemConversionFactor; // --- Events --- event Join(uint256 val); event Exit(uint256 val); event Flee(); event Tack(address indexed src, address indexed dst, uint256 wad); constructor(address vat_, bytes32 ilk_, address gem_, address bonus_) public { vat = VatLike(vat_); ilk = ilk_; gem = ERC20(gem_); uint256 dec_ = ERC20(gem_).decimals(); require(dec_ <= 18); dec = dec_; to18ConversionFactor = 10 ** (18 - dec_); toGemConversionFactor = 10 ** dec_; bonus = ERC20(bonus_); } function add(uint256 x, uint256 y) public pure returns (uint256 z) { require((z = x + y) >= x, "ds-math-add-overflow"); } function sub(uint256 x, uint256 y) public pure returns (uint256 z) { require((z = x - y) <= x, "ds-math-sub-underflow"); } function mul(uint256 x, uint256 y) public pure returns (uint256 z) { require(y == 0 || (z = x * y) / y == x, "ds-math-mul-overflow"); } function divup(uint256 x, uint256 y) internal pure returns (uint256 z) { z = add(x, sub(y, 1)) / y; } uint256 constant WAD = 10 ** 18; function wmul(uint256 x, uint256 y) public pure returns (uint256 z) { z = mul(x, y) / WAD; } function wdiv(uint256 x, uint256 y) public pure returns (uint256 z) { z = mul(x, WAD) / y; } function wdivup(uint256 x, uint256 y) public pure returns (uint256 z) { z = divup(mul(x, WAD), y); } uint256 constant RAY = 10 ** 27; function rmul(uint256 x, uint256 y) public pure returns (uint256 z) { z = mul(x, y) / RAY; } function rmulup(uint256 x, uint256 y) public pure returns (uint256 z) { z = divup(mul(x, y), RAY); } function rdiv(uint256 x, uint256 y) public pure returns (uint256 z) { z = mul(x, RAY) / y; } // Net Asset Valuation [wad] function nav() public virtual returns (uint256) { uint256 _nav = gem.balanceOf(address(this)); return mul(_nav, to18ConversionFactor); } // Net Assets per Share [wad] function nps() public returns (uint256) { if (total == 0) return WAD; else return wdiv(nav(), total); } function crop() internal virtual returns (uint256) { return sub(bonus.balanceOf(address(this)), stock); } function harvest(address from, address to) internal { if (total > 0) share = add(share, rdiv(crop(), total)); uint256 last = crops[from]; uint256 curr = rmul(stake[from], share); if (curr > last) require(bonus.transfer(to, curr - last)); stock = bonus.balanceOf(address(this)); } function join(address urn, uint256 val) internal virtual { harvest(urn, urn); if (val > 0) { uint256 wad = wdiv(mul(val, to18ConversionFactor), nps()); // Overflow check for int256(wad) cast below // Also enforces a non-zero wad require(int256(wad) > 0); require(gem.transferFrom(msg.sender, address(this), val)); vat.slip(ilk, urn, int256(wad)); total = add(total, wad); stake[urn] = add(stake[urn], wad); } crops[urn] = rmulup(stake[urn], share); emit Join(val); } function exit(address guy, uint256 val) internal virtual { harvest(msg.sender, guy); if (val > 0) { uint256 wad = wdivup(mul(val, to18ConversionFactor), nps()); // Overflow check for int256(wad) cast below // Also enforces a non-zero wad require(int256(wad) > 0); require(gem.transfer(guy, val)); vat.slip(ilk, msg.sender, -int256(wad)); total = sub(total, wad); stake[msg.sender] = sub(stake[msg.sender], wad); } crops[msg.sender] = rmulup(stake[msg.sender], share); emit Exit(val); } }
10,574
45
// This Pool ignores the `dueProtocolFees` return value, so we simply return a zeroed-out array.
return (amountsOut, new uint256[](balances.length));
return (amountsOut, new uint256[](balances.length));
21,761
33
// Add a new friend request to the mapping/_to To friend address/_pubKey PubKey associated with the request
function makeRequest(address _to, string memory _pubKey) public whenNotPaused { uint index = requestsTracker[_to][msg.sender]; require(msg.sender != _to, "You cannot send a friend request to yourself"); // You have already sent a friend request to this address require(index == 0 || index == MAX_UINT, "Friend request already sent"); // You have already received a friend request from this address require(requestsTracker[msg.sender][_to] == 0 || requestsTracker[msg.sender][_to] == MAX_UINT, "Friend request already sent"); // Must not be friend require(friendsTracker[msg.sender][_to] == 0 || friendsTracker[msg.sender][_to] == MAX_UINT, "You are already friends"); _addRequest( _to, FriendRequest(msg.sender, _pubKey) ); emit FriendRequestSent(_to); }
function makeRequest(address _to, string memory _pubKey) public whenNotPaused { uint index = requestsTracker[_to][msg.sender]; require(msg.sender != _to, "You cannot send a friend request to yourself"); // You have already sent a friend request to this address require(index == 0 || index == MAX_UINT, "Friend request already sent"); // You have already received a friend request from this address require(requestsTracker[msg.sender][_to] == 0 || requestsTracker[msg.sender][_to] == MAX_UINT, "Friend request already sent"); // Must not be friend require(friendsTracker[msg.sender][_to] == 0 || friendsTracker[msg.sender][_to] == MAX_UINT, "You are already friends"); _addRequest( _to, FriendRequest(msg.sender, _pubKey) ); emit FriendRequestSent(_to); }
42,987
9
// We need to consume some amount of L1 gas in order to rate limit transactions going into L2. However, L2 is cheaper than L1 so we only need to burn some small proportion of the provided L1 gas.
uint256 gasToConsume = _gasLimit/L2_GAS_DISCOUNT_DIVISOR; uint256 startingGas = gasleft();
uint256 gasToConsume = _gasLimit/L2_GAS_DISCOUNT_DIVISOR; uint256 startingGas = gasleft();
27,895
10
// Allow owner to change base fee:
function setBaseFee(uint256 newFee) external onlyOwner returns (uint256) { _baseFee = newFee; return _baseFee; }
function setBaseFee(uint256 newFee) external onlyOwner returns (uint256) { _baseFee = newFee; return _baseFee; }
71,048
53
// We count ETH invested by person, for refunds (see below)
mapping(address => uint) ethInvestedBy; uint collectedWei = 0;
mapping(address => uint) ethInvestedBy; uint collectedWei = 0;
19,130
0
// Create the events
event RegisteredContent(uint256 counter, bytes32 indexed hashId, string indexed contentUrl, address indexed owner, uint256 timestamp, string email, string termsOfUse);
event RegisteredContent(uint256 counter, bytes32 indexed hashId, string indexed contentUrl, address indexed owner, uint256 timestamp, string email, string termsOfUse);
27,886
3
// a library for performing overflow-safe math, updated with awesomeness from of DappHub (https:github.com/dapphub/ds-math)
library BoringMath { function add(uint256 a, uint256 b) internal pure returns (uint256 c) {require((c = a + b) >= b, "BoringMath: Add Overflow");} function sub(uint256 a, uint256 b) internal pure returns (uint256 c) {require((c = a - b) <= a, "BoringMath: Underflow");} function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {require(b == 0 || (c = a * b)/b == a, "BoringMath: Mul Overflow");} function to128(uint256 a) internal pure returns (uint128 c) { require(a <= uint128(-1), "BoringMath: uint128 Overflow"); c = uint128(a); } function to64(uint256 a) internal pure returns (uint64 c) { require(a <= uint64(-1), "BoringMath: uint64 Overflow"); c = uint64(a); } function to32(uint256 a) internal pure returns (uint32 c) { require(a <= uint32(-1), "BoringMath: uint32 Overflow"); c = uint32(a); } }
library BoringMath { function add(uint256 a, uint256 b) internal pure returns (uint256 c) {require((c = a + b) >= b, "BoringMath: Add Overflow");} function sub(uint256 a, uint256 b) internal pure returns (uint256 c) {require((c = a - b) <= a, "BoringMath: Underflow");} function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {require(b == 0 || (c = a * b)/b == a, "BoringMath: Mul Overflow");} function to128(uint256 a) internal pure returns (uint128 c) { require(a <= uint128(-1), "BoringMath: uint128 Overflow"); c = uint128(a); } function to64(uint256 a) internal pure returns (uint64 c) { require(a <= uint64(-1), "BoringMath: uint64 Overflow"); c = uint64(a); } function to32(uint256 a) internal pure returns (uint32 c) { require(a <= uint32(-1), "BoringMath: uint32 Overflow"); c = uint32(a); } }
5,776
74
// The beneficiary at any time can take rights in all roles and prescribe his wallet in all the rollers. Thus, he will become the recipient of tokens for the role of Accountant, Team, etc. Works at any time. @ Do I have to use the functionno @ When it is possible to callany time @ When it is launched automatically- @ Who can call the functiononly Beneficiary
function resetAllWallets() external{ address _beneficiary = wallets[uint8(Roles.beneficiary)]; require(msg.sender == _beneficiary); for(uint8 i = 0; i < wallets.length; i++){ if(uint8(Roles.fees) == i || uint8(Roles.team) == i) continue; wallets[i] = _beneficiary; } token.setUnpausedWallet(_beneficiary, true); }
function resetAllWallets() external{ address _beneficiary = wallets[uint8(Roles.beneficiary)]; require(msg.sender == _beneficiary); for(uint8 i = 0; i < wallets.length; i++){ if(uint8(Roles.fees) == i || uint8(Roles.team) == i) continue; wallets[i] = _beneficiary; } token.setUnpausedWallet(_beneficiary, true); }
80,371
252
// 9. Emit the event
emit CollateralDeposited(account, id, amount, loan.collateral);
emit CollateralDeposited(account, id, amount, loan.collateral);
2,321
92
// {address[]}return {bool} /
function addWhitelist(address[] memory addresses, uint256 tier) external onlyOwner returns (bool) { uint256 addressesLength = addresses.length; for (uint256 i = 0; i < addressesLength; i++) { address address_ = addresses[i]; Whitelist memory whitelist_ =
function addWhitelist(address[] memory addresses, uint256 tier) external onlyOwner returns (bool) { uint256 addressesLength = addresses.length; for (uint256 i = 0; i < addressesLength; i++) { address address_ = addresses[i]; Whitelist memory whitelist_ =
13,004
85
// Buy
else if (automatedMarketMakerPairs[from]) { _taxFee = _buyTaxFee; _liquidityFee = _buyLiquidityFee + _buyMarketingFee; if(_liquidityFee > 0){ buyOrSellSwitch = BUY; }
else if (automatedMarketMakerPairs[from]) { _taxFee = _buyTaxFee; _liquidityFee = _buyLiquidityFee + _buyMarketingFee; if(_liquidityFee > 0){ buyOrSellSwitch = BUY; }
861
174
// assumes that loan, collateral, and interest token are the same
borrowAmount = depositAmount .mul(WEI_PERCENT_PRECISION * WEI_PERCENT_PRECISION) .div(_adjustValue( interestRate, 2419200, // 28 day duration for margin trades initialMargin)) .div(initialMargin);
borrowAmount = depositAmount .mul(WEI_PERCENT_PRECISION * WEI_PERCENT_PRECISION) .div(_adjustValue( interestRate, 2419200, // 28 day duration for margin trades initialMargin)) .div(initialMargin);
21,966
415
// Removes a value from a set. O(1). Returns true if the key was removed from the map, that is if it was present. /
function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) { return _remove(map._inner, bytes32(key)); }
function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) { return _remove(map._inner, bytes32(key)); }
35,926
90
// Enables a fee amount with the given tickSpacing/Fee amounts may never be removed once enabled/fee The fee amount to enable, denominated in hundredths of a bip (i.e. 1e-6)/tickSpacing The spacing between ticks to be enforced for all pools created with the given fee amount
function enableFeeAmount(uint24 fee, int24 tickSpacing) external;
function enableFeeAmount(uint24 fee, int24 tickSpacing) external;
40,964
67
// Ensure that currentMessageBatchIndex is within range
require( currentMessageBatchIndex <= messageTreeMaxLeafIndex, "MACI: currentMessageBatchIndex not within range" );
require( currentMessageBatchIndex <= messageTreeMaxLeafIndex, "MACI: currentMessageBatchIndex not within range" );
5,998