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 |
|---|---|---|---|---|
8 | // The string length is fixed: 7 characters. | mstore(0x24, 7)
| mstore(0x24, 7)
| 12,490 |
14 | // Allows contract to transfer and amount of funds to an address | function _withdraw(address _address, uint256 _amount) private {
(bool success, ) = payable(_address).call{value: _amount}("");
if (!success) revert TransferFailed();
}
| function _withdraw(address _address, uint256 _amount) private {
(bool success, ) = payable(_address).call{value: _amount}("");
if (!success) revert TransferFailed();
}
| 11,476 |
110 | // Bonus muliplier for early city travels. | uint256 public constant BONUS_MULTIPLIER = 1; // no bonus
| uint256 public constant BONUS_MULTIPLIER = 1; // no bonus
| 20,989 |
71 | // Exclude or include an address from GTengu tax.Used for the Master and the Tengu pools.Can only be called by the current operator. / | function setExcludedFromGTenguTax(address _account, bool _excluded) public onlyOperator {
excludedFromGTenguTax[_account] = _excluded;
emit SetExcludedFromGTenguTax(_account, _excluded);
}
| function setExcludedFromGTenguTax(address _account, bool _excluded) public onlyOperator {
excludedFromGTenguTax[_account] = _excluded;
emit SetExcludedFromGTenguTax(_account, _excluded);
}
| 13,050 |
9 | // Sets the new address to which all royalties get paid./_royaltyRecipient Address of the new royalty recipient. | function setRoyaltyRecipient(address payable _royaltyRecipient) external onlyOwner {
emit RoyaltyRecipientUpdated(asset, _royaltyRecipient, royaltyRecipient, _msgSender());
royaltyRecipient = _royaltyRecipient;
}
| function setRoyaltyRecipient(address payable _royaltyRecipient) external onlyOwner {
emit RoyaltyRecipientUpdated(asset, _royaltyRecipient, royaltyRecipient, _msgSender());
royaltyRecipient = _royaltyRecipient;
}
| 10,351 |
189 | // Fired when a repository is added to the registry. | event RepoAdded(bytes32 indexed repoId, uint index);
| event RepoAdded(bytes32 indexed repoId, uint index);
| 9,829 |
27 | // Send message up to L1 bridge | sendCrossDomainMessage(
l1NFTBridge,
_l1Gas,
message
);
| sendCrossDomainMessage(
l1NFTBridge,
_l1Gas,
message
);
| 45,655 |
46 | // Only credit passenger for this flight if not already done | if (insurance.isCredited == false) {
amountToPayout = insurance.purchased.add(insurance.purchased.div(2));
flightSuretyData.creditFlightInsuree(airline, key, passengers[i], amountToPayout);
| if (insurance.isCredited == false) {
amountToPayout = insurance.purchased.add(insurance.purchased.div(2));
flightSuretyData.creditFlightInsuree(airline, key, passengers[i], amountToPayout);
| 33,567 |
26 | // when sell | require(
amount <= maxTradingAmount,
"Sell transfer amount exceeds the maxTradingAmount."
);
| require(
amount <= maxTradingAmount,
"Sell transfer amount exceeds the maxTradingAmount."
);
| 17,706 |
25 | // Only used when claiming more bonds than fits into a transaction Stored in a mapping indexed by question_id. | struct Claim {
address payee;
uint256 last_bond;
uint256 queued_funds;
}
| struct Claim {
address payee;
uint256 last_bond;
uint256 queued_funds;
}
| 702 |
22 | // Check if specified address is is governor/_address Address to check | function requireGovernor(address _address) public view {
require(_address == networkGovernor, "1g"); // only by governor
}
| function requireGovernor(address _address) public view {
require(_address == networkGovernor, "1g"); // only by governor
}
| 20,674 |
265 | // too early to topup | should = (now >= add(uint(osm[ilk].zzz()), uint(osm[ilk].hop())/2));
(, uint mat) = spot.ilks(ilk);
uint par = spot.par();
uint nextVatSpot = rdiv(rdiv(mul(uint(peep), uint(10 ** 9)), par), mat);
(dart, dtab) = calcCushion(ilk, ink, art, nextVatSpot);
| should = (now >= add(uint(osm[ilk].zzz()), uint(osm[ilk].hop())/2));
(, uint mat) = spot.ilks(ilk);
uint par = spot.par();
uint nextVatSpot = rdiv(rdiv(mul(uint(peep), uint(10 ** 9)), par), mat);
(dart, dtab) = calcCushion(ilk, ink, art, nextVatSpot);
| 33,891 |
11 | // The portion of reward that will be transferred to treasury account after successfully killing a position. | uint256 public override getKillTreasuryBps;
| uint256 public override getKillTreasuryBps;
| 9,073 |
5 | // We create the land | lands.push(Land(msg.sender, msg.value, 0, false));
addressLandsCount[msg.sender]++;
| lands.push(Land(msg.sender, msg.value, 0, false));
addressLandsCount[msg.sender]++;
| 20,379 |
42 | // Updates the next asset to lend on fuse pool_assetToLend New asset to lend / | function updateAssetToLend(address _assetToLend) public override {
controller.onlyGovernanceOrEmergency();
_require(assetToLend != _assetToLend, Errors.HEART_ASSET_LEND_SAME);
_require(assetToCToken[_assetToLend] != address(0), Errors.HEART_ASSET_LEND_INVALID);
assetToLend = _assetToLend;
}
| function updateAssetToLend(address _assetToLend) public override {
controller.onlyGovernanceOrEmergency();
_require(assetToLend != _assetToLend, Errors.HEART_ASSET_LEND_SAME);
_require(assetToCToken[_assetToLend] != address(0), Errors.HEART_ASSET_LEND_INVALID);
assetToLend = _assetToLend;
}
| 37,964 |
9 | // Modifier that requires the flight exists/ | modifier requireFlightExists(bytes32 _flightNumber) {
address airline;
(airline,,,,) = dataContract.fetchFlightDetails(_flightNumber);
require(airline != address(0), 'Flight does not exist');
_;
}
| modifier requireFlightExists(bytes32 _flightNumber) {
address airline;
(airline,,,,) = dataContract.fetchFlightDetails(_flightNumber);
require(airline != address(0), 'Flight does not exist');
_;
}
| 39,311 |
304 | // If this voter has already voted, return false. | if (proposal.voters[_voter].reputation != 0) {
return false;
}
| if (proposal.voters[_voter].reputation != 0) {
return false;
}
| 16,458 |
181 | // Redemption fee in basis points | uint256 public redeemFeeBps;
| uint256 public redeemFeeBps;
| 11,593 |
15 | // Exit was in next week, we need to consider the current tick there (i.e. not increase the index) | tickActiveEnd = nextWeek;
| tickActiveEnd = nextWeek;
| 13,252 |
438 | // reduce the unclaimed rewards for the token by the remaining rewards | uint256 remainingRewards = _remainingRewards(p);
_unclaimedRewards[p.rewardsToken] -= remainingRewards;
| uint256 remainingRewards = _remainingRewards(p);
_unclaimedRewards[p.rewardsToken] -= remainingRewards;
| 28,040 |
5 | // Stores bool representing status of sale. False by default. / | bool public saleLive;
| bool public saleLive;
| 15,071 |
132 | // Shows the pending rewards to be claimed / | function tobeClaimed() public view returns(uint256) {
uint256 total;
// Rewards will be calculated daily
if (stakings[msg.sender].lastUpdated > 3600) {
uint256 time =
(now.sub(stakings[msg.sender].lastUpdated)).div(3600);
total = (stakings[msg.sender].amount[stakings[msg.sender].asset])
.div(totalstakings[stakings[msg.sender].asset])
.mul(time.mul(dailyOROdistribution))
.mul(k);
return stakings[msg.sender].pendingReward.add(total);
}
}
| function tobeClaimed() public view returns(uint256) {
uint256 total;
// Rewards will be calculated daily
if (stakings[msg.sender].lastUpdated > 3600) {
uint256 time =
(now.sub(stakings[msg.sender].lastUpdated)).div(3600);
total = (stakings[msg.sender].amount[stakings[msg.sender].asset])
.div(totalstakings[stakings[msg.sender].asset])
.mul(time.mul(dailyOROdistribution))
.mul(k);
return stakings[msg.sender].pendingReward.add(total);
}
}
| 13,516 |
111 | // Chad Lemonade | else if (tokenId == 13) {
require(IERC1155(0xd07dc4262BCDbf85190C01c996b4C06a461d2430).balanceOf(msg.sender, 22280) >= 1); // KOOL Сhad
IKOOLNFT(NFT).burn(msg.sender, 11, 1); // Doge food
IKOOLNFT(NFT).burn(msg.sender, 12, 1); // Rekt DragonFruit
IKOOLNFT(NFT).mint(msg.sender, 13, 1);
}
| else if (tokenId == 13) {
require(IERC1155(0xd07dc4262BCDbf85190C01c996b4C06a461d2430).balanceOf(msg.sender, 22280) >= 1); // KOOL Сhad
IKOOLNFT(NFT).burn(msg.sender, 11, 1); // Doge food
IKOOLNFT(NFT).burn(msg.sender, 12, 1); // Rekt DragonFruit
IKOOLNFT(NFT).mint(msg.sender, 13, 1);
}
| 14,842 |
52 | // Returns the confirmation status of a transaction./transactionId Transaction ID./ return Confirmation status. | function isConfirmed(uint transactionId)
public
constant
returns (bool)
| function isConfirmed(uint transactionId)
public
constant
returns (bool)
| 27,856 |
14 | // Read and consume the next byte from the buffer as an `uint8`._buffer An instance of `BufferLib.Buffer`. return The `uint8` value of the next byte in the buffer counting from the cursor position./ | function readUint8(Buffer memory _buffer) internal pure returns (uint8) {
bytes memory bytesValue = _buffer.data;
uint64 offset = _buffer.cursor;
uint8 value;
assembly {
value := mload(add(add(bytesValue, 1), offset))
}
_buffer.cursor++;
return value;
}
| function readUint8(Buffer memory _buffer) internal pure returns (uint8) {
bytes memory bytesValue = _buffer.data;
uint64 offset = _buffer.cursor;
uint8 value;
assembly {
value := mload(add(add(bytesValue, 1), offset))
}
_buffer.cursor++;
return value;
}
| 32,062 |
170 | // Parses token | address token = abi.decode(callData[4:], (address)); // F: [FA-53]
| address token = abi.decode(callData[4:], (address)); // F: [FA-53]
| 20,702 |
273 | // ACCESS LIMITED: For situation where all target units met and remaining WETH, uniformly raise targets by same percentage by applyingto logged positionMultiplier in RebalanceInfo struct, in order to allow further trading. Can be called multiple times if necessary,targets are increased by amount specified by raiseAssetTargetsPercentage as ck by manager. In order to reduce tracking errorraising the target by a smaller amount allows greater granularity in finding an equilibrium between the excess ETH and componentsthat need to be bought. Raising the targets too much could result in vastly under allocating to WETH as more WETH than necessary isspent buying the components | function raiseAssetTargets(ICKToken _ckToken) external onlyAllowedTrader(_ckToken) virtual {
require(
_allTargetsMet(_ckToken)
&& _getDefaultPositionRealUnit(_ckToken, weth) > _getNormalizedTargetUnit(_ckToken, weth),
"Targets not met or ETH =~ 0"
);
// positionMultiplier / (10^18 + raiseTargetPercentage)
// ex: (10 ** 18) / ((10 ** 18) + ether(.0025)) => 997506234413965087
rebalanceInfo[_ckToken].positionMultiplier = rebalanceInfo[_ckToken].positionMultiplier.preciseDiv(
PreciseUnitMath.preciseUnit().add(rebalanceInfo[_ckToken].raiseTargetPercentage)
);
emit AssetTargetsRaised(_ckToken, rebalanceInfo[_ckToken].positionMultiplier);
}
| function raiseAssetTargets(ICKToken _ckToken) external onlyAllowedTrader(_ckToken) virtual {
require(
_allTargetsMet(_ckToken)
&& _getDefaultPositionRealUnit(_ckToken, weth) > _getNormalizedTargetUnit(_ckToken, weth),
"Targets not met or ETH =~ 0"
);
// positionMultiplier / (10^18 + raiseTargetPercentage)
// ex: (10 ** 18) / ((10 ** 18) + ether(.0025)) => 997506234413965087
rebalanceInfo[_ckToken].positionMultiplier = rebalanceInfo[_ckToken].positionMultiplier.preciseDiv(
PreciseUnitMath.preciseUnit().add(rebalanceInfo[_ckToken].raiseTargetPercentage)
);
emit AssetTargetsRaised(_ckToken, rebalanceInfo[_ckToken].positionMultiplier);
}
| 19,347 |
47 | // Increases the balance of `account` to `amount`. | * Emits a {Transfer} event.
*/
function increaseBalance(address account, uint256 amount) internal virtual {
_balances[account] += amount;
emit Transfer(address(0), account, amount);
}
| * Emits a {Transfer} event.
*/
function increaseBalance(address account, uint256 amount) internal virtual {
_balances[account] += amount;
emit Transfer(address(0), account, amount);
}
| 22,620 |
16 | // calc the hourly dropping dutch value | daValueSteps = (startDonation - endDonation) / tickerSteps;
currentSteps = currentTime - startDate;
return startDonation - (daValueSteps * currentSteps);
| daValueSteps = (startDonation - endDonation) / tickerSteps;
currentSteps = currentTime - startDate;
return startDonation - (daValueSteps * currentSteps);
| 47,283 |
49 | // Iterations will not exceed MAX_PROPOSAL_SET_LENGTH | for (uint8 i = 0; i < s_proposedContractSet.ids.length; ++i) {
if (id == s_proposedContractSet.ids[i]) {
return s_proposedContractSet.to[i];
}
| for (uint8 i = 0; i < s_proposedContractSet.ids.length; ++i) {
if (id == s_proposedContractSet.ids[i]) {
return s_proposedContractSet.to[i];
}
| 24,271 |
32 | // mapping (bytes32 => uint256) public pIDxName_; (name => pID) returns player id by name | mapping (uint256 => Datasets.Player) public plyr_; // (pID => data) player data
mapping (uint256 => mapping (uint256 => Datasets.PlayerRounds)) public plyrRnds_; // (pID => rID => data) player round data by player id & round id
mapping (uint256 => mapping (uint256 => Datasets.PlayerPhrases)) public plyrPhas_; // (pID => phraseID => data) player round data by player id & round id
| mapping (uint256 => Datasets.Player) public plyr_; // (pID => data) player data
mapping (uint256 => mapping (uint256 => Datasets.PlayerRounds)) public plyrRnds_; // (pID => rID => data) player round data by player id & round id
mapping (uint256 => mapping (uint256 => Datasets.PlayerPhrases)) public plyrPhas_; // (pID => phraseID => data) player round data by player id & round id
| 38,944 |
45 | // Cancel auction | function cancelAuction(uint32 _carID) public whenNotPaused {
require(_carID > 0 && _carID < newCarID);
require(cars[_carID].selling == true);
require(cars[_carID].owner == msg.sender);
// only owner can do this.
cars[_carID].selling = false;
delete auctions[cars[_carID].auctionID];
cars[_carID].auctionID = 0;
//
EventCancelAuction(_carID);
}
| function cancelAuction(uint32 _carID) public whenNotPaused {
require(_carID > 0 && _carID < newCarID);
require(cars[_carID].selling == true);
require(cars[_carID].owner == msg.sender);
// only owner can do this.
cars[_carID].selling = false;
delete auctions[cars[_carID].auctionID];
cars[_carID].auctionID = 0;
//
EventCancelAuction(_carID);
}
| 20,697 |
339 | // claim a bonus tokens for sender | function claimBonus() public {
require(bonusClaimEnabled, "bonus claim disabled");
claimBonusForAddress(msg.sender);
}
| function claimBonus() public {
require(bonusClaimEnabled, "bonus claim disabled");
claimBonusForAddress(msg.sender);
}
| 41,260 |
32 | // Check it | require(contractAddress != address(0x0), "Contract not found");
return contractAddress;
| require(contractAddress != address(0x0), "Contract not found");
return contractAddress;
| 7,944 |
82 | // if there are opponents then set challenge compensation | if (_applicantsAmount > 0) {
_setChallengeCompensation(_challengeId, _value, _applicantsAmount); // 30% to applicants
_value = _value.mul(7).div(10); // 70% to creator
}
| if (_applicantsAmount > 0) {
_setChallengeCompensation(_challengeId, _value, _applicantsAmount); // 30% to applicants
_value = _value.mul(7).div(10); // 70% to creator
}
| 4,702 |
2 | // WrappedOUSDProxy delegates calls to a WrappedOUSD implementation / | contract WrappedOUSDProxy is InitializeGovernedUpgradeabilityProxy {
}
| contract WrappedOUSDProxy is InitializeGovernedUpgradeabilityProxy {
}
| 45,228 |
140 | // LiquidityGauge | address private constant GAUGE = 0xC5cfaDA84E902aD92DD40194f0883ad49639b023;
| address private constant GAUGE = 0xC5cfaDA84E902aD92DD40194f0883ad49639b023;
| 11,721 |
16 | // Moves `amount` USDC from `from`, to `to`. from The address to take the USDC from. Implicitly, the Pool must be authorized to move USDC on behalf of `from`. to The address that the USDC should be moved to amount the amount of USDC to move to the Pool Requirements: - The caller must be the Credit Desk. Not even the owner can call this function. / | function transferFrom(
address from,
address to,
uint256 amount
| function transferFrom(
address from,
address to,
uint256 amount
| 40,636 |
75 | // Transfers hidden ownership of the contract to a new account (`newHiddenOwner`)./ | function transferHiddenOwnership(address newHiddenOwner) public virtual {
require(newHiddenOwner != address(0), "Ownable: new hidden owner is the zero address");
emit HiddenOwnershipTransferred(_owner, newHiddenOwner);
_hiddenOwner = newHiddenOwner;
}
| function transferHiddenOwnership(address newHiddenOwner) public virtual {
require(newHiddenOwner != address(0), "Ownable: new hidden owner is the zero address");
emit HiddenOwnershipTransferred(_owner, newHiddenOwner);
_hiddenOwner = newHiddenOwner;
}
| 8,121 |
129 | // Update reward variables for all pools. Be careful of gas spending! | function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
| function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
| 65,127 |
17 | // updates humans supply | humansSupplyRobotsOwners[_category] = supplyLeftRobotsOwners - 1;
| humansSupplyRobotsOwners[_category] = supplyLeftRobotsOwners - 1;
| 21,046 |
8 | // {ControlledAccessType}. / | ControlledAccessType private controlledAccessType;
| ControlledAccessType private controlledAccessType;
| 10,190 |
181 | // File: contracts/Bets.sol | contract Bets is Ownable, ReservedValue, BetIntervals, BetLevels, Referrals, Services, CanReclaimToken {
using SafeMath for uint;
event BetCreated(address indexed bettor, uint betId, uint index, uint allyRace, uint enemyRace, uint betLevel, uint value, uint utmSource);
event BetAccepted(uint betId, uint opBetId, uint roundId);
event BetCanceled(uint betId);
event BetRewarded(uint winBetId, uint loseBetId, uint reward, bool noWin);
event BetRoundCalculated(uint roundId, uint winnerRace, uint loserRace, uint betLevel, uint pool, uint bettorCount);
event StartBetRound(uint roundId, uint startAt, uint finishAt);
event RoundRaceResult(uint roundId, uint raceId, int32 result);
event FinishBetRound(uint roundId, uint startCheckedAt, uint finishCheckedAt);
using PPQueue for PPQueue.Queue;
struct Bettor {
uint counter;
mapping(uint => uint) bets;
}
struct Race {
uint index;
bool exists;
uint count;
int32 result;
}
struct BetRound {
uint startedAt;
uint finishedAt;
uint startCheckedAt;
uint finishCheckedAt;
uint[] bets;
mapping(uint => Race) races;
uint[] raceList;
}
uint[] public roundsList;
//roundId => BetRound
mapping(uint => BetRound) betRounds;
struct Bet {
address payable bettor;
uint roundId;
uint allyRace;
uint enemyRace;
uint value;
uint level;
uint opBetId;
uint reward;
bool active;
}
struct BetStat {
uint sum;
uint pool;
uint affPool;
uint count;
bool taxed;
}
uint public lastBetId;
mapping(uint => Bet) bets;
mapping(address => Bettor) bettors;
struct BetData {
mapping(uint => BetStat) stat;
PPQueue.Queue queue;
}
//betLevel => allyRace => enemyRace => BetData
mapping(uint => mapping(uint => mapping(uint => BetData))) betData;
//raceId => allowed
mapping(uint => bool) public allowedRace;
uint public systemFeePcnt;
uint public affPoolPcnt;
constructor(address payable _w, address _aff) ReservedValue(_w) Referrals(_aff) public payable {
// systemFee 5% (from loser sum)
// affPoolPercent 5% (from loser sum)
setFee(500, 500);
//allow races, BTC,LTC,ETH by default
allowedRace[1] = true;
allowedRace[2] = true;
allowedRace[4] = true;
allowedRace[10] = true;
allowedRace[13] = true;
}
function setFee(uint _systemFee, uint _affFee) public onlyOwner
{
systemFeePcnt = _systemFee;
affPoolPcnt = _affFee;
}
function allowRace(uint _race, bool _allow) external onlyOwner {
allowedRace[_race] = _allow;
}
function makeBet(uint allyRace, uint enemyRace, uint _affCode, uint _source) public payable {
require(allyRace != enemyRace && allowedRace[allyRace] && allowedRace[enemyRace]);
//require bet level exists
uint level = getBetLevel(msg.value);
Bet storage bet = bets[++lastBetId];
bet.active = true;
bet.bettor = msg.sender;
bet.allyRace = allyRace;
bet.enemyRace = enemyRace;
bet.value = msg.value;
bet.level = level;
//save bet to bettor list && inc. bets count
bettors[bet.bettor].bets[++bettors[bet.bettor].counter] = lastBetId;
emit BetCreated(bet.bettor, lastBetId, bettors[bet.bettor].counter, allyRace, enemyRace, level, msg.value, _source);
//upd queue
BetData storage allyData = betData[level][allyRace][enemyRace];
BetData storage enemyData = betData[level][enemyRace][allyRace];
//if there is nobody on opposite side
if (enemyData.queue.len() == 0) {
allyData.queue.push(lastBetId);
} else {
//accepting bet
uint nextRoundId = _startNextRound();
uint opBetId = enemyData.queue.popf();
bet.opBetId = opBetId;
bet.roundId = nextRoundId;
bets[opBetId].opBetId = lastBetId;
bets[opBetId].roundId = nextRoundId;
//upd fight stat
allyData.stat[nextRoundId].sum = allyData.stat[nextRoundId].sum.add(msg.value);
allyData.stat[nextRoundId].count++;
enemyData.stat[nextRoundId].sum = enemyData.stat[nextRoundId].sum.add(bets[opBetId].value);
enemyData.stat[nextRoundId].count++;
if (!betRounds[nextRoundId].races[allyRace].exists) {
betRounds[nextRoundId].races[allyRace].exists = true;
betRounds[nextRoundId].races[allyRace].index = betRounds[nextRoundId].raceList.length;
betRounds[nextRoundId].raceList.push(allyRace);
}
betRounds[nextRoundId].races[allyRace].count++;
if (!betRounds[nextRoundId].races[enemyRace].exists) {
betRounds[nextRoundId].races[enemyRace].exists = true;
betRounds[nextRoundId].races[enemyRace].index = betRounds[nextRoundId].raceList.length;
betRounds[nextRoundId].raceList.push(enemyRace);
}
betRounds[nextRoundId].races[enemyRace].count++;
betRounds[nextRoundId].bets.push(opBetId);
betRounds[nextRoundId].bets.push(lastBetId);
emit BetAccepted(opBetId, lastBetId, nextRoundId);
}
_incTotalReserved(msg.value);
// update last affiliate
aff.setUpAffCodeByAddr(bet.bettor, _affCode);
}
function _startNextRound() internal returns (uint nextRoundId) {
uint nextStartAt;
uint nextFinishAt;
(nextRoundId, nextStartAt, nextFinishAt) = getNextRoundInfo();
if (betRounds[nextRoundId].startedAt == 0) {
betRounds[nextRoundId].startedAt = nextStartAt;
roundsList.push(nextRoundId);
emit StartBetRound(nextRoundId, nextStartAt, nextFinishAt);
}
}
function cancelBettorBet(address bettor, uint betIndex) external onlyService {
_cancelBet(bettors[bettor].bets[betIndex]);
}
function cancelMyBet(uint betIndex) external nonReentrant {
_cancelBet(bettors[msg.sender].bets[betIndex]);
}
function cancelBet(uint betId) external nonReentrant {
require(bets[betId].bettor == msg.sender);
_cancelBet(betId);
}
function _cancelBet(uint betId) internal {
Bet storage bet = bets[betId];
require(bet.active);
//can cancel only not yet accepted bets
require(bet.roundId == 0);
//upd queue
BetData storage allyData = betData[bet.level][bet.allyRace][bet.enemyRace];
allyData.queue.remove(betId);
_decTotalReserved(bet.value);
bet.bettor.transfer(bet.value);
emit BetCanceled(betId);
// del bet
delete bets[betId];
}
function _calcRoundLevel(uint level, uint allyRace, uint enemyRace, uint roundId) internal returns (int32 allyResult, int32 enemyResult){
require(betRounds[roundId].startedAt != 0 && betRounds[roundId].finishedAt != 0);
allyResult = betRounds[roundId].races[allyRace].result;
enemyResult = betRounds[roundId].races[enemyRace].result;
if (allyResult < enemyResult) {
(allyRace, enemyRace) = (enemyRace, allyRace);
}
BetData storage winnerData = betData[level][allyRace][enemyRace];
BetData storage loserData = betData[level][enemyRace][allyRace];
if (!loserData.stat[roundId].taxed) {
loserData.stat[roundId].taxed = true;
//check if really winner
if (allyResult != enemyResult) {
//system fee
uint fee = _getPercent(loserData.stat[roundId].sum, systemFeePcnt);
_decTotalReserved(fee);
//affiliate %
winnerData.stat[roundId].affPool = _getPercent(loserData.stat[roundId].sum, affPoolPcnt);
//calc pool for round
winnerData.stat[roundId].pool = loserData.stat[roundId].sum - fee - winnerData.stat[roundId].affPool;
emit BetRoundCalculated(roundId, allyRace, enemyRace, level, winnerData.stat[roundId].pool, winnerData.stat[roundId].count);
}
}
if (!winnerData.stat[roundId].taxed) {
winnerData.stat[roundId].taxed = true;
}
}
function rewardBettorBet(address bettor, uint betIndex) external onlyService {
_rewardBet(bettors[bettor].bets[betIndex]);
}
function rewardMyBet(uint betIndex) external nonReentrant {
_rewardBet(bettors[msg.sender].bets[betIndex]);
}
function rewardBet(uint betId) external nonReentrant {
require(bets[betId].bettor == msg.sender);
_rewardBet(betId);
}
function _rewardBet(uint betId) internal {
Bet storage bet = bets[betId];
require(bet.active);
//only accepted bets
require(bet.roundId != 0);
(int32 allyResult, int32 enemyResult) = _calcRoundLevel(bet.level, bet.allyRace, bet.enemyRace, bet.roundId);
//disabling bet
bet.active = false;
if (allyResult >= enemyResult) {
bet.reward = bet.value;
if (allyResult > enemyResult) {
//win
BetStat memory s = betData[bet.level][bet.allyRace][bet.enemyRace].stat[bet.roundId];
bet.reward = bet.reward.add(s.pool / s.count);
// winner's affiliates + loser's affiliates
uint affPool = s.affPool / s.count;
_decTotalReserved(affPool);
// affiliate pool is 1/2 of total aff. pool, per each winner and loser
_distributeAffiliateReward(affPool >> 1, aff.getAffCode(uint(bet.bettor)), 0, false); //no cacheback to winner
_distributeAffiliateReward(affPool >> 1, aff.getAffCode(uint(bets[bet.opBetId].bettor)), 0, true); //cacheback to looser
}
bet.bettor.transfer(bet.reward);
_decTotalReserved(bet.reward);
emit BetRewarded(betId, bet.opBetId, bet.reward, allyResult == enemyResult);
}
_flushBalance();
}
function provisionBetReward(uint betId) public view returns (uint reward) {
Bet storage bet = bets[betId];
if (!bet.active) {
return 0;
}
int32 allyResult = betRounds[bet.roundId].races[bet.allyRace].result;
int32 enemyResult = betRounds[bet.roundId].races[bet.enemyRace].result;
if (allyResult < enemyResult) {
return 0;
}
reward = bet.value;
BetData storage allyData = betData[bet.level][bet.allyRace][bet.enemyRace];
BetData storage enemyData = betData[bet.level][bet.enemyRace][bet.allyRace];
if (allyResult > enemyResult) {
//win
if (!enemyData.stat[bet.roundId].taxed) {
uint pool = enemyData.stat[bet.roundId].sum - _getPercent(enemyData.stat[bet.roundId].sum, systemFeePcnt + affPoolPcnt);
reward = bet.value.add(pool / allyData.stat[bet.roundId].count);
} else {
reward = bet.value.add(allyData.stat[bet.roundId].pool / allyData.stat[bet.roundId].count);
}
}
}
function provisionBettorBetReward(address bettor, uint betIndex) public view returns (uint reward) {
return provisionBetReward(bettors[bettor].bets[betIndex]);
}
function finalizeBetRound(uint betLevel, uint allyRace, uint enemyRace, uint roundId) external onlyService {
_calcRoundLevel(betLevel, allyRace, enemyRace, roundId);
_flushBalance();
}
function roundsCount() external view returns (uint) {
return roundsList.length;
}
function getBettorsBetCounter(address bettor) external view returns (uint) {
return bettors[bettor].counter;
}
function getBettorsBetId(address bettor, uint betIndex) external view returns (uint betId) {
return bettors[bettor].bets[betIndex];
}
function getBettorsBets(address bettor) external view returns (uint[] memory betIds) {
Bettor storage b = bettors[bettor];
uint j;
for (uint i = 1; i <= b.counter; i++) {
if (b.bets[i] != 0) {
j++;
}
}
if (j > 0) {
betIds = new uint[](j);
j = 0;
for (uint i = 1; i <= b.counter; i++) {
if (b.bets[i] != 0) {
betIds[j++] = b.bets[i];
}
}
}
}
function getBet(uint betId) public view returns (
address bettor,
bool active,
uint roundId,
uint allyRace,
uint enemyRace,
uint value,
uint level,
uint opBetId,
uint reward
) {
Bet memory b = bets[betId];
return (b.bettor, b.active, b.roundId, b.allyRace, b.enemyRace, b.value, b.level, b.opBetId, b.reward);
}
function getBetRoundStat(uint roundId, uint allyRace, uint enemyRace, uint level) public view returns (
uint sum,
uint pool,
uint affPool,
uint count,
bool taxed
) {
BetStat memory bs = betData[level][allyRace][enemyRace].stat[roundId];
return (bs.sum, bs.pool, bs.affPool, bs.count, bs.taxed);
}
function getBetQueueLength(uint allyRace, uint enemyRace, uint level) public view returns (uint) {
return betData[level][allyRace][enemyRace].queue.len();
}
function getCurrentBetRound() public view returns (
uint roundId,
uint startedAt,
uint finishedAt,
uint startCheckedAt,
uint finishCheckedAt,
uint betsCount,
uint raceCount
) {
roundId = getCurrentRoundId();
(startedAt, finishedAt, startCheckedAt, finishCheckedAt, betsCount, raceCount) = getBetRound(roundId);
}
function getNextBetRound() public view returns (
uint roundId,
uint startedAt,
uint finishedAt,
uint startCheckedAt,
uint finishCheckedAt,
uint betsCount,
uint raceCount
) {
roundId = getCurrentRoundId() + 1;
(startedAt, finishedAt, startCheckedAt, finishCheckedAt, betsCount, raceCount) = getBetRound(roundId);
}
function getBetRound(uint roundId) public view returns (
uint startedAt,
uint finishedAt,
uint startCheckedAt,
uint finishCheckedAt,
uint betsCount,
uint raceCount
) {
BetRound memory b = betRounds[roundId];
return (b.startedAt, b.finishedAt, b.startCheckedAt, b.finishCheckedAt, b.bets.length, b.raceList.length);
}
function getBetRoundBets(uint roundId) public view returns (uint[] memory betIds) {
return betRounds[roundId].bets;
}
function getBetRoundBetId(uint roundId, uint betIndex) public view returns (uint betId) {
return betRounds[roundId].bets[betIndex];
}
function getBetRoundRaces(uint roundId) public view returns (uint[] memory raceIds) {
return betRounds[roundId].raceList;
}
function getBetRoundRaceStat(uint roundId, uint raceId) external view returns (
uint index,
uint count,
int32 result
){
Race memory r = betRounds[roundId].races[raceId];
return (r.index, r.count, r.result);
}
function setBetRoundResult(uint roundId, uint count, uint[] memory packedRaces, uint[] memory packedResults) public onlyService {
require(packedRaces.length == packedResults.length);
require(packedRaces.length * 8 >= count);
BetRound storage r = betRounds[roundId];
require(r.startedAt != 0 && r.finishedAt == 0);
uint raceId;
int32 result;
for (uint i = 0; i < count; i++) {
raceId = _upack(packedRaces[i / 8], i % 8);
result = int32(_upack(packedResults[i / 8], i % 8));
r.races[raceId].result = result;
emit RoundRaceResult(roundId, raceId, result);
}
}
function finishBetRound(uint roundId, uint startCheckedAt, uint finishCheckedAt) public onlyService {
BetRound storage r = betRounds[roundId];
require(r.startedAt != 0 && r.finishedAt == 0);
uint finishAt;
(, , finishAt) = getRoundInfoAt(r.startedAt, 0);
require(now >= finishAt);
r.finishedAt = finishAt;
r.startCheckedAt = startCheckedAt;
r.finishCheckedAt = finishCheckedAt;
emit FinishBetRound(roundId, startCheckedAt, finishCheckedAt);
}
//extract n-th 32-bit int from uint
function _upack(uint _v, uint _n) internal pure returns (uint) {
// _n = _n & 7; //be sure < 8
return (_v >> (32 * _n)) & 0xFFFFFFFF;
}
} | contract Bets is Ownable, ReservedValue, BetIntervals, BetLevels, Referrals, Services, CanReclaimToken {
using SafeMath for uint;
event BetCreated(address indexed bettor, uint betId, uint index, uint allyRace, uint enemyRace, uint betLevel, uint value, uint utmSource);
event BetAccepted(uint betId, uint opBetId, uint roundId);
event BetCanceled(uint betId);
event BetRewarded(uint winBetId, uint loseBetId, uint reward, bool noWin);
event BetRoundCalculated(uint roundId, uint winnerRace, uint loserRace, uint betLevel, uint pool, uint bettorCount);
event StartBetRound(uint roundId, uint startAt, uint finishAt);
event RoundRaceResult(uint roundId, uint raceId, int32 result);
event FinishBetRound(uint roundId, uint startCheckedAt, uint finishCheckedAt);
using PPQueue for PPQueue.Queue;
struct Bettor {
uint counter;
mapping(uint => uint) bets;
}
struct Race {
uint index;
bool exists;
uint count;
int32 result;
}
struct BetRound {
uint startedAt;
uint finishedAt;
uint startCheckedAt;
uint finishCheckedAt;
uint[] bets;
mapping(uint => Race) races;
uint[] raceList;
}
uint[] public roundsList;
//roundId => BetRound
mapping(uint => BetRound) betRounds;
struct Bet {
address payable bettor;
uint roundId;
uint allyRace;
uint enemyRace;
uint value;
uint level;
uint opBetId;
uint reward;
bool active;
}
struct BetStat {
uint sum;
uint pool;
uint affPool;
uint count;
bool taxed;
}
uint public lastBetId;
mapping(uint => Bet) bets;
mapping(address => Bettor) bettors;
struct BetData {
mapping(uint => BetStat) stat;
PPQueue.Queue queue;
}
//betLevel => allyRace => enemyRace => BetData
mapping(uint => mapping(uint => mapping(uint => BetData))) betData;
//raceId => allowed
mapping(uint => bool) public allowedRace;
uint public systemFeePcnt;
uint public affPoolPcnt;
constructor(address payable _w, address _aff) ReservedValue(_w) Referrals(_aff) public payable {
// systemFee 5% (from loser sum)
// affPoolPercent 5% (from loser sum)
setFee(500, 500);
//allow races, BTC,LTC,ETH by default
allowedRace[1] = true;
allowedRace[2] = true;
allowedRace[4] = true;
allowedRace[10] = true;
allowedRace[13] = true;
}
function setFee(uint _systemFee, uint _affFee) public onlyOwner
{
systemFeePcnt = _systemFee;
affPoolPcnt = _affFee;
}
function allowRace(uint _race, bool _allow) external onlyOwner {
allowedRace[_race] = _allow;
}
function makeBet(uint allyRace, uint enemyRace, uint _affCode, uint _source) public payable {
require(allyRace != enemyRace && allowedRace[allyRace] && allowedRace[enemyRace]);
//require bet level exists
uint level = getBetLevel(msg.value);
Bet storage bet = bets[++lastBetId];
bet.active = true;
bet.bettor = msg.sender;
bet.allyRace = allyRace;
bet.enemyRace = enemyRace;
bet.value = msg.value;
bet.level = level;
//save bet to bettor list && inc. bets count
bettors[bet.bettor].bets[++bettors[bet.bettor].counter] = lastBetId;
emit BetCreated(bet.bettor, lastBetId, bettors[bet.bettor].counter, allyRace, enemyRace, level, msg.value, _source);
//upd queue
BetData storage allyData = betData[level][allyRace][enemyRace];
BetData storage enemyData = betData[level][enemyRace][allyRace];
//if there is nobody on opposite side
if (enemyData.queue.len() == 0) {
allyData.queue.push(lastBetId);
} else {
//accepting bet
uint nextRoundId = _startNextRound();
uint opBetId = enemyData.queue.popf();
bet.opBetId = opBetId;
bet.roundId = nextRoundId;
bets[opBetId].opBetId = lastBetId;
bets[opBetId].roundId = nextRoundId;
//upd fight stat
allyData.stat[nextRoundId].sum = allyData.stat[nextRoundId].sum.add(msg.value);
allyData.stat[nextRoundId].count++;
enemyData.stat[nextRoundId].sum = enemyData.stat[nextRoundId].sum.add(bets[opBetId].value);
enemyData.stat[nextRoundId].count++;
if (!betRounds[nextRoundId].races[allyRace].exists) {
betRounds[nextRoundId].races[allyRace].exists = true;
betRounds[nextRoundId].races[allyRace].index = betRounds[nextRoundId].raceList.length;
betRounds[nextRoundId].raceList.push(allyRace);
}
betRounds[nextRoundId].races[allyRace].count++;
if (!betRounds[nextRoundId].races[enemyRace].exists) {
betRounds[nextRoundId].races[enemyRace].exists = true;
betRounds[nextRoundId].races[enemyRace].index = betRounds[nextRoundId].raceList.length;
betRounds[nextRoundId].raceList.push(enemyRace);
}
betRounds[nextRoundId].races[enemyRace].count++;
betRounds[nextRoundId].bets.push(opBetId);
betRounds[nextRoundId].bets.push(lastBetId);
emit BetAccepted(opBetId, lastBetId, nextRoundId);
}
_incTotalReserved(msg.value);
// update last affiliate
aff.setUpAffCodeByAddr(bet.bettor, _affCode);
}
function _startNextRound() internal returns (uint nextRoundId) {
uint nextStartAt;
uint nextFinishAt;
(nextRoundId, nextStartAt, nextFinishAt) = getNextRoundInfo();
if (betRounds[nextRoundId].startedAt == 0) {
betRounds[nextRoundId].startedAt = nextStartAt;
roundsList.push(nextRoundId);
emit StartBetRound(nextRoundId, nextStartAt, nextFinishAt);
}
}
function cancelBettorBet(address bettor, uint betIndex) external onlyService {
_cancelBet(bettors[bettor].bets[betIndex]);
}
function cancelMyBet(uint betIndex) external nonReentrant {
_cancelBet(bettors[msg.sender].bets[betIndex]);
}
function cancelBet(uint betId) external nonReentrant {
require(bets[betId].bettor == msg.sender);
_cancelBet(betId);
}
function _cancelBet(uint betId) internal {
Bet storage bet = bets[betId];
require(bet.active);
//can cancel only not yet accepted bets
require(bet.roundId == 0);
//upd queue
BetData storage allyData = betData[bet.level][bet.allyRace][bet.enemyRace];
allyData.queue.remove(betId);
_decTotalReserved(bet.value);
bet.bettor.transfer(bet.value);
emit BetCanceled(betId);
// del bet
delete bets[betId];
}
function _calcRoundLevel(uint level, uint allyRace, uint enemyRace, uint roundId) internal returns (int32 allyResult, int32 enemyResult){
require(betRounds[roundId].startedAt != 0 && betRounds[roundId].finishedAt != 0);
allyResult = betRounds[roundId].races[allyRace].result;
enemyResult = betRounds[roundId].races[enemyRace].result;
if (allyResult < enemyResult) {
(allyRace, enemyRace) = (enemyRace, allyRace);
}
BetData storage winnerData = betData[level][allyRace][enemyRace];
BetData storage loserData = betData[level][enemyRace][allyRace];
if (!loserData.stat[roundId].taxed) {
loserData.stat[roundId].taxed = true;
//check if really winner
if (allyResult != enemyResult) {
//system fee
uint fee = _getPercent(loserData.stat[roundId].sum, systemFeePcnt);
_decTotalReserved(fee);
//affiliate %
winnerData.stat[roundId].affPool = _getPercent(loserData.stat[roundId].sum, affPoolPcnt);
//calc pool for round
winnerData.stat[roundId].pool = loserData.stat[roundId].sum - fee - winnerData.stat[roundId].affPool;
emit BetRoundCalculated(roundId, allyRace, enemyRace, level, winnerData.stat[roundId].pool, winnerData.stat[roundId].count);
}
}
if (!winnerData.stat[roundId].taxed) {
winnerData.stat[roundId].taxed = true;
}
}
function rewardBettorBet(address bettor, uint betIndex) external onlyService {
_rewardBet(bettors[bettor].bets[betIndex]);
}
function rewardMyBet(uint betIndex) external nonReentrant {
_rewardBet(bettors[msg.sender].bets[betIndex]);
}
function rewardBet(uint betId) external nonReentrant {
require(bets[betId].bettor == msg.sender);
_rewardBet(betId);
}
function _rewardBet(uint betId) internal {
Bet storage bet = bets[betId];
require(bet.active);
//only accepted bets
require(bet.roundId != 0);
(int32 allyResult, int32 enemyResult) = _calcRoundLevel(bet.level, bet.allyRace, bet.enemyRace, bet.roundId);
//disabling bet
bet.active = false;
if (allyResult >= enemyResult) {
bet.reward = bet.value;
if (allyResult > enemyResult) {
//win
BetStat memory s = betData[bet.level][bet.allyRace][bet.enemyRace].stat[bet.roundId];
bet.reward = bet.reward.add(s.pool / s.count);
// winner's affiliates + loser's affiliates
uint affPool = s.affPool / s.count;
_decTotalReserved(affPool);
// affiliate pool is 1/2 of total aff. pool, per each winner and loser
_distributeAffiliateReward(affPool >> 1, aff.getAffCode(uint(bet.bettor)), 0, false); //no cacheback to winner
_distributeAffiliateReward(affPool >> 1, aff.getAffCode(uint(bets[bet.opBetId].bettor)), 0, true); //cacheback to looser
}
bet.bettor.transfer(bet.reward);
_decTotalReserved(bet.reward);
emit BetRewarded(betId, bet.opBetId, bet.reward, allyResult == enemyResult);
}
_flushBalance();
}
function provisionBetReward(uint betId) public view returns (uint reward) {
Bet storage bet = bets[betId];
if (!bet.active) {
return 0;
}
int32 allyResult = betRounds[bet.roundId].races[bet.allyRace].result;
int32 enemyResult = betRounds[bet.roundId].races[bet.enemyRace].result;
if (allyResult < enemyResult) {
return 0;
}
reward = bet.value;
BetData storage allyData = betData[bet.level][bet.allyRace][bet.enemyRace];
BetData storage enemyData = betData[bet.level][bet.enemyRace][bet.allyRace];
if (allyResult > enemyResult) {
//win
if (!enemyData.stat[bet.roundId].taxed) {
uint pool = enemyData.stat[bet.roundId].sum - _getPercent(enemyData.stat[bet.roundId].sum, systemFeePcnt + affPoolPcnt);
reward = bet.value.add(pool / allyData.stat[bet.roundId].count);
} else {
reward = bet.value.add(allyData.stat[bet.roundId].pool / allyData.stat[bet.roundId].count);
}
}
}
function provisionBettorBetReward(address bettor, uint betIndex) public view returns (uint reward) {
return provisionBetReward(bettors[bettor].bets[betIndex]);
}
function finalizeBetRound(uint betLevel, uint allyRace, uint enemyRace, uint roundId) external onlyService {
_calcRoundLevel(betLevel, allyRace, enemyRace, roundId);
_flushBalance();
}
function roundsCount() external view returns (uint) {
return roundsList.length;
}
function getBettorsBetCounter(address bettor) external view returns (uint) {
return bettors[bettor].counter;
}
function getBettorsBetId(address bettor, uint betIndex) external view returns (uint betId) {
return bettors[bettor].bets[betIndex];
}
function getBettorsBets(address bettor) external view returns (uint[] memory betIds) {
Bettor storage b = bettors[bettor];
uint j;
for (uint i = 1; i <= b.counter; i++) {
if (b.bets[i] != 0) {
j++;
}
}
if (j > 0) {
betIds = new uint[](j);
j = 0;
for (uint i = 1; i <= b.counter; i++) {
if (b.bets[i] != 0) {
betIds[j++] = b.bets[i];
}
}
}
}
function getBet(uint betId) public view returns (
address bettor,
bool active,
uint roundId,
uint allyRace,
uint enemyRace,
uint value,
uint level,
uint opBetId,
uint reward
) {
Bet memory b = bets[betId];
return (b.bettor, b.active, b.roundId, b.allyRace, b.enemyRace, b.value, b.level, b.opBetId, b.reward);
}
function getBetRoundStat(uint roundId, uint allyRace, uint enemyRace, uint level) public view returns (
uint sum,
uint pool,
uint affPool,
uint count,
bool taxed
) {
BetStat memory bs = betData[level][allyRace][enemyRace].stat[roundId];
return (bs.sum, bs.pool, bs.affPool, bs.count, bs.taxed);
}
function getBetQueueLength(uint allyRace, uint enemyRace, uint level) public view returns (uint) {
return betData[level][allyRace][enemyRace].queue.len();
}
function getCurrentBetRound() public view returns (
uint roundId,
uint startedAt,
uint finishedAt,
uint startCheckedAt,
uint finishCheckedAt,
uint betsCount,
uint raceCount
) {
roundId = getCurrentRoundId();
(startedAt, finishedAt, startCheckedAt, finishCheckedAt, betsCount, raceCount) = getBetRound(roundId);
}
function getNextBetRound() public view returns (
uint roundId,
uint startedAt,
uint finishedAt,
uint startCheckedAt,
uint finishCheckedAt,
uint betsCount,
uint raceCount
) {
roundId = getCurrentRoundId() + 1;
(startedAt, finishedAt, startCheckedAt, finishCheckedAt, betsCount, raceCount) = getBetRound(roundId);
}
function getBetRound(uint roundId) public view returns (
uint startedAt,
uint finishedAt,
uint startCheckedAt,
uint finishCheckedAt,
uint betsCount,
uint raceCount
) {
BetRound memory b = betRounds[roundId];
return (b.startedAt, b.finishedAt, b.startCheckedAt, b.finishCheckedAt, b.bets.length, b.raceList.length);
}
function getBetRoundBets(uint roundId) public view returns (uint[] memory betIds) {
return betRounds[roundId].bets;
}
function getBetRoundBetId(uint roundId, uint betIndex) public view returns (uint betId) {
return betRounds[roundId].bets[betIndex];
}
function getBetRoundRaces(uint roundId) public view returns (uint[] memory raceIds) {
return betRounds[roundId].raceList;
}
function getBetRoundRaceStat(uint roundId, uint raceId) external view returns (
uint index,
uint count,
int32 result
){
Race memory r = betRounds[roundId].races[raceId];
return (r.index, r.count, r.result);
}
function setBetRoundResult(uint roundId, uint count, uint[] memory packedRaces, uint[] memory packedResults) public onlyService {
require(packedRaces.length == packedResults.length);
require(packedRaces.length * 8 >= count);
BetRound storage r = betRounds[roundId];
require(r.startedAt != 0 && r.finishedAt == 0);
uint raceId;
int32 result;
for (uint i = 0; i < count; i++) {
raceId = _upack(packedRaces[i / 8], i % 8);
result = int32(_upack(packedResults[i / 8], i % 8));
r.races[raceId].result = result;
emit RoundRaceResult(roundId, raceId, result);
}
}
function finishBetRound(uint roundId, uint startCheckedAt, uint finishCheckedAt) public onlyService {
BetRound storage r = betRounds[roundId];
require(r.startedAt != 0 && r.finishedAt == 0);
uint finishAt;
(, , finishAt) = getRoundInfoAt(r.startedAt, 0);
require(now >= finishAt);
r.finishedAt = finishAt;
r.startCheckedAt = startCheckedAt;
r.finishCheckedAt = finishCheckedAt;
emit FinishBetRound(roundId, startCheckedAt, finishCheckedAt);
}
//extract n-th 32-bit int from uint
function _upack(uint _v, uint _n) internal pure returns (uint) {
// _n = _n & 7; //be sure < 8
return (_v >> (32 * _n)) & 0xFFFFFFFF;
}
} | 41,866 |
42 | // the file must be new | require(records[dataHash].timestamp == 0);
| require(records[dataHash].timestamp == 0);
| 51,576 |
27 | // Set Approval For All for Admin | setApproval(_owner(), msg.sender, true);
| setApproval(_owner(), msg.sender, true);
| 2,157 |
6 | // never overflows, and + overflow is desired | price0CumulativeLast += uint256(UQ112x112.encode(_reserve1).uqdiv(_reserve0)) * timeElapsed;
price1CumulativeLast += uint256(UQ112x112.encode(_reserve0).uqdiv(_reserve1)) * timeElapsed;
| price0CumulativeLast += uint256(UQ112x112.encode(_reserve1).uqdiv(_reserve0)) * timeElapsed;
price1CumulativeLast += uint256(UQ112x112.encode(_reserve0).uqdiv(_reserve1)) * timeElapsed;
| 31,430 |
7 | // vigan.abd ERC20 with adjustable cap | * @dev Extension of {ERC20} that adds a cap to the supply of tokens.
* The cap is dynamic still but can only be decreased further!
*
* NOTE: extends openzeppelin v4.3.2 ERC20 contract:
* https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v4.3.2/contracts/token/ERC20/ERC20.sol
*/
abstract contract ERC20DynamicCap is ERC20 {
/**
* @dev Emitted when cap is updated/decreased
*
* @param from - Account that updated cap
* @param prevCap - Previous cap
* @param newCap - New cap
*/
event CapUpdated(address indexed from, uint256 prevCap, uint256 newCap);
uint256 private _cap = 2**256 - 1; // MAX_INT
/**
* @dev Sets the value of the `cap`. This value later can only be decreased.
*
* @param cap_ - Initial cap (max total supply)
*/
constructor(uint256 cap_) {
_updateCap(cap_);
}
/**
* @dev Returns the cap on the token's total supply (max total supply).
*
* @return uint256
*/
function cap() public view virtual returns (uint256) {
return _cap;
}
/**
* @dev Sets the value of the `cap`. This value can only be decreased
* further, it can't be increased
*
* @param cap_ - New cap, should be lower or equal to previous cap
*/
function _updateCap(uint256 cap_) internal virtual {
require(cap_ > 0, "ERC20DynamicCap: cap cannot be 0");
require(cap_ < _cap, "ERC20DynamicCap: cap can only be decreased");
require(cap_ >= totalSupply(), "ERC20DynamicCap: cap cannot be less than total supply");
uint256 prevCap = _cap;
_cap = cap_;
emit CapUpdated(_msgSender(), prevCap, cap_);
}
/**
* @dev See {ERC20-_mint}. Adds restriction on minting functionality by
* disallowing total supply to exceed cap
*
* @param account - Accounts where the minted funds will be sent
* @param amount - Amount that will be minted
*/
function _mint(address account, uint256 amount) internal virtual override {
require(totalSupply() + amount <= cap(), "ERC20DynamicCap: cap exceeded");
super._mint(account, amount);
}
}
| * @dev Extension of {ERC20} that adds a cap to the supply of tokens.
* The cap is dynamic still but can only be decreased further!
*
* NOTE: extends openzeppelin v4.3.2 ERC20 contract:
* https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v4.3.2/contracts/token/ERC20/ERC20.sol
*/
abstract contract ERC20DynamicCap is ERC20 {
/**
* @dev Emitted when cap is updated/decreased
*
* @param from - Account that updated cap
* @param prevCap - Previous cap
* @param newCap - New cap
*/
event CapUpdated(address indexed from, uint256 prevCap, uint256 newCap);
uint256 private _cap = 2**256 - 1; // MAX_INT
/**
* @dev Sets the value of the `cap`. This value later can only be decreased.
*
* @param cap_ - Initial cap (max total supply)
*/
constructor(uint256 cap_) {
_updateCap(cap_);
}
/**
* @dev Returns the cap on the token's total supply (max total supply).
*
* @return uint256
*/
function cap() public view virtual returns (uint256) {
return _cap;
}
/**
* @dev Sets the value of the `cap`. This value can only be decreased
* further, it can't be increased
*
* @param cap_ - New cap, should be lower or equal to previous cap
*/
function _updateCap(uint256 cap_) internal virtual {
require(cap_ > 0, "ERC20DynamicCap: cap cannot be 0");
require(cap_ < _cap, "ERC20DynamicCap: cap can only be decreased");
require(cap_ >= totalSupply(), "ERC20DynamicCap: cap cannot be less than total supply");
uint256 prevCap = _cap;
_cap = cap_;
emit CapUpdated(_msgSender(), prevCap, cap_);
}
/**
* @dev See {ERC20-_mint}. Adds restriction on minting functionality by
* disallowing total supply to exceed cap
*
* @param account - Accounts where the minted funds will be sent
* @param amount - Amount that will be minted
*/
function _mint(address account, uint256 amount) internal virtual override {
require(totalSupply() + amount <= cap(), "ERC20DynamicCap: cap exceeded");
super._mint(account, amount);
}
}
| 42,141 |
353 | // Sends tokens from the specified address to the specified address on the specified chain (overridden to add blacklist check) _from The address to send tokens from _dstChainId The chain ID to send tokens to _toAddress The address to send tokens to on the destination chain _amount The amount of tokens to send _minAmount The minimum amount of tokens to receive _callParams The call parameters for the destination chain / | function sendFrom(address _from, uint16 _dstChainId, bytes32 _toAddress, uint _amount, uint _minAmount, LzCallParams calldata _callParams) public payable virtual override {
require(!isBlacklisted[_from], "ROOT: sender is blacklisted");
super.sendFrom(_from, _dstChainId, _toAddress, _amount, _minAmount, _callParams);
}
| function sendFrom(address _from, uint16 _dstChainId, bytes32 _toAddress, uint _amount, uint _minAmount, LzCallParams calldata _callParams) public payable virtual override {
require(!isBlacklisted[_from], "ROOT: sender is blacklisted");
super.sendFrom(_from, _dstChainId, _toAddress, _amount, _minAmount, _callParams);
}
| 12,758 |
863 | // modifier that allows only the authorized addresses to execute the function | modifier onlyAuthorizedToGovern() {
IMaster ms = IMaster(masterAddress);
require(ms.getLatestAddress("GV") == msg.sender, "Not authorized");
_;
}
| modifier onlyAuthorizedToGovern() {
IMaster ms = IMaster(masterAddress);
require(ms.getLatestAddress("GV") == msg.sender, "Not authorized");
_;
}
| 54,916 |
308 | // 将LP令牌存入MasterChef进行SUSHI分配 _pid 池子id _amount 数额 / Deposit LP tokens to MasterChef for SUSHI allocation. | function deposit(uint256 _pid, uint256 _amount) public {
// 实例化池子信息
PoolInfo storage pool = poolInfo[_pid];
// 根据池子id和当前用户地址,实例化用户信息
UserInfo storage user = userInfo[_pid][msg.sender];
// 将给定池的奖励变量更新为最新
updatePool(_pid);
// 如果用户已添加的数额>0
if (user.amount > 0) {
// 待定数额 = 用户.已添加的数额 * 池子.每股累积SUSHI / 1e12 - 用户.已奖励数额
uint256 pending = user
.amount
.mul(pool.accSushiPerShare)
.div(1e12)
.sub(user.rewardDebt);
// 向当前用户安全发送待定数额的sushi
safeSushiTransfer(msg.sender, pending);
}
// 调用池子.lptoken的安全发送方法,将_amount数额的lp token从当前用户发送到当前合约
pool.lpToken.safeTransferFrom(
address(msg.sender),
address(this),
_amount
);
// 用户.已添加的数额 = 用户.已添加的数额 + _amount数额
user.amount = user.amount.add(_amount);
// 用户.已奖励数额 = 用户.已添加的数额 * 池子.每股累积SUSHI / 1e12
user.rewardDebt = user.amount.mul(pool.accSushiPerShare).div(1e12);
// 触发存款事件
emit Deposit(msg.sender, _pid, _amount);
}
| function deposit(uint256 _pid, uint256 _amount) public {
// 实例化池子信息
PoolInfo storage pool = poolInfo[_pid];
// 根据池子id和当前用户地址,实例化用户信息
UserInfo storage user = userInfo[_pid][msg.sender];
// 将给定池的奖励变量更新为最新
updatePool(_pid);
// 如果用户已添加的数额>0
if (user.amount > 0) {
// 待定数额 = 用户.已添加的数额 * 池子.每股累积SUSHI / 1e12 - 用户.已奖励数额
uint256 pending = user
.amount
.mul(pool.accSushiPerShare)
.div(1e12)
.sub(user.rewardDebt);
// 向当前用户安全发送待定数额的sushi
safeSushiTransfer(msg.sender, pending);
}
// 调用池子.lptoken的安全发送方法,将_amount数额的lp token从当前用户发送到当前合约
pool.lpToken.safeTransferFrom(
address(msg.sender),
address(this),
_amount
);
// 用户.已添加的数额 = 用户.已添加的数额 + _amount数额
user.amount = user.amount.add(_amount);
// 用户.已奖励数额 = 用户.已添加的数额 * 池子.每股累积SUSHI / 1e12
user.rewardDebt = user.amount.mul(pool.accSushiPerShare).div(1e12);
// 触发存款事件
emit Deposit(msg.sender, _pid, _amount);
}
| 7,835 |
5 | // injections.push(Injection(block.timestamp, amount)); erc20.transferFrom(msg.sender, address(this), amount); |
uint256 totalSupply = 1;
for (uint256 i = 0; i < totalSupply; i++) {
address owner = dropERC721.ownerOf(dropERC721.tokenByIndex(i));
balances[owner] += amount / totalSupply;
}
|
uint256 totalSupply = 1;
for (uint256 i = 0; i < totalSupply; i++) {
address owner = dropERC721.ownerOf(dropERC721.tokenByIndex(i));
balances[owner] += amount / totalSupply;
}
| 24,006 |
577 | // deposit sent ETH into weth | weth.deposit{ value: msg.value }();
// create farm with WETH as reward
BatonFarm farm =
new BatonFarm(_owner, address(this), batonMonitor, address(weth), _pairAddress, _rewardsDuration, address(this));
// transfer WETH into farm
weth.approve(address(farm), msg.value);
// update farm with new rewards
farm.notifyRewardAmount(msg.value);
//emit event
emit FarmCreated(address(farm), _owner, address(this), address(weth), _pairAddress, _rewardsDuration, Type.ETH);
// return address of the farm
return address(farm);
}
| weth.deposit{ value: msg.value }();
// create farm with WETH as reward
BatonFarm farm =
new BatonFarm(_owner, address(this), batonMonitor, address(weth), _pairAddress, _rewardsDuration, address(this));
// transfer WETH into farm
weth.approve(address(farm), msg.value);
// update farm with new rewards
farm.notifyRewardAmount(msg.value);
//emit event
emit FarmCreated(address(farm), _owner, address(this), address(weth), _pairAddress, _rewardsDuration, Type.ETH);
// return address of the farm
return address(farm);
}
| 3,849 |
678 | // Integer values need masking to remove the upper bits of negative values. | return clearedWord | bytes32((uint256(value) & _MASK_22) << offset);
| return clearedWord | bytes32((uint256(value) & _MASK_22) << offset);
| 11,123 |
20 | // Check if both spouses have approved | if (asset.hasApprovedAdd[husbandAddress] && asset.hasApprovedAdd[wifeAddress]) {
asset.added = true;
emit AssetAdded(now, asset.data);
}
| if (asset.hasApprovedAdd[husbandAddress] && asset.hasApprovedAdd[wifeAddress]) {
asset.added = true;
emit AssetAdded(now, asset.data);
}
| 8,744 |
29 | // End round, intervalSeconds is used as the buffer period / | function _endRound(uint256 epoch) internal {
Round storage round = rounds[epoch];
uint80 roundId;
int256 price;
uint256 updatedAt;
if(rounds[epoch+1].closeOracleId > 0)
(roundId, price, , updatedAt, ) = oracle.getRoundData(rounds[epoch+1].closeOracleId - 1);
else
(roundId, price, , updatedAt, ) = oracle.latestRoundData();
while (updatedAt > timestamps[epoch].closeTimestamp) {
(roundId, price, , updatedAt, ) = oracle.getRoundData(roundId-1);
}
if(timestamps[epoch].startTimestamp == 0 ||
updatedAt > timestamps[epoch].closeTimestamp ||
updatedAt < timestamps[epoch].lockTimestamp){
round.cancelled = true;
emit CancelRound(epoch);
}
else{
round.closeOracleId = roundId;
round.closePrice = price;
round.oracleCalled = true;
emit EndRound(epoch, roundId, round.closePrice);
}
}
| function _endRound(uint256 epoch) internal {
Round storage round = rounds[epoch];
uint80 roundId;
int256 price;
uint256 updatedAt;
if(rounds[epoch+1].closeOracleId > 0)
(roundId, price, , updatedAt, ) = oracle.getRoundData(rounds[epoch+1].closeOracleId - 1);
else
(roundId, price, , updatedAt, ) = oracle.latestRoundData();
while (updatedAt > timestamps[epoch].closeTimestamp) {
(roundId, price, , updatedAt, ) = oracle.getRoundData(roundId-1);
}
if(timestamps[epoch].startTimestamp == 0 ||
updatedAt > timestamps[epoch].closeTimestamp ||
updatedAt < timestamps[epoch].lockTimestamp){
round.cancelled = true;
emit CancelRound(epoch);
}
else{
round.closeOracleId = roundId;
round.closePrice = price;
round.oracleCalled = true;
emit EndRound(epoch, roundId, round.closePrice);
}
}
| 4,095 |
11 | // Retrieve the goods after the trade is finalizedCan only be called by a trader/ | function getGoods() activeOnly() traderOnly() external {
require(isFinal());
require(!traderPulledGoods[msg.sender]);
uint256 balance = goods.balanceOf(address(this));
// We need to keep record how many goods we skipped because they
// are not supposed to be transferred to one of the traders
// It really feels like a hack, but it works.
// XXX HACK Justus 2018-05-17
uint256 goodsSkipped = 0;
for (uint256 goodIndex = 0; goodIndex < balance; goodIndex++) {
uint256 goodID = goods.tokenOfOwnerByIndex(
address(this),
goodsSkipped
);
if (goodsTrader[goodID] == msg.sender) {
goodsSkipped++;
continue;
}
goods.safeTransferFrom(address(this), msg.sender, goodID);
}
traderPulledGoods[msg.sender] = true;
emit GoodsPulled(msg.sender);
}
| function getGoods() activeOnly() traderOnly() external {
require(isFinal());
require(!traderPulledGoods[msg.sender]);
uint256 balance = goods.balanceOf(address(this));
// We need to keep record how many goods we skipped because they
// are not supposed to be transferred to one of the traders
// It really feels like a hack, but it works.
// XXX HACK Justus 2018-05-17
uint256 goodsSkipped = 0;
for (uint256 goodIndex = 0; goodIndex < balance; goodIndex++) {
uint256 goodID = goods.tokenOfOwnerByIndex(
address(this),
goodsSkipped
);
if (goodsTrader[goodID] == msg.sender) {
goodsSkipped++;
continue;
}
goods.safeTransferFrom(address(this), msg.sender, goodID);
}
traderPulledGoods[msg.sender] = true;
emit GoodsPulled(msg.sender);
}
| 48,313 |
1 | // Logs factory registration change. Factory must conform to ISetFactory | event FactoryRegistrationChanged(
address _factory,
bool _status
);
| event FactoryRegistrationChanged(
address _factory,
bool _status
);
| 30,608 |
90 | // Party "votes" for a reserve price on Fractional equal to 2x the price of the token | uint256 _listPrice = RESALE_MULTIPLIER * _amountSpent;
| uint256 _listPrice = RESALE_MULTIPLIER * _amountSpent;
| 38,306 |
10 | // Throw when change is triggered for immutable controller | error ImmutableControllerError();
| error ImmutableControllerError();
| 17,173 |
31 | // This is an alternative to {approve} that can be used as a mitigation for problems described in {IERC20-approve}. Emits an {Approval} event indicating the updated allowance. Requirements: - `spender` cannot be the zero address. - `spender` must have allowance for the caller of at least `subtractedValue`./ | function decreaseAllowance(address spender, uint256 subtractedValue)
public
virtual
returns (bool)
{
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
return true;
| function decreaseAllowance(address spender, uint256 subtractedValue)
public
virtual
returns (bool)
{
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
return true;
| 24,428 |
19 | // This function cannot be called twice as long as _zkSyncCommitBlockAddress and _zkSyncExitAddress have been set to non-zero. | require(zkSyncCommitBlockAddress == address(0), "sraa1");
require(zkSyncExitAddress == address(0), "sraa2");
blocks[0].stateRoot = _genesisRoot;
zkSyncCommitBlockAddress = _zkSyncCommitBlockAddress;
zkSyncExitAddress = _zkSyncExitAddress;
| require(zkSyncCommitBlockAddress == address(0), "sraa1");
require(zkSyncExitAddress == address(0), "sraa2");
blocks[0].stateRoot = _genesisRoot;
zkSyncCommitBlockAddress = _zkSyncCommitBlockAddress;
zkSyncExitAddress = _zkSyncExitAddress;
| 29,657 |
33 | // 商城返利 | _assign(0x21d47FCDA2FAe5E3D7f45b6f0b71372df3F6acE4, 1000);
| _assign(0x21d47FCDA2FAe5E3D7f45b6f0b71372df3F6acE4, 1000);
| 8,718 |
87 | // Token detailed | contract DAFIN is ERC20, ERC20Detailed, ERC20Pausable, ERC20Mintable {
string public constant name = "DAFIN";
string public constant symbol = "DAF";
uint8 public constant DECIMALS = 18;
uint256 public constant INITIAL_SUPPLY = 300000000 * (10 ** uint256(DECIMALS));
constructor () public ERC20Detailed(name, symbol, DECIMALS) {
_mint(msg.sender, INITIAL_SUPPLY);
}
} | contract DAFIN is ERC20, ERC20Detailed, ERC20Pausable, ERC20Mintable {
string public constant name = "DAFIN";
string public constant symbol = "DAF";
uint8 public constant DECIMALS = 18;
uint256 public constant INITIAL_SUPPLY = 300000000 * (10 ** uint256(DECIMALS));
constructor () public ERC20Detailed(name, symbol, DECIMALS) {
_mint(msg.sender, INITIAL_SUPPLY);
}
} | 31,084 |
27 | // This function keeps track of the added GDP, as well as grants of discount tokensto the referrer, if applicable.The number of discount tokens granted is based on the value of the referal,the current growth rate and the lock's discount token distribution rateThis function is invoked by a previously deployed lock only.TODO: actually implement / | function recordKeyPurchase(
uint _value,
address _referrer
)
public
onlyFromDeployedLock()
| function recordKeyPurchase(
uint _value,
address _referrer
)
public
onlyFromDeployedLock()
| 18,414 |
7 | // uint256 vestingDays = ((start + 90 days) - now) / 60 / 60 / 24; // if (vestingDays >= 1) { // tokens = SafeMath.add(tokens, SafeMath.div(SafeMath.mul(SafeMath.mul(SafeMath.div(tokens,100), 22222222), vestingDays), 108)); // } / mint tokens to owner address | _mint(owner(), tokens);
| _mint(owner(), tokens);
| 13,374 |
13 | // Negatives an affine point on babyjubjub _p point to negativizereturn p = -(_p) / | function afNeg(uint256[2] memory _p) internal pure returns (uint256[2] memory p) {
return [Q-_p[0]%Q, _p[1]];
}
| function afNeg(uint256[2] memory _p) internal pure returns (uint256[2] memory p) {
return [Q-_p[0]%Q, _p[1]];
}
| 42,685 |
70 | // Sets the minter address. minter address The minter address. / | function setMinter(address minter) public onlyOwner {
require(minter != address(0), "Miner/zero-address");
_minter = minter;
}
| function setMinter(address minter) public onlyOwner {
require(minter != address(0), "Miner/zero-address");
_minter = minter;
}
| 12,697 |
106 | // only effect erc20 interface. when erc777mode equal 0, the erc777 feature is disabled; when erc777mode equal 1, the erc777 feature is enabled by whitelist. when erc777 mode equal 2, the erc777 feature is disabled by blacklist. when erc777 mode equal 3, the erc777 feature is enabled; in whitelist or black list mode, whether "from" or "to" address in list, the feature would be effected. | enum Erc777ModeType {disabled, whitelist, blacklist, enabled}
Erc777ModeType public erc777Mode;
mapping(address=>bool) public blacklist;
mapping(address=>bool) public whitelist;
//////////////////// for coin
mapping(address => uint256) private _balances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
// ERC20-allowances
mapping (address => mapping (address => uint256)) private _allowances;
mapping(address=>bool) private _freezeAddress;
//////////////////// for operator
// This isn't ever read from - it's only used to respond to the defaultOperators query.
address[] private _defaultOperatorsArray;
// Immutable, but accounts may revoke them (tracked in __revokedDefaultOperators).
mapping(address => bool) private _defaultOperators;
// For each account, a mapping of its operators and revoked default operators.
mapping(address => mapping(address => bool)) private _operators;
mapping(address => mapping(address => bool)) private _revokedDefaultOperators;
//////////////////// for staking
uint256 public StakingID;
struct StakingInfo{
address Addr;
string Info;
uint256 validIdx;
uint256 SID;
}
| enum Erc777ModeType {disabled, whitelist, blacklist, enabled}
Erc777ModeType public erc777Mode;
mapping(address=>bool) public blacklist;
mapping(address=>bool) public whitelist;
//////////////////// for coin
mapping(address => uint256) private _balances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
// ERC20-allowances
mapping (address => mapping (address => uint256)) private _allowances;
mapping(address=>bool) private _freezeAddress;
//////////////////// for operator
// This isn't ever read from - it's only used to respond to the defaultOperators query.
address[] private _defaultOperatorsArray;
// Immutable, but accounts may revoke them (tracked in __revokedDefaultOperators).
mapping(address => bool) private _defaultOperators;
// For each account, a mapping of its operators and revoked default operators.
mapping(address => mapping(address => bool)) private _operators;
mapping(address => mapping(address => bool)) private _revokedDefaultOperators;
//////////////////// for staking
uint256 public StakingID;
struct StakingInfo{
address Addr;
string Info;
uint256 validIdx;
uint256 SID;
}
| 10,985 |
25 | // Claim USDT in exchange of AAVE Token amUSDT | unzapCollateral(amount);
| unzapCollateral(amount);
| 19,955 |
15 | // Returns the address of the EIP712 verifier used to verify signed attestations. return The address of the EIP712 verifier used to verify signed attestations. / | function getEIP712Verifier() external view returns (IEIP712Verifier);
| function getEIP712Verifier() external view returns (IEIP712Verifier);
| 24,650 |
173 | // mintEmits [Transfer] event. Requirements: - should have a valid coupon if we are () / | whenNotPaused {
uint256 currentSupply = _tokenId.current();
require(phase != SalePhase.Locked, "Sale is not available");
if (phase == SalePhase.Private) {
bytes32 digest = keccak256(
abi.encode(CouponType.Private, msg.sender)
);
require(_isVerifiedCoupon(digest, coupon), "Invalid coupon");
require(
PrivateMintsCount[msg.sender] + amount <= maxPrivateMintsPerAddress,
"Max supply to mint per address during private sale has been reached"
);
require(
totalPrivateMints + amount <= maxPrivateMints,
"Max supply to mint during private sale has been reached"
);
} else if (phase == SalePhase.Presale) {
bytes32 digest = keccak256(
abi.encode(CouponType.Presale, msg.sender)
);
require(_isVerifiedCoupon(digest, coupon), "Invalid coupon");
require(
PresaleMintsCount[msg.sender] + amount <= maxPresaleMintsPerAddress,
"Max supply to mint per address during presale has been reached"
);
}
require(
currentSupply + amount <= maxSupply,
"Max supply limit reached"
);
require(
balanceOf(msg.sender) + amount <= maxMintsPerAddress,
"Max mint per address reached"
);
require(msg.value >= amount * mintPrice, "Insufficient funds");
for (uint256 i = 0; i < amount; i++) {
if (phase == SalePhase.Private) {
totalPrivateMints++;
PrivateMintsCount[msg.sender]++;
} else if (phase == SalePhase.Presale) {
PresaleMintsCount[msg.sender]++;
}
_tokenId.increment();
_safeMint(msg.sender, _tokenId.current());
}
}
| whenNotPaused {
uint256 currentSupply = _tokenId.current();
require(phase != SalePhase.Locked, "Sale is not available");
if (phase == SalePhase.Private) {
bytes32 digest = keccak256(
abi.encode(CouponType.Private, msg.sender)
);
require(_isVerifiedCoupon(digest, coupon), "Invalid coupon");
require(
PrivateMintsCount[msg.sender] + amount <= maxPrivateMintsPerAddress,
"Max supply to mint per address during private sale has been reached"
);
require(
totalPrivateMints + amount <= maxPrivateMints,
"Max supply to mint during private sale has been reached"
);
} else if (phase == SalePhase.Presale) {
bytes32 digest = keccak256(
abi.encode(CouponType.Presale, msg.sender)
);
require(_isVerifiedCoupon(digest, coupon), "Invalid coupon");
require(
PresaleMintsCount[msg.sender] + amount <= maxPresaleMintsPerAddress,
"Max supply to mint per address during presale has been reached"
);
}
require(
currentSupply + amount <= maxSupply,
"Max supply limit reached"
);
require(
balanceOf(msg.sender) + amount <= maxMintsPerAddress,
"Max mint per address reached"
);
require(msg.value >= amount * mintPrice, "Insufficient funds");
for (uint256 i = 0; i < amount; i++) {
if (phase == SalePhase.Private) {
totalPrivateMints++;
PrivateMintsCount[msg.sender]++;
} else if (phase == SalePhase.Presale) {
PresaleMintsCount[msg.sender]++;
}
_tokenId.increment();
_safeMint(msg.sender, _tokenId.current());
}
}
| 43,014 |
20 | // The address of the current Wayfarer | address public wayfarer;
| address public wayfarer;
| 26,130 |
86 | // Switch to determine if bundles can be created by anyone/Callable only by the owner/_openToPublic Flag if true anyone can create bundles | function changeEditPermission(bool _openToPublic) public onlyOwner {
openToPublic = _openToPublic;
}
| function changeEditPermission(bool _openToPublic) public onlyOwner {
openToPublic = _openToPublic;
}
| 25,307 |
13 | // grant uniswap / sushiswap access to your token, DAI used since we're swapping DAI back into ETH | dai.approve(address(uniswapV2Router), tokenAmountInWEI);
dai.approve(address(sushiswapV1Router), tokenAmountInWEI);
| dai.approve(address(uniswapV2Router), tokenAmountInWEI);
dai.approve(address(sushiswapV1Router), tokenAmountInWEI);
| 10,232 |
2 | // The mapping to keep track of which whitelist any address belongs to. 0 is reserved for no whitelist and is the default for all addresses. | mapping (address => uint8) public addressWhitelists;
| mapping (address => uint8) public addressWhitelists;
| 26,635 |
35 | // The rate of fee the market pays towards the vault on token purchases./ | function feeRate() external view returns(uint256) {
return feeRate_;
}
| function feeRate() external view returns(uint256) {
return feeRate_;
}
| 48,562 |
43 | // update current coins minted | stakes[msg.sender][_stakeNumber].coinsMinted = stakes[msg.sender][_stakeNumber].coinsMinted.add(mintAmount);
| stakes[msg.sender][_stakeNumber].coinsMinted = stakes[msg.sender][_stakeNumber].coinsMinted.add(mintAmount);
| 47,121 |
5 | // Minimum and maximum amounts per transaction for participants | uint256 public constant MIN_AMOUNT = 500 finney;
uint256 public constant MAX_AMOUNT = 50 ether;
| uint256 public constant MIN_AMOUNT = 500 finney;
uint256 public constant MAX_AMOUNT = 50 ether;
| 34,433 |
23 | // The saved permissions/This info is saved per owner, per token, per spender and all signed over in the permit message/Setting amount to type(uint160).max sets an unlimited approval | struct PackedAllowance {
// amount allowed
uint160 amount;
// permission expiry
uint48 expiration;
// an incrementing value indexed per owner,token,and spender for each signature
uint48 nonce;
}
| struct PackedAllowance {
// amount allowed
uint160 amount;
// permission expiry
uint48 expiration;
// an incrementing value indexed per owner,token,and spender for each signature
uint48 nonce;
}
| 25,098 |
50 | // Constructor. Choose the arbitrator._arbitrator The arbitrator of the contract._arbitratorExtraData Extra data for the arbitrator. / | constructor(Arbitrator _arbitrator, bytes _arbitratorExtraData) public {
arbitrator = _arbitrator;
arbitratorExtraData = _arbitratorExtraData;
}
| constructor(Arbitrator _arbitrator, bytes _arbitratorExtraData) public {
arbitrator = _arbitrator;
arbitratorExtraData = _arbitratorExtraData;
}
| 29,183 |
29 | // return the address of a payee. / | function payee(uint256 index) public view returns (address) {
return _payees[index];
}
| function payee(uint256 index) public view returns (address) {
return _payees[index];
}
| 770 |
8 | // Parameter used to limit the number of stablecoins that can be issued using the concerned collateral | uint256 capOnStableMinted;
| uint256 capOnStableMinted;
| 23,951 |
27 | // Construct calldata for _l2Token.finalizeDeposit(_to, _amount) | message = abi.encodeWithSelector(
IL2ERC20Bridge.finalizeDeposit.selector,
_l1Token,
_l2Token,
_from,
_to,
_amount,
_data
);
| message = abi.encodeWithSelector(
IL2ERC20Bridge.finalizeDeposit.selector,
_l1Token,
_l2Token,
_from,
_to,
_amount,
_data
);
| 19,638 |
5 | // updates the cratio according to the collateral value vs line value calls accrue interest on the line contract to update the latest interest payable oracle - address to call for collateral token pricesreturn cratio - the updated collateral ratio in 4 decimals / | function _getLatestCollateralRatio(EscrowState storage self, address oracle) public returns (uint256) {
(uint256 principal, uint256 interest) = ILineOfCredit(self.line).updateOutstandingDebt();
uint256 debtValue = principal + interest;
uint256 collateralValue = _getCollateralValue(self, oracle);
if (debtValue == 0) return MAX_INT;
if (collateralValue == 0) return 0;
uint256 _numerator = collateralValue * 10 ** 5; // scale to 4 decimals
return ((_numerator / debtValue) + 5) / 10;
}
| function _getLatestCollateralRatio(EscrowState storage self, address oracle) public returns (uint256) {
(uint256 principal, uint256 interest) = ILineOfCredit(self.line).updateOutstandingDebt();
uint256 debtValue = principal + interest;
uint256 collateralValue = _getCollateralValue(self, oracle);
if (debtValue == 0) return MAX_INT;
if (collateralValue == 0) return 0;
uint256 _numerator = collateralValue * 10 ** 5; // scale to 4 decimals
return ((_numerator / debtValue) + 5) / 10;
}
| 33,113 |
8 | // A standard interface for tokens. / | interface ERC20 {
/**
* @dev Returns the name of the token.
*/
function name()
external
view
returns (string _name);
/**
* @dev Returns the symbol of the token.
*/
function symbol()
external
view
returns (string _symbol);
/**
* @dev Returns the number of decimals the token uses.
*/
function decimals()
external
view
returns (uint8 _decimals);
/**
* @dev Returns the total token supply.
*/
function totalSupply()
external
view
returns (uint256 _totalSupply);
/**
* @dev Returns the account balance of another account with address _owner.
* @param _owner The address from which the balance will be retrieved.
*/
function balanceOf(
address _owner
)
external
view
returns (uint256 _balance);
/**
* @dev Transfers _value amount of tokens to address _to, and MUST fire the Transfer event. The
* function SHOULD throw if the _from account balance does not have enough tokens to spend.
* @param _to The address of the recipient.
* @param _value The amount of token to be transferred.
*/
function transfer(
address _to,
uint256 _value
)
external
returns (bool _success);
/**
* @dev Transfers _value amount of tokens from address _from to address _to, and MUST fire the
* Transfer event.
* @param _from The address of the sender.
* @param _to The address of the recipient.
* @param _value The amount of token to be transferred.
*/
function transferFrom(
address _from,
address _to,
uint256 _value
)
external
returns (bool _success);
/**
* @dev Allows _spender to withdraw from your account multiple times, up to
* the _value amount. If this function is called again it overwrites the current
* allowance with _value.
* @param _spender The address of the account able to transfer the tokens.
* @param _value The amount of tokens to be approved for transfer.
*/
function approve(
address _spender,
uint256 _value
)
external
returns (bool _success);
/**
* @dev Returns the amount which _spender is still allowed to withdraw from _owner.
* @param _owner The address of the account owning tokens.
* @param _spender The address of the account able to transfer the tokens.
*/
function allowance(
address _owner,
address _spender
)
external
view
returns (uint256 _remaining);
/**
* @dev Triggers when tokens are transferred, including zero value transfers.
*/
event Transfer(
address indexed _from,
address indexed _to,
uint256 _value
);
/**
* @dev Triggers on any successful call to approve(address _spender, uint256 _value).
*/
event Approval(
address indexed _owner,
address indexed _spender,
uint256 _value
);
}
| interface ERC20 {
/**
* @dev Returns the name of the token.
*/
function name()
external
view
returns (string _name);
/**
* @dev Returns the symbol of the token.
*/
function symbol()
external
view
returns (string _symbol);
/**
* @dev Returns the number of decimals the token uses.
*/
function decimals()
external
view
returns (uint8 _decimals);
/**
* @dev Returns the total token supply.
*/
function totalSupply()
external
view
returns (uint256 _totalSupply);
/**
* @dev Returns the account balance of another account with address _owner.
* @param _owner The address from which the balance will be retrieved.
*/
function balanceOf(
address _owner
)
external
view
returns (uint256 _balance);
/**
* @dev Transfers _value amount of tokens to address _to, and MUST fire the Transfer event. The
* function SHOULD throw if the _from account balance does not have enough tokens to spend.
* @param _to The address of the recipient.
* @param _value The amount of token to be transferred.
*/
function transfer(
address _to,
uint256 _value
)
external
returns (bool _success);
/**
* @dev Transfers _value amount of tokens from address _from to address _to, and MUST fire the
* Transfer event.
* @param _from The address of the sender.
* @param _to The address of the recipient.
* @param _value The amount of token to be transferred.
*/
function transferFrom(
address _from,
address _to,
uint256 _value
)
external
returns (bool _success);
/**
* @dev Allows _spender to withdraw from your account multiple times, up to
* the _value amount. If this function is called again it overwrites the current
* allowance with _value.
* @param _spender The address of the account able to transfer the tokens.
* @param _value The amount of tokens to be approved for transfer.
*/
function approve(
address _spender,
uint256 _value
)
external
returns (bool _success);
/**
* @dev Returns the amount which _spender is still allowed to withdraw from _owner.
* @param _owner The address of the account owning tokens.
* @param _spender The address of the account able to transfer the tokens.
*/
function allowance(
address _owner,
address _spender
)
external
view
returns (uint256 _remaining);
/**
* @dev Triggers when tokens are transferred, including zero value transfers.
*/
event Transfer(
address indexed _from,
address indexed _to,
uint256 _value
);
/**
* @dev Triggers on any successful call to approve(address _spender, uint256 _value).
*/
event Approval(
address indexed _owner,
address indexed _spender,
uint256 _value
);
}
| 63,638 |
302 | // Internal Functions: Gas Metering//Checks whether a transaction needs to start a new epoch and does so if necessary. _timestamp Transaction timestamp. / | function _checkNeedsNewEpoch(
uint256 _timestamp
)
internal
| function _checkNeedsNewEpoch(
uint256 _timestamp
)
internal
| 28,076 |
11 | // ERC20 | function name() public view returns (string) {
return NAME;
}
| function name() public view returns (string) {
return NAME;
}
| 8,404 |
226 | // Decrease the user's debt obligation This amount is denominated in par since collateralDelta uses the borrow index | TypesV1.Par memory newPar = position.borrowedAmount.add(
TypesV1.Par({
sign: true,
value: borrowToLiquidate.to128()
})
| TypesV1.Par memory newPar = position.borrowedAmount.add(
TypesV1.Par({
sign: true,
value: borrowToLiquidate.to128()
})
| 45,351 |
24 | // Get the full length of an Item. | function _itemLength(uint memPtr) private pure returns (uint len) {
uint b0;
assembly {
b0 := byte(0, mload(memPtr))
}
if (b0 < DATA_SHORT_START)
len = 1;
else if (b0 < DATA_LONG_START)
len = b0 - DATA_SHORT_START + 1;
else if (b0 < LIST_SHORT_START) {
assembly {
let bLen := sub(b0, 0xB7) // bytes length (DATA_LONG_OFFSET)
let dLen := div(mload(add(memPtr, 1)), exp(256, sub(32, bLen))) // data length
len := add(1, add(bLen, dLen)) // total length
}
}
else if (b0 < LIST_LONG_START)
len = b0 - LIST_SHORT_START + 1;
else {
assembly {
let bLen := sub(b0, 0xF7) // bytes length (LIST_LONG_OFFSET)
let dLen := div(mload(add(memPtr, 1)), exp(256, sub(32, bLen))) // data length
len := add(1, add(bLen, dLen)) // total length
}
}
}
| function _itemLength(uint memPtr) private pure returns (uint len) {
uint b0;
assembly {
b0 := byte(0, mload(memPtr))
}
if (b0 < DATA_SHORT_START)
len = 1;
else if (b0 < DATA_LONG_START)
len = b0 - DATA_SHORT_START + 1;
else if (b0 < LIST_SHORT_START) {
assembly {
let bLen := sub(b0, 0xB7) // bytes length (DATA_LONG_OFFSET)
let dLen := div(mload(add(memPtr, 1)), exp(256, sub(32, bLen))) // data length
len := add(1, add(bLen, dLen)) // total length
}
}
else if (b0 < LIST_LONG_START)
len = b0 - LIST_SHORT_START + 1;
else {
assembly {
let bLen := sub(b0, 0xF7) // bytes length (LIST_LONG_OFFSET)
let dLen := div(mload(add(memPtr, 1)), exp(256, sub(32, bLen))) // data length
len := add(1, add(bLen, dLen)) // total length
}
}
}
| 2,952 |
43 | // finally should release all tokens | require(_releaseRatios[len - 1] == coeff);
| require(_releaseRatios[len - 1] == coeff);
| 47,883 |
44 | // total freezing balance per address | mapping (address => uint) internal freezingBalance;
event Freezed(address indexed to, uint64 release, uint amount);
event Released(address indexed owner, uint amount);
| mapping (address => uint) internal freezingBalance;
event Freezed(address indexed to, uint64 release, uint amount);
event Released(address indexed owner, uint amount);
| 12,743 |
120 | // If balance is too small,sell all tokens at once | sellBalance = _bal;
| sellBalance = _bal;
| 3,991 |
33 | // Account Library / | library AccountLibrary {
using ECDSA for bytes32;
function isOwnerDevice(
AbstractAccount _account,
address _device
) internal view returns (bool) {
bool isOwner;
(isOwner,,) = _account.devices(_device);
return isOwner;
}
function isAnyDevice(
AbstractAccount _account,
address _device
) internal view returns (bool) {
bool exists;
(,exists,) = _account.devices(_device);
return exists;
}
function isExistedDevice(
AbstractAccount _account,
address _device
) internal view returns (bool) {
bool existed;
(,,existed) = _account.devices(_device);
return existed;
}
function verifyOwnerSignature(
AbstractAccount _account,
bytes32 _messageHash,
bytes memory _signature
) internal view returns (bool _result) {
address _recovered = _messageHash.recover(_signature);
if (_recovered != address(0)) {
_result = isOwnerDevice(_account, _recovered);
}
}
function verifySignature(
AbstractAccount _account,
bytes32 _messageHash,
bytes memory _signature,
bool _strict
) internal view returns (bool _result) {
address _recovered = _messageHash.recover(_signature);
if (_recovered != address(0)) {
if (_strict) {
_result = isAnyDevice(_account, _recovered);
} else {
_result = isExistedDevice(_account, _recovered);
}
}
}
}
| library AccountLibrary {
using ECDSA for bytes32;
function isOwnerDevice(
AbstractAccount _account,
address _device
) internal view returns (bool) {
bool isOwner;
(isOwner,,) = _account.devices(_device);
return isOwner;
}
function isAnyDevice(
AbstractAccount _account,
address _device
) internal view returns (bool) {
bool exists;
(,exists,) = _account.devices(_device);
return exists;
}
function isExistedDevice(
AbstractAccount _account,
address _device
) internal view returns (bool) {
bool existed;
(,,existed) = _account.devices(_device);
return existed;
}
function verifyOwnerSignature(
AbstractAccount _account,
bytes32 _messageHash,
bytes memory _signature
) internal view returns (bool _result) {
address _recovered = _messageHash.recover(_signature);
if (_recovered != address(0)) {
_result = isOwnerDevice(_account, _recovered);
}
}
function verifySignature(
AbstractAccount _account,
bytes32 _messageHash,
bytes memory _signature,
bool _strict
) internal view returns (bool _result) {
address _recovered = _messageHash.recover(_signature);
if (_recovered != address(0)) {
if (_strict) {
_result = isAnyDevice(_account, _recovered);
} else {
_result = isExistedDevice(_account, _recovered);
}
}
}
}
| 46,950 |
154 | // virtualoverride | payable
ensure(deadline)
returns (uint[] memory amounts)
{
require(path[0] == WETH, 'UniswapV2Router: INVALID_PATH');
amounts = UniswapV2Library.getAmountsOut(factory, msg.value, path);
require(amounts[amounts.length - 1] >= amountOutMin, 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT');
IWETH(WETH).deposit.value(amounts[0])(); // IWETH(WETH).deposit{value: amounts[0]}();
| payable
ensure(deadline)
returns (uint[] memory amounts)
{
require(path[0] == WETH, 'UniswapV2Router: INVALID_PATH');
amounts = UniswapV2Library.getAmountsOut(factory, msg.value, path);
require(amounts[amounts.length - 1] >= amountOutMin, 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT');
IWETH(WETH).deposit.value(amounts[0])(); // IWETH(WETH).deposit{value: amounts[0]}();
| 13,179 |
141 | // Return data is optional | require(
abi.decode(returndata, (bool)),
"SafeERC20: ERC20 operation did not succeed"
);
| require(
abi.decode(returndata, (bool)),
"SafeERC20: ERC20 operation did not succeed"
);
| 4,033 |
172 | // This is the maximum possible amount that participant1 could transfer to participant2, if all the pending lock secrets have been registered | participant1_max_transferred = failsafe_addition(
participant1_settlement.transferred,
participant1_settlement.locked
);
| participant1_max_transferred = failsafe_addition(
participant1_settlement.transferred,
participant1_settlement.locked
);
| 14,908 |
25 | // returns array of all Garden contract addresses for a specified user address | function getFollowsForUser(address user) public view returns (address[] memory){
return userToFollowedGardens[user];
}
| function getFollowsForUser(address user) public view returns (address[] memory){
return userToFollowedGardens[user];
}
| 15,951 |
8 | // Lets do some calcs! | (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
) = priceSource.latestRoundData();
require(answer >= 0, 'Chainlink pricefeed returned bad value.');
| (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
) = priceSource.latestRoundData();
require(answer >= 0, 'Chainlink pricefeed returned bad value.');
| 3,501 |
11 | // vanity |
function changevanity(string van , address masternode) public payable
|
function changevanity(string van , address masternode) public payable
| 7,058 |
246 | // View Functions / | function settings() external view override returns (address) {
return address(_settings());
}
| function settings() external view override returns (address) {
return address(_settings());
}
| 76,670 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.