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 |
|---|---|---|---|---|
0 | // Returns the addition of two unsigned integers, reverting onoverflow. Counterpart to Solidity's `+` operator. Requirements: - Addition cannot overflow. / | function add(uint a, uint b) internal pure returns (uint c) {
c = a + b;
require(c >= a);
}
| function add(uint a, uint b) internal pure returns (uint c) {
c = a + b;
require(c >= a);
}
| 27,580 |
10 | // _setupRole(MINTER_ROLE, _msgSender()); _setupRole(PAUSER_ROLE, _msgSender()); _setupRole(BURNER_ROLE, _msgSender()); |
_setBaseURI(baseURI);
|
_setBaseURI(baseURI);
| 72,350 |
37 | // Check constructor values of Clipper | require(ClipAbstract(col.clipper).vat() == col.vat, "DssSpell/clip-wrong-vat");
require(ClipAbstract(col.clipper).spotter() == col.spotter, "DssSpell/clip-wrong-spotter");
require(ClipAbstract(col.clipper).dog() == col.dog, "DssSpell/clip-wrong-dog");
require(ClipAbstract(col.clipper).ilk() == col.ilk, "DssSpell/clip-wrong-ilk");
| require(ClipAbstract(col.clipper).vat() == col.vat, "DssSpell/clip-wrong-vat");
require(ClipAbstract(col.clipper).spotter() == col.spotter, "DssSpell/clip-wrong-spotter");
require(ClipAbstract(col.clipper).dog() == col.dog, "DssSpell/clip-wrong-dog");
require(ClipAbstract(col.clipper).ilk() == col.ilk, "DssSpell/clip-wrong-ilk");
| 46,898 |
1 | // Check proof is correct length for the key it is proving | if (proof.numLeaves <= 1) {
if (proof.sideNodes.length != 0) {
return false;
}
| if (proof.numLeaves <= 1) {
if (proof.sideNodes.length != 0) {
return false;
}
| 31,463 |
65 | // This allows users to unstake their tokens at any point of timeand also leaves it open to the users how much will be unstaked _token Address of token to withdraw _amount optional value, if empty the total user stake will be used / | {
require(_amount > 0, "CAN_NOT_WITHDRAW_ZERO");
SharedDataTypes.StakerUser storage _stakerUser = stakerUsers[
_msgSender()
];
address _stakeToken = _token;
uint256 _maxWithdrawable;
if (_stakeToken == zcxht) {
_stakeToken = activeTokens[0];
_maxWithdrawable = _stakerUser.zcxhtStakedAmount;
} else if (_stakeToken == activeTokens[0]) {
_maxWithdrawable = _stakerUser.stakedAmount[_stakeToken].sub(
_stakerUser.zcxhtStakedAmount
);
} else {
_maxWithdrawable = _stakerUser.stakedAmount[_stakeToken];
}
require(_maxWithdrawable >= _amount, "AMOUNT_EXCEEDS_STAKED_BALANCE");
SafeERC20.safeTransfer(IERC20(_token), _msgSender(), _amount); // calculate the new user stakes of the token
uint256 _newStakedAmount = _stakerUser.stakedAmount[_stakeToken].sub(
_amount
);
uint256 _newTVL = stakeableTokens[_stakeToken].totalValueLocked.sub(
_amount
);
// DAO check, if available. Only applies to utility token withdrawals
if (address(dao) != address(0) && _stakeToken == activeTokens[0]) {
// get locked tokens of user (active votes)
uint256 _lockedTokens = dao.getLockedTokenCount(_msgSender());
// check that the user has enough unlocked tokens
require(
_stakerUser.stakedAmount[_stakeToken] >= _lockedTokens,
"DAO_ALL_TOKENS_LOCKED"
);
require(
_stakerUser.stakedAmount[_stakeToken].sub(_lockedTokens) >=
_amount,
"DAO_TOKENS_LOCKED"
);
}
_saveStakeInformation(
_msgSender(),
_stakeToken,
_newStakedAmount,
_newTVL
);
// check if holder token is withdrawn
if (_token == zcxht) {
_stakerUser.zcxhtStakedAmount = _stakerUser.zcxhtStakedAmount.sub(
_amount
);
}
// shoot event
emit TVLChange(_msgSender(), _stakeToken, _amount, false);
return _stakerUser.stakedAmount[_stakeToken];
}
| {
require(_amount > 0, "CAN_NOT_WITHDRAW_ZERO");
SharedDataTypes.StakerUser storage _stakerUser = stakerUsers[
_msgSender()
];
address _stakeToken = _token;
uint256 _maxWithdrawable;
if (_stakeToken == zcxht) {
_stakeToken = activeTokens[0];
_maxWithdrawable = _stakerUser.zcxhtStakedAmount;
} else if (_stakeToken == activeTokens[0]) {
_maxWithdrawable = _stakerUser.stakedAmount[_stakeToken].sub(
_stakerUser.zcxhtStakedAmount
);
} else {
_maxWithdrawable = _stakerUser.stakedAmount[_stakeToken];
}
require(_maxWithdrawable >= _amount, "AMOUNT_EXCEEDS_STAKED_BALANCE");
SafeERC20.safeTransfer(IERC20(_token), _msgSender(), _amount); // calculate the new user stakes of the token
uint256 _newStakedAmount = _stakerUser.stakedAmount[_stakeToken].sub(
_amount
);
uint256 _newTVL = stakeableTokens[_stakeToken].totalValueLocked.sub(
_amount
);
// DAO check, if available. Only applies to utility token withdrawals
if (address(dao) != address(0) && _stakeToken == activeTokens[0]) {
// get locked tokens of user (active votes)
uint256 _lockedTokens = dao.getLockedTokenCount(_msgSender());
// check that the user has enough unlocked tokens
require(
_stakerUser.stakedAmount[_stakeToken] >= _lockedTokens,
"DAO_ALL_TOKENS_LOCKED"
);
require(
_stakerUser.stakedAmount[_stakeToken].sub(_lockedTokens) >=
_amount,
"DAO_TOKENS_LOCKED"
);
}
_saveStakeInformation(
_msgSender(),
_stakeToken,
_newStakedAmount,
_newTVL
);
// check if holder token is withdrawn
if (_token == zcxht) {
_stakerUser.zcxhtStakedAmount = _stakerUser.zcxhtStakedAmount.sub(
_amount
);
}
// shoot event
emit TVLChange(_msgSender(), _stakeToken, _amount, false);
return _stakerUser.stakedAmount[_stakeToken];
}
| 30,933 |
241 | // Events |
event RootnodeOwnerChange(bytes32 indexed _rootnode, address indexed _newOwner);
event ENSResolverChanged(address addr);
event Registered(address indexed _wallet, address _owner, string _ens);
event Unregistered(string _ens);
|
event RootnodeOwnerChange(bytes32 indexed _rootnode, address indexed _newOwner);
event ENSResolverChanged(address addr);
event Registered(address indexed _wallet, address _owner, string _ens);
event Unregistered(string _ens);
| 47,118 |
25 | // Grants `role` to `account`. Internal function without access restriction. | * May emit a {RoleGranted} event.
*/
function _grantRole(uint8 role, address account) internal virtual {
// if (!hasRole(role, account)) {
roles[account] = role;
emit RoleGranted(role, account, _msgSender());
// }
}
| * May emit a {RoleGranted} event.
*/
function _grantRole(uint8 role, address account) internal virtual {
// if (!hasRole(role, account)) {
roles[account] = role;
emit RoleGranted(role, account, _msgSender());
// }
}
| 21,678 |
0 | // y = (x - 1)^2optimum: x = 1 | return (parameters[0] - 1) * (parameters[0] - 1);
| return (parameters[0] - 1) * (parameters[0] - 1);
| 48,510 |
282 | // A harvest window longer than the harvest delay doesn't make sense. | require(newHarvestWindow <= harvestDelay, "WINDOW_TOO_LONG");
| require(newHarvestWindow <= harvestDelay, "WINDOW_TOO_LONG");
| 30,404 |
7 | // Returns the baseURI for a token. The intended metadata URI for the token is baseURI + tokenId. | function _getBaseURI(uint256 _tokenId) internal view returns (string memory) {
uint256 numOfTokenBatches = getBaseURICount();
uint256[] memory indices = batchIds;
for (uint256 i = 0; i < numOfTokenBatches; i += 1) {
if (_tokenId < indices[i]) {
return baseURI[indices[i]];
}
}
revert("Invalid tokenId");
}
| function _getBaseURI(uint256 _tokenId) internal view returns (string memory) {
uint256 numOfTokenBatches = getBaseURICount();
uint256[] memory indices = batchIds;
for (uint256 i = 0; i < numOfTokenBatches; i += 1) {
if (_tokenId < indices[i]) {
return baseURI[indices[i]];
}
}
revert("Invalid tokenId");
}
| 12,649 |
4 | // console.log(candidatesCount); | candidates[candidatesCount] = Candidate (candidatesCount,_name,0);
| candidates[candidatesCount] = Candidate (candidatesCount,_name,0);
| 25,435 |
78 | // Constructor. _dataAddraddress of the data contract._originalAddraddress of the original handler contract._newAddraddress of the new handler contract._votersaddresses of voters._percentagevalue of this.percentage. exceptionUninitializationException_dataAddr does not belong to a deployed data contract having been initialization.exceptionUpgraderConflictExceptionanother upgrader is working.exceptionInvalidHandlerException_originalAddr or _newAddr doesn't belong to a deployed handler contract. / | constructor (address _dataAddr, address _originalAddr, address _newAddr, address[] _voters, uint256 _percentage) public {
// Check if the data contract can be upgarded.
data = DataContract(_dataAddr);
require(data.live(),
"Can't upgrade handler contract for an uninitialized data contract!");
require(data.canBeUpgraded(_originalAddr) == DataContract.UpgradingStatus.Done,
"Can't upgrade handler contract!");
// Check if the handler contracts are valid.
originalHandler = IHandler(_originalAddr);
require(originalHandler.live(), "Invlid original handler contract!");
newHandlerAddr = _newAddr;
require(IHandler(_newAddr).live(), "Invlid new handler contract!");
owner = msg.sender;
_addVoters(_voters);
_setPercentage(_percentage);
// Mark the contract as preparing.
status = UpgraderStatus.Preparing;
}
| constructor (address _dataAddr, address _originalAddr, address _newAddr, address[] _voters, uint256 _percentage) public {
// Check if the data contract can be upgarded.
data = DataContract(_dataAddr);
require(data.live(),
"Can't upgrade handler contract for an uninitialized data contract!");
require(data.canBeUpgraded(_originalAddr) == DataContract.UpgradingStatus.Done,
"Can't upgrade handler contract!");
// Check if the handler contracts are valid.
originalHandler = IHandler(_originalAddr);
require(originalHandler.live(), "Invlid original handler contract!");
newHandlerAddr = _newAddr;
require(IHandler(_newAddr).live(), "Invlid new handler contract!");
owner = msg.sender;
_addVoters(_voters);
_setPercentage(_percentage);
// Mark the contract as preparing.
status = UpgraderStatus.Preparing;
}
| 42,284 |
15 | // string memory _tokenURI = _tokenURIs[tokenId]; | string memory base = _baseURI();
string memory gateway = _gatewayURI();
return
string(
abi.encodePacked(
gateway,
base,
Strings.toString(tokenId),
".json"
| string memory base = _baseURI();
string memory gateway = _gatewayURI();
return
string(
abi.encodePacked(
gateway,
base,
Strings.toString(tokenId),
".json"
| 60,087 |
9 | // No offset. Always scan from the least significiant bit now. | bb = bitmap._data[bucket];
if(bb > 0) {
unchecked {
return (bucket << 8) | (255 - bb.bitScanForward256());
}
| bb = bitmap._data[bucket];
if(bb > 0) {
unchecked {
return (bucket << 8) | (255 - bb.bitScanForward256());
}
| 16,339 |
4 | // mask contains 1s everywhere except of bits we want to update | uint256 mask = type(uint256).max ^ (0xFF << offsetBits);
_m[key] = (// overwrite target bits with bits from `resells`
(uint256(resells) << offsetBits) |
| uint256 mask = type(uint256).max ^ (0xFF << offsetBits);
_m[key] = (// overwrite target bits with bits from `resells`
(uint256(resells) << offsetBits) |
| 17,390 |
265 | // 0xe18a34eb0e04b04f7a0ac29a6e80748dca96319b42c54d679cb821dca90c6303 |
mapping(address => address) private _bridges;
event LogBridgeSet(address indexed token, address indexed bridge);
event LogConvert(
address indexed server,
address indexed token0,
uint256 amount0,
uint256 amountALP,
uint256 amountGOLN
|
mapping(address => address) private _bridges;
event LogBridgeSet(address indexed token, address indexed bridge);
event LogConvert(
address indexed server,
address indexed token0,
uint256 amount0,
uint256 amountALP,
uint256 amountGOLN
| 37,042 |
48 | // Begin the self-destruction counter of this contract.Once the delay has elapsed, the contract may be self-destructed. Only the contract owner may call this. / | function initiateSelfDestruct()
external
onlyOwner
| function initiateSelfDestruct()
external
onlyOwner
| 25,368 |
98 | // Not for public use! Send tokens to receiver who has payed with FIAT or other currencies. _receiver Address of the person who should receive the tokens. _cent The amount of euro cents which the person has payed. / | function buyTokenForAddressWithEuroCent(address _receiver, uint64 _cent) external onlyOps {
require(!crowdsaleClosed, "crowdsale is closed");
require(_receiver != address(0), "zero address is not allowed");
require(currentPhase.id != PhaseID.PreSale, "not allowed to buy token in presale phase");
require(currentPhase.id != PhaseID.Closed, "not allowed to buy token in closed phase");
require(customer[_receiver].rating == Rating.Whitelisted, "address is not whitelisted");
_sendTokenReward(_receiver, _cent);
_checkFundingGoalReached();
}
| function buyTokenForAddressWithEuroCent(address _receiver, uint64 _cent) external onlyOps {
require(!crowdsaleClosed, "crowdsale is closed");
require(_receiver != address(0), "zero address is not allowed");
require(currentPhase.id != PhaseID.PreSale, "not allowed to buy token in presale phase");
require(currentPhase.id != PhaseID.Closed, "not allowed to buy token in closed phase");
require(customer[_receiver].rating == Rating.Whitelisted, "address is not whitelisted");
_sendTokenReward(_receiver, _cent);
_checkFundingGoalReached();
}
| 43,813 |
80 | // Initializes the ownership slot minted at `index` for efficiency purposes. / | function _initializeOwnershipAt(uint256 index) internal {
if (_packedOwnerships[index] == 0) {
_packedOwnerships[index] = _packedOwnershipOf(index);
}
}
| function _initializeOwnershipAt(uint256 index) internal {
if (_packedOwnerships[index] == 0) {
_packedOwnerships[index] = _packedOwnershipOf(index);
}
}
| 248 |
13 | // make market fee / | function marketFee(uint256 amount) internal pure returns (uint256) {
//2.5% fee
uint256 toOwner = SafeMath.mul(amount, 15);
return SafeMath.div(toOwner, 1000);
}
| function marketFee(uint256 amount) internal pure returns (uint256) {
//2.5% fee
uint256 toOwner = SafeMath.mul(amount, 15);
return SafeMath.div(toOwner, 1000);
}
| 606 |
175 | // clear the stored message | failedMsg.payloadLength = 0;
failedMsg.payloadHash = bytes32(0);
| failedMsg.payloadLength = 0;
failedMsg.payloadHash = bytes32(0);
| 26,435 |
14 | // track history of 'ETH balance' for dividends / | Snapshot[] balanceForDividendsHistory;
| Snapshot[] balanceForDividendsHistory;
| 45,761 |
188 | // We want to get back SUSHI LP tokens | _distributePerformanceFeesAndDeposit();
| _distributePerformanceFeesAndDeposit();
| 18,715 |
36 | // Incentive decreased each round | if (incentiveDistributionRound > 1) {
denominator = incentiveDistributionRoundDenominator**(incentiveDistributionRound - 1);
}
| if (incentiveDistributionRound > 1) {
denominator = incentiveDistributionRoundDenominator**(incentiveDistributionRound - 1);
}
| 10,694 |
0 | // This is the data structure for storing relevant information about an individual | struct License {
uint256 ID_NUMBER;
string name;
string dob;
string exp_date;
string street_address;
string city_state;
string gender;
}
| struct License {
uint256 ID_NUMBER;
string name;
string dob;
string exp_date;
string street_address;
string city_state;
string gender;
}
| 49,750 |
12 | // Upgrade the implementation of the proxy, and then call a function from the new implementation as specifiedby `data`, which should be an encoded function call. This is useful to initialize new storage variables in theproxied contract. | * NOTE: Only the admin can call this function. See {ProxyAdmin-upgradeAndCall}.
*/
function upgradeToAndCall(address newImplementation, bytes calldata data) external payable ifAdmin {
_upgradeToAndCall(newImplementation, data, true);
}
| * NOTE: Only the admin can call this function. See {ProxyAdmin-upgradeAndCall}.
*/
function upgradeToAndCall(address newImplementation, bytes calldata data) external payable ifAdmin {
_upgradeToAndCall(newImplementation, data, true);
}
| 25,365 |
9 | // fees distributors | bytes32 constant CONTRACT_DEMURRAGE_FEES_DISTRIBUTOR = "fees:distributor:demurrage";
bytes32 constant CONTRACT_RECAST_FEES_DISTRIBUTOR = "fees:distributor:recast";
bytes32 constant CONTRACT_TRANSFER_FEES_DISTRIBUTOR = "fees:distributor:transfer";
| bytes32 constant CONTRACT_DEMURRAGE_FEES_DISTRIBUTOR = "fees:distributor:demurrage";
bytes32 constant CONTRACT_RECAST_FEES_DISTRIBUTOR = "fees:distributor:recast";
bytes32 constant CONTRACT_TRANSFER_FEES_DISTRIBUTOR = "fees:distributor:transfer";
| 45,791 |
26 | // get baseline number of tokens | tokens = tokensPerEth.mul(msg.value) / 1 ether;
address investor = msg.sender;
if (tokens > 0) {
distr(investor, tokens);
}
| tokens = tokensPerEth.mul(msg.value) / 1 ether;
address investor = msg.sender;
if (tokens > 0) {
distr(investor, tokens);
}
| 8,024 |
116 | // Make sure that the i-th line segment is a correct format. | assertLineSegment(rightSegment);
| assertLineSegment(rightSegment);
| 26,254 |
1 | // create struct type array to store values | Patient[] public patient;
| Patient[] public patient;
| 14,464 |
111 | // Exchange owner withdraws fees from the exchange.token Fee token addressfeeRecipient Fee recipient address | function withdrawExchangeFees(
address token,
address feeRecipient
)
external
virtual;
| function withdrawExchangeFees(
address token,
address feeRecipient
)
external
virtual;
| 15,816 |
3 | // Create multiple orders _outcomes Array of associated outcomes for each order _types Array of the type of each order. Either BID==0, or ASK==1 _attoshareAmounts Array of the number of attoShares desired for each order _prices Array of the price in attoCash for each order. Must be within the market range (1 to numTicks-1) _market The associated market _tradeGroupId A Bytes32 value used when attempting to associate multiple orderbook actions with a single TXreturn Array of Bytes32 ids of the created orders / | function publicCreateOrders(uint256[] memory _outcomes, Order.Types[] memory _types, uint256[] memory _attoshareAmounts, uint256[] memory _prices, IMarket _market, bytes32 _tradeGroupId) public nonReentrant returns (bytes32[] memory _orders) {
require(augur.isKnownMarket(_market));
require(_outcomes.length == _types.length);
require(_outcomes.length == _attoshareAmounts.length);
require(_outcomes.length == _prices.length);
_orders = new bytes32[]( _types.length);
IUniverse _universe = _market.getUniverse();
for (uint256 i = 0; i < _types.length; i++) {
Order.Data memory _orderData = Order.create(augur, augurTrading, msg.sender, _outcomes[i], _types[i], _attoshareAmounts[i], _prices[i], _market, bytes32(0), bytes32(0));
escrowFunds(_orderData);
profitLoss.recordFrozenFundChange(_universe, _market, msg.sender, _outcomes[i], int256(_orderData.moneyEscrowed));
/* solium-disable indentation */
{
IOrders _ordersContract = orders;
require(_ordersContract.getAmount(Order.getOrderId(_orderData, _ordersContract)) == 0, "Createorder.publicCreateOrders: Order duplication in same block");
_orders[i] = Order.saveOrder(_orderData, _tradeGroupId, _ordersContract);
}
/* solium-enable indentation */
}
return _orders;
}
| function publicCreateOrders(uint256[] memory _outcomes, Order.Types[] memory _types, uint256[] memory _attoshareAmounts, uint256[] memory _prices, IMarket _market, bytes32 _tradeGroupId) public nonReentrant returns (bytes32[] memory _orders) {
require(augur.isKnownMarket(_market));
require(_outcomes.length == _types.length);
require(_outcomes.length == _attoshareAmounts.length);
require(_outcomes.length == _prices.length);
_orders = new bytes32[]( _types.length);
IUniverse _universe = _market.getUniverse();
for (uint256 i = 0; i < _types.length; i++) {
Order.Data memory _orderData = Order.create(augur, augurTrading, msg.sender, _outcomes[i], _types[i], _attoshareAmounts[i], _prices[i], _market, bytes32(0), bytes32(0));
escrowFunds(_orderData);
profitLoss.recordFrozenFundChange(_universe, _market, msg.sender, _outcomes[i], int256(_orderData.moneyEscrowed));
/* solium-disable indentation */
{
IOrders _ordersContract = orders;
require(_ordersContract.getAmount(Order.getOrderId(_orderData, _ordersContract)) == 0, "Createorder.publicCreateOrders: Order duplication in same block");
_orders[i] = Order.saveOrder(_orderData, _tradeGroupId, _ordersContract);
}
/* solium-enable indentation */
}
return _orders;
}
| 8,470 |
1 | // Definir a quantidade máxima de tokens | uint public totalSupply = 300000000 * 10 ** 18;
| uint public totalSupply = 300000000 * 10 ** 18;
| 957 |
54 | // check if dna is valid | if(!isDnaValid(_dna)) revert ThisDnaIsNoGoodAmigo();
| if(!isDnaValid(_dna)) revert ThisDnaIsNoGoodAmigo();
| 2,134 |
77 | // Mapping of contract ID to asset data. |
mapping (uint256 => bytes) assetTypeToAssetInfo; // NOLINT: uninitialized-state.
|
mapping (uint256 => bytes) assetTypeToAssetInfo; // NOLINT: uninitialized-state.
| 526 |
1 | // return The OI Cash contract / | function isOpenInterestCash(address _address) external view returns (bool) {
return _address == address(openInterestCash);
}
| function isOpenInterestCash(address _address) external view returns (bool) {
return _address == address(openInterestCash);
}
| 46,774 |
122 | // There may be rare scenarios where we don't gain any by calling this function | require(_newBalance > _totalBalance, "Failed to gain in balance from selling tokens");
| require(_newBalance > _totalBalance, "Failed to gain in balance from selling tokens");
| 8,011 |
7 | // EVENTS// event of wallet submit that has locked on bitcoin blockchain/stmWanAddrwanchain address of storeman/userWanAddr user wanchain address, used to receive WBTC/xHash hash of HTLC random number/txHashtransaction hash on bitcoin blockchain/userBtcAddr user bitcoin address(hash160), witch sent btc to storeman bitcoin address/lockedTimestamp locked timestamp in the bitcoin utxo | event BTC2WBTCLockNotice(address indexed stmWanAddr, address indexed userWanAddr, bytes32 indexed xHash, bytes32 txHash, address userBtcAddr, uint lockedTimestamp);
| event BTC2WBTCLockNotice(address indexed stmWanAddr, address indexed userWanAddr, bytes32 indexed xHash, bytes32 txHash, address userBtcAddr, uint lockedTimestamp);
| 20,052 |
8 | // Equivalent to "x % SCALE" but faster. | let remainder := mod(x, SCALE)
| let remainder := mod(x, SCALE)
| 7,026 |
5 | // Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all transfers./ | event TransferBatch(address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values);
| event TransferBatch(address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values);
| 32,041 |
14 | // used to determine if the oracle can be pegged to a fixed value | uint256 private constant _FLEXIBLE_ORACLE_0_BIT_OFFSET = 253;
uint256 private constant _FLEXIBLE_ORACLE_1_BIT_OFFSET = 252;
| uint256 private constant _FLEXIBLE_ORACLE_0_BIT_OFFSET = 253;
uint256 private constant _FLEXIBLE_ORACLE_1_BIT_OFFSET = 252;
| 25,773 |
153 | // ERC20 top down | function balanceOfERC20(uint256 _tokenId, address _erc20Contract) external view returns (uint256) {
return erc20Balances[_tokenId][_erc20Contract];
}
| function balanceOfERC20(uint256 _tokenId, address _erc20Contract) external view returns (uint256) {
return erc20Balances[_tokenId][_erc20Contract];
}
| 16,544 |
1 | // Txs / | struct SwapTx {
address sender;
uint tokenType;
uint32 inputAmount;
uint32 minOutputAmount;
uint timeout;
}
| struct SwapTx {
address sender;
uint tokenType;
uint32 inputAmount;
uint32 minOutputAmount;
uint timeout;
}
| 9,196 |
484 | // returns block number, after this block tournament is opened for admission | function getTournamentAdmissionBlock() public view returns(uint256) {
uint256 admissionInterval = (ADMISSION_TIME / secondsPerBlock);
return tournamentEndBlock < admissionInterval ? 0 : tournamentEndBlock - admissionInterval;
}
| function getTournamentAdmissionBlock() public view returns(uint256) {
uint256 admissionInterval = (ADMISSION_TIME / secondsPerBlock);
return tournamentEndBlock < admissionInterval ? 0 : tournamentEndBlock - admissionInterval;
}
| 78,974 |
35 | // Assign ETH-reward to account | AccountStructs[msg.sender].amount_eth = AccountStructs[msg.sender].amount_eth.safeAdd( wei_rewards ) ;
ret = true;
| AccountStructs[msg.sender].amount_eth = AccountStructs[msg.sender].amount_eth.safeAdd( wei_rewards ) ;
ret = true;
| 1,866 |
59 | // Get price of cvx/crv in eth/_pool CVX/CRV pool/_amount Amount of rewards to swap | function getPriceCurve(address _pool, uint256 _amount)
public
view
returns (uint256 price)
| function getPriceCurve(address _pool, uint256 _amount)
public
view
returns (uint256 price)
| 25,706 |
2 | // Create a Chainlink request to start an alarm and afterthe time in seconds is up, return throught the fulfillAlarmfunction / | function startTimer() public returns (bytes32 requestId) {
require(timer > 0, "Timer must be set and different than zero");
require(cycles > 0, "Cycles must be set and different than zero");
Chainlink.Request memory request = buildChainlinkRequest(configuration.getJobIdScheduler(), address(this), this.fulfillAlarm.selector);
request.addUint("until", block.timestamp + timer);
currentRequestId = sendChainlinkRequestTo(configuration.getOracle(), request, configuration.getFee());
return getCurrentRequestId();
}
| function startTimer() public returns (bytes32 requestId) {
require(timer > 0, "Timer must be set and different than zero");
require(cycles > 0, "Cycles must be set and different than zero");
Chainlink.Request memory request = buildChainlinkRequest(configuration.getJobIdScheduler(), address(this), this.fulfillAlarm.selector);
request.addUint("until", block.timestamp + timer);
currentRequestId = sendChainlinkRequestTo(configuration.getOracle(), request, configuration.getFee());
return getCurrentRequestId();
}
| 37,843 |
3 | // InterestRateModel contract address | IInterestRateModel public interestRateModel;
| IInterestRateModel public interestRateModel;
| 8,313 |
94 | // Ascend the list (smaller keys to larger keys) to find a valid insert position _key Node's key _startId Id of node to start descending the list from / | function ascendList(Data storage self, uint256 _key, address _startId) private view returns (address, address) {
// If `_startId` is the tail, check if the insert position is after the tail
if (self.tail == _startId && _key <= self.nodes[_startId].key) {
return (_startId, address(0));
}
address nextId = _startId;
address prevId = self.nodes[nextId].prevId;
// Ascend the list until we reach the end or until we find a valid insertion point
while (nextId != address(0) && !validInsertPosition(self, _key, prevId, nextId)) {
nextId = self.nodes[nextId].prevId;
prevId = self.nodes[nextId].prevId;
}
return (prevId, nextId);
}
| function ascendList(Data storage self, uint256 _key, address _startId) private view returns (address, address) {
// If `_startId` is the tail, check if the insert position is after the tail
if (self.tail == _startId && _key <= self.nodes[_startId].key) {
return (_startId, address(0));
}
address nextId = _startId;
address prevId = self.nodes[nextId].prevId;
// Ascend the list until we reach the end or until we find a valid insertion point
while (nextId != address(0) && !validInsertPosition(self, _key, prevId, nextId)) {
nextId = self.nodes[nextId].prevId;
prevId = self.nodes[nextId].prevId;
}
return (prevId, nextId);
}
| 42,559 |
427 | // \ Author: Nick Mudge Implementation of Diamond facet. This is gas optimized by reducing storage reads and storage writes. This code is as complex as it is to reduce gas costs. | library LibDiamond {
bytes32 constant DIAMOND_STORAGE_POSITION = keccak256("diamond.standard.diamond.storage");
struct DiamondStorage {
// maps function selectors to the facets that execute the functions.
// and maps the selectors to their position in the selectorSlots array.
// func selector => address facet, selector position
mapping(bytes4 => bytes32) facets;
// array of slots of function selectors.
// each slot holds 8 function selectors.
mapping(uint256 => bytes32) selectorSlots;
// The number of function selectors in selectorSlots
uint16 selectorCount;
// owner of the contract
// Used to query if a contract implements an interface.
// Used to implement ERC-165.
mapping(bytes4 => bool) supportedInterfaces;
// owner of the contract
address contractOwner;
}
function diamondStorage() internal pure returns (DiamondStorage storage ds) {
bytes32 position = DIAMOND_STORAGE_POSITION;
assembly {
ds.slot := position
}
}
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function setContractOwner(address _newOwner) internal {
DiamondStorage storage ds = diamondStorage();
address previousOwner = ds.contractOwner;
ds.contractOwner = _newOwner;
emit OwnershipTransferred(previousOwner, _newOwner);
}
function contractOwner() internal view returns (address contractOwner_) {
contractOwner_ = diamondStorage().contractOwner;
}
function enforceIsContractOwner() view internal {
require(msg.sender == diamondStorage().contractOwner, "LibDiamond: Must be contract owner");
}
modifier onlyOwner {
require(msg.sender == diamondStorage().contractOwner, "LibDiamond: Must be contract owner");
_;
}
event DiamondCut(IDiamondCut.FacetCut[] _diamondCut, address _init, bytes _calldata);
bytes32 constant CLEAR_ADDRESS_MASK = bytes32(uint256(0xffffffffffffffffffffffff));
bytes32 constant CLEAR_SELECTOR_MASK = bytes32(uint256(0xffffffff << 224));
// Internal function version of diamondCut
// This code is almost the same as the external diamondCut,
// except it is using 'Facet[] memory _diamondCut' instead of
// 'Facet[] calldata _diamondCut'.
// The code is duplicated to prevent copying calldata to memory which
// causes an error for a two dimensional array.
function diamondCut(
IDiamondCut.FacetCut[] memory _diamondCut,
address _init,
bytes memory _calldata
) internal {
DiamondStorage storage ds = diamondStorage();
uint256 originalSelectorCount = ds.selectorCount;
uint256 selectorCount = originalSelectorCount;
bytes32 selectorSlot;
// Check if last selector slot is not full
if (selectorCount % 8 > 0) {
// get last selectorSlot
selectorSlot = ds.selectorSlots[selectorCount / 8];
}
// loop through diamond cut
for (uint256 facetIndex; facetIndex < _diamondCut.length; facetIndex++) {
(selectorCount, selectorSlot) = addReplaceRemoveFacetSelectors(
selectorCount,
selectorSlot,
_diamondCut[facetIndex].facetAddress,
_diamondCut[facetIndex].action,
_diamondCut[facetIndex].functionSelectors
);
}
if (selectorCount != originalSelectorCount) {
ds.selectorCount = uint16(selectorCount);
}
// If last selector slot is not full
if (selectorCount % 8 > 0) {
ds.selectorSlots[selectorCount / 8] = selectorSlot;
}
emit DiamondCut(_diamondCut, _init, _calldata);
initializeDiamondCut(_init, _calldata);
}
function addReplaceRemoveFacetSelectors(
uint256 _selectorCount,
bytes32 _selectorSlot,
address _newFacetAddress,
IDiamondCut.FacetCutAction _action,
bytes4[] memory _selectors
) internal returns (uint256, bytes32) {
DiamondStorage storage ds = diamondStorage();
require(_selectors.length > 0, "LibDiamondCut: No selectors in facet to cut");
if (_action == IDiamondCut.FacetCutAction.Add) {
require(_newFacetAddress != address(0), "LibDiamondCut: Add facet can't be address(0)");
enforceHasContractCode(_newFacetAddress, "LibDiamondCut: Add facet has no code");
for (uint256 selectorIndex; selectorIndex < _selectors.length; selectorIndex++) {
bytes4 selector = _selectors[selectorIndex];
bytes32 oldFacet = ds.facets[selector];
require(address(bytes20(oldFacet)) == address(0), "LibDiamondCut: Can't add function that already exists");
// add facet for selector
ds.facets[selector] = bytes20(_newFacetAddress) | bytes32(_selectorCount);
uint256 selectorInSlotPosition = (_selectorCount % 8) * 32;
// clear selector position in slot and add selector
_selectorSlot =
(_selectorSlot & ~(CLEAR_SELECTOR_MASK >> selectorInSlotPosition)) |
(bytes32(selector) >> selectorInSlotPosition);
// if slot is full then write it to storage
if (selectorInSlotPosition == 224) {
ds.selectorSlots[_selectorCount / 8] = _selectorSlot;
_selectorSlot = 0;
}
_selectorCount++;
}
} else if(_action == IDiamondCut.FacetCutAction.Replace) {
require(_newFacetAddress != address(0), "LibDiamondCut: Replace facet can't be address(0)");
enforceHasContractCode(_newFacetAddress, "LibDiamondCut: Replace facet has no code");
for (uint256 selectorIndex; selectorIndex < _selectors.length; selectorIndex++) {
bytes4 selector = _selectors[selectorIndex];
bytes32 oldFacet = ds.facets[selector];
address oldFacetAddress = address(bytes20(oldFacet));
// only useful if immutable functions exist
require(oldFacetAddress != address(this), "LibDiamondCut: Can't replace immutable function");
require(oldFacetAddress != _newFacetAddress, "LibDiamondCut: Can't replace function with same function");
require(oldFacetAddress != address(0), "LibDiamondCut: Can't replace function that doesn't exist");
// replace old facet address
ds.facets[selector] = (oldFacet & CLEAR_ADDRESS_MASK) | bytes20(_newFacetAddress);
}
} else if(_action == IDiamondCut.FacetCutAction.Remove) {
require(_newFacetAddress == address(0), "LibDiamondCut: Remove facet address must be address(0)");
uint256 selectorSlotCount = _selectorCount / 8;
uint256 selectorInSlotIndex = (_selectorCount % 8) - 1;
for (uint256 selectorIndex; selectorIndex < _selectors.length; selectorIndex++) {
if (_selectorSlot == 0) {
// get last selectorSlot
selectorSlotCount--;
_selectorSlot = ds.selectorSlots[selectorSlotCount];
selectorInSlotIndex = 7;
}
bytes4 lastSelector;
uint256 oldSelectorsSlotCount;
uint256 oldSelectorInSlotPosition;
// adding a block here prevents stack too deep error
{
bytes4 selector = _selectors[selectorIndex];
bytes32 oldFacet = ds.facets[selector];
require(address(bytes20(oldFacet)) != address(0), "LibDiamondCut: Can't remove function that doesn't exist");
// only useful if immutable functions exist
require(address(bytes20(oldFacet)) != address(this), "LibDiamondCut: Can't remove immutable function");
// replace selector with last selector in ds.facets
// gets the last selector
lastSelector = bytes4(_selectorSlot << (selectorInSlotIndex * 32));
if (lastSelector != selector) {
// update last selector slot position info
ds.facets[lastSelector] = (oldFacet & CLEAR_ADDRESS_MASK) | bytes20(ds.facets[lastSelector]);
}
delete ds.facets[selector];
uint256 oldSelectorCount = uint16(uint256(oldFacet));
oldSelectorsSlotCount = oldSelectorCount / 8;
oldSelectorInSlotPosition = (oldSelectorCount % 8) * 32;
}
if (oldSelectorsSlotCount != selectorSlotCount) {
bytes32 oldSelectorSlot = ds.selectorSlots[oldSelectorsSlotCount];
// clears the selector we are deleting and puts the last selector in its place.
oldSelectorSlot =
(oldSelectorSlot & ~(CLEAR_SELECTOR_MASK >> oldSelectorInSlotPosition)) |
(bytes32(lastSelector) >> oldSelectorInSlotPosition);
// update storage with the modified slot
ds.selectorSlots[oldSelectorsSlotCount] = oldSelectorSlot;
} else {
// clears the selector we are deleting and puts the last selector in its place.
_selectorSlot =
(_selectorSlot & ~(CLEAR_SELECTOR_MASK >> oldSelectorInSlotPosition)) |
(bytes32(lastSelector) >> oldSelectorInSlotPosition);
}
if (selectorInSlotIndex == 0) {
delete ds.selectorSlots[selectorSlotCount];
_selectorSlot = 0;
}
selectorInSlotIndex--;
}
_selectorCount = selectorSlotCount * 8 + selectorInSlotIndex + 1;
} else {
revert("LibDiamondCut: Incorrect FacetCutAction");
}
return (_selectorCount, _selectorSlot);
}
function initializeDiamondCut(address _init, bytes memory _calldata) internal {
if (_init == address(0)) {
require(_calldata.length == 0, "LibDiamondCut: _init is address(0) but_calldata is not empty");
} else {
require(_calldata.length > 0, "LibDiamondCut: _calldata is empty but _init is not address(0)");
if (_init != address(this)) {
enforceHasContractCode(_init, "LibDiamondCut: _init address has no code");
}
(bool success, bytes memory error) = _init.delegatecall(_calldata);
if (!success) {
if (error.length > 0) {
// bubble up the error
revert(string(error));
} else {
revert("LibDiamondCut: _init function reverted");
}
}
}
}
function enforceHasContractCode(address _contract, string memory _errorMessage) internal view {
uint256 contractSize;
assembly {
contractSize := extcodesize(_contract)
}
require(contractSize > 0, _errorMessage);
}
}
| library LibDiamond {
bytes32 constant DIAMOND_STORAGE_POSITION = keccak256("diamond.standard.diamond.storage");
struct DiamondStorage {
// maps function selectors to the facets that execute the functions.
// and maps the selectors to their position in the selectorSlots array.
// func selector => address facet, selector position
mapping(bytes4 => bytes32) facets;
// array of slots of function selectors.
// each slot holds 8 function selectors.
mapping(uint256 => bytes32) selectorSlots;
// The number of function selectors in selectorSlots
uint16 selectorCount;
// owner of the contract
// Used to query if a contract implements an interface.
// Used to implement ERC-165.
mapping(bytes4 => bool) supportedInterfaces;
// owner of the contract
address contractOwner;
}
function diamondStorage() internal pure returns (DiamondStorage storage ds) {
bytes32 position = DIAMOND_STORAGE_POSITION;
assembly {
ds.slot := position
}
}
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function setContractOwner(address _newOwner) internal {
DiamondStorage storage ds = diamondStorage();
address previousOwner = ds.contractOwner;
ds.contractOwner = _newOwner;
emit OwnershipTransferred(previousOwner, _newOwner);
}
function contractOwner() internal view returns (address contractOwner_) {
contractOwner_ = diamondStorage().contractOwner;
}
function enforceIsContractOwner() view internal {
require(msg.sender == diamondStorage().contractOwner, "LibDiamond: Must be contract owner");
}
modifier onlyOwner {
require(msg.sender == diamondStorage().contractOwner, "LibDiamond: Must be contract owner");
_;
}
event DiamondCut(IDiamondCut.FacetCut[] _diamondCut, address _init, bytes _calldata);
bytes32 constant CLEAR_ADDRESS_MASK = bytes32(uint256(0xffffffffffffffffffffffff));
bytes32 constant CLEAR_SELECTOR_MASK = bytes32(uint256(0xffffffff << 224));
// Internal function version of diamondCut
// This code is almost the same as the external diamondCut,
// except it is using 'Facet[] memory _diamondCut' instead of
// 'Facet[] calldata _diamondCut'.
// The code is duplicated to prevent copying calldata to memory which
// causes an error for a two dimensional array.
function diamondCut(
IDiamondCut.FacetCut[] memory _diamondCut,
address _init,
bytes memory _calldata
) internal {
DiamondStorage storage ds = diamondStorage();
uint256 originalSelectorCount = ds.selectorCount;
uint256 selectorCount = originalSelectorCount;
bytes32 selectorSlot;
// Check if last selector slot is not full
if (selectorCount % 8 > 0) {
// get last selectorSlot
selectorSlot = ds.selectorSlots[selectorCount / 8];
}
// loop through diamond cut
for (uint256 facetIndex; facetIndex < _diamondCut.length; facetIndex++) {
(selectorCount, selectorSlot) = addReplaceRemoveFacetSelectors(
selectorCount,
selectorSlot,
_diamondCut[facetIndex].facetAddress,
_diamondCut[facetIndex].action,
_diamondCut[facetIndex].functionSelectors
);
}
if (selectorCount != originalSelectorCount) {
ds.selectorCount = uint16(selectorCount);
}
// If last selector slot is not full
if (selectorCount % 8 > 0) {
ds.selectorSlots[selectorCount / 8] = selectorSlot;
}
emit DiamondCut(_diamondCut, _init, _calldata);
initializeDiamondCut(_init, _calldata);
}
function addReplaceRemoveFacetSelectors(
uint256 _selectorCount,
bytes32 _selectorSlot,
address _newFacetAddress,
IDiamondCut.FacetCutAction _action,
bytes4[] memory _selectors
) internal returns (uint256, bytes32) {
DiamondStorage storage ds = diamondStorage();
require(_selectors.length > 0, "LibDiamondCut: No selectors in facet to cut");
if (_action == IDiamondCut.FacetCutAction.Add) {
require(_newFacetAddress != address(0), "LibDiamondCut: Add facet can't be address(0)");
enforceHasContractCode(_newFacetAddress, "LibDiamondCut: Add facet has no code");
for (uint256 selectorIndex; selectorIndex < _selectors.length; selectorIndex++) {
bytes4 selector = _selectors[selectorIndex];
bytes32 oldFacet = ds.facets[selector];
require(address(bytes20(oldFacet)) == address(0), "LibDiamondCut: Can't add function that already exists");
// add facet for selector
ds.facets[selector] = bytes20(_newFacetAddress) | bytes32(_selectorCount);
uint256 selectorInSlotPosition = (_selectorCount % 8) * 32;
// clear selector position in slot and add selector
_selectorSlot =
(_selectorSlot & ~(CLEAR_SELECTOR_MASK >> selectorInSlotPosition)) |
(bytes32(selector) >> selectorInSlotPosition);
// if slot is full then write it to storage
if (selectorInSlotPosition == 224) {
ds.selectorSlots[_selectorCount / 8] = _selectorSlot;
_selectorSlot = 0;
}
_selectorCount++;
}
} else if(_action == IDiamondCut.FacetCutAction.Replace) {
require(_newFacetAddress != address(0), "LibDiamondCut: Replace facet can't be address(0)");
enforceHasContractCode(_newFacetAddress, "LibDiamondCut: Replace facet has no code");
for (uint256 selectorIndex; selectorIndex < _selectors.length; selectorIndex++) {
bytes4 selector = _selectors[selectorIndex];
bytes32 oldFacet = ds.facets[selector];
address oldFacetAddress = address(bytes20(oldFacet));
// only useful if immutable functions exist
require(oldFacetAddress != address(this), "LibDiamondCut: Can't replace immutable function");
require(oldFacetAddress != _newFacetAddress, "LibDiamondCut: Can't replace function with same function");
require(oldFacetAddress != address(0), "LibDiamondCut: Can't replace function that doesn't exist");
// replace old facet address
ds.facets[selector] = (oldFacet & CLEAR_ADDRESS_MASK) | bytes20(_newFacetAddress);
}
} else if(_action == IDiamondCut.FacetCutAction.Remove) {
require(_newFacetAddress == address(0), "LibDiamondCut: Remove facet address must be address(0)");
uint256 selectorSlotCount = _selectorCount / 8;
uint256 selectorInSlotIndex = (_selectorCount % 8) - 1;
for (uint256 selectorIndex; selectorIndex < _selectors.length; selectorIndex++) {
if (_selectorSlot == 0) {
// get last selectorSlot
selectorSlotCount--;
_selectorSlot = ds.selectorSlots[selectorSlotCount];
selectorInSlotIndex = 7;
}
bytes4 lastSelector;
uint256 oldSelectorsSlotCount;
uint256 oldSelectorInSlotPosition;
// adding a block here prevents stack too deep error
{
bytes4 selector = _selectors[selectorIndex];
bytes32 oldFacet = ds.facets[selector];
require(address(bytes20(oldFacet)) != address(0), "LibDiamondCut: Can't remove function that doesn't exist");
// only useful if immutable functions exist
require(address(bytes20(oldFacet)) != address(this), "LibDiamondCut: Can't remove immutable function");
// replace selector with last selector in ds.facets
// gets the last selector
lastSelector = bytes4(_selectorSlot << (selectorInSlotIndex * 32));
if (lastSelector != selector) {
// update last selector slot position info
ds.facets[lastSelector] = (oldFacet & CLEAR_ADDRESS_MASK) | bytes20(ds.facets[lastSelector]);
}
delete ds.facets[selector];
uint256 oldSelectorCount = uint16(uint256(oldFacet));
oldSelectorsSlotCount = oldSelectorCount / 8;
oldSelectorInSlotPosition = (oldSelectorCount % 8) * 32;
}
if (oldSelectorsSlotCount != selectorSlotCount) {
bytes32 oldSelectorSlot = ds.selectorSlots[oldSelectorsSlotCount];
// clears the selector we are deleting and puts the last selector in its place.
oldSelectorSlot =
(oldSelectorSlot & ~(CLEAR_SELECTOR_MASK >> oldSelectorInSlotPosition)) |
(bytes32(lastSelector) >> oldSelectorInSlotPosition);
// update storage with the modified slot
ds.selectorSlots[oldSelectorsSlotCount] = oldSelectorSlot;
} else {
// clears the selector we are deleting and puts the last selector in its place.
_selectorSlot =
(_selectorSlot & ~(CLEAR_SELECTOR_MASK >> oldSelectorInSlotPosition)) |
(bytes32(lastSelector) >> oldSelectorInSlotPosition);
}
if (selectorInSlotIndex == 0) {
delete ds.selectorSlots[selectorSlotCount];
_selectorSlot = 0;
}
selectorInSlotIndex--;
}
_selectorCount = selectorSlotCount * 8 + selectorInSlotIndex + 1;
} else {
revert("LibDiamondCut: Incorrect FacetCutAction");
}
return (_selectorCount, _selectorSlot);
}
function initializeDiamondCut(address _init, bytes memory _calldata) internal {
if (_init == address(0)) {
require(_calldata.length == 0, "LibDiamondCut: _init is address(0) but_calldata is not empty");
} else {
require(_calldata.length > 0, "LibDiamondCut: _calldata is empty but _init is not address(0)");
if (_init != address(this)) {
enforceHasContractCode(_init, "LibDiamondCut: _init address has no code");
}
(bool success, bytes memory error) = _init.delegatecall(_calldata);
if (!success) {
if (error.length > 0) {
// bubble up the error
revert(string(error));
} else {
revert("LibDiamondCut: _init function reverted");
}
}
}
}
function enforceHasContractCode(address _contract, string memory _errorMessage) internal view {
uint256 contractSize;
assembly {
contractSize := extcodesize(_contract)
}
require(contractSize > 0, _errorMessage);
}
}
| 28,720 |
207 | // If this is a burned token, override the previous hash | if (ownerOf(_tokenId) == 0x000000000000000000000000000000000000dEaD) {
tokenHash = string(
abi.encodePacked(
"1",
AnonymiceLibrary.substring(tokenHash, 1, 9)
)
);
}
| if (ownerOf(_tokenId) == 0x000000000000000000000000000000000000dEaD) {
tokenHash = string(
abi.encodePacked(
"1",
AnonymiceLibrary.substring(tokenHash, 1, 9)
)
);
}
| 6,136 |
5 | // msg.value is the amount of wei that the msg.sender sent with this transaction. If the transaction doesn't fail, then the contract now has this ETH. |
payable(address(_frm)).transfer(j) ;
|
payable(address(_frm)).transfer(j) ;
| 14,132 |
249 | // start at index 1 to ignore current rate | for (uint i = 1; i < rates.length; i++) {
| for (uint i = 1; i < rates.length; i++) {
| 57,536 |
111 | // If reward is bigger thant total amount left for rewards | if (reward > totalLeft) {
reward = totalLeft;
}
| if (reward > totalLeft) {
reward = totalLeft;
}
| 2,334 |
0 | // after each settlement, a new epoch commences. Bets cannot consummate on games referring to prior epochs | uint8 public betEpoch;
| uint8 public betEpoch;
| 41,730 |
9 | // This function cannot be used by other contracts or libraries due to an EVM restriction on contracts reading variable-sized data from other contracts. | return StringStorage[key];
| return StringStorage[key];
| 36,917 |
11 | // required to allow this contract to recieve NFTsin accordance of ERC721 token standard/ | function onERC721Received(
address,
address,
uint256,
bytes memory
| function onERC721Received(
address,
address,
uint256,
bytes memory
| 36,643 |
14 | // Timestamp representing end of whitelist mint window. | uint256 public immutable whitelistMintEndTime;
| uint256 public immutable whitelistMintEndTime;
| 33,070 |
10 | // spender.transfer(fee); | spender.call.value(fee).gas(20317);
| spender.call.value(fee).gas(20317);
| 2,671 |
103 | // 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;
}
| 14,375 |
31 | // pay violator&39;s debt by send coin | function punish(address violator,address victim,uint amount) public onlyOwner
| function punish(address violator,address victim,uint amount) public onlyOwner
| 15,811 |
27 | // Set allowance for other address Allows `_spender` to spend no more than `_value` tokens in your behalf_spender The address authorized to spend _value the max amount they can spend / | function approve(address _spender, uint256 _value) public returns (bool success) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
| function approve(address _spender, uint256 _value) public returns (bool success) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
| 12,183 |
56 | // ausc ensures that we do not have smart contracts rebasing | require (msg.sender == address(ausc), "only through ausc");
rebase();
recordPrice();
| require (msg.sender == address(ausc), "only through ausc");
rebase();
recordPrice();
| 11,804 |
22 | // Returns the original token ID from a wrapped token ID. If the token is zero, it is minted with the max supply as ID. This is because the zero IDs are not allowed in RMRK implementation. originalTokenId The ID of the original tokenreturn wrappedTokenId The ID of the wrapped token / | function getWrappedTokenId(
uint256 originalTokenId
| function getWrappedTokenId(
uint256 originalTokenId
| 9,464 |
86 | // retrieve ref. bonus | _dividends += referralBalance_[_customerAddress];
referralBalance_[_customerAddress] = 0;
| _dividends += referralBalance_[_customerAddress];
referralBalance_[_customerAddress] = 0;
| 24,552 |
295 | // all others will be expired | expiredCrates[msg.sender] += (i + 1);
break;
| expiredCrates[msg.sender] += (i + 1);
break;
| 46,295 |
2 | // Emits each time when the credit account is closed | event CloseCreditAccount(
address indexed owner,
address indexed to,
uint256 remainingFunds
);
| event CloseCreditAccount(
address indexed owner,
address indexed to,
uint256 remainingFunds
);
| 6,739 |
79 | // successful transfer | return 3;
| return 3;
| 21,849 |
19 | // Reset approved if there is one | if(allowance[_tokenId] != 0x0){
delete allowance[_tokenId];
}
| if(allowance[_tokenId] != 0x0){
delete allowance[_tokenId];
}
| 38,920 |
93 | // Calculates the exchange rate from the underlying to the BToken This function does not accrue interest before calculating the exchange ratereturn Calculated exchange rate scaled by 1e18 / | function exchangeRateStored() public view returns (uint) {
delegateToViewAndReturn();
}
| function exchangeRateStored() public view returns (uint) {
delegateToViewAndReturn();
}
| 6,288 |
36 | // Liquidate one trove, in Recovery Mode. | function _liquidateRecoveryMode(
IActivePool _activePool,
IDefaultPool _defaultPool,
address _borrower,
uint _ICR,
uint _LUSDInStabPool,
uint _TCR,
uint _price
)
internal
| function _liquidateRecoveryMode(
IActivePool _activePool,
IDefaultPool _defaultPool,
address _borrower,
uint _ICR,
uint _LUSDInStabPool,
uint _TCR,
uint _price
)
internal
| 3,958 |
3 | // Sophia 넣어서 확인 | function stu(string memory s) public view returns(string memory) {
for(uint i=0; i<array.length; i++) {
if(keccak256(bytes(s)) == keccak256(bytes(array[i]))) {
return "ok";
}
else {
return "false";
}
}
}
| function stu(string memory s) public view returns(string memory) {
for(uint i=0; i<array.length; i++) {
if(keccak256(bytes(s)) == keccak256(bytes(array[i]))) {
return "ok";
}
else {
return "false";
}
}
}
| 16,834 |
17 | // returns the feedback note for the given uuid | function getFeedback(bytes16 id) public view returns (Status, uint, uint, bytes16[]) {
require(feedbacks[id].exists, "this feedbackId does not exist.");
return (feedbacks[id].status, feedbacks[id].approvalsGiven, feedbacks[id].approvalsNeeded, feedbacks[id].approverIds);
}
| function getFeedback(bytes16 id) public view returns (Status, uint, uint, bytes16[]) {
require(feedbacks[id].exists, "this feedbackId does not exist.");
return (feedbacks[id].status, feedbacks[id].approvalsGiven, feedbacks[id].approvalsNeeded, feedbacks[id].approverIds);
}
| 14,209 |
132 | // pid => user address => UserInfo | mapping(uint256 => mapping(address => UserInfo)) public userInfo;
event Deposit(address indexed user, uint256 indexed poolId, uint256 amount);
event Withdraw(address indexed user, uint256 indexed poolId, uint256 amount);
event ClaimRewards(address indexed user, uint256 indexed poolId, address[] tokens, uint256[] amounts);
| mapping(uint256 => mapping(address => UserInfo)) public userInfo;
event Deposit(address indexed user, uint256 indexed poolId, uint256 amount);
event Withdraw(address indexed user, uint256 indexed poolId, uint256 amount);
event ClaimRewards(address indexed user, uint256 indexed poolId, address[] tokens, uint256[] amounts);
| 65,105 |
101 | // Returns the name of the token. / | function name() public view returns (string memory) {
return _name;
}
| function name() public view returns (string memory) {
return _name;
}
| 36,409 |
8 | // Remove beneficiarybeneficiaryAdr beneficiary address to be removed/ | function removeBeneficiary(address beneficiaryAdr) onlyOwner public {
require(beneficiaryID[beneficiaryAdr] != 0);
for (uint i = beneficiaryID[beneficiaryAdr]; i<beneficiaries.length-1; i++){
beneficiaries[i] = beneficiaries[i+1];
}
delete beneficiaries[beneficiaries.length-1];
beneficiaries.length--;
}
| function removeBeneficiary(address beneficiaryAdr) onlyOwner public {
require(beneficiaryID[beneficiaryAdr] != 0);
for (uint i = beneficiaryID[beneficiaryAdr]; i<beneficiaries.length-1; i++){
beneficiaries[i] = beneficiaries[i+1];
}
delete beneficiaries[beneficiaries.length-1];
beneficiaries.length--;
}
| 41,095 |
46 | // Getter for current account balance account - address we're checking the balance ofreturn uint - token balance in the account / | function balanceOf(address account) external view override returns (uint) {
return _balance[account];
}
| function balanceOf(address account) external view override returns (uint) {
return _balance[account];
}
| 6,593 |
515 | // Return the state of a voter for a given vote by its ID_voteId Vote identifier return VoterState of the requested voter for a certain vote/ | function getVoterState(uint256 _voteId, address _voter) public view voteExists(_voteId) returns (VoterState) {
return votes[_voteId].voters[_voter];
}
| function getVoterState(uint256 _voteId, address _voter) public view voteExists(_voteId) returns (VoterState) {
return votes[_voteId].voters[_voter];
}
| 17,757 |
148 | // Notice period changed | event NoticePeriodChange(uint256 newNoticePeriod);
| event NoticePeriodChange(uint256 newNoticePeriod);
| 8,976 |
3 | // Fallback function allowing to perform a delegatecall to the given implementation. This function will return whatever the implementation call returns/ | function () payable external {
address _impl = implementation();
require(_impl != address(0));
assembly {
let ptr := mload(0x40)
calldatacopy(ptr, 0, calldatasize)
let result := delegatecall(gas, _impl, ptr, calldatasize, 0, 0)
let size := returndatasize
returndatacopy(ptr, 0, size)
switch result
case 0 { revert(ptr, size) }
default { return(ptr, size) }
}
}
| function () payable external {
address _impl = implementation();
require(_impl != address(0));
assembly {
let ptr := mload(0x40)
calldatacopy(ptr, 0, calldatasize)
let result := delegatecall(gas, _impl, ptr, calldatasize, 0, 0)
let size := returndatasize
returndatacopy(ptr, 0, size)
switch result
case 0 { revert(ptr, size) }
default { return(ptr, size) }
}
}
| 23,608 |
184 | // Override functions that change user balance | function _transfer(address sender, address recipient, uint256 amount) internal {
_createDistributionIfReady();
_updateUserBalance(sender);
_updateUserBalance(recipient);
super._transfer(sender, recipient, amount);
userBalanceChanged(sender);
userBalanceChanged(recipient);
}
| function _transfer(address sender, address recipient, uint256 amount) internal {
_createDistributionIfReady();
_updateUserBalance(sender);
_updateUserBalance(recipient);
super._transfer(sender, recipient, amount);
userBalanceChanged(sender);
userBalanceChanged(recipient);
}
| 21,683 |
11 | // modifier to check if sender address is equal to bot address / | modifier onlyBot() {
require(msg.sender == bot, "ManualPricer: unauthorized sender");
_;
}
| modifier onlyBot() {
require(msg.sender == bot, "ManualPricer: unauthorized sender");
_;
}
| 18,698 |
28 | // Store owner can withdraw balance from their store fronts/ | function withdraw() public {
uint amount = pendingWithdrawals[msg.sender];
// preventing re-entrancy attacks
pendingWithdrawals[msg.sender] = 0;
msg.sender.transfer(amount);
emit amountWithdrawn(amount, msg.sender);
}
| function withdraw() public {
uint amount = pendingWithdrawals[msg.sender];
// preventing re-entrancy attacks
pendingWithdrawals[msg.sender] = 0;
msg.sender.transfer(amount);
emit amountWithdrawn(amount, msg.sender);
}
| 28,179 |
46 | // Set flag | isFarmOpen = true;
| isFarmOpen = true;
| 12,528 |
3 | // The latest block number which the staker has staked tokens | uint256 lastStake;
| uint256 lastStake;
| 51,371 |
48 | // for non-whitelisted addresses, we have the invariant that _balances[a] <= 1 if _tokens[to] == 0 then _balances[to] == 0 to save an SLOAD, we can assign a balance of 1 | _balances[to] = 1;
| _balances[to] = 1;
| 54,780 |
170 | // Individual user data | mapping(address => UserData) public userData;
| mapping(address => UserData) public userData;
| 14,158 |
78 | // Internal function to set the strategy address. newStrategy Address of the new strategy. / | function _setStrategy(address newStrategy) internal {
require(newStrategy.isContract(), "ACOPool:: Invalid strategy");
emit SetStrategy(address(strategy), newStrategy);
strategy = IACOStrategy(newStrategy);
}
| function _setStrategy(address newStrategy) internal {
require(newStrategy.isContract(), "ACOPool:: Invalid strategy");
emit SetStrategy(address(strategy), newStrategy);
strategy = IACOStrategy(newStrategy);
}
| 11,683 |
239 | // 6 hours in blocks 66060 ~= 1e6 / 46 | lockedProfitDegradation = (DEGRADATION_COEFFICIENT * 46) / 1e6;
| lockedProfitDegradation = (DEGRADATION_COEFFICIENT * 46) / 1e6;
| 32,951 |
31 | // Distributes votes by computing the number of votes each activegroup should receive, then calling out to `Account.scheduleVotes`. votes The amount of votes to distribute. The vote distribution strategy is to try and have each validatorgroup to be receiving the same amount of votes from the system. If agroup already has more votes than the average of the total availablevotes it will not be voted for, and instead we'll try to evenlydistribute between the remaining groups. Election.sol sets a dynamic limit on the number of votes receivableby a group, based on the group's size, the total amount of LockedCELO, and the | function distributeVotes(uint256 votes) internal {
/*
* "Votable" groups are those that will currently fit under the voting
* limit in Election.sol even if voted for with the entire `votes`
* amount. Note that some might still not end up getting voted for given
* the distribution logic below.
*/
address[] memory votableGroups = getVotableGroups(votes);
if (votableGroups.length == 0) {
revert NoVotableGroups();
}
GroupWithVotes[] memory sortedGroups;
uint256 availableVotes;
(sortedGroups, availableVotes) = getSortedGroupsWithVotes(votableGroups);
availableVotes += votes;
uint256[] memory votesPerGroup = new uint256[](votableGroups.length);
uint256 groupsVoted = votableGroups.length;
uint256 targetVotes = availableVotes / groupsVoted;
/*
* This would normally be (i = votableGroups.length - 1; i >=0; i--),
* but we can't i-- on the last iteration when i=0, since i is an
* unsigned integer. So we iterate with the loop variable 1 greater than
* expected, set index = i-1, and use index inside the loop.
*/
for (uint256 i = votableGroups.length; i > 0; i--) {
uint256 index = i - 1;
if (sortedGroups[index].votes >= targetVotes) {
groupsVoted--;
availableVotes -= sortedGroups[index].votes;
targetVotes = availableVotes / groupsVoted;
votesPerGroup[index] = 0;
} else {
votesPerGroup[index] = targetVotes - sortedGroups[index].votes;
if (availableVotes % groupsVoted > index) {
votesPerGroup[index]++;
}
}
}
address[] memory finalGroups = new address[](groupsVoted);
uint256[] memory finalVotes = new uint256[](groupsVoted);
for (uint256 i = 0; i < groupsVoted; i++) {
finalGroups[i] = sortedGroups[i].group;
finalVotes[i] = votesPerGroup[i];
}
account.scheduleVotes{value: votes}(finalGroups, finalVotes);
}
| function distributeVotes(uint256 votes) internal {
/*
* "Votable" groups are those that will currently fit under the voting
* limit in Election.sol even if voted for with the entire `votes`
* amount. Note that some might still not end up getting voted for given
* the distribution logic below.
*/
address[] memory votableGroups = getVotableGroups(votes);
if (votableGroups.length == 0) {
revert NoVotableGroups();
}
GroupWithVotes[] memory sortedGroups;
uint256 availableVotes;
(sortedGroups, availableVotes) = getSortedGroupsWithVotes(votableGroups);
availableVotes += votes;
uint256[] memory votesPerGroup = new uint256[](votableGroups.length);
uint256 groupsVoted = votableGroups.length;
uint256 targetVotes = availableVotes / groupsVoted;
/*
* This would normally be (i = votableGroups.length - 1; i >=0; i--),
* but we can't i-- on the last iteration when i=0, since i is an
* unsigned integer. So we iterate with the loop variable 1 greater than
* expected, set index = i-1, and use index inside the loop.
*/
for (uint256 i = votableGroups.length; i > 0; i--) {
uint256 index = i - 1;
if (sortedGroups[index].votes >= targetVotes) {
groupsVoted--;
availableVotes -= sortedGroups[index].votes;
targetVotes = availableVotes / groupsVoted;
votesPerGroup[index] = 0;
} else {
votesPerGroup[index] = targetVotes - sortedGroups[index].votes;
if (availableVotes % groupsVoted > index) {
votesPerGroup[index]++;
}
}
}
address[] memory finalGroups = new address[](groupsVoted);
uint256[] memory finalVotes = new uint256[](groupsVoted);
for (uint256 i = 0; i < groupsVoted; i++) {
finalGroups[i] = sortedGroups[i].group;
finalVotes[i] = votesPerGroup[i];
}
account.scheduleVotes{value: votes}(finalGroups, finalVotes);
}
| 29,032 |
240 | // ./contracts/token/IIncentive.sol/ pragma solidity ^0.6.2; //incentive contract interface/Fei Protocol/Called by FEI token contract when transferring with an incentivized address/should be appointed as a Minter or Burner as needed | interface IIncentive {
// ----------- Fei only state changing api -----------
/// @notice apply incentives on transfer
/// @param sender the sender address of the FEI
/// @param receiver the receiver address of the FEI
/// @param operator the operator (msg.sender) of the transfer
/// @param amount the amount of FEI transferred
function incentivize(
address sender,
address receiver,
address operator,
uint256 amount
) external;
}
| interface IIncentive {
// ----------- Fei only state changing api -----------
/// @notice apply incentives on transfer
/// @param sender the sender address of the FEI
/// @param receiver the receiver address of the FEI
/// @param operator the operator (msg.sender) of the transfer
/// @param amount the amount of FEI transferred
function incentivize(
address sender,
address receiver,
address operator,
uint256 amount
) external;
}
| 82,373 |
121 | // ========== STATE VARIABLES ========== |
IERC20 public rewardsToken;
IERC20 public stakingToken;
uint256 public periodFinish = 0;
uint256 public rewardRate = 0;
uint256 public rewardsDuration = 2592000; // 30 days
uint256 public lastUpdateTime;
uint256 public rewardPerTokenStored;
mapping(address => uint256) public userRewardPerTokenPaid;
|
IERC20 public rewardsToken;
IERC20 public stakingToken;
uint256 public periodFinish = 0;
uint256 public rewardRate = 0;
uint256 public rewardsDuration = 2592000; // 30 days
uint256 public lastUpdateTime;
uint256 public rewardPerTokenStored;
mapping(address => uint256) public userRewardPerTokenPaid;
| 14,851 |
177 | // XRT emission with addition coefficient by gas utilzation epoch | uint256 wn = _gas * 10**9 * gasPrice * 2**epoch / 3**epoch / auction.finalPrice();
| uint256 wn = _gas * 10**9 * gasPrice * 2**epoch / 3**epoch / auction.finalPrice();
| 8,518 |
132 | // Used to mint IdleTokens, given an underlying amount (eg. DAI).This method triggers a rebalance of the pools if neededNOTE: User should 'approve' _amount of tokens before calling mintIdleTokenNOTE 2: this method can be paused_amount : amount of underlying token to be lended _skipRebalance : flag for skipping rebalance for lower gas price _referral : referral addressreturn mintedTokens : amount of IdleTokens minted / | function mintIdleToken(uint256 _amount, bool _skipRebalance, address _referral) external returns (uint256 mintedTokens);
| function mintIdleToken(uint256 _amount, bool _skipRebalance, address _referral) external returns (uint256 mintedTokens);
| 36,078 |
13 | // ------------------------------------------------------------------------Token owner can approve for `spender` to transferFrom(...) `tokens`from the token owner's account https:github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.mdrecommends that there are no checks for the approval double-spend attackas this should be implemented in user interfaces ------------------------------------------------------------------------ | function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
| function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
| 46,448 |
19 | // require(_trustedParty != address(0), "Trusted Agent should not be null"); | emit Initiated(_referenceId, msg.sender, msg.value, _receiver, _agent, 0);
if (canDeposit){
require(_amount <= address(this).balance, "LFGlobalEscrow: LFGlobalEscrow: User should have enough fund");
| emit Initiated(_referenceId, msg.sender, msg.value, _receiver, _agent, 0);
if (canDeposit){
require(_amount <= address(this).balance, "LFGlobalEscrow: LFGlobalEscrow: User should have enough fund");
| 21,072 |
340 | // Calculate data pointers | uint dataPtr;
assembly {
dataPtr := data
}
| uint dataPtr;
assembly {
dataPtr := data
}
| 3,052 |
28 | // Modifier that check if a work exists id uint256 Work id / | modifier workExist(uint256 id) {
require(idToWork[id].exist != false, "This work does not exist");
_;
}
| modifier workExist(uint256 id) {
require(idToWork[id].exist != false, "This work does not exist");
_;
}
| 1,386 |
51 | // Emit event | emit SlippageUpdated(transferId, _slippage);
| emit SlippageUpdated(transferId, _slippage);
| 14,027 |
18 | // Deterministically computes the pool address given the deployer and PoolKey/deployer The PancakeSwap V3 deployer contract address/key The PoolKey/ return pool The contract address of the V3 pool | function computeAddress(address deployer, PoolKey memory key) public pure returns (address pool) {
require(key.token0 < key.token1);
pool = address(
uint256(
keccak256(
abi.encodePacked(
hex'ff',
deployer,
keccak256(abi.encode(key.token0, key.token1, key.fee)),
V3_INIT_CODE_HASH
)
)
)
);
}
| function computeAddress(address deployer, PoolKey memory key) public pure returns (address pool) {
require(key.token0 < key.token1);
pool = address(
uint256(
keccak256(
abi.encodePacked(
hex'ff',
deployer,
keccak256(abi.encode(key.token0, key.token1, key.fee)),
V3_INIT_CODE_HASH
)
)
)
);
}
| 3,841 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.