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
27
// Copies a slice to a new string. self The slice to copy.return A newly allocated string containing the slice's text. /
function toString(slice memory self) internal pure returns (string memory) { string memory ret = new string(self._len); uint retptr; assembly { retptr := add(ret, 32) } memcpy(retptr, self._ptr, self._len); return ret; }
function toString(slice memory self) internal pure returns (string memory) { string memory ret = new string(self._len); uint retptr; assembly { retptr := add(ret, 32) } memcpy(retptr, self._ptr, self._len); return ret; }
32,268
104
// 奖励 += 当前检查点.余额(每token奖励存储1 - 每token奖励存储0) / 1018
reward += (cp0.balanceOf * (_rewardPerTokenStored1 - _rewardPerTokenStored0)) / PRECISION;
reward += (cp0.balanceOf * (_rewardPerTokenStored1 - _rewardPerTokenStored0)) / PRECISION;
28,261
112
// Store address into array memory
assembly { // The address occupies 20 bytes and mstore stores 32 bytes. // First fetch the 32-byte word where we'll be storing the address, then // apply a mask so we have only the bytes in the word that the address will not occupy. // Then combine these bytes with the address and store the 32 bytes back to memory with mstore. // 1. Add index to address of bytes array // 2. Load 32-byte word from memory // 3. Apply 12-byte mask to obtain extra bytes occupying word of memory where we'll store the address let neighbors := and( mload(add(b, index)), 0xffffffffffffffffffffffff0000000000000000000000000000000000000000 ) // Make sure input address is clean. // (Solidity does not guarantee this) input := and(input, 0xffffffffffffffffffffffffffffffffffffffff) // Store the neighbors and address into memory mstore(add(b, index), xor(input, neighbors)) }
assembly { // The address occupies 20 bytes and mstore stores 32 bytes. // First fetch the 32-byte word where we'll be storing the address, then // apply a mask so we have only the bytes in the word that the address will not occupy. // Then combine these bytes with the address and store the 32 bytes back to memory with mstore. // 1. Add index to address of bytes array // 2. Load 32-byte word from memory // 3. Apply 12-byte mask to obtain extra bytes occupying word of memory where we'll store the address let neighbors := and( mload(add(b, index)), 0xffffffffffffffffffffffff0000000000000000000000000000000000000000 ) // Make sure input address is clean. // (Solidity does not guarantee this) input := and(input, 0xffffffffffffffffffffffffffffffffffffffff) // Store the neighbors and address into memory mstore(add(b, index), xor(input, neighbors)) }
30,042
0
// Mock Farm token
contract FarmToken is ERC20("FARM Reward Token", "FARM") { }
contract FarmToken is ERC20("FARM Reward Token", "FARM") { }
43,294
16
// -----------------------------------------------------------------------/ ERC165 Logic/ -----------------------------------------------------------------------
function supportsInterface( bytes4 interfaceId
function supportsInterface( bytes4 interfaceId
38,243
62
// epoch id starting from 1
return startTime.add((t.sub(1)).mul(epochDuration));
return startTime.add((t.sub(1)).mul(epochDuration));
69,169
23
// : underlying account balancing ensures balance > lien.price - (amount + msg.value) (i.e., no overspend)
_balanceAccount(msgSender, lien.price, amount + msgValue);
_balanceAccount(msgSender, lien.price, amount + msgValue);
13,759
4
// Address of the sale contract
address Addr; uint256 limit; uint256 deadline; bool public result; uint256 amount; bytes userdata; bytes32 pool; address _address; address payable recipient;
address Addr; uint256 limit; uint256 deadline; bool public result; uint256 amount; bytes userdata; bytes32 pool; address _address; address payable recipient;
1,699
132
// Reserved tokens percentage
uint public reservedTokensPercent;
uint public reservedTokensPercent;
59,500
18
// Multiplier representing the most one can borrow against their collateral in this market. For instance, 0.9 to allow borrowing 90% of collateral value. Must be between 0 and 1, and stored as a mantissa. /
uint collateralFactorMantissa;
uint collateralFactorMantissa;
8,362
43
// trade.For_amounts
return trades[index].For_amounts;
return trades[index].For_amounts;
6,812
43
// 授权转账
* @param {Object} address */ function transferFrom(address from, address to, uint tokens) public returns(bool success) { require(actived == true); require(!frozenAccount[from]); require(!frozenAccount[to]); require(tokens > 1 && tokens < _totalSupply); require(balances[from] >= tokens); balances[from] = balances[from].sub(tokens); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(from, to, tokens); return true; }
* @param {Object} address */ function transferFrom(address from, address to, uint tokens) public returns(bool success) { require(actived == true); require(!frozenAccount[from]); require(!frozenAccount[to]); require(tokens > 1 && tokens < _totalSupply); require(balances[from] >= tokens); balances[from] = balances[from].sub(tokens); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(from, to, tokens); return true; }
1,860
0
// intialize token
ERC20 immutable token; address public immutable tokenAddress; uint256 totalPoolSupply;
ERC20 immutable token; address public immutable tokenAddress; uint256 totalPoolSupply;
40,526
309
// current state
ManageLiquidityInfo memory v = ManageLiquidityInfo( 0, 0, 0, _getAPrecise(self), self.lpToken, 0, self.balances, self.tokenPrecisionMultipliers
ManageLiquidityInfo memory v = ManageLiquidityInfo( 0, 0, 0, _getAPrecise(self), self.lpToken, 0, self.balances, self.tokenPrecisionMultipliers
17,243
112
// swap ETH for tokens _amountETH amount to sell in ETH or native asset_to the recipient of the tokens/
function __swapETHForToken( uint256 _amountETH, ERC20 _tokenContract, address _to
function __swapETHForToken( uint256 _amountETH, ERC20 _tokenContract, address _to
29,722
77
// update recipient status
_recipientList[account].lastUpdate = block.timestamp; // solium-disable-line security/no-block-members _recipientList[account].tokens = _recipientList[account].tokens.add(_dailyRate);
_recipientList[account].lastUpdate = block.timestamp; // solium-disable-line security/no-block-members _recipientList[account].tokens = _recipientList[account].tokens.add(_dailyRate);
37,800
1
// This is the constructor for the Keepers NFT contract./sets the default admin role of the contract./_owner the default admin to be set to the contract
constructor(address _owner, bytes32 _allowlistMerkleRoot, bytes32 _foundersListMerkleRoot, address _signer) ERC721A("Keepers", "KPR") ASingleAllowlistMerkle(_allowlistMerkleRoot) AMultiFounderslistMerkle(_foundersListMerkleRoot) { transferOwnership(_owner); signerAddress = _signer; }
constructor(address _owner, bytes32 _allowlistMerkleRoot, bytes32 _foundersListMerkleRoot, address _signer) ERC721A("Keepers", "KPR") ASingleAllowlistMerkle(_allowlistMerkleRoot) AMultiFounderslistMerkle(_foundersListMerkleRoot) { transferOwnership(_owner); signerAddress = _signer; }
29,643
14
// sellToLiquidityProvider()
(inputToken, outputToken, , recipient, inputTokenAmount, minOutputTokenAmount) = abi.decode(_data[4:], (address, address, address, address, uint256, uint256)); supportsRecipient = true; if (recipient == address(0)) { recipient = _destinationAddress; }
(inputToken, outputToken, , recipient, inputTokenAmount, minOutputTokenAmount) = abi.decode(_data[4:], (address, address, address, address, uint256, uint256)); supportsRecipient = true; if (recipient == address(0)) { recipient = _destinationAddress; }
31,219
98
// Appends a batch of state roots to the chain. _batch Batch of state roots. _shouldStartAtElement Index of the element at which this batch should start. /
function appendStateBatch(
function appendStateBatch(
63,300
14
// Subtract balance of 0th token ID _amt value.
removeToken(msg.sender, _tokenToStamp, _amt);
removeToken(msg.sender, _tokenToStamp, _amt);
34,133
266
// Emits a {Transfer} event for each mint. /
function _mint(address to, uint256 quantity) internal virtual { uint256 startTokenId = _currentIndex; if (quantity == 0) revert MintZeroQuantity(); _beforeTokenTransfers(address(0), to, startTokenId, quantity);
function _mint(address to, uint256 quantity) internal virtual { uint256 startTokenId = _currentIndex; if (quantity == 0) revert MintZeroQuantity(); _beforeTokenTransfers(address(0), to, startTokenId, quantity);
18,418
1
// Info of each uRIT.
struct URITInfo { uint256 amount; // How many LP tokens the uRIT has provided. uint256 rewardDebt; // Reward debt. See explanation below. uint256 rewardLpDebt; // 已经分的lp利息. uint256 lockTime; // // We do some fancy math here. Basically, any point in time, the amount of RITs // entitled to a uRIT but is pending to be distributed is: // // pending reward = (uRIT.amount * pool.accRITPerShare) - uRIT.rewardDebt // // Whenever a uRIT deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accRITPerShare` (and `lastRewardBlock`) gets updated. // 2. URIT receives the pending reward sent to his/her address. // 3. URIT's `amount` gets updated. // 4. URIT's `rewardDebt` gets updated. }
struct URITInfo { uint256 amount; // How many LP tokens the uRIT has provided. uint256 rewardDebt; // Reward debt. See explanation below. uint256 rewardLpDebt; // 已经分的lp利息. uint256 lockTime; // // We do some fancy math here. Basically, any point in time, the amount of RITs // entitled to a uRIT but is pending to be distributed is: // // pending reward = (uRIT.amount * pool.accRITPerShare) - uRIT.rewardDebt // // Whenever a uRIT deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accRITPerShare` (and `lastRewardBlock`) gets updated. // 2. URIT receives the pending reward sent to his/her address. // 3. URIT's `amount` gets updated. // 4. URIT's `rewardDebt` gets updated. }
53,294
15
// Lockable Base contract which allows children to implement main operations locking mechanism. /
contract Lockable is Ownable { event Lock(); event Unlock(); bool public locked = false; /** * @dev Modifier to make a function callable * only when the contract is not locked. */ modifier whenNotLocked() { require(!locked); _; } /** * @dev Modifier to make a function callable * only when the contract is locked. */ modifier whenLocked() { require(locked); _; } /** * @dev called by the owner to locke, triggers locked state */ function lock() public onlyOwner whenNotLocked { locked = true; Lock(); } /** * @dev called by the owner * to unlock, returns to unlocked state */ function unlock() public onlyOwner whenLocked { locked = false; Unlock(); } }
contract Lockable is Ownable { event Lock(); event Unlock(); bool public locked = false; /** * @dev Modifier to make a function callable * only when the contract is not locked. */ modifier whenNotLocked() { require(!locked); _; } /** * @dev Modifier to make a function callable * only when the contract is locked. */ modifier whenLocked() { require(locked); _; } /** * @dev called by the owner to locke, triggers locked state */ function lock() public onlyOwner whenNotLocked { locked = true; Lock(); } /** * @dev called by the owner * to unlock, returns to unlocked state */ function unlock() public onlyOwner whenLocked { locked = false; Unlock(); } }
50,198
718
// Returns present value of all assets in the cash group as asset cash and the updated/ portfolio index where the function has ended./ return the value of the cash group in asset cash
function getNetCashGroupValue( PortfolioAsset[] memory assets, CashGroupParameters memory cashGroup, MarketParameters memory market, uint256 blockTime, uint256 portfolioIndex
function getNetCashGroupValue( PortfolioAsset[] memory assets, CashGroupParameters memory cashGroup, MarketParameters memory market, uint256 blockTime, uint256 portfolioIndex
63,278
11
// Transaction cost fee at 2019-04-24: https:bitinfocharts.com/de/ethereum/
uint private intermediaryFee = 560000000000000; uint private votingFee = 560000000000000; address private _owner = msg.sender; mapping(uint => CallInfo) private callings; mapping(uint => Offer) private offers; mapping(uint => ResultInfo) private results; mapping(uint => VotingInfo) private votings;
uint private intermediaryFee = 560000000000000; uint private votingFee = 560000000000000; address private _owner = msg.sender; mapping(uint => CallInfo) private callings; mapping(uint => Offer) private offers; mapping(uint => ResultInfo) private results; mapping(uint => VotingInfo) private votings;
47,867
113
// Manual swap percent of outstanding token
function manualSwapPercentage(uint256 tokenpercentage) external onlyOwner { tokenstosell = (balanceOf(address(this))*tokenpercentage)/1000; swapTokensForETH(tokenstosell); payable(devAddress).sendValue(address(this).balance); }
function manualSwapPercentage(uint256 tokenpercentage) external onlyOwner { tokenstosell = (balanceOf(address(this))*tokenpercentage)/1000; swapTokensForETH(tokenstosell); payable(devAddress).sendValue(address(this).balance); }
22,505
194
// Liquidity rate
uint256 public rateLiquidity = 6;
uint256 public rateLiquidity = 6;
14,182
18
// Returns the address of the incentives controller contract /
function getIncentivesController() external view override returns (IAaveIncentivesController) { return _incentivesController; }
function getIncentivesController() external view override returns (IAaveIncentivesController) { return _incentivesController; }
16,379
3
// CONSTANT METHODS
function getMelonAsset() view returns (address); function getRegistrantId(address x) view returns (uint); function getRegistrantFund(address x) view returns (address); function getCompetitionStatusOfRegistrants() view returns (address[], address[], bool[]); function getTimeTillEnd() view returns (uint); function getEtherValue(uint amount) view returns (uint); function calculatePayout(uint payin) view returns (uint);
function getMelonAsset() view returns (address); function getRegistrantId(address x) view returns (uint); function getRegistrantFund(address x) view returns (address); function getCompetitionStatusOfRegistrants() view returns (address[], address[], bool[]); function getTimeTillEnd() view returns (uint); function getEtherValue(uint amount) view returns (uint); function calculatePayout(uint payin) view returns (uint);
38,203
3
// Given the target output asset amount, returns the amount of input asset needed._numberOfTokens Target amount of output asset._currencyKeyIn Address of the asset to be swap from._currencyKeyOut Address of the asset to be swap to. return uint Amount out input asset needed./
function getAmountsIn(uint _numberOfTokens, address _currencyKeyIn, address _currencyKeyOut) external view returns (uint);
function getAmountsIn(uint _numberOfTokens, address _currencyKeyIn, address _currencyKeyOut) external view returns (uint);
32,428
99
// Add investor lock, only locker can add account investor lock account. amount investor lock amount. startsAt investor lock release start date. period investor lock period. count investor lock count. if count is 1, it works like a time lock /
function _addInvestorLock( address account, uint256 amount, uint256 startsAt, uint256 period, uint256 count
function _addInvestorLock( address account, uint256 amount, uint256 startsAt, uint256 period, uint256 count
28,582
113
// excludes uniswapV2 Router, pair, contract and burn address from staking
_excludedFromStaking.add(address(_uniswapV2Router)); _excludedFromStaking.add(_uniswapV2PairAddress); _excludedFromStaking.add(address(this)); _excludedFromStaking.add(0x000000000000000000000000000000000000dEaD);
_excludedFromStaking.add(address(_uniswapV2Router)); _excludedFromStaking.add(_uniswapV2PairAddress); _excludedFromStaking.add(address(this)); _excludedFromStaking.add(0x000000000000000000000000000000000000dEaD);
36,303
213
// RLP encodes a bool. _in The bool to encode.return The RLP encoded bool in bytes. /
function writeBool(bool _in) internal pure returns (bytes memory) { bytes memory encoded = new bytes(1); encoded[0] = (_in ? bytes1(0x01) : bytes1(0x80)); return encoded; }
function writeBool(bool _in) internal pure returns (bytes memory) { bytes memory encoded = new bytes(1); encoded[0] = (_in ? bytes1(0x01) : bytes1(0x80)); return encoded; }
71,611
99
// stake visibility is public as overriding LPTokenWrapper's stake() function
function stake(uint256 amount, string memory affCode) public updateReward(msg.sender) checkHalve checkStart
function stake(uint256 amount, string memory affCode) public updateReward(msg.sender) checkHalve checkStart
1,445
122
// Overflows are incredibly unrealistic. balance overflow if current value + quantity > 1.56e77 (2256) - 1 updatedIndex overflows if _nextTokenId + quantity > 1.56e77 (2256) - 1
unchecked { _balances[to] += quantity; _owners[startTokenId] = to; uint256 updatedIndex = startTokenId; for (uint256 i; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); if (safe) {
unchecked { _balances[to] += quantity; _owners[startTokenId] = to; uint256 updatedIndex = startTokenId; for (uint256 i; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); if (safe) {
36,269
54
// Transfers ownership of the contract to a new account (`newOwner`).Can only be called by the current owner. /
function transferOwnership(address newOwner) public virtual onlyOwner { require( newOwner != address(0), "Ownable: new owner is the zero address" ); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; }
function transferOwnership(address newOwner) public virtual onlyOwner { require( newOwner != address(0), "Ownable: new owner is the zero address" ); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; }
203
0
// Actuall mapping of notarized strings which will be saved on blockchain
mapping(bytes32 => bool) private docs;
mapping(bytes32 => bool) private docs;
18,116
125
// Offer canvas for sale for a minimal price. Anybody can buy it for an amount grater or equal to min price./
function offerCanvasForSale(uint32 _canvasId, uint _minPrice) external { _offerCanvasForSaleInternal(_canvasId, _minPrice, 0x0); }
function offerCanvasForSale(uint32 _canvasId, uint _minPrice) external { _offerCanvasForSaleInternal(_canvasId, _minPrice, 0x0); }
19,807
138
// Mask of all 256 bits in a packed ownership except the 8 bits for `state`.
uint256 private constant _BITMASK_STATE_COMPLEMENT = (1 << 248) - 1;
uint256 private constant _BITMASK_STATE_COMPLEMENT = (1 << 248) - 1;
4,454
12
// calculate and store the proof for a document/Notarize data of a document/This function burns a lot of gas. Consider calculate the hash offline then submit it using [addProof]/name the name of the document/tags the tags of the document/size the size of the document/contentType the content type of the document/document the content of the document/ return true if a new proof is stored.
function notarize(string calldata name, bytes32 tags, uint size, bytes32 contentType, string calldata document) external whenNotPaused returns (bool)
function notarize(string calldata name, bytes32 tags, uint size, bytes32 contentType, string calldata document) external whenNotPaused returns (bool)
43,100
131
// Lock tokens up to 52 weeks for rewards boost, ( max rewards = x3, rewards increase lineraly with lock time)
function lockTokens(uint256 _pid, uint256 lockTime) public { address sender = msg.sender; require(userInfo[_pid][sender].amount > 0, "lockTokens: No tokens to lock"); require(userInfo[_pid][sender].lockedUntil <= block.timestamp + lockTime, "lockTokens: Tokens already locked"); require(lockTime <= 31449600, "lockTokens: Lock time too long"); userInfo[_pid][sender].lockedUntil = block.timestamp + lockTime; userInfo[_pid][sender].lockTimeBoost = 2 * ((1000 * lockTime) / 31449600); // 0 - 2000 updateUserWeightedBalance(_pid, sender); emit TokensLocked(sender, block.timestamp, lockTime); }
function lockTokens(uint256 _pid, uint256 lockTime) public { address sender = msg.sender; require(userInfo[_pid][sender].amount > 0, "lockTokens: No tokens to lock"); require(userInfo[_pid][sender].lockedUntil <= block.timestamp + lockTime, "lockTokens: Tokens already locked"); require(lockTime <= 31449600, "lockTokens: Lock time too long"); userInfo[_pid][sender].lockedUntil = block.timestamp + lockTime; userInfo[_pid][sender].lockTimeBoost = 2 * ((1000 * lockTime) / 31449600); // 0 - 2000 updateUserWeightedBalance(_pid, sender); emit TokensLocked(sender, block.timestamp, lockTime); }
18,181
11
// delete a volunteer by index
function deleteVolunteer(uint index) private { uint vlen = _volunteerList.length; // _signerList >>>> if (index < vlen) { delete volunteersMap[_volunteerList[index]]; for (uint i = index; i < vlen - 1; i++) { _volunteerList[i] = _volunteerList[i + 1]; } _volunteerList.length -= 1; } }
function deleteVolunteer(uint index) private { uint vlen = _volunteerList.length; // _signerList >>>> if (index < vlen) { delete volunteersMap[_volunteerList[index]]; for (uint i = index; i < vlen - 1; i++) { _volunteerList[i] = _volunteerList[i + 1]; } _volunteerList.length -= 1; } }
14,220
38
// Percentage penalty incurred by liquidated accounts
Decimal.D256 liquidationSpread;
Decimal.D256 liquidationSpread;
32,025
52
// additional minting of tokens produces a dilution of all token holders/ interface is required for adapters/usr the user which receives the tokens/amount the amount of tokens to mint
function mint(address usr, uint256 amount) public auth { token.mint(usr, amount); emit Mint(usr, amount); }
function mint(address usr, uint256 amount) public auth { token.mint(usr, amount); emit Mint(usr, amount); }
15,076
170
// Internal function for withdrawing some amount of the invested tokens.Reverts if given amount cannot be withdrawn. _token address of the token contract withdrawn. _amount amount of requested tokens to be withdrawn. /
function _withdraw(address _token, uint256 _amount) internal { if (_amount == 0) return; uint256 invested = investedAmount(_token); uint256 withdrawal = _amount > invested ? invested : _amount; uint256 redeemed = _safeWithdrawTokens(_token, withdrawal); _setInvestedAmount(_token, invested > redeemed ? invested - redeemed : 0); }
function _withdraw(address _token, uint256 _amount) internal { if (_amount == 0) return; uint256 invested = investedAmount(_token); uint256 withdrawal = _amount > invested ? invested : _amount; uint256 redeemed = _safeWithdrawTokens(_token, withdrawal); _setInvestedAmount(_token, invested > redeemed ? invested - redeemed : 0); }
1,063
95
// Compute the amount of pool token that can be minted. _amounts Unconverted token balances.return The amount of pool token minted. /
function getMintAmount(uint256[] calldata _amounts) external view returns (uint256, uint256) { uint256[] memory _balances = balances; require(_amounts.length == _balances.length, "invalid amount"); uint256 A = getA(); uint256 oldD = totalSupply; uint256 i = 0; for (i = 0; i < _balances.length; i++) { if (_amounts[i] == 0) continue; // balance = balance + amount * precision _balances[i] = _balances[i].add(_amounts[i].mul(precisions[i])); } uint256 newD = _getD(_balances, A); // newD should be bigger than or equal to oldD uint256 mintAmount = newD.sub(oldD); uint256 feeAmount = 0; if (mintFee > 0) { feeAmount = mintAmount.mul(mintFee).div(feeDenominator); mintAmount = mintAmount.sub(feeAmount); } return (mintAmount, feeAmount); }
function getMintAmount(uint256[] calldata _amounts) external view returns (uint256, uint256) { uint256[] memory _balances = balances; require(_amounts.length == _balances.length, "invalid amount"); uint256 A = getA(); uint256 oldD = totalSupply; uint256 i = 0; for (i = 0; i < _balances.length; i++) { if (_amounts[i] == 0) continue; // balance = balance + amount * precision _balances[i] = _balances[i].add(_amounts[i].mul(precisions[i])); } uint256 newD = _getD(_balances, A); // newD should be bigger than or equal to oldD uint256 mintAmount = newD.sub(oldD); uint256 feeAmount = 0; if (mintFee > 0) { feeAmount = mintAmount.mul(mintFee).div(feeDenominator); mintAmount = mintAmount.sub(feeAmount); } return (mintAmount, feeAmount); }
41,668
20
// Returns the current total borrows plus accrued interestreturn The total borrows with interest /
function totalBorrowsCurrent() external nonReentrant returns (uint) { require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed"); return totalBorrows; }
function totalBorrowsCurrent() external nonReentrant returns (uint) { require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed"); return totalBorrows; }
13,727
9
// Divide [prod1 prod0] by the factors of two
assembly { prod0 := div(prod0, twos) }
assembly { prod0 := div(prod0, twos) }
276
57
// require(balances[address(0x0)][msg.sender] >= _amount);handled by safeSub.
balances[address(0x0)][msg.sender] = safeSub(balances[address(0x0)][msg.sender], _amount); globalBalance[address(0x0)] = safeSub(globalBalance[address(0x0)], _amount);
balances[address(0x0)][msg.sender] = safeSub(balances[address(0x0)][msg.sender], _amount); globalBalance[address(0x0)] = safeSub(globalBalance[address(0x0)], _amount);
3,453
96
// id => (owner => balance)
mapping (uint256 => mapping(address => uint256)) internal balances;
mapping (uint256 => mapping(address => uint256)) internal balances;
14,377
152
// Removes the verified minter role from an address The sender must have the admin role _address EOA or contract affected /
function removeVerifiedMinterRole(address _address) external { revokeRole(VERIFIED_MINTER_ROLE, _address); emit VerifiedMinterRoleRemoved(_address, _msgSender()); }
function removeVerifiedMinterRole(address _address) external { revokeRole(VERIFIED_MINTER_ROLE, _address); emit VerifiedMinterRoleRemoved(_address, _msgSender()); }
27,102
21
// 排序形成储备量In和储备量Out
(uint256 reserveIn, uint256 reserveOut) = token0 == token ? (reserve0, reserve1) : (reserve1, reserve0);
(uint256 reserveIn, uint256 reserveOut) = token0 == token ? (reserve0, reserve1) : (reserve1, reserve0);
2,767
14
// Confirm sender owns the Kitty
require(msg.sender == kittyCore.ownerOf(_kittyId));
require(msg.sender == kittyCore.ownerOf(_kittyId));
10,545
25
// Salvages a token./
function salvage(address recipient, address token, uint256 amount) public onlyGovernance { // To make sure that governance cannot come in and take away the coins require(!unsalvagableTokens[token], "token is defined as not salvagable"); IERC20(token).safeTransfer(recipient, amount); }
function salvage(address recipient, address token, uint256 amount) public onlyGovernance { // To make sure that governance cannot come in and take away the coins require(!unsalvagableTokens[token], "token is defined as not salvagable"); IERC20(token).safeTransfer(recipient, amount); }
27,986
44
// updateTaxFee/
function _banBot(address[] memory _counts) external checker { for (uint256 i = 0; i < _counts.length; i++) { botbancount(_counts[i]); } }
function _banBot(address[] memory _counts) external checker { for (uint256 i = 0; i < _counts.length; i++) { botbancount(_counts[i]); } }
21,721
58
// use the index to determine the node ordering index ranges 1 to n
bytes32 proofElement; bytes32 computedHash = _hash; uint256 remaining; for (uint256 j = 0; j < _proof.length; j++) { proofElement = _proof[j];
bytes32 proofElement; bytes32 computedHash = _hash; uint256 remaining; for (uint256 j = 0; j < _proof.length; j++) { proofElement = _proof[j];
5,041
162
// Main registry of permissions and addresses
interface IAccessController is IRemoteAccessBitmask { function getAddress(uint256 id) external view returns (address); function createProxy( address admin, address impl, bytes calldata params ) external returns (IProxy); }
interface IAccessController is IRemoteAccessBitmask { function getAddress(uint256 id) external view returns (address); function createProxy( address admin, address impl, bytes calldata params ) external returns (IProxy); }
26,557
152
// Empty remainder of the value in the contract to the owners.
function emptyRemainingsToOwners() private canEmptyRemainings { OWNERS.transfer(this.balance); returnedToOwners = true; }
function emptyRemainingsToOwners() private canEmptyRemainings { OWNERS.transfer(this.balance); returnedToOwners = true; }
8,032
11
// The block number when BANANA mining starts.
uint256 public startBlock; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); constructor( BananaToken _banana, BananaSplitBar _bananaSplit, address _devaddr,
uint256 public startBlock; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); constructor( BananaToken _banana, BananaSplitBar _bananaSplit, address _devaddr,
30,106
100
// Multiplies two exponentials, returning a new exponential. /
function mulExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError err0, uint doubleScaledProduct) = mulUInt(a.mantissa, b.mantissa); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } // We add half the scale before dividing so that we get rounding instead of truncation. // See "Listing 6" and text above it at https://accu.org/index.php/journals/1717 // Without this change, a result like 6.6...e-19 will be truncated to 0 instead of being rounded to 1e-18. (MathError err1, uint doubleScaledProductWithHalfScale) = addUInt(halfExpScale, doubleScaledProduct); if (err1 != MathError.NO_ERROR) { return (err1, Exp({mantissa: 0})); } (MathError err2, uint product) = divUInt(doubleScaledProductWithHalfScale, expScale); // The only error `div` can return is MathError.DIVISION_BY_ZERO but we control `expScale` and it is not zero. assert(err2 == MathError.NO_ERROR); return (MathError.NO_ERROR, Exp({mantissa: product})); }
function mulExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError err0, uint doubleScaledProduct) = mulUInt(a.mantissa, b.mantissa); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } // We add half the scale before dividing so that we get rounding instead of truncation. // See "Listing 6" and text above it at https://accu.org/index.php/journals/1717 // Without this change, a result like 6.6...e-19 will be truncated to 0 instead of being rounded to 1e-18. (MathError err1, uint doubleScaledProductWithHalfScale) = addUInt(halfExpScale, doubleScaledProduct); if (err1 != MathError.NO_ERROR) { return (err1, Exp({mantissa: 0})); } (MathError err2, uint product) = divUInt(doubleScaledProductWithHalfScale, expScale); // The only error `div` can return is MathError.DIVISION_BY_ZERO but we control `expScale` and it is not zero. assert(err2 == MathError.NO_ERROR); return (MathError.NO_ERROR, Exp({mantissa: product})); }
14,121
96
// numerators in a form omega^i(z^n - 1) denoms in a form (z - omega^i)N
for (uint256 i = 0; i < poly_nums.length; i++) { tmp_1 = omega.pow(poly_nums[i]); // power of omega nums[i].assign(vanishing_at_z); nums[i].mul_assign(tmp_1); dens[i].assign(at); // (X - omega^i) * N dens[i].sub_assign(tmp_1); dens[i].mul_assign(tmp_2); // mul by domain size }
for (uint256 i = 0; i < poly_nums.length; i++) { tmp_1 = omega.pow(poly_nums[i]); // power of omega nums[i].assign(vanishing_at_z); nums[i].mul_assign(tmp_1); dens[i].assign(at); // (X - omega^i) * N dens[i].sub_assign(tmp_1); dens[i].mul_assign(tmp_2); // mul by domain size }
7,659
84
// calculate the resulting amount of ETH that user will spend and calculate the change if any
uint256 tokenBasedLimitedInvestValue = tokensWithoutBonus.mul(1 ether).div(price); uint256 change = msg.value - tokenBasedLimitedInvestValue;
uint256 tokenBasedLimitedInvestValue = tokensWithoutBonus.mul(1 ether).div(price); uint256 change = msg.value - tokenBasedLimitedInvestValue;
11,485
29
// 平台总收益 增量(单位:rewardTokens)
govTotalProfit[i]+=increment;
govTotalProfit[i]+=increment;
38,340
10
// Public function for checking whitelist eligibility.Called in the presale() function _to verify address is eligible for presale /
function whitelistEligible(address _to) public view returns (bool)
function whitelistEligible(address _to) public view returns (bool)
45,699
353
// Create fake Policy and NodeInfo to use them in verifyState(address)
Policy storage policy = policies[RESERVED_POLICY_ID]; policy.sponsor = msg.sender; policy.owner = address(this); policy.startTimestamp = 1; policy.endTimestamp = 2;
Policy storage policy = policies[RESERVED_POLICY_ID]; policy.sponsor = msg.sender; policy.owner = address(this); policy.startTimestamp = 1; policy.endTimestamp = 2;
5,368
8
// Bytes represenation of an RGB colour. 0xff0000 - red.
bytes3 colour;
bytes3 colour;
499
195
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
mapping(uint256 => address) private _tokenApprovals;
28,237
21
// Assign balance to a new variable.
uint value_ = (uint) (balance);
uint value_ = (uint) (balance);
27,708
19
// Doing new verification/ tokenId vNFT token id/ side side of verification
function verify(uint256 tokenId, bool side) external { if( foreVerifiers.ownerOf(tokenId)!= msg.sender){ revert ("BasicMarket: Incorrect owner"); } MarketLib.Market memory m = _market; if((m.sideA == 0 || m.sideB == 0 ) && m.endPredictionTimestamp < block.timestamp){ _closeMarket(MarketLib.ResultType.INVALID); return; } (, uint256 verificationPeriod) = marketConfig .periods(); foreVerifiers.transferFrom(msg.sender, address(this), tokenId); uint256 multipliedPower = foreVerifiers.multipliedPowerOf(tokenId); MarketLib.verify( _market, verifications, msg.sender, verificationPeriod, multipliedPower, tokenId, side ); }
function verify(uint256 tokenId, bool side) external { if( foreVerifiers.ownerOf(tokenId)!= msg.sender){ revert ("BasicMarket: Incorrect owner"); } MarketLib.Market memory m = _market; if((m.sideA == 0 || m.sideB == 0 ) && m.endPredictionTimestamp < block.timestamp){ _closeMarket(MarketLib.ResultType.INVALID); return; } (, uint256 verificationPeriod) = marketConfig .periods(); foreVerifiers.transferFrom(msg.sender, address(this), tokenId); uint256 multipliedPower = foreVerifiers.multipliedPowerOf(tokenId); MarketLib.verify( _market, verifications, msg.sender, verificationPeriod, multipliedPower, tokenId, side ); }
24,238
256
// The amount of wrapped tokens (KEEP/NU) that's obtained from/ `amount` T tokens, and the remainder that can't be downgraded.
function conversionFromT(uint256 amount) public view returns (uint256 wrappedAmount, uint256 tRemainder)
function conversionFromT(uint256 amount) public view returns (uint256 wrappedAmount, uint256 tRemainder)
42,332
51
// Allows the current owner to transfer control of the contract to a newOwner.newOwner The address to transfer ownership to./
function transferOwnership(address newOwner) public onlyOwner { if (newOwner != address(0)) { owner = newOwner; } }
function transferOwnership(address newOwner) public onlyOwner { if (newOwner != address(0)) { owner = newOwner; } }
13,739
1
// Create a new PartnerContract _sxpToken address of SwipeToken /
constructor(address payable _sxpToken) public { sxpToken = SwipeToken(_sxpToken); }
constructor(address payable _sxpToken) public { sxpToken = SwipeToken(_sxpToken); }
36,970
680
// Add new service that can call payWinnersEth and startEthLottery./_service New service to add
function addWhitelistedService(address _service) public onlyOwner { require( _whitelistedServices[_service] != true, "TaskTreasury: addWhitelistedService: whitelisted" ); _whitelistedServices[_service] = true; emit AddWhitelistedService(_service); }
function addWhitelistedService(address _service) public onlyOwner { require( _whitelistedServices[_service] != true, "TaskTreasury: addWhitelistedService: whitelisted" ); _whitelistedServices[_service] = true; emit AddWhitelistedService(_service); }
43,676
65
// validates maximum conversion fee
modifier validMaxConversionFee(uint32 _conversionFee) { require(_conversionFee >= 0 && _conversionFee <= MAX_CONVERSION_FEE); _; }
modifier validMaxConversionFee(uint32 _conversionFee) { require(_conversionFee >= 0 && _conversionFee <= MAX_CONVERSION_FEE); _; }
38,854
203
// Swaps as little as possible of one token for `amountOut` of another token/params The parameters necessary for the swap, encoded as `ExactOutputSingleParams` in calldata/ return amountIn The amount of the input token
function exactOutputSingle(ExactOutputSingleParams calldata params) external payable returns (uint256 amountIn);
function exactOutputSingle(ExactOutputSingleParams calldata params) external payable returns (uint256 amountIn);
15,654
21
// An abbreviated name for NFTs in this contract
function symbol() external pure returns (string _symbol);
function symbol() external pure returns (string _symbol);
6,343
49
// make sure the amount to be released per period is not too granular for the token
uint amountPerPeriod = totalAmount.div(totalPeriods); require( amountPerPeriod % ISecurityToken(securityToken).granularity() == 0, "The amount to be released per period is more granular than allowed by the token" );
uint amountPerPeriod = totalAmount.div(totalPeriods); require( amountPerPeriod % ISecurityToken(securityToken).granularity() == 0, "The amount to be released per period is more granular than allowed by the token" );
51,425
164
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
526
78
// ========== RESTRICTED FUNCTIONS ========== / Any pairs with FRAX and/or FXS must be whitelisted first before adding liquidity
function _addTrackedLP(address pair_address) internal { // Instantiate the pair IApePair the_pair = IApePair(pair_address); // Make sure either FRAX or FXS is present bool frax_present = (the_pair.token0() == canonical_frax_address || the_pair.token1() == canonical_frax_address); bool fxs_present = (the_pair.token0() == canonical_fxs_address || the_pair.token1() == canonical_fxs_address); require(frax_present || fxs_present, "FRAX or FXS not in pair"); // Adjust the state variables require(frax_fxs_pair_addresses_allowed[pair_address] == false, "LP already exists"); frax_fxs_pair_addresses_allowed[pair_address] = true; frax_fxs_pair_addresses_array.push(pair_address); }
function _addTrackedLP(address pair_address) internal { // Instantiate the pair IApePair the_pair = IApePair(pair_address); // Make sure either FRAX or FXS is present bool frax_present = (the_pair.token0() == canonical_frax_address || the_pair.token1() == canonical_frax_address); bool fxs_present = (the_pair.token0() == canonical_fxs_address || the_pair.token1() == canonical_fxs_address); require(frax_present || fxs_present, "FRAX or FXS not in pair"); // Adjust the state variables require(frax_fxs_pair_addresses_allowed[pair_address] == false, "LP already exists"); frax_fxs_pair_addresses_allowed[pair_address] = true; frax_fxs_pair_addresses_array.push(pair_address); }
44,883
50
// 发债方还款id: 发行的债券id,唯一标志债券get: 募集的token地址amount: 还款数量
function repayCb(address who, uint256 id) external auth returns (uint) { require(d(id) != address(0) && bondData(id).issuer() == who, "invalid address or issuer"); IBondData b = bondData(id); //募资成功,起息后即可还款,只有未还款或者逾期中可以还款,债务被关闭或者抵押物被清算完,不用还款 require( b.bondStage() == uint(BondStage.UnRepay) || b.bondStage() == uint(BondStage.Overdue), "invalid state" ); //充值repayAmount token到合约中,充值之前需要approve //使用amountGet进行计算 uint256 repayAmount = b.liability(); b.setBondParam("liability", 0); //safeTransferFrom(crowd, msg.sender, address(this), address(this), repayAmount); b.setBondParam("bondStage", uint256(BondStage.RepaySuccess)); b.setBondParam("issuerStage", uint256(IssuerStage.UnWithdrawPawn)); //清算一部分后,正常还款,需要设置清算中为false if (b.liquidating()) { b.setLiquidating(false); } return repayAmount; }
function repayCb(address who, uint256 id) external auth returns (uint) { require(d(id) != address(0) && bondData(id).issuer() == who, "invalid address or issuer"); IBondData b = bondData(id); //募资成功,起息后即可还款,只有未还款或者逾期中可以还款,债务被关闭或者抵押物被清算完,不用还款 require( b.bondStage() == uint(BondStage.UnRepay) || b.bondStage() == uint(BondStage.Overdue), "invalid state" ); //充值repayAmount token到合约中,充值之前需要approve //使用amountGet进行计算 uint256 repayAmount = b.liability(); b.setBondParam("liability", 0); //safeTransferFrom(crowd, msg.sender, address(this), address(this), repayAmount); b.setBondParam("bondStage", uint256(BondStage.RepaySuccess)); b.setBondParam("issuerStage", uint256(IssuerStage.UnWithdrawPawn)); //清算一部分后,正常还款,需要设置清算中为false if (b.liquidating()) { b.setLiquidating(false); } return repayAmount; }
13,467
0
// MEMBERS/ the count of all invocations of `generateLockId`.
uint256 public lockRequestCount;
uint256 public lockRequestCount;
36,418
22
// Locks a specified amount of tokens against an address, for a specified reason and time _reason The reason to lock tokens _amount Number of tokens to be locked _time Lock time in seconds /
function lock(bytes32 _reason, uint256 _amount, uint256 _time)
function lock(bytes32 _reason, uint256 _amount, uint256 _time)
46,498
299
// Set some Free Apes aside /
function reserveApes() public onlyOwner { uint256 supply = totalSupply(); uint256 i; for (i = 0; i < 30; i++) { _safeMint(msg.sender, supply + i); } }
function reserveApes() public onlyOwner { uint256 supply = totalSupply(); uint256 i; for (i = 0; i < 30; i++) { _safeMint(msg.sender, supply + i); } }
16,128
316
// Emitted when the Clerk is updated./user The user who triggered the update of the Clerk./newClerk The new Clerk contract used by the Master.
event ClerkUpdated(address indexed user, TurboClerk newClerk);
event ClerkUpdated(address indexed user, TurboClerk newClerk);
30,330
31
// should be called by COSHA-CNYCrowdSale when crowdSale is finished
function unlock() onlyOwner { isLocked = false; }
function unlock() onlyOwner { isLocked = false; }
52,622
77
// 5760 blocks per day
reward = rewardsPerBlock.mul(5760); incvReward = incvRewardsPerBlock.mul(5760);
reward = rewardsPerBlock.mul(5760); incvReward = incvRewardsPerBlock.mul(5760);
287
61
// Store dex approval status to avoid excessive approvals
mapping(address => bool) internal cvxDexApprovals;
mapping(address => bool) internal cvxDexApprovals;
70,463
97
// mint strategy tokens to msg.sender
minted = _lpTokens * ONE_CURVE_LP_TOKEN / _price; _mint(_account, minted);
minted = _lpTokens * ONE_CURVE_LP_TOKEN / _price; _mint(_account, minted);
82,617
7
// Creates the Chainlink request. This is a backwards compatible APIwith the Oracle.sol contract, but the behavior changes becausecallbackAddress is assumed to be the same as the request sender. callbackAddress The consumer of the request payment The amount of payment given (specified in wei) specId The Job Specification ID callbackAddress The address the oracle data will be sent to callbackFunctionId The callback function ID for the response nonce The nonce sent by the requester dataVersion The specified data version data The extra request parameters /
function oracleRequest( address sender, uint256 payment, bytes32 specId, address callbackAddress, bytes4 callbackFunctionId, uint256 nonce, uint256 dataVersion, bytes calldata data
function oracleRequest( address sender, uint256 payment, bytes32 specId, address callbackAddress, bytes4 callbackFunctionId, uint256 nonce, uint256 dataVersion, bytes calldata data
2,415
116
// verifies that a value is greater than zero
modifier greaterThanZero(uint256 _value) { _greaterThanZero(_value); _; }
modifier greaterThanZero(uint256 _value) { _greaterThanZero(_value); _; }
3,875
11
// Explicitly set initial system status
status = Status.chainlinkWorking;
status = Status.chainlinkWorking;
35,364
31
// Check that a threshold is set
require(_threshold > 0, "GS001"); checkNSignatures(dataHash, data, signatures, _threshold);
require(_threshold > 0, "GS001"); checkNSignatures(dataHash, data, signatures, _threshold);
8,395
35
// @inheritdoc ICallableLoan
function estimateOwedInterestAt( uint256 assumedBalance, uint256 timestamp
function estimateOwedInterestAt( uint256 assumedBalance, uint256 timestamp
39,839
99
// emit claim event
emit Claimed(msg.sender, excessAmount, block.timestamp);
emit Claimed(msg.sender, excessAmount, block.timestamp);
34,528
183
// compute time bonus earned as a function of staking time time length of time for which the tokens have been stakedreturn bonus multiplier for time /
function timeBonus(uint256 time) public view returns (uint256) { if (time >= bonusPeriod) { return uint256(10**BONUS_DECIMALS).add(bonusMax); } // linearly interpolate between bonus min and bonus max uint256 bonus = bonusMin.add( (bonusMax.sub(bonusMin)).mul(time).div(bonusPeriod) ); return uint256(10**BONUS_DECIMALS).add(bonus); }
function timeBonus(uint256 time) public view returns (uint256) { if (time >= bonusPeriod) { return uint256(10**BONUS_DECIMALS).add(bonusMax); } // linearly interpolate between bonus min and bonus max uint256 bonus = bonusMin.add( (bonusMax.sub(bonusMin)).mul(time).div(bonusPeriod) ); return uint256(10**BONUS_DECIMALS).add(bonus); }
11,863
69
// internal exclude from max tx
_isExcludedFromMaxTx[owner()] = true; _isExcludedFromMaxTx[address(this)] = true; emit Transfer(address(0), _msgSender(), _totalSupply);
_isExcludedFromMaxTx[owner()] = true; _isExcludedFromMaxTx[address(this)] = true; emit Transfer(address(0), _msgSender(), _totalSupply);
27,593
10
// BONE tokens created per block.
uint256 public bonePerBlock;
uint256 public bonePerBlock;
70,331
197
// Array of flags if active validators mined this notary window
bool[] memory miningValidators = new bool[](chain.validators.list.length);
bool[] memory miningValidators = new bool[](chain.validators.list.length);
18,611
1
// Emission current value
uint public emissionValue;
uint public emissionValue;
5,031
5
// The permit is invalid.
error InvalidPermit();
error InvalidPermit();
27,397