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 |
|---|---|---|---|---|
20 | // Change delegation for `delegator` to `delegatee`. | * Emits events {DelegateChanged} and {DelegateVotesChanged}.
*/
function _delegate(address delegator, address delegatee) internal virtual {
address currentDelegate = delegates(delegator);
uint256 delegatorBalance = balanceOf(delegator);
_delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveVotingPower(currentDelegate, delegatee, delegatorBalance);
}
| * Emits events {DelegateChanged} and {DelegateVotesChanged}.
*/
function _delegate(address delegator, address delegatee) internal virtual {
address currentDelegate = delegates(delegator);
uint256 delegatorBalance = balanceOf(delegator);
_delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveVotingPower(currentDelegate, delegatee, delegatorBalance);
}
| 26,657 |
31 | // OLA_ADDITIONS : Using 'core asset price' instead of 'ethPrice | uint referenceAssetPrice = fetchreferenceAssetPrice();
| uint referenceAssetPrice = fetchreferenceAssetPrice();
| 31,833 |
17 | // Returns the admin of the given proxy address._proxy Address of the proxy to get the admin of. return Address of the admin of the proxy. / | function getProxyAdmin(address payable _proxy) external view returns (address) {
ProxyType ptype = proxyType[_proxy];
if (ptype == ProxyType.ERC1967) {
return IStaticERC1967Proxy(_proxy).admin();
} else if (ptype == ProxyType.CHUGSPLASH) {
return IStaticL1ChugSplashProxy(_proxy).getOwner();
} else if (ptype == ProxyType.RESOLVED) {
return addressManager.owner();
} else {
revert("ProxyAdmin: unknown proxy type");
}
}
| function getProxyAdmin(address payable _proxy) external view returns (address) {
ProxyType ptype = proxyType[_proxy];
if (ptype == ProxyType.ERC1967) {
return IStaticERC1967Proxy(_proxy).admin();
} else if (ptype == ProxyType.CHUGSPLASH) {
return IStaticL1ChugSplashProxy(_proxy).getOwner();
} else if (ptype == ProxyType.RESOLVED) {
return addressManager.owner();
} else {
revert("ProxyAdmin: unknown proxy type");
}
}
| 20,998 |
117 | // Retrieve remaining amount on the offer item. | uint256 unspentAmount = offerItem.startAmount;
| uint256 unspentAmount = offerItem.startAmount;
| 20,639 |
86 | // If its a LP we sell it | safeTransferFrom(_token, msg.sender, _token, _amountContribution);
uint256 balanceToken0Before = IERC20(token0).balanceOf(address(this));
uint256 balanceToken1Before = IERC20(token1).balanceOf(address(this));
IUniswapV2Pair(_token).burn(address(this));
uint256 balanceToken0After = IERC20(token0).balanceOf(address(this));
uint256 balanceToken1After = IERC20(token1).balanceOf(address(this));
uint256 amountOutToken0 = token0 == WETH ?
balanceToken0After.sub(balanceToken0Before)
: sellTokenForWETH(token0, balanceToken0After.sub(balanceToken0Before), false);
| safeTransferFrom(_token, msg.sender, _token, _amountContribution);
uint256 balanceToken0Before = IERC20(token0).balanceOf(address(this));
uint256 balanceToken1Before = IERC20(token1).balanceOf(address(this));
IUniswapV2Pair(_token).burn(address(this));
uint256 balanceToken0After = IERC20(token0).balanceOf(address(this));
uint256 balanceToken1After = IERC20(token1).balanceOf(address(this));
uint256 amountOutToken0 = token0 == WETH ?
balanceToken0After.sub(balanceToken0Before)
: sellTokenForWETH(token0, balanceToken0After.sub(balanceToken0Before), false);
| 45,525 |
9 | // Send multiple types of Tokens from the _from address to the _to address (with safety call) MUST emit TransferBatch event on successCaller must be approved to manage the _from account's tokens (see isApprovedForAll)MUST throw if `_to` is the zero addressMUST throw if length of `_ids` is not the same as length of `_amounts`MUST throw if any of the balance of sender for token `_ids` is lower than the respective `_amounts` sentMUST throw on any other errorWhen transfer is complete, this function MUST check if `_to` is a smart contract (code size > 0). If so, it MUST call `onERC1155BatchReceived` on | function safeBatchTransferFrom(
| function safeBatchTransferFrom(
| 21,126 |
8 | // Check if the RLP item is a list. /self The RLP item. / return 'true' if the item is a list. | function isList(RLPItem memory self) internal constant returns (bool ret) {
if (self._unsafe_length == 0)
return false;
uint memPtr = self._unsafe_memPtr;
assembly {
ret := iszero(lt(byte(0, mload(memPtr)), 0xC0))
}
}
| function isList(RLPItem memory self) internal constant returns (bool ret) {
if (self._unsafe_length == 0)
return false;
uint memPtr = self._unsafe_memPtr;
assembly {
ret := iszero(lt(byte(0, mload(memPtr)), 0xC0))
}
}
| 44,255 |
20 | // Reclaim any unused LINK amount of LINK to withdraw / | function withdrawLINK(uint256 amount) external onlyOwner {
LINK.transfer(_msgSender(), amount);
}
| function withdrawLINK(uint256 amount) external onlyOwner {
LINK.transfer(_msgSender(), amount);
}
| 55,591 |
48 | // update flow (update metadata) | if (requestedFlowRate > 0 && FlowRate.unwrap(oldFlowRate) > 0) {
gasLeftBefore = gasleft();
try IConstantOutflowNFT(constantOutflowNFTAddress).onUpdate(token, from, address(pool)) {
| if (requestedFlowRate > 0 && FlowRate.unwrap(oldFlowRate) > 0) {
gasLeftBefore = gasleft();
try IConstantOutflowNFT(constantOutflowNFTAddress).onUpdate(token, from, address(pool)) {
| 23,633 |
25 | // Implementation of the {IERC20} interface.that a supply mechanism has to be added in a derived contract using {_mint}.For a generic mechanism see {ERC20MinterPauser}.Additionally, an {Approval} event is emitted on calls to {transferFrom}.Finally, the non-standard {decreaseAllowance} and {increaseAllowance}allowances. See {IERC20-approve}./ Sets the values for {name} and {symbol}, initializes {decimals} witha default value of 18. All three of these values are immutable: they can only be set once duringconstruction. / | constructor (string memory name, string memory symbol, uint256 totalSupply, address owner) public {
_name = name;
_symbol = symbol;
_decimals = 18;
_totalSupply = totalSupply;
_balances[owner] = totalSupply;
emit Transfer(address(0), owner, _totalSupply);
}
| constructor (string memory name, string memory symbol, uint256 totalSupply, address owner) public {
_name = name;
_symbol = symbol;
_decimals = 18;
_totalSupply = totalSupply;
_balances[owner] = totalSupply;
emit Transfer(address(0), owner, _totalSupply);
}
| 52,638 |
97 | // lock totalAssetSupply for duration of flash loan | _flTotalAssetSupply = beforeAssetsBalance;
| _flTotalAssetSupply = beforeAssetsBalance;
| 21,937 |
51 | // Implementation of the ERC20Decimals. Extension of {ERC20} that adds decimals storage slot./ Sets the value of the `decimals`. This value is immutable, it can only beset once during construction. / | constructor () ERC20('Nexus', 'NEXUS') {
_mint(_msgSender(), _totalSupply);
}
| constructor () ERC20('Nexus', 'NEXUS') {
_mint(_msgSender(), _totalSupply);
}
| 7,299 |
269 | // address of user => schainHash => true if unlocked for transferring | mapping(address => mapping(bytes32 => bool)) public activeUsers;
uint public minTransactionGas;
| mapping(address => mapping(bytes32 => bool)) public activeUsers;
uint public minTransactionGas;
| 13,856 |
38 | // Handles auth and calls subscription contract | contract SubscriptionProxy is StrategyData {
address public constant FACTORY_ADDRESS = 0x5a15566417e6C1c9546523066500bDDBc53F88C7;
function subscribe(address _executorAddr, address _subAddr, Trigger[] memory _triggers, Action[] memory _actions) public {
address currAuthority = address(DSAuth(address(this)).authority());
DSGuard guard = DSGuard(currAuthority);
if (currAuthority == address(0)) {
guard = DSGuardFactory(FACTORY_ADDRESS).newGuard();
DSAuth(address(this)).setAuthority(DSAuthority(address(guard)));
}
guard.permit(_executorAddr, address(this), bytes4(keccak256("execute(address,bytes)")));
Subscriptions(_subAddr).subscribe(_triggers, _actions);
}
function update(address _subAddr, uint _subId, Trigger[] memory _triggers, Action[] memory _actions) public {
Subscriptions(_subAddr).update(_subId, _triggers, _actions);
}
// TODO: should we remove permission if no more strategies left?
function unsubscribe(address _subAddr, uint _subId) public {
Subscriptions(_subAddr).unsubscribe(_subId);
}
} | contract SubscriptionProxy is StrategyData {
address public constant FACTORY_ADDRESS = 0x5a15566417e6C1c9546523066500bDDBc53F88C7;
function subscribe(address _executorAddr, address _subAddr, Trigger[] memory _triggers, Action[] memory _actions) public {
address currAuthority = address(DSAuth(address(this)).authority());
DSGuard guard = DSGuard(currAuthority);
if (currAuthority == address(0)) {
guard = DSGuardFactory(FACTORY_ADDRESS).newGuard();
DSAuth(address(this)).setAuthority(DSAuthority(address(guard)));
}
guard.permit(_executorAddr, address(this), bytes4(keccak256("execute(address,bytes)")));
Subscriptions(_subAddr).subscribe(_triggers, _actions);
}
function update(address _subAddr, uint _subId, Trigger[] memory _triggers, Action[] memory _actions) public {
Subscriptions(_subAddr).update(_subId, _triggers, _actions);
}
// TODO: should we remove permission if no more strategies left?
function unsubscribe(address _subAddr, uint _subId) public {
Subscriptions(_subAddr).unsubscribe(_subId);
}
} | 80,818 |
18 | // internal method that returns a slice of an array. | function sliceArray(address[] memory arr, uint len)
internal
pure
returns (address[] memory)
| function sliceArray(address[] memory arr, uint len)
internal
pure
returns (address[] memory)
| 18,319 |
40 | // calculate and pick the winner(s), for now we just consider tickets by their buy order ascending, but later we will change the order by ticket hash in order to reduce manipulating | (
bool calcStat,
string memory calcMsg,
uint256 winnerTicketInx
) = calculateWinner(false);
if (!calcStat) emit LogPickedWinner(false, calcMsg, theWinner);
theWinner = tickets[winnerTicketInx];
if (shouldPayToWinner) {
| (
bool calcStat,
string memory calcMsg,
uint256 winnerTicketInx
) = calculateWinner(false);
if (!calcStat) emit LogPickedWinner(false, calcMsg, theWinner);
theWinner = tickets[winnerTicketInx];
if (shouldPayToWinner) {
| 30,874 |
0 | // Snure that 'msg.value' is an even number. Division will truncate if it is an odd number./Check via multiplication that it wasnt an odd numer. | constructor() public payable {
seller = msg.sender;
value = msg.value /2;
require((2*value) == msg.value, "Value has to be even")
}
| constructor() public payable {
seller = msg.sender;
value = msg.value /2;
require((2*value) == msg.value, "Value has to be even")
}
| 45,040 |
155 | // returns player info based on address.if no address is given, it willuse msg.sender-functionhash- 0xee0b5d8b _addr address of the player you want to lookupreturn player IDreturn player namereturn keys owned (current round)return winnings vaultreturn general vaultreturn affiliate vaultreturn player round eth / | function getPlayerInfoByAddress(address _addr)
public
view
returns(uint256, bytes32, uint256, uint256, uint256, uint256, uint256)
| function getPlayerInfoByAddress(address _addr)
public
view
returns(uint256, bytes32, uint256, uint256, uint256, uint256, uint256)
| 18,105 |
1 | // The number of votes required in order for a voter to become a proposer | function proposalThreshold() public view returns (uint) {return lever.totalSupply() / 400;} //0.25% of Lever
| function proposalThreshold() public view returns (uint) {return lever.totalSupply() / 400;} //0.25% of Lever
| 10,862 |
300 | // Composition of the gToken deposit formula with the Compound conversion formula to obtain the gcToken deposit formula in terms of the cToken underlying asset. / | function _calcDepositSharesFromUnderlyingCost(uint256 _underlyingCost, uint256 _totalReserve, uint256 _totalSupply, uint256 _depositFee, uint256 _exchangeRate) internal pure returns (uint256 _netShares, uint256 _feeShares)
| function _calcDepositSharesFromUnderlyingCost(uint256 _underlyingCost, uint256 _totalReserve, uint256 _totalSupply, uint256 _depositFee, uint256 _exchangeRate) internal pure returns (uint256 _netShares, uint256 _feeShares)
| 66,286 |
19 | // Update the timeOfLastUpdate for the staker | stakers[msg.sender].timeOfLastUpdate = block.timestamp;
| stakers[msg.sender].timeOfLastUpdate = block.timestamp;
| 4,007 |
1,244 | // Ensure the SNX proxy has the correct Synthetix target set; | proxysynthetix_i.setTarget(Proxyable(new_Synthetix_contract));
| proxysynthetix_i.setTarget(Proxyable(new_Synthetix_contract));
| 4,073 |
101 | // preallocated company token | uint public companyTokens;
| uint public companyTokens;
| 8,097 |
6 | // The event fired when other contracts have been connected: | event connectedContracts(address factory, address ruleList, address escrowedDeposit);
| event connectedContracts(address factory, address ruleList, address escrowedDeposit);
| 13,797 |
3 | // Function to call Twelvedata API via Chainlink oracle_cbContract - address of the calling contract for callback _cbFunction - address of the callback function from the calling contract _symbol - the symbol of the DAX stock (e.g. "DAI") for the url _date - the date of the prediction, within Xetra opening hours (e.g. 2021-06-17 17:28) / | function requestStockPrice(
address _cbContract,
bytes4 _cbFunction,
string calldata _symbol,
string calldata _date
| function requestStockPrice(
address _cbContract,
bytes4 _cbFunction,
string calldata _symbol,
string calldata _date
| 17,220 |
279 | // Wildcards percentage calc | if (wildcardsPercentages[tokenId] == 0) {
wildcardsPercentages[tokenId] = 50000;
}
| if (wildcardsPercentages[tokenId] == 0) {
wildcardsPercentages[tokenId] = 50000;
}
| 30,521 |
2 | // Constructor/ |
constructor(
address[] _benefitiaries,
uint256[] _shares,
string _name,
string _symbol
)
SplitPaymentChangeable(_benefitiaries, _shares)
ERC721Token(_name, _symbol)
public
|
constructor(
address[] _benefitiaries,
uint256[] _shares,
string _name,
string _symbol
)
SplitPaymentChangeable(_benefitiaries, _shares)
ERC721Token(_name, _symbol)
public
| 20,186 |
0 | // Allows a user to deposit ETH into the contract.Once the deposit is recognized, the owner is able to make transactions on the OMG network. _depositTx RLP encoded transaction to act as the deposit. / | function deposit(bytes calldata _depositTx) external payable {
IEthDepositVerifier(getEffectiveDepositVerifier()).verify(_depositTx, msg.value, msg.sender);
uint256 blknum = super._submitDepositBlock(_depositTx);
emit DepositCreated(msg.sender, blknum, address(0), msg.value);
}
| function deposit(bytes calldata _depositTx) external payable {
IEthDepositVerifier(getEffectiveDepositVerifier()).verify(_depositTx, msg.value, msg.sender);
uint256 blknum = super._submitDepositBlock(_depositTx);
emit DepositCreated(msg.sender, blknum, address(0), msg.value);
}
| 23,555 |
193 | // supposed to be called once while initializing. one of the contracts that inherits this contract follows proxy pattern so it is not possible to do this in a constructor | function _initializeEIP712(
string memory name
)
internal
initializer
| function _initializeEIP712(
string memory name
)
internal
initializer
| 23,010 |
47 | // Firing the mint event | emit Mint(msg.sender, _value);
| emit Mint(msg.sender, _value);
| 9,891 |
5 | // The internal ID tracker | uint256 public _currentTokenId;
uint256 public maxSupply;
string public baseURI;
constructor(
string memory name_,
string memory symbol_,
address _minter,
| uint256 public _currentTokenId;
uint256 public maxSupply;
string public baseURI;
constructor(
string memory name_,
string memory symbol_,
address _minter,
| 19,196 |
329 | // check latest voting power history record block number: if history was not updated after the block of interest | if(history[history.length - 1].blockNumber <= _blockNum) {
| if(history[history.length - 1].blockNumber <= _blockNum) {
| 49,899 |
187 | // abi.encode() the payload with the values to send | bytes memory payload = abi.encode(msg.sender, tokenId);
| bytes memory payload = abi.encode(msg.sender, tokenId);
| 56,418 |
25 | // swap 0.5 eth for at least 4 dai | uniswap.swapExactTokensForTokens(500000000000000000, 4000000000000000000, _path, msg.sender,deadlineInDays);
| uniswap.swapExactTokensForTokens(500000000000000000, 4000000000000000000, _path, msg.sender,deadlineInDays);
| 38,641 |
15 | // External functions | function commit_transfer_ownership(address) external;
function apply_transfer_ownership() external;
function add_gauge(
address,
int128,
uint256
) external;
function checkpoint() external;
function checkpoint_gauge(address) external;
function global_emission_rate() external view returns (uint256);
| function commit_transfer_ownership(address) external;
function apply_transfer_ownership() external;
function add_gauge(
address,
int128,
uint256
) external;
function checkpoint() external;
function checkpoint_gauge(address) external;
function global_emission_rate() external view returns (uint256);
| 11,618 |
40 | // Check if buyer or seller are not passed as moderator | require(
!transactions[scriptHash].isOwner[moderator],
"Either buyer or seller is passed as moderator"
);
transactions[scriptHash].isOwner[moderator] = true;
transactionCount++;
| require(
!transactions[scriptHash].isOwner[moderator],
"Either buyer or seller is passed as moderator"
);
transactions[scriptHash].isOwner[moderator] = true;
transactionCount++;
| 4,539 |
481 | // Mint tiers if they were specified. | if (_tierIdsToMint.length != 0)
_leftoverAmount = _mintAll(_leftoverAmount, _tierIdsToMint, _data.beneficiary);
| if (_tierIdsToMint.length != 0)
_leftoverAmount = _mintAll(_leftoverAmount, _tierIdsToMint, _data.beneficiary);
| 11,828 |
9 | // uint id = _totalSupply(); | _safeMint(_to, id);
emit CreateDraco(id);
| _safeMint(_to, id);
emit CreateDraco(id);
| 81,189 |
12 | // not sure what was returned: dont mark as success | default { }
| default { }
| 48,077 |
56 | // Check the token amount | if (tokenAmount == 0) {
revert ZeroValue();
}
| if (tokenAmount == 0) {
revert ZeroValue();
}
| 29,963 |
343 | // unset the set bit | bitmap = bitmap - (ONE << nextSetBit);
| bitmap = bitmap - (ONE << nextSetBit);
| 7,588 |
39 | // Redeem `dDaiToBurn` dDai from `msg.sender` and transfer thecorresponding amount of cDai to `msg.sender`. dDaiToBurn uint256 The amount of dDai to provide for Dai.return The amount of cDai received in return for the provided dDai. / | function redeemToCToken(
uint256 dDaiToBurn
| function redeemToCToken(
uint256 dDaiToBurn
| 30,746 |
184 | // overridable for testing | function getReserves(address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) {
(address token0,) = UniswapV2Library.sortTokens(tokenA, tokenB);
(uint reserve0, uint reserve1,) = IUniswapV2Pair(UniswapV2Library.pairFor(UNISWAP_FACTORY, tokenA, tokenB)).getReserves();
(reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
}
| function getReserves(address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) {
(address token0,) = UniswapV2Library.sortTokens(tokenA, tokenB);
(uint reserve0, uint reserve1,) = IUniswapV2Pair(UniswapV2Library.pairFor(UNISWAP_FACTORY, tokenA, tokenB)).getReserves();
(reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
}
| 15,577 |
58 | // Bool if address is excluded from max transaction amount | mapping(address => bool) public _isExcludedMaxTransactionAmount;
| mapping(address => bool) public _isExcludedMaxTransactionAmount;
| 15,880 |
1 | // Limit withdrawal amount | require(withdraw_amount <= 100000000000000000);
| require(withdraw_amount <= 100000000000000000);
| 2,474 |
21 | // Change the pre sale and claim status to over (false), and general sale status to live (true) / | function switchPreToGeneral() external onlyOwner {
claimStatus = false;
preSaleStatus = false;
generalSaleStatus = true;
}
| function switchPreToGeneral() external onlyOwner {
claimStatus = false;
preSaleStatus = false;
generalSaleStatus = true;
}
| 22,473 |
126 | // for blacklist table/ | mapping(address => bool) internal _blacklists;
| mapping(address => bool) internal _blacklists;
| 28,143 |
102 | // the ultimate role of Tribe. Controls all other roles and protocol functionality. | bytes32 internal constant GOVERNOR = keccak256("GOVERN_ROLE");
| bytes32 internal constant GOVERNOR = keccak256("GOVERN_ROLE");
| 48,396 |
17 | // store note hash in `s + 0x60` | mstore(add(s, 0x60), mload(0xc0))
| mstore(add(s, 0x60), mload(0xc0))
| 48,675 |
4 | // voted eventevent votedEvent (uint indexed _candidateId); | event votedEvent ();
| event votedEvent ();
| 10,698 |
171 | // Resumes the contract. Emits the `Unpaused` event. Reverts if called by any other than the contract owner. Reverts if the contract has not been started yet. Reverts if the contract is not paused. / | function unpause() public virtual onlyOwner whenStarted {
_unpause();
}
| function unpause() public virtual onlyOwner whenStarted {
_unpause();
}
| 21,426 |
2 | // Modifies price and reward for the next purchase | uint256 kModifier = 10000 + PRICE_MODIFIER;
EVENT_TOKEN_PRICE = EVENT_TOKEN_PRICE * kModifier / 10000;
EVENT_TOKEN_PRICE_ETH = EVENT_TOKEN_PRICE_ETH * kModifier / 10000;
ETH_PURCHASE_REWARD = ETH_PURCHASE_REWARD * kModifier / 10000;
uint256 tokenId = EVENT_TOKEN.safeMint(msg.sender);
if (mintReward && reward > 0) {
PAYMENT_TOKEN.mint(msg.sender, reward);
}
| uint256 kModifier = 10000 + PRICE_MODIFIER;
EVENT_TOKEN_PRICE = EVENT_TOKEN_PRICE * kModifier / 10000;
EVENT_TOKEN_PRICE_ETH = EVENT_TOKEN_PRICE_ETH * kModifier / 10000;
ETH_PURCHASE_REWARD = ETH_PURCHASE_REWARD * kModifier / 10000;
uint256 tokenId = EVENT_TOKEN.safeMint(msg.sender);
if (mintReward && reward > 0) {
PAYMENT_TOKEN.mint(msg.sender, reward);
}
| 28,495 |
201 | // ============ Internal ============ //Instructs the SetToken to set approvals of the ERC20 token to a spender._setTokenSetToken instance to invoke _token ERC20 token to approve _spender The account allowed to spend the SetToken's balance _quantityThe quantity of allowance to allow / | function invokeApprove(
ISetToken _setToken,
address _token,
address _spender,
uint256 _quantity
)
internal
{
bytes memory callData = abi.encodeWithSignature("approve(address,uint256)", _spender, _quantity);
_setToken.invoke(_token, 0, callData);
| function invokeApprove(
ISetToken _setToken,
address _token,
address _spender,
uint256 _quantity
)
internal
{
bytes memory callData = abi.encodeWithSignature("approve(address,uint256)", _spender, _quantity);
_setToken.invoke(_token, 0, callData);
| 57,550 |
14 | // Sets temporary buy tax. Taxes are entirely removed when ownership is renounced. / | function setBuyTax(uint8 buyTax) external onlyOwner {
| function setBuyTax(uint8 buyTax) external onlyOwner {
| 21,385 |
29 | // Gets the balance of the specified address. _owner The address to query the the balance of.return An uint256 representing the amount owned by the passed address. / | function balanceOf(address _owner) public view returns(uint256 balance) {
return balances[_owner];
}
| function balanceOf(address _owner) public view returns(uint256 balance) {
return balances[_owner];
}
| 20,886 |
273 | // Save the old sub stake values to prevent decreasing reward for the previous periodSaving happens only if the previous period is committed_info Staker structure_firstPeriod First period of the old sub stake_lockedValue Locked value of the old sub stake_currentPeriod Current period, when the old sub stake is already unlocked/ | function saveOldSubStake(
StakerInfo storage _info,
uint16 _firstPeriod,
uint256 _lockedValue,
uint16 _currentPeriod
)
internal
| function saveOldSubStake(
StakerInfo storage _info,
uint16 _firstPeriod,
uint256 _lockedValue,
uint16 _currentPeriod
)
internal
| 50,104 |
1 | // An event thats emitted when a new governance address is pending | event GovernancePending(address indexed _previousGovernance, address indexed _newGovernance, uint256 _at);
| event GovernancePending(address indexed _previousGovernance, address indexed _newGovernance, uint256 _at);
| 15,608 |
13 | // Debug event | event DebugEvent(string description, uint256 value);
| event DebugEvent(string description, uint256 value);
| 2,484 |
28 | // Internal function for the calculation of user's rewards on a distribution principalUserBalance Amount staked by the user on a distribution reserveIndex Current index of the distribution userIndex Index stored for the user, representation his staking momentreturn rewards The rewards / | function _getRewards(
uint256 principalUserBalance,
uint256 reserveIndex,
uint256 userIndex
| function _getRewards(
uint256 principalUserBalance,
uint256 reserveIndex,
uint256 userIndex
| 5,936 |
31 | // `updateValueAtNow` used to update the `balances` map and the/`totalSupplyHistory`/checkpoints The history of data being updated/_value The new number of reputation | function updateValueAtNow(Checkpoint[] storage checkpoints, uint256 _value) internal {
require(uint128(_value) == _value); //check value is in the 128 bits bounderies
if ((checkpoints.length == 0) || (checkpoints[checkpoints.length - 1].fromBlock < block.number)) {
Checkpoint storage newCheckPoint = checkpoints[checkpoints.length++];
newCheckPoint.fromBlock = uint128(block.number);
newCheckPoint.value = uint128(_value);
} else {
Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length-1];
oldCheckPoint.value = uint128(_value);
}
}
| function updateValueAtNow(Checkpoint[] storage checkpoints, uint256 _value) internal {
require(uint128(_value) == _value); //check value is in the 128 bits bounderies
if ((checkpoints.length == 0) || (checkpoints[checkpoints.length - 1].fromBlock < block.number)) {
Checkpoint storage newCheckPoint = checkpoints[checkpoints.length++];
newCheckPoint.fromBlock = uint128(block.number);
newCheckPoint.value = uint128(_value);
} else {
Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length-1];
oldCheckPoint.value = uint128(_value);
}
}
| 6,516 |
143 | // Scenario in which all staked has already been requested to be unstaked. | if (requested >= stake) {
return 0;
}
| if (requested >= stake) {
return 0;
}
| 37,418 |
26 | // if its the first sale | if(assets[asset].firstSale==true){
| if(assets[asset].firstSale==true){
| 16,744 |
8 | // protocol state | mapping(MarginLiquidityPoolInterface => mapping(address => int256)) public balances;
mapping(MarginLiquidityPoolInterface => mapping(address => bool)) public traderIsMarginCalled;
uint256 public nextPositionId;
int256 private constant MAX_INT = type(int256).max;
uint256 private constant MAX_UINT = type(uint256).max;
| mapping(MarginLiquidityPoolInterface => mapping(address => int256)) public balances;
mapping(MarginLiquidityPoolInterface => mapping(address => bool)) public traderIsMarginCalled;
uint256 public nextPositionId;
int256 private constant MAX_INT = type(int256).max;
uint256 private constant MAX_UINT = type(uint256).max;
| 50,980 |
19 | // Set limits for mystery boxes | _mysteryBoxesLimits[COMMON] = 2000;
_mysteryBoxesLimits[PRO] = 800;
_mysteryBoxesLimits[MASTER] = 200;
| _mysteryBoxesLimits[COMMON] = 2000;
_mysteryBoxesLimits[PRO] = 800;
_mysteryBoxesLimits[MASTER] = 200;
| 23,609 |
1,177 | // The last element is a queue tx, therefore pull timestamp and block number from the queue element. curContext.numSubsequentQueueTransactions > 0 which means that we've processed at least one queue element. We increment nextQueueIndex after processing each queue element, so the index of the last element we processed is nextQueueIndex - 1. | Lib_OVMCodec.QueueElement memory lastElement = _getQueueElement(
nextQueueIndex - 1,
queueRef
);
blockTimestamp = lastElement.timestamp;
blockNumber = lastElement.blockNumber;
| Lib_OVMCodec.QueueElement memory lastElement = _getQueueElement(
nextQueueIndex - 1,
queueRef
);
blockTimestamp = lastElement.timestamp;
blockNumber = lastElement.blockNumber;
| 57,125 |
7 | // https:explorer.optimism.io/address/0x41140Bf6498a36f2E44eFd49f21dAe3bbb7367c8 | FeePoolEternalStorage public constant feepooleternalstorage_i = FeePoolEternalStorage(0x41140Bf6498a36f2E44eFd49f21dAe3bbb7367c8);
| FeePoolEternalStorage public constant feepooleternalstorage_i = FeePoolEternalStorage(0x41140Bf6498a36f2E44eFd49f21dAe3bbb7367c8);
| 6,403 |
61 | // Compute the opaque data that will be emitted as part of the TransactionDeposited event. We use opaque data so that we can update the TransactionDeposited event in the future without breaking the current interface. | bytes memory opaqueData = abi.encodePacked(
msg.value,
_value,
_gasLimit,
_isCreation,
_data
);
| bytes memory opaqueData = abi.encodePacked(
msg.value,
_value,
_gasLimit,
_isCreation,
_data
);
| 25,642 |
1 | // Get the RAW balance of a given account _account User for which to retrieve balance / | function rawBalanceOf(address _account) external view returns (uint256);
| function rawBalanceOf(address _account) external view returns (uint256);
| 12,166 |
2 | // Comparing input with the hash of another input. / | contract Barrier016 {
function send(address payable receiver, uint256 amount, bytes32 inputA, bytes32 inputB) public payable {
bytes32 hashInputA = keccak256(abi.encode(inputA));
if(hashInputA == inputB) {
receiver.send(amount);
}
}
function() external payable {
}
}
| contract Barrier016 {
function send(address payable receiver, uint256 amount, bytes32 inputA, bytes32 inputB) public payable {
bytes32 hashInputA = keccak256(abi.encode(inputA));
if(hashInputA == inputB) {
receiver.send(amount);
}
}
function() external payable {
}
}
| 9,313 |
4 | // dev Returns the product of a and b. Throws an exception if it exceeds uint256 limits/ | function safeMult(uint256 x, uint256 y) internal returns(uint256) {
uint256 z = x * y;
assert((x == 0) || (z / x == y));
return z;
}
| function safeMult(uint256 x, uint256 y) internal returns(uint256) {
uint256 z = x * y;
assert((x == 0) || (z / x == y));
return z;
}
| 10,357 |
104 | // is the token balance of this contract address over the min number of tokens that we need to initiate a swap? also, don't get caught in a circular team event. also, don't swap if sender is uniswap pair. | uint256 contractTokenBalance = balanceOf(address(this));
if (contractTokenBalance >= _maxTxAmount) {
contractTokenBalance = _maxTxAmount;
}
| uint256 contractTokenBalance = balanceOf(address(this));
if (contractTokenBalance >= _maxTxAmount) {
contractTokenBalance = _maxTxAmount;
}
| 55,513 |
283 | // Calculate e^x with a sensible maximum iteration count to wait untilconvergence. Note that it is potentially possible to get an un-convergedvalue; lack of convergence does not throw. / | function exp(int256 realArg) internal pure returns (int256) {
return expLimited(realArg, 100);
}
| function exp(int256 realArg) internal pure returns (int256) {
return expLimited(realArg, 100);
}
| 37,141 |
83 | // to calculate refund later from totalCoreRefund + CORE total contributed | mapping (address => uint256) public unitsContributed; // unit to keep track how much each person should get of LP
mapping (address => uint256) public unitsClaimed;
mapping (address => bool) public CORERefundClaimed;
mapping (address => address) public pairWithWETHAddressForToken;
mapping (address => uint256) public wrappedTokenContributed; // To calculate units
| mapping (address => uint256) public unitsContributed; // unit to keep track how much each person should get of LP
mapping (address => uint256) public unitsClaimed;
mapping (address => bool) public CORERefundClaimed;
mapping (address => address) public pairWithWETHAddressForToken;
mapping (address => uint256) public wrappedTokenContributed; // To calculate units
| 80,407 |
19 | // High level dynamic information about an asset / | struct AssetDynamic {
address id; // Asset address
string typeId; // Asset typeId (for example "VAULT_V2" or "IRON_BANK_MARKET")
address tokenId; // Underlying token address;
TokenAmount underlyingTokenBalance; // Underlying token balances
TokenAmount delegatedBalance; // Delegated balances
AssetMetadata metadata; // Metadata specific to the asset type of this adapter
}
| struct AssetDynamic {
address id; // Asset address
string typeId; // Asset typeId (for example "VAULT_V2" or "IRON_BANK_MARKET")
address tokenId; // Underlying token address;
TokenAmount underlyingTokenBalance; // Underlying token balances
TokenAmount delegatedBalance; // Delegated balances
AssetMetadata metadata; // Metadata specific to the asset type of this adapter
}
| 27,869 |
11 | // Set default roles | _setupRole(DEFAULT_ADMIN_ROLE, to);
_setupRole(ADMIN_ROLE, to);
| _setupRole(DEFAULT_ADMIN_ROLE, to);
_setupRole(ADMIN_ROLE, to);
| 60,942 |
72 | // total amount the contract has released. | uint256 public totalReleased;
uint256 public immutable VESTING_PERIOD = 2629746; // 1 month in seconds
| uint256 public totalReleased;
uint256 public immutable VESTING_PERIOD = 2629746; // 1 month in seconds
| 36,852 |
16 | // The maximum `quantity` that can be minted with {_mintERC2309}. This limit is to prevent overflows on the address data entries. For a limit of 5000, a total of 3.689e15 calls to {_mintERC2309} is required to cause an overflow, which is unrealistic. | uint256 private constant _MAX_MINT_ERC2309_QUANTITY_LIMIT = 5000;
| uint256 private constant _MAX_MINT_ERC2309_QUANTITY_LIMIT = 5000;
| 40,141 |
34 | // check each token. NB Tokens must be in same order in original commitment package as in attestation package | for (uint256 index = 0; index < attestationNFTs.length; index++)
{
if (attestationNFTs[index].erc721 != commitmentNFTs[index].erc721
|| attestationNFTs[index].tokenId != commitmentNFTs[index].tokenId)
{
return false;
}
| for (uint256 index = 0; index < attestationNFTs.length; index++)
{
if (attestationNFTs[index].erc721 != commitmentNFTs[index].erc721
|| attestationNFTs[index].tokenId != commitmentNFTs[index].tokenId)
{
return false;
}
| 13,331 |
10 | // send back the calculated earnings + token. | soulLabFT.transferFrom(owner(), msg.sender, (stakes[msg.sender].amount * 15)/100 + stakes[msg.sender].amount);
| soulLabFT.transferFrom(owner(), msg.sender, (stakes[msg.sender].amount * 15)/100 + stakes[msg.sender].amount);
| 46,348 |
61 | // max amount of funds raised | uint256 public cap;
| uint256 public cap;
| 35,725 |
65 | // this is ETHbalances[address(0)] = balances[address(0)].sub(_amount); _to.transfer(_amount); UNSAFE | (bool sent,) = _to.call{gas: SAFE_GAS_STIPEND, value: receivedAmount}("");
| (bool sent,) = _to.call{gas: SAFE_GAS_STIPEND, value: receivedAmount}("");
| 49,621 |
22 | // Calculate vesting rate per second | uint256 jiffysPerSecond = (vestingGrants[account].grantJiffys.div(vestingGrants[account].endTimestamp.sub(vestingGrants[account].startTimestamp)));
| uint256 jiffysPerSecond = (vestingGrants[account].grantJiffys.div(vestingGrants[account].endTimestamp.sub(vestingGrants[account].startTimestamp)));
| 51,055 |
375 | // TODO: [Optimization] Allow contract to circumvent blockLock to dedup deposit operations |
uint256 treeHelperVaultBefore = cvxCrvHelperVault.balanceOf(badgerTree);
|
uint256 treeHelperVaultBefore = cvxCrvHelperVault.balanceOf(badgerTree);
| 38,626 |
17 | // require(canTransfer(msg.sender)); |
uint256 _allowance = allowed[_from][msg.sender];
|
uint256 _allowance = allowed[_from][msg.sender];
| 4,718 |
268 | // Sets a new comptroller for the marketAdmin function to set a new comptroller return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)/ | function _setComptroller(ComptrollerInterface newComptroller) public returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_COMPTROLLER_OWNER_CHECK);
}
ComptrollerInterface oldComptroller = comptroller;
// Ensure invoke comptroller.isComptroller() returns true
require(newComptroller.isComptroller(), "marker method returned false");
// Set market's comptroller to newComptroller
comptroller = newComptroller;
// Emit NewComptroller(oldComptroller, newComptroller)
emit NewComptroller(oldComptroller, newComptroller);
return uint(Error.NO_ERROR);
}
| function _setComptroller(ComptrollerInterface newComptroller) public returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_COMPTROLLER_OWNER_CHECK);
}
ComptrollerInterface oldComptroller = comptroller;
// Ensure invoke comptroller.isComptroller() returns true
require(newComptroller.isComptroller(), "marker method returned false");
// Set market's comptroller to newComptroller
comptroller = newComptroller;
// Emit NewComptroller(oldComptroller, newComptroller)
emit NewComptroller(oldComptroller, newComptroller);
return uint(Error.NO_ERROR);
}
| 627 |
204 | // chop all trailing zeros for numbers with decimals | params.sigfigs = number / (10 ** (digits - numSigfigs));
if(tenPowDecimals > number){
| params.sigfigs = number / (10 ** (digits - numSigfigs));
if(tenPowDecimals > number){
| 56,155 |
20 | // User must have approved contract to transfer working ZAP | require(token.transferFrom(msg.sender, address(this), numZap), "Error: User must have approved contract to transfer ZAP");
if (!isProviderInitialized(holderAddress, oracleAddress)) {
setProviderInitialized(holderAddress, oracleAddress);
addHolderOracle(holderAddress, oracleAddress);
}
| require(token.transferFrom(msg.sender, address(this), numZap), "Error: User must have approved contract to transfer ZAP");
if (!isProviderInitialized(holderAddress, oracleAddress)) {
setProviderInitialized(holderAddress, oracleAddress);
addHolderOracle(holderAddress, oracleAddress);
}
| 1,346 |
362 | // expmods_and_points.points[33] = -(g^71z). | mstore(add(expmodsAndPoints, 0x6c0), point)
| mstore(add(expmodsAndPoints, 0x6c0), point)
| 63,938 |
141 | // Also emits a {IERC20-Transfer} event for ERC20 compatibility. / | function burn(uint256 amount, bytes memory data) public {
| function burn(uint256 amount, bytes memory data) public {
| 67,305 |
100 | // return initial release + the remainder proportionally to time from vesting start mul first for best precision, v.8 compiler reverts on overflows | vestedTokens = ((totalTokens - initialRelease) * timeVestedSoFar) / _vestingPeriod + initialRelease;
| vestedTokens = ((totalTokens - initialRelease) * timeVestedSoFar) / _vestingPeriod + initialRelease;
| 81,728 |
57 | // Helper function that determines the value of assets using `_getValues`. / | function getValues(
ERC20[] calldata baseAssets,
uint256[] calldata amounts,
ERC20 quoteAsset
| function getValues(
ERC20[] calldata baseAssets,
uint256[] calldata amounts,
ERC20 quoteAsset
| 42,120 |
0 | // emitted after a leveraged swap. targetToken The address of the token that will be borrowed pairToken The address of the token that will be swapped to and deposited user The user address targetAmount The amount of target token in wei borrowRateMode The interest rate mode of the debt the user wants to repay: 1 for Stable, 2 for Variable slippage The max slippage allowed during swap pairAmountReturned The remaining amount of the pair token in wei that will be returned to user / | event Leverage(
address indexed targetToken,
address indexed pairToken,
address user,
uint targetAmount,
uint borrowRateMode,
uint slippage,
uint pairAmountReturned
);
| event Leverage(
address indexed targetToken,
address indexed pairToken,
address user,
uint targetAmount,
uint borrowRateMode,
uint slippage,
uint pairAmountReturned
);
| 31,213 |
12 | // Action execution failed./reason Data returned by the function called by the action. | error FailedActionExecution(bytes reason);
| error FailedActionExecution(bytes reason);
| 33,678 |
16 | // Next, set up memory for execution | assembly {
mstore(0x80, sload(0)) // Execution id, read from storage
mstore(0xa0, sload(1)) // Original sender address, read from storage
mstore(0xc0, 0) // Pointer to storage buffer
mstore(0xe0, 0) // Bytes4 value of the current action requestor being used
mstore(0x100, 0) // Enum representing the next type of function to be called (when pushing to buffer)
mstore(0x120, 0) // Number of storage slots written to in buffer
mstore(0x140, 0) // Number of events pushed to buffer
mstore(0x160, 0) // Number of payment destinations pushed to buffer
| assembly {
mstore(0x80, sload(0)) // Execution id, read from storage
mstore(0xa0, sload(1)) // Original sender address, read from storage
mstore(0xc0, 0) // Pointer to storage buffer
mstore(0xe0, 0) // Bytes4 value of the current action requestor being used
mstore(0x100, 0) // Enum representing the next type of function to be called (when pushing to buffer)
mstore(0x120, 0) // Number of storage slots written to in buffer
mstore(0x140, 0) // Number of events pushed to buffer
mstore(0x160, 0) // Number of payment destinations pushed to buffer
| 74,452 |
13 | // Calculate shares values in sdex tokens _shares amount of shares. _shares <= totalShares _currentBalance contract balance in sdexreturn tokens_ qty of sdex token equivalent to the _shares. tokens_ <= _currentBalance / | function _sharesToTokens(uint256 _shares, uint256 _currentBalance) internal view returns (uint256 tokens_) {
tokens_ = totalShares != 0 ? (_shares * _currentBalance) / totalShares : _shares / SHARES_FACTOR;
}
| function _sharesToTokens(uint256 _shares, uint256 _currentBalance) internal view returns (uint256 tokens_) {
tokens_ = totalShares != 0 ? (_shares * _currentBalance) / totalShares : _shares / SHARES_FACTOR;
}
| 42,285 |
76 | // VotingEscrowDelegation needs the percent of available tokens for delegation when creating the boost, instead of the percent of the users balance. We calculate this percent representing the amount of tokens wanted by the buyer | vars.boostPercent = (vars.toDelegateAmount * MAX_PCT) /
(vars.delegatorBalance - delegationBoost.delegated_boost(delegator));
| vars.boostPercent = (vars.toDelegateAmount * MAX_PCT) /
(vars.delegatorBalance - delegationBoost.delegated_boost(delegator));
| 32,799 |
8 | // IN REVISION - Returns SecureBox given a user_user is the username to check / | function getUserList(string memory _user) public view returns(SecureBox memory){
return user_pass[_user];
}
| function getUserList(string memory _user) public view returns(SecureBox memory){
return user_pass[_user];
}
| 12,450 |
1 | // Address of the `FxRoot` contract on the mainnet/Goerli network/`FxRoot` is the contract of the "Fx-Portal" on the mainnet/Goerli. | address public immutable FX_ROOT;
| address public immutable FX_ROOT;
| 32,402 |
2 | // Modifier used internally that will delegate the call to the implementation unless the sender is the admin. / | modifier ifAdmin() {
if (msg.sender == _getAdmin()) {
_;
} else {
_fallback();
}
}
| modifier ifAdmin() {
if (msg.sender == _getAdmin()) {
_;
} else {
_fallback();
}
}
| 8,433 |
151 | // Transfer tokens from one address to another and then execute a callback on recipient. sender The address which you want to send tokens from recipient The address which you want to transfer to amount The amount of tokens to be transferred data Additional data with no specified formatreturn A boolean that indicates if the operation was successful. / | function transferFromAndCall(address sender, address recipient, uint256 amount, bytes memory data) public virtual override returns (bool) {
transferFrom(sender, recipient, amount);
require(_checkAndCallTransfer(sender, recipient, amount, data), "ERC1363: _checkAndCallTransfer reverts");
return true;
}
| function transferFromAndCall(address sender, address recipient, uint256 amount, bytes memory data) public virtual override returns (bool) {
transferFrom(sender, recipient, amount);
require(_checkAndCallTransfer(sender, recipient, amount, data), "ERC1363: _checkAndCallTransfer reverts");
return true;
}
| 26,384 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.