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
412
// Creates a new token for `creator`. Its token ID will be automatically
* assigned (and available on the emitted {IERC721-Transfer} event), and the token * URI autogenerated based on the base URI passed at construction. * * See {ERC721-_safeMint}. * * On mint, also set the sha256 hashes of the content and its metadata for integrity * checks, along with the initial URIs to point to the content and metadata. Attribute * the token ID to the creator, mark the content hash as used, and set the bid shares for * the media's market. * * Note that although the content hash must be unique for future mints to prevent duplicate media, * metadata has no such requirement. */ function _mintForCreator( address creator, MediaData memory data, IMarket.BidShares memory bidShares ) internal onlyValidURI(data.tokenURI) onlyValidURI(data.metadataURI) { require(data.contentHash != 0, "Media: content hash must be non-zero"); require( _contentHashes[data.contentHash] == false, "Media: a token has already been created with this content hash" ); require( data.metadataHash != 0, "Media: metadata hash must be non-zero" ); uint256 tokenId = _tokenIdTracker.current(); _safeMint(creator, tokenId); _tokenIdTracker.increment(); _setTokenContentHash(tokenId, data.contentHash); _setTokenMetadataHash(tokenId, data.metadataHash); _setTokenMetadataURI(tokenId, data.metadataURI); _setTokenURI(tokenId, data.tokenURI); _creatorTokens[creator].add(tokenId); _contentHashes[data.contentHash] = true; tokenCreators[tokenId] = creator; previousTokenOwners[tokenId] = creator; IMarket(marketContract).setBidShares(tokenId, bidShares); }
* assigned (and available on the emitted {IERC721-Transfer} event), and the token * URI autogenerated based on the base URI passed at construction. * * See {ERC721-_safeMint}. * * On mint, also set the sha256 hashes of the content and its metadata for integrity * checks, along with the initial URIs to point to the content and metadata. Attribute * the token ID to the creator, mark the content hash as used, and set the bid shares for * the media's market. * * Note that although the content hash must be unique for future mints to prevent duplicate media, * metadata has no such requirement. */ function _mintForCreator( address creator, MediaData memory data, IMarket.BidShares memory bidShares ) internal onlyValidURI(data.tokenURI) onlyValidURI(data.metadataURI) { require(data.contentHash != 0, "Media: content hash must be non-zero"); require( _contentHashes[data.contentHash] == false, "Media: a token has already been created with this content hash" ); require( data.metadataHash != 0, "Media: metadata hash must be non-zero" ); uint256 tokenId = _tokenIdTracker.current(); _safeMint(creator, tokenId); _tokenIdTracker.increment(); _setTokenContentHash(tokenId, data.contentHash); _setTokenMetadataHash(tokenId, data.metadataHash); _setTokenMetadataURI(tokenId, data.metadataURI); _setTokenURI(tokenId, data.tokenURI); _creatorTokens[creator].add(tokenId); _contentHashes[data.contentHash] = true; tokenCreators[tokenId] = creator; previousTokenOwners[tokenId] = creator; IMarket(marketContract).setBidShares(tokenId, bidShares); }
4,961
37
// Set a new heartbeater. heartbeater address to designate as the heartbeating address. /
function newHeartbeater(address heartbeater) external onlyOwner { require(heartbeater != address(0), "Must specify a heartbeater address."); _heartbeater = heartbeater; }
function newHeartbeater(address heartbeater) external onlyOwner { require(heartbeater != address(0), "Must specify a heartbeater address."); _heartbeater = heartbeater; }
17,549
78
// Send the crosschain message.
bytes32 messageHash = _sendMessage( transferId, _params.destinationDomain, remoteInstance, canonical, local, _params.bridgedAmt, isCanonical );
bytes32 messageHash = _sendMessage( transferId, _params.destinationDomain, remoteInstance, canonical, local, _params.bridgedAmt, isCanonical );
14,049
4
// SafeMath Math operations with safety checks that throw on error /
library SafeMath { function mul(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal constant returns(uint256) { assert(b > 0); uint256 c = a / b; assert(a == b * c + a % b); return c; } function sub(uint256 a, uint256 b) internal constant returns(uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal constant returns(uint256) { uint256 c = a + b; assert(c >= a); return c; } }
library SafeMath { function mul(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal constant returns(uint256) { assert(b > 0); uint256 c = a / b; assert(a == b * c + a % b); return c; } function sub(uint256 a, uint256 b) internal constant returns(uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal constant returns(uint256) { uint256 c = a + b; assert(c >= a); return c; } }
19,248
6,158
// 3081
entry "nounally" : ENG_ADVERB
entry "nounally" : ENG_ADVERB
23,917
36
// Returns the controller which created the domain on behalf of a user id The domain /
function domainController(uint256 id) public view override returns (address) { address controller = records[id].controller; return controller; }
function domainController(uint256 id) public view override returns (address) { address controller = records[id].controller; return controller; }
73,594
20
// Runs a check and transfers reserve tokens as needed To avoid too many fees, this should be run at wide intervals such as dailytokenIn - Address of reserve token pool - Address of collateral token amountIn - The amount being traded recipient - Address of person to receive the swapped tokens /
function sellReserveToken( address tokenIn, address pool, uint256 amountIn, address recipient
function sellReserveToken( address tokenIn, address pool, uint256 amountIn, address recipient
23,924
8
// Transfer claimed pxa token
function getFunds(Options _option) public { int256 duration = int256(nextFundingTime[msg.sender] - block.timestamp); require(duration < 1, "PF : FAUCET_COOLDOWN"); if (_option == Options.Every24Hours) { transferFund(hours24InSeconds, hours24Fund); } else if (_option == Options.Every72Hours) { transferFund(hours72InSeconds, hours72Fund); } else { transferFund(hours8InSeconds, hours8Fund); } }
function getFunds(Options _option) public { int256 duration = int256(nextFundingTime[msg.sender] - block.timestamp); require(duration < 1, "PF : FAUCET_COOLDOWN"); if (_option == Options.Every24Hours) { transferFund(hours24InSeconds, hours24Fund); } else if (_option == Options.Every72Hours) { transferFund(hours72InSeconds, hours72Fund); } else { transferFund(hours8InSeconds, hours8Fund); } }
15,737
127
// Safe city transfer function, just in case if rounding error causes pool to not have enough CITYs.
function safeCityTransfer(address _to, uint256 _amount) internal { uint256 cityBal = city.balanceOf(address(this)); if (_amount > cityBal) { city.transfer(_to, cityBal); } else { city.transfer(_to, _amount); } }
function safeCityTransfer(address _to, uint256 _amount) internal { uint256 cityBal = city.balanceOf(address(this)); if (_amount > cityBal) { city.transfer(_to, cityBal); } else { city.transfer(_to, _amount); } }
40,545
81
// 100% == 1 ether; for ex. for 1% extra usdc to unwrap set to 1.01 ether
uint256 public immutable extraOutPct; constructor( address tokenOut_, address zap_, uint256 extraOutPct_
uint256 public immutable extraOutPct; constructor( address tokenOut_, address zap_, uint256 extraOutPct_
16,098
232
// Can not tranche bonds for 3 days from last execution of this function /
function trancheBonds() external override isActive endCoolTime { uint256 currentPriceE8 = ORACLE.latestPrice(); uint256 bondGroupId = _getSuitableBondGroup(currentPriceE8); if (bondGroupId == 0) { bondGroupId = _addSuitableBondGroup(currentPriceE8); } (uint256 amount, uint256 ethAmount, uint256[2] memory reverseBonds) = STRATEGY .getTrancheBonds( BONDMAKER, address(this), bondGroupId, currentPriceE8, issuableBondGroupIds[currentTerm], priceUnit, REVERSE_ORACLE ); if (ethAmount > 0) { DOTC.depositEth{value: ethAmount}(); } if (reverseBonds[1] > 0) { // Burn bond and get collateral asset require( BONDMAKER.reverseBondGroupToCollateral(reverseBonds[0], reverseBonds[1]), "Reverse" ); } if (amount > 0) { _issueBonds(bondGroupId, amount); } lastTrancheTime = block.timestamp.toUint64(); emit TrancheBond( uint64(bondGroupId), uint64(amount), uint64(reverseBonds[0]), uint64(reverseBonds[1]) ); }
function trancheBonds() external override isActive endCoolTime { uint256 currentPriceE8 = ORACLE.latestPrice(); uint256 bondGroupId = _getSuitableBondGroup(currentPriceE8); if (bondGroupId == 0) { bondGroupId = _addSuitableBondGroup(currentPriceE8); } (uint256 amount, uint256 ethAmount, uint256[2] memory reverseBonds) = STRATEGY .getTrancheBonds( BONDMAKER, address(this), bondGroupId, currentPriceE8, issuableBondGroupIds[currentTerm], priceUnit, REVERSE_ORACLE ); if (ethAmount > 0) { DOTC.depositEth{value: ethAmount}(); } if (reverseBonds[1] > 0) { // Burn bond and get collateral asset require( BONDMAKER.reverseBondGroupToCollateral(reverseBonds[0], reverseBonds[1]), "Reverse" ); } if (amount > 0) { _issueBonds(bondGroupId, amount); } lastTrancheTime = block.timestamp.toUint64(); emit TrancheBond( uint64(bondGroupId), uint64(amount), uint64(reverseBonds[0]), uint64(reverseBonds[1]) ); }
9,997
15
// Marketing & Business Development245,000,000 (18.85%)
uint constant public maxMKTBDSupply = 245000000 * E18;
uint constant public maxMKTBDSupply = 245000000 * E18;
11,160
215
// borrowFresh emits borrow-specific logs on errors, so we don't need to
return borrowFresh(msg.sender, borrowAmount);
return borrowFresh(msg.sender, borrowAmount);
3,453
12
// ba doi co tong duong chay duoc dai nhat doi co nhieu thanh vien nhat va thuc hien chay tren 50% cu li
function Top3TeamByDistance_Top1TeamByMember() view public returns(string memory note,Team memory top1, Team memory top2, Team memory top3, Team memory top1_member){ Team[] memory sums = new Team[](athletes.length); uint count = 1; sums[0].teamid = athletes[0].teamid; sums[0].totalDistance = athletes[0].distance; sums[0].totalCompleteDistance = athletes[0].conpletedistance; sums[0].sldk = 1; for(uint i = 1; i < athletes.length; i++) { bool flag = false; for(uint j= 0; j< count; j++){ if(athletes[i].teamid == sums[j].teamid){ sums[j].totalDistance += athletes[i].distance; sums[j].totalCompleteDistance += athletes[i].conpletedistance; sums[j].sldk += 1; flag = true; } } if(flag == false){ sums[count].teamid = athletes[i].teamid; sums[count].totalDistance = athletes[i].distance; sums[count].totalCompleteDistance = athletes[i].conpletedistance; sums[count].sldk = 1; count++; } } for (uint i = 0; i < count - 1; i++){ for(uint j = i+1; j < count; j++){ if(sums[i].totalCompleteDistance < sums[j].totalCompleteDistance){ Team memory temp = sums[i]; sums[i] = sums[j]; sums[j] = temp; } } } note = "Team, Tong khoang cach, Tong khoang cach da chay, SL Thanh vien"; top1 = sums[0]; top2 = sums[1]; top3 = sums[2]; //Tim team co so thanh vien nhieu nhat va chay tren 50% cu ly for (uint i = 0; i < count - 1; i++){ for(uint j = i+1; j < count; j++){ if(sums[i].sldk < sums[j].sldk){ Team memory temp = sums[i]; sums[i] = sums[j]; sums[j] = temp; } } } for(uint i = 0; i < count; i++){ if(sums[i].totalCompleteDistance > sums[i].totalDistance/2){ top1_member = sums[i]; break; } } }
function Top3TeamByDistance_Top1TeamByMember() view public returns(string memory note,Team memory top1, Team memory top2, Team memory top3, Team memory top1_member){ Team[] memory sums = new Team[](athletes.length); uint count = 1; sums[0].teamid = athletes[0].teamid; sums[0].totalDistance = athletes[0].distance; sums[0].totalCompleteDistance = athletes[0].conpletedistance; sums[0].sldk = 1; for(uint i = 1; i < athletes.length; i++) { bool flag = false; for(uint j= 0; j< count; j++){ if(athletes[i].teamid == sums[j].teamid){ sums[j].totalDistance += athletes[i].distance; sums[j].totalCompleteDistance += athletes[i].conpletedistance; sums[j].sldk += 1; flag = true; } } if(flag == false){ sums[count].teamid = athletes[i].teamid; sums[count].totalDistance = athletes[i].distance; sums[count].totalCompleteDistance = athletes[i].conpletedistance; sums[count].sldk = 1; count++; } } for (uint i = 0; i < count - 1; i++){ for(uint j = i+1; j < count; j++){ if(sums[i].totalCompleteDistance < sums[j].totalCompleteDistance){ Team memory temp = sums[i]; sums[i] = sums[j]; sums[j] = temp; } } } note = "Team, Tong khoang cach, Tong khoang cach da chay, SL Thanh vien"; top1 = sums[0]; top2 = sums[1]; top3 = sums[2]; //Tim team co so thanh vien nhieu nhat va chay tren 50% cu ly for (uint i = 0; i < count - 1; i++){ for(uint j = i+1; j < count; j++){ if(sums[i].sldk < sums[j].sldk){ Team memory temp = sums[i]; sums[i] = sums[j]; sums[j] = temp; } } } for(uint i = 0; i < count; i++){ if(sums[i].totalCompleteDistance > sums[i].totalDistance/2){ top1_member = sums[i]; break; } } }
28,972
452
// Service function to calculate and pay pending vault and yield rewards to the senderInternally executes similar function `_processRewards` from the parent smart contract to calculate and pay yield rewards; adds vault rewards processingCan be executed by anyone at any time, but has an effect only when executed by deposit holder and when at least one block passes from the previous reward processing Executed internally when "staking as a pool" (`stakeAsPool`) When timing conditions are not met (executed too frequently, or after factory end block), function doesn't throw and exits silently_useSILV flag has a context of yield rewards only_useSILV flag indicating
function processRewards(bool _useSILV) external override { _processRewards(msg.sender, _useSILV, true); }
function processRewards(bool _useSILV) external override { _processRewards(msg.sender, _useSILV, true); }
68,156
66
// check imbalance
int totalImbalance; int blockImbalance; (totalImbalance, blockImbalance) = getImbalance(token, updateRateBlock, currentBlockNumber);
int totalImbalance; int blockImbalance; (totalImbalance, blockImbalance) = getImbalance(token, updateRateBlock, currentBlockNumber);
45,973
105
// Bonus in percent added to donations at beginning of donation round 1
uint public constant round1InitialBonus = 25;
uint public constant round1InitialBonus = 25;
37,368
1,015
// Cancels fund migration/_vaultProxy The VaultProxy for which to cancel migration
function cancelMigration(address _vaultProxy) external { __cancelMigration(_vaultProxy, false); }
function cancelMigration(address _vaultProxy) external { __cancelMigration(_vaultProxy, false); }
83,082
8
// mint new OHM using excess reserves _recipient address _amount uint256 /
function mint(address _recipient, uint256 _amount) external override { require(permissions[STATUS.REWARDMANAGER][msg.sender], notApproved); require(_amount <= excessReserves(), insufficientReserves); OHM.mint(_recipient, _amount); emit Minted(msg.sender, _recipient, _amount); }
function mint(address _recipient, uint256 _amount) external override { require(permissions[STATUS.REWARDMANAGER][msg.sender], notApproved); require(_amount <= excessReserves(), insufficientReserves); OHM.mint(_recipient, _amount); emit Minted(msg.sender, _recipient, _amount); }
21,020
205
// Price
uint256 public constant PRE_SALES_PRICE = PUBLIC_SALES_PRICE; uint256 public constant PUBLIC_SALES_PRICE = 0.3 ether; bool public isSaleActive = false; bool public isBurnEnabled = false; event SaleStarted(); event SalePaused(); event PubSaleMinted(address indexed minter, uint256 amount, uint256 supply); event PreSaleMinted(address indexed minter, uint256 amount, uint256 supply);
uint256 public constant PRE_SALES_PRICE = PUBLIC_SALES_PRICE; uint256 public constant PUBLIC_SALES_PRICE = 0.3 ether; bool public isSaleActive = false; bool public isBurnEnabled = false; event SaleStarted(); event SalePaused(); event PubSaleMinted(address indexed minter, uint256 amount, uint256 supply); event PreSaleMinted(address indexed minter, uint256 amount, uint256 supply);
20,793
34
// Emitted when `account` is revoked `role`. `sender` is the account that originated the contract call:- if using `revokeRole`, it is the admin role bearer /
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
54,711
29
// Reverts on failure
_feeHandler.collectFee{value: msg.value}(sender, _domainID, destinationDomainID, resourceID, depositData, feeData);
_feeHandler.collectFee{value: msg.value}(sender, _domainID, destinationDomainID, resourceID, depositData, feeData);
15,427
51
// Returns whether or not a domain's metadata is locked id The domain /
function isDomainMetadataLocked(uint256 id) public view override returns (bool)
function isDomainMetadataLocked(uint256 id) public view override returns (bool)
74,073
1
// Creates a new blob. It is guaranteed that different users will never receive the same blobId, even before consensus has been reached. This prevents blobId sniping. Consider createWithNonce() if not calling from another contract. flags Packed blob settings. contents Contents of the blob to be stored.return blobId Id of the blob. /
function create(bytes4 flags, bytes contents) external returns (bytes20 blobId);
function create(bytes4 flags, bytes contents) external returns (bytes20 blobId);
780
25
// ballot redemption rate rate in bits 56-71 (16 bits). ballot redemption rate is a number 0-10000. Store the reverse so the most common case of 100% results in no storage needs.
packed |= (JBConstants.MAX_REDEMPTION_RATE - _metadata.ballotRedemptionRate) << 56;
packed |= (JBConstants.MAX_REDEMPTION_RATE - _metadata.ballotRedemptionRate) << 56;
23,942
68
// Sync the book-keeping variable to be up-to-date for the next transfer
lastTotalSupplyOfLPTokens = _LPSupplyOfPairTotal; _;
lastTotalSupplyOfLPTokens = _LPSupplyOfPairTotal; _;
22,707
194
// Revert if you try to claim a protected token, this is to avoid rugging
_onlyNotProtectedTokens(token);
_onlyNotProtectedTokens(token);
25,896
20
// WE WILL USE IT TO RETRIEVE INFORMATION FOR THE ESCROW SO THAT THE ESCROW CAN ALSO SEEWHAT IS HAPPENING.
13,385
73
// В редких случаях может быть связывание с НА+предл. падеж
wordentry_set Сущ_НА_Предл=существительное:{ заявление, // Заявление на материнский капитал оформляется в органах Пенсионного фонда по месту жительства. проводы, // Ежегодно устраиваются торжественные проводы на пенсию. пересадка, // В Москве предстоит пересадка на Сочи. испытание, // Начинаются испытания стволовых клеток на людях ПОЕДИНОК, // но была большая разница между поединком на рапирах и грязной поножовщиной без всяких правил СОБЫТИЕ, // События на Кипре - сигнал большой опасности для России. (СОБЫТИЕ) БЕЗОПАСНОСТЬ, // NASA усиливает безопасность на своих объектах (БЕЗОПАСНОСТЬ) ЕЗДА, // снаряжение для езды на лошади (ЕЗДА) наличие, // Доказательство наличия подповерхностного океана на Европе проверка, // Чиновников отстранили от госзаказа после проверки на полиграфе СЛУЖБА, // Служба на каникулах помешает учебному процессу (СЛУЖБА) ПЯТНО, // Гигантское пятно на Солнце может привести к солнечным бурям (ПЯТНО) ПОРЯДОК, // По мнению руководителя администрации города , продление сроков операции позволит , во-первых , навести порядок на рынке пиротехники (ПОРЯДОК НА предл) ВОЗРОЖДЕНИЕ, // Общественная оборона — это возрождение идеи и практики земства на новом уровне развития русского общества (ВОЗРОЖДЕНИЕ НА) АВАРИЯ, // Я очень сожалею , что произошла авария на одной из наших шахт (АВАРИЯ) ПОЗИЦИЯ, // Политик пояснил , что различные страны продолжают осуществлять политику по укреплению своих позиций на Южном Кавказе (ПОЗИЦИЯ НА) ГОЛОСОВАНИЕ, // Мне также довелось отслеживать процесс голосования на избирательном участке , расположенном на территории исправительной колонии (ГОЛОСОВАНИЕ НА предл) ГИБЕЛЬ, // В Москве проводится проверка по факту гибели людей на железнодорожных путях (ГИБЕЛЬ НА) давка, // Снегопад парализовал Москву и привёл к давке на некоторых станциях столичного метро (давка на) интервенция, // Они даже рассматривали военные интервенции на Ближнем Востоке как способ что-то изменить (ИНТЕРВЕНЦИЯ НА предл) покров, // Почему у человека редуцировался волосяной покров на теле? (ПОКРОВ НА) убийство, // Он совершил убийство на почве ревности. (УБИЙСТВО НА ПОЧВЕ ...) поездка, // Москвичей призывают воздержаться от поездок на личных автомобилях. (ПОЕЗДКА НА чем-то) проблема, // Вслед за Западной Украиной проблемы на дорогах начались в восточных областях (проблема на) поражение, // Лидер оппозиции Южной Кореи признал поражение на выборах. (ПОРАЖЕНИЕ НА) ситуация, // Два министерства по-разному оценивают ситуацию на дорогах в западных областях (СИТУАЦИЯ НА) опыт, // Опыты на крысах показали, что употребление сахара вызывает зависимость (ОПЫТ НА) взрыв, // Взрыв на мясокомбинате в Мордовии (ВЗРЫВ НА) катастрофа, // все помнят ту катастрофу на комбинате (КАТАСТРОФА НА) операция, // Ему сделали операцию на сердце. (ОПЕРАЦИЯ НА) торг, // возобновление торгов на бирже (торг на) напряжение, // регулировать напряжением на базе игра, // обучиться игре на скрипке оглавление, // книга с картинками и оглавлением на иностранном языке пожар, // пожар на фабрике огнетушителей доля, // Банки увеличивают свою долю на рынке пластиковых карт. присутствие, // Мелкие банки усиливают свое присутствие на рынке розничного кредитования. обстановка, // Обстановка на дороге осложнена густым туманом. трагедия, // трагедия на авиашоу программирование, // прослушать учебный курс по программированию на функциональных языках работа, // работа на стройках коммунизма изображение, // четкое изображение на экране случай, // С ним произошел несчастный случай на охоте выступление, // Это было моё первое выступление на сцене. применение, // Эта теория находит широкое применение на практике. дело, // Дела на фронте поправляются. преподавание, // в вузы можно вернуть преподавание на русском языке исчезновение, // Исчезновение на 7-ой улице трещина, // трещины на коже торговля, // стандарт для торговли на лондонской бирже металла сандалия // соломенные сандалии на верёвочной подошве }
wordentry_set Сущ_НА_Предл=существительное:{ заявление, // Заявление на материнский капитал оформляется в органах Пенсионного фонда по месту жительства. проводы, // Ежегодно устраиваются торжественные проводы на пенсию. пересадка, // В Москве предстоит пересадка на Сочи. испытание, // Начинаются испытания стволовых клеток на людях ПОЕДИНОК, // но была большая разница между поединком на рапирах и грязной поножовщиной без всяких правил СОБЫТИЕ, // События на Кипре - сигнал большой опасности для России. (СОБЫТИЕ) БЕЗОПАСНОСТЬ, // NASA усиливает безопасность на своих объектах (БЕЗОПАСНОСТЬ) ЕЗДА, // снаряжение для езды на лошади (ЕЗДА) наличие, // Доказательство наличия подповерхностного океана на Европе проверка, // Чиновников отстранили от госзаказа после проверки на полиграфе СЛУЖБА, // Служба на каникулах помешает учебному процессу (СЛУЖБА) ПЯТНО, // Гигантское пятно на Солнце может привести к солнечным бурям (ПЯТНО) ПОРЯДОК, // По мнению руководителя администрации города , продление сроков операции позволит , во-первых , навести порядок на рынке пиротехники (ПОРЯДОК НА предл) ВОЗРОЖДЕНИЕ, // Общественная оборона — это возрождение идеи и практики земства на новом уровне развития русского общества (ВОЗРОЖДЕНИЕ НА) АВАРИЯ, // Я очень сожалею , что произошла авария на одной из наших шахт (АВАРИЯ) ПОЗИЦИЯ, // Политик пояснил , что различные страны продолжают осуществлять политику по укреплению своих позиций на Южном Кавказе (ПОЗИЦИЯ НА) ГОЛОСОВАНИЕ, // Мне также довелось отслеживать процесс голосования на избирательном участке , расположенном на территории исправительной колонии (ГОЛОСОВАНИЕ НА предл) ГИБЕЛЬ, // В Москве проводится проверка по факту гибели людей на железнодорожных путях (ГИБЕЛЬ НА) давка, // Снегопад парализовал Москву и привёл к давке на некоторых станциях столичного метро (давка на) интервенция, // Они даже рассматривали военные интервенции на Ближнем Востоке как способ что-то изменить (ИНТЕРВЕНЦИЯ НА предл) покров, // Почему у человека редуцировался волосяной покров на теле? (ПОКРОВ НА) убийство, // Он совершил убийство на почве ревности. (УБИЙСТВО НА ПОЧВЕ ...) поездка, // Москвичей призывают воздержаться от поездок на личных автомобилях. (ПОЕЗДКА НА чем-то) проблема, // Вслед за Западной Украиной проблемы на дорогах начались в восточных областях (проблема на) поражение, // Лидер оппозиции Южной Кореи признал поражение на выборах. (ПОРАЖЕНИЕ НА) ситуация, // Два министерства по-разному оценивают ситуацию на дорогах в западных областях (СИТУАЦИЯ НА) опыт, // Опыты на крысах показали, что употребление сахара вызывает зависимость (ОПЫТ НА) взрыв, // Взрыв на мясокомбинате в Мордовии (ВЗРЫВ НА) катастрофа, // все помнят ту катастрофу на комбинате (КАТАСТРОФА НА) операция, // Ему сделали операцию на сердце. (ОПЕРАЦИЯ НА) торг, // возобновление торгов на бирже (торг на) напряжение, // регулировать напряжением на базе игра, // обучиться игре на скрипке оглавление, // книга с картинками и оглавлением на иностранном языке пожар, // пожар на фабрике огнетушителей доля, // Банки увеличивают свою долю на рынке пластиковых карт. присутствие, // Мелкие банки усиливают свое присутствие на рынке розничного кредитования. обстановка, // Обстановка на дороге осложнена густым туманом. трагедия, // трагедия на авиашоу программирование, // прослушать учебный курс по программированию на функциональных языках работа, // работа на стройках коммунизма изображение, // четкое изображение на экране случай, // С ним произошел несчастный случай на охоте выступление, // Это было моё первое выступление на сцене. применение, // Эта теория находит широкое применение на практике. дело, // Дела на фронте поправляются. преподавание, // в вузы можно вернуть преподавание на русском языке исчезновение, // Исчезновение на 7-ой улице трещина, // трещины на коже торговля, // стандарт для торговли на лондонской бирже металла сандалия // соломенные сандалии на верёвочной подошве }
27,575
69
// Update the server-side signers for this nft contracton SeaDrop.Only the owner can use this function.seaDropImplThe allowed SeaDrop contract. signer The signer to update. signedMintValidationParams Minimum and maximum parameters toenforce for signed mints. /
function updateSignedMintValidationParams( address seaDropImpl, address signer, SignedMintValidationParams memory signedMintValidationParams
function updateSignedMintValidationParams( address seaDropImpl, address signer, SignedMintValidationParams memory signedMintValidationParams
20,357
609
// Calls marketSellOrdersNoThrow then reverts if < takerAssetFillAmount has been sold./NOTE: This function does not enforce that the takerAsset is the same for each order./orders Array of order specifications./takerAssetFillAmount Minimum amount of takerAsset to sell./signatures Proofs that orders have been signed by makers./ return Amounts filled and fees paid by makers and taker.
function marketSellOrdersFillOrKill( LibOrder.Order[] memory orders, uint256 takerAssetFillAmount, bytes[] memory signatures ) public payable returns (LibFillResults.FillResults memory fillResults);
function marketSellOrdersFillOrKill( LibOrder.Order[] memory orders, uint256 takerAssetFillAmount, bytes[] memory signatures ) public payable returns (LibFillResults.FillResults memory fillResults);
54,998
4
// _setTokenURI(nextTokenIdToMint(), string(abi.encodePacked( placeholderURIPrefix,Strings.toString(_tokenId),"?random=",Strings.toString(_random))));
_safeMint(_burnerAddress, 1, ""); emit MintViaLootbox(_tokenId, _burnerAddress, msg.sender);
_safeMint(_burnerAddress, 1, ""); emit MintViaLootbox(_tokenId, _burnerAddress, msg.sender);
31,033
373
// if we are withdrawing we take more to cover fee
cToken.redeemUnderlying(repayAmount);
cToken.redeemUnderlying(repayAmount);
47,279
78
// Modifier to make a function callable only when the contract has transfer fees enabled. /
modifier whenFeesEnabled() { require(feesEnabled); _; }
modifier whenFeesEnabled() { require(feesEnabled); _; }
23,157
99
// Update the lockFromBlock
function lockFromUpdate(uint256 _newLockFrom) public onlyAuthorized { lockFromBlock = _newLockFrom; }
function lockFromUpdate(uint256 _newLockFrom) public onlyAuthorized { lockFromBlock = _newLockFrom; }
6,790
33
// do we have against votes for this sender?
if (votesAgainst > 0) {
if (votesAgainst > 0) {
25,636
44
// the user still has qty that they desire to contribute to the exchange for liquidity
( tokenQtys.baseTokenQty, tokenQtys.quoteTokenQty, tokenQtys.liquidityTokenQty ) = calculateAddTokenPairLiquidityQuantities( _baseTokenQtyDesired - baseTokenQtyFromDecay, // safe from underflow quoted on above IF _quoteTokenQtyDesired - quoteTokenQtyFromDecay, // safe from underflow quoted on above IF 0, // we will check minimums below 0, // we will check minimums below _totalSupplyOfLiquidityTokens +
( tokenQtys.baseTokenQty, tokenQtys.quoteTokenQty, tokenQtys.liquidityTokenQty ) = calculateAddTokenPairLiquidityQuantities( _baseTokenQtyDesired - baseTokenQtyFromDecay, // safe from underflow quoted on above IF _quoteTokenQtyDesired - quoteTokenQtyFromDecay, // safe from underflow quoted on above IF 0, // we will check minimums below 0, // we will check minimums below _totalSupplyOfLiquidityTokens +
39,502
4
// Checks the validity of a Bitcoin signed request & the expiration date. requestData bytes containing all the data packed : payeesPaymentAddress array of payees payment addresses (the index 0 will be the payee the others are subPayees) expirationDate timestamp after that the signed request cannot be broadcasted signature ECDSA signature containing v, r and s as bytes return Validity of order signature. /
function checkBtcRequestSignature( bytes requestData, bytes payeesPaymentAddress, uint256 expirationDate, bytes signature) internal view returns (bool)
function checkBtcRequestSignature( bytes requestData, bytes payeesPaymentAddress, uint256 expirationDate, bytes signature) internal view returns (bool)
7,443
277
// Return list of whitelisted addresses
function feeWhitelist() external view returns (address[] memory) { return _feeWhitelist.values(); }
function feeWhitelist() external view returns (address[] memory) { return _feeWhitelist.values(); }
59,260
44
// Check if the _transactionHash exists and this balance hasn't been received already. We would normally do this with a require(), but to keep it more private we need themethod to be executed also if it will not result.
if (balances[_transactionHash] == 0) { emit RetrieveSuccess(0); return false; }
if (balances[_transactionHash] == 0) { emit RetrieveSuccess(0); return false; }
60,536
18
// Escrow contract for ERC20 token based escrows /
contract ERC20Escrow { using SafeMath for uint256; using SafeERC20 for IERC20; using ECDSA for bytes32; event FundsDeposited(address indexed buyer, uint256 amount); event FundsRefunded(); event FundsReleased(address indexed seller, uint256 amount); event DisputeResolved(); event OwnershipTransferred(address indexed oldOwner, address newOwner); event MediatorChanged(address indexed oldMediator, address newMediator); enum Status { AWAITING_PAYMENT, PAID, REFUNDED, MEDIATED, COMPLETE } Status public status; bytes32 public escrowID; uint256 public amount; uint256 public fee; uint256 public commission; address public owner; address public mediator; address public affiliate; address public buyer; address public seller; IERC20 public token; bool public funded = false; bool public completed = false; bytes32 public releaseMsgHash; bytes32 public resolveMsgHash; modifier onlyBuyer() { require(msg.sender == buyer, "Only the buyer can call this function."); _; } modifier onlyWithBuyerSignature(bytes32 hash, bytes memory signature) { require( hash.toEthSignedMessageHash() .recover(signature) == buyer, "Must be signed by buyer." ); _; } modifier onlyWithParticipantSignature(bytes32 hash, bytes memory signature) { address signer = hash.toEthSignedMessageHash() .recover(signature); require( signer == buyer || signer == seller, "Must be signed by either buyer or seller." ); _; } modifier onlySeller() { require(msg.sender == seller, "Only the seller can call this function."); _; } modifier onlyOwner() { require(msg.sender == owner, "Only the owner can call this function."); _; } modifier onlyMediator() { require(msg.sender == mediator, "Only the mediator can call this function."); _; } modifier onlyUnfunded() { require(funded == false, "Escrow already funded."); funded = true; _; } modifier onlyFunded() { require(funded == true, "Escrow not funded."); _; } modifier onlyIncompleted() { require(completed == false, "Escrow already completed."); completed = true; _; } constructor( bytes32 _escrowID, IERC20 _token, address _owner, address _buyer, address _seller, address _mediator, address _affiliate, uint256 _amount, uint256 _fee, uint256 _commission ) { status = Status.AWAITING_PAYMENT; escrowID = _escrowID; token = _token; owner = _owner; buyer = _buyer; mediator = _mediator; affiliate = _affiliate; seller = _seller; amount = _amount; fee = _fee; commission = _commission; releaseMsgHash = keccak256( abi.encodePacked("releaseFunds()", escrowID, address(this)) ); resolveMsgHash = keccak256( abi.encodePacked("resolveDispute()", escrowID, address(this)) ); emit OwnershipTransferred(address(0), _owner); emit MediatorChanged(address(0), _owner); } function depositAmount() public view returns (uint256) { return amount; } function deposit() public onlyUnfunded { token.safeTransferFrom(msg.sender, address(this), depositAmount()); status = Status.PAID; emit FundsDeposited(msg.sender, depositAmount()); } function _releaseFees() private { token.safeTransfer(mediator, fee); if (affiliate != address(0) && commission > 0) { token.safeTransfer(affiliate, commission); } } function refund() public onlySeller onlyFunded onlyIncompleted { token.safeTransfer(buyer, depositAmount()); status = Status.REFUNDED; emit FundsRefunded(); } function releaseFunds( bytes calldata _signature ) external onlyFunded onlyIncompleted onlyWithBuyerSignature(releaseMsgHash, _signature) { uint256 releaseAmount = depositAmount().sub(fee); if (affiliate != address(0) && commission > 0) { releaseAmount = releaseAmount.sub(commission); } token.safeTransfer(seller, releaseAmount); _releaseFees(); status = Status.COMPLETE; emit FundsReleased(seller, releaseAmount); } function resolveDispute( bytes calldata _signature, uint8 _buyerPercent ) external onlyFunded onlyMediator onlyIncompleted onlyWithParticipantSignature(resolveMsgHash, _signature) { require(_buyerPercent <= 100, "_buyerPercent must be 100 or lower"); uint256 releaseAmount = depositAmount().sub(fee); if (affiliate != address(0) && commission > 0) { releaseAmount = releaseAmount.sub(commission); } status = Status.MEDIATED; emit DisputeResolved(); if (_buyerPercent > 0) token.safeTransfer(buyer, releaseAmount.mul(uint256(_buyerPercent)).div(100)); if (_buyerPercent < 100) token.safeTransfer(seller, releaseAmount.mul(uint256(100).sub(_buyerPercent)).div(100)); _releaseFees(); } function setOwner(address _newOwner) external onlyOwner { emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } function setMediator(address _newMediator) external onlyOwner { emit MediatorChanged(mediator, _newMediator); mediator = _newMediator; } }
contract ERC20Escrow { using SafeMath for uint256; using SafeERC20 for IERC20; using ECDSA for bytes32; event FundsDeposited(address indexed buyer, uint256 amount); event FundsRefunded(); event FundsReleased(address indexed seller, uint256 amount); event DisputeResolved(); event OwnershipTransferred(address indexed oldOwner, address newOwner); event MediatorChanged(address indexed oldMediator, address newMediator); enum Status { AWAITING_PAYMENT, PAID, REFUNDED, MEDIATED, COMPLETE } Status public status; bytes32 public escrowID; uint256 public amount; uint256 public fee; uint256 public commission; address public owner; address public mediator; address public affiliate; address public buyer; address public seller; IERC20 public token; bool public funded = false; bool public completed = false; bytes32 public releaseMsgHash; bytes32 public resolveMsgHash; modifier onlyBuyer() { require(msg.sender == buyer, "Only the buyer can call this function."); _; } modifier onlyWithBuyerSignature(bytes32 hash, bytes memory signature) { require( hash.toEthSignedMessageHash() .recover(signature) == buyer, "Must be signed by buyer." ); _; } modifier onlyWithParticipantSignature(bytes32 hash, bytes memory signature) { address signer = hash.toEthSignedMessageHash() .recover(signature); require( signer == buyer || signer == seller, "Must be signed by either buyer or seller." ); _; } modifier onlySeller() { require(msg.sender == seller, "Only the seller can call this function."); _; } modifier onlyOwner() { require(msg.sender == owner, "Only the owner can call this function."); _; } modifier onlyMediator() { require(msg.sender == mediator, "Only the mediator can call this function."); _; } modifier onlyUnfunded() { require(funded == false, "Escrow already funded."); funded = true; _; } modifier onlyFunded() { require(funded == true, "Escrow not funded."); _; } modifier onlyIncompleted() { require(completed == false, "Escrow already completed."); completed = true; _; } constructor( bytes32 _escrowID, IERC20 _token, address _owner, address _buyer, address _seller, address _mediator, address _affiliate, uint256 _amount, uint256 _fee, uint256 _commission ) { status = Status.AWAITING_PAYMENT; escrowID = _escrowID; token = _token; owner = _owner; buyer = _buyer; mediator = _mediator; affiliate = _affiliate; seller = _seller; amount = _amount; fee = _fee; commission = _commission; releaseMsgHash = keccak256( abi.encodePacked("releaseFunds()", escrowID, address(this)) ); resolveMsgHash = keccak256( abi.encodePacked("resolveDispute()", escrowID, address(this)) ); emit OwnershipTransferred(address(0), _owner); emit MediatorChanged(address(0), _owner); } function depositAmount() public view returns (uint256) { return amount; } function deposit() public onlyUnfunded { token.safeTransferFrom(msg.sender, address(this), depositAmount()); status = Status.PAID; emit FundsDeposited(msg.sender, depositAmount()); } function _releaseFees() private { token.safeTransfer(mediator, fee); if (affiliate != address(0) && commission > 0) { token.safeTransfer(affiliate, commission); } } function refund() public onlySeller onlyFunded onlyIncompleted { token.safeTransfer(buyer, depositAmount()); status = Status.REFUNDED; emit FundsRefunded(); } function releaseFunds( bytes calldata _signature ) external onlyFunded onlyIncompleted onlyWithBuyerSignature(releaseMsgHash, _signature) { uint256 releaseAmount = depositAmount().sub(fee); if (affiliate != address(0) && commission > 0) { releaseAmount = releaseAmount.sub(commission); } token.safeTransfer(seller, releaseAmount); _releaseFees(); status = Status.COMPLETE; emit FundsReleased(seller, releaseAmount); } function resolveDispute( bytes calldata _signature, uint8 _buyerPercent ) external onlyFunded onlyMediator onlyIncompleted onlyWithParticipantSignature(resolveMsgHash, _signature) { require(_buyerPercent <= 100, "_buyerPercent must be 100 or lower"); uint256 releaseAmount = depositAmount().sub(fee); if (affiliate != address(0) && commission > 0) { releaseAmount = releaseAmount.sub(commission); } status = Status.MEDIATED; emit DisputeResolved(); if (_buyerPercent > 0) token.safeTransfer(buyer, releaseAmount.mul(uint256(_buyerPercent)).div(100)); if (_buyerPercent < 100) token.safeTransfer(seller, releaseAmount.mul(uint256(100).sub(_buyerPercent)).div(100)); _releaseFees(); } function setOwner(address _newOwner) external onlyOwner { emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } function setMediator(address _newMediator) external onlyOwner { emit MediatorChanged(mediator, _newMediator); mediator = _newMediator; } }
8,388
77
// Name
ERC721B("THE MAON", "TMN") { }
ERC721B("THE MAON", "TMN") { }
5,514
178
// Return the value of the approval status for the DB
function getArtApproval(uint _tokennumber, address _wallet) public view returns (bool)
function getArtApproval(uint _tokennumber, address _wallet) public view returns (bool)
3,354
55
// Make sure block timestamp exceeds nextEarliestUpdate
require( block.timestamp >= nextEarliestUpdate, "TimeSeriesFeed.poke: Not enough time elapsed since last update" ); TimeSeriesStateLibrary.State memory timeSeriesState = getTimeSeriesFeedState();
require( block.timestamp >= nextEarliestUpdate, "TimeSeriesFeed.poke: Not enough time elapsed since last update" ); TimeSeriesStateLibrary.State memory timeSeriesState = getTimeSeriesFeedState();
18,895
101
// breed
rarities[1] = [255, 255, 255, 255, 255, 255, 255, 255]; aliases[1] = [7, 7, 7, 7, 7, 7, 7, 7];
rarities[1] = [255, 255, 255, 255, 255, 255, 255, 255]; aliases[1] = [7, 7, 7, 7, 7, 7, 7, 7];
17,025
4,922
// 2462
entry "gentlehanded" : ENG_ADJECTIVE
entry "gentlehanded" : ENG_ADJECTIVE
19,074
25
// compute time bonus earned as a function of staking time time length of time for which the tokens have been stakedreturn bonus multiplier for time /
function timeBonus(uint256 time) public view returns (uint256) { if (time >= bonusPeriod) { return 10**DECIMALS + bonusMax; } // linearly interpolate between bonus min and bonus max uint256 bonus = bonusMin + ((bonusMax - bonusMin) * time) / bonusPeriod; return 10**DECIMALS + bonus; }
function timeBonus(uint256 time) public view returns (uint256) { if (time >= bonusPeriod) { return 10**DECIMALS + bonusMax; } // linearly interpolate between bonus min and bonus max uint256 bonus = bonusMin + ((bonusMax - bonusMin) * time) / bonusPeriod; return 10**DECIMALS + bonus; }
31,364
415
// Internal function encoding a trade parameter into a bytes32 variable needed for Notional _tradeType, Identification of the trade to perform, following the Notional classification in enum 'TradeActionType' _marketIndex, Market index in which to trade into _amount, fCash amount to tradereturn bytes32 result, the encoded trade ready to be used in Notional's 'BatchTradeAction' /
function getTradeFrom(uint8 _tradeType, uint256 _marketIndex, uint256 _amount) internal returns (bytes32 result) { uint8 tradeType = uint8(_tradeType); uint8 marketIndex = uint8(_marketIndex); uint88 fCashAmount = uint88(_amount); uint32 minSlippage = uint32(0); uint120 padding = uint120(0); // We create result of trade in a bitmap packed encoded bytes32 // (unpacking of the trade in Notional happens here: // https://github.com/notional-finance/contracts-v2/blob/master/contracts/external/actions/TradingAction.sol#L322) result = bytes32(uint(tradeType)) << 248; result |= bytes32(uint(marketIndex) << 240); result |= bytes32(uint(fCashAmount) << 152); result |= bytes32(uint(minSlippage) << 120); return result; }
function getTradeFrom(uint8 _tradeType, uint256 _marketIndex, uint256 _amount) internal returns (bytes32 result) { uint8 tradeType = uint8(_tradeType); uint8 marketIndex = uint8(_marketIndex); uint88 fCashAmount = uint88(_amount); uint32 minSlippage = uint32(0); uint120 padding = uint120(0); // We create result of trade in a bitmap packed encoded bytes32 // (unpacking of the trade in Notional happens here: // https://github.com/notional-finance/contracts-v2/blob/master/contracts/external/actions/TradingAction.sol#L322) result = bytes32(uint(tradeType)) << 248; result |= bytes32(uint(marketIndex) << 240); result |= bytes32(uint(fCashAmount) << 152); result |= bytes32(uint(minSlippage) << 120); return result; }
2,331
19
// Emits a {EnableUserRedeemAddress} event. Requirements: - `_account` should be a registered as user.- `_account` should be KYC verified. /
function enableRedeemAddress(address _account) public onlyOwner { require(_isUser(_account), "not a user"); require(_isKyced(_account), "user has not KYC"); setAttribute(getRedeemAddress(_account), CAN_BURN, 1); emit EnableRedeemAddress(_account); }
function enableRedeemAddress(address _account) public onlyOwner { require(_isUser(_account), "not a user"); require(_isKyced(_account), "user has not KYC"); setAttribute(getRedeemAddress(_account), CAN_BURN, 1); emit EnableRedeemAddress(_account); }
54,715
130
// add the liquidity
uniswapV2Router.addLiquidityETH{ value: ethAmount }(
uniswapV2Router.addLiquidityETH{ value: ethAmount }(
22,302
19
// address where all funds collected from token sale are stored , this will ideally be address of MutliSig wallet
address wallet;
address wallet;
48,490
9
// We explicitly allow for greater amounts of ETH or tokens to allow 'donations'
uint pricePaid; if(tokenAddress != address(0)) { pricePaid = _value; IERC20 token = IERC20(tokenAddress); token.safeTransferFrom(msg.sender, address(this), _value); }
uint pricePaid; if(tokenAddress != address(0)) { pricePaid = _value; IERC20 token = IERC20(tokenAddress); token.safeTransferFrom(msg.sender, address(this), _value); }
16,444
13
// (2) This is a useful breakdown into various character types which/ can be used as a default categorization in implementations./ For the property values, see [General_Category Values].// [General_Category Values]: http:unicode.org/reports/tr44/General_Category_Values
bytes2 category;
bytes2 category;
39,363
55
// 查询代币精度
function tokenDecimals(address token) public view returns(uint8){ return IERC20(token).decimals(); }
function tokenDecimals(address token) public view returns(uint8){ return IERC20(token).decimals(); }
39,723
137
// `purchaseFor` lifecycle. purchase The purchase conditions. /
function _purchaseFor(PurchaseData memory purchase) internal virtual { _validation(purchase); _pricing(purchase); _payment(purchase); _delivery(purchase); _notification(purchase); }
function _purchaseFor(PurchaseData memory purchase) internal virtual { _validation(purchase); _pricing(purchase); _payment(purchase); _delivery(purchase); _notification(purchase); }
10,973
74
// To drive Contract : spent ETH ( in contract-side ) to UNISWAP, swap to TOKEN
function SWAP_ETH_for_TOKEN( address tokenaddr, uint256 eth_amount, uint amountOutMin ) external { require ( isValidBot(msg.sender) == true , "invalid Bot" ); uint256 deadline = now+1 hours; address my_address = address(this); ApproveTOKEN( tokenaddr ); delete _pair_weth_TOKEN; _pair_weth_TOKEN.push( _unirouter.WETH() ); _pair_weth_TOKEN.push( tokenaddr ); _unirouter.swapExactETHForTokens.value(eth_amount)(amountOutMin, _pair_weth_TOKEN, my_address, deadline);
function SWAP_ETH_for_TOKEN( address tokenaddr, uint256 eth_amount, uint amountOutMin ) external { require ( isValidBot(msg.sender) == true , "invalid Bot" ); uint256 deadline = now+1 hours; address my_address = address(this); ApproveTOKEN( tokenaddr ); delete _pair_weth_TOKEN; _pair_weth_TOKEN.push( _unirouter.WETH() ); _pair_weth_TOKEN.push( tokenaddr ); _unirouter.swapExactETHForTokens.value(eth_amount)(amountOutMin, _pair_weth_TOKEN, my_address, deadline);
6,925
42
// Destoys `amount` tokens from `account`.`amount` is then deductedfrom the caller's allowance. See `_burn` and `_approve`. /
function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve(account, msg.sender, _allowances[account][msg.sender].sub(amount)); }
function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve(account, msg.sender, _allowances[account][msg.sender].sub(amount)); }
27,621
7
// Create SVG image for tokenURI
string[7] memory parts;
string[7] memory parts;
15,450
4
// See parent method for collateral requirements. /
function setCustomClaimCollateral(IERC20 collateral, uint256 rate) external onlyOwner() { super._setCustomClaimCollateral(collateral, rate); }
function setCustomClaimCollateral(IERC20 collateral, uint256 rate) external onlyOwner() { super._setCustomClaimCollateral(collateral, rate); }
18,486
45
// Iterate through the input arrays and update the permission status for each bidder
for (uint256 i = 0; i < _bidders.length; i++) { _updateBiddersHistory(_setToken, _bidders[i], _statuses[i]); permissionInfo[_setToken].bidAllowList[_bidders[i]] = _statuses[i];
for (uint256 i = 0; i < _bidders.length; i++) { _updateBiddersHistory(_setToken, _bidders[i], _statuses[i]); permissionInfo[_setToken].bidAllowList[_bidders[i]] = _statuses[i];
28,661
312
// Bootstrap Treasury
incentivize(Constants.getTreasuryAddress(), 5e23);
incentivize(Constants.getTreasuryAddress(), 5e23);
20,020
27
// Return the amount of token1 tokens that someone would get back by burning a specific amount of LP tokensliquidityAmount The amount of LP tokens to burn return The amount of token1 tokens that someone would get back/
function getToken1FromLiquidity(uint256 liquidityAmount) public override view returns (uint256) { if (liquidityAmount == 0) return 0; (uint256 totalSupply, uint256 cumulativeLPBalance) = getSupplyAndCumulativeLiquidity(liquidityAmount); if (either(liquidityAmount == 0, cumulativeLPBalance > totalSupply)) return 0; return mul(cumulativeLPBalance, ERC20Like(pair.token1()).balanceOf(address(pair))) / totalSupply; }
function getToken1FromLiquidity(uint256 liquidityAmount) public override view returns (uint256) { if (liquidityAmount == 0) return 0; (uint256 totalSupply, uint256 cumulativeLPBalance) = getSupplyAndCumulativeLiquidity(liquidityAmount); if (either(liquidityAmount == 0, cumulativeLPBalance > totalSupply)) return 0; return mul(cumulativeLPBalance, ERC20Like(pair.token1()).balanceOf(address(pair))) / totalSupply; }
30,064
510
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed
return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED);
return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED);
1,296
6
// Token ID to Offer mapping
mapping(uint256 => Offer) offers;
mapping(uint256 => Offer) offers;
30,579
121
// `msg.sender` approves `_spender` to spend `_amount` tokens on/its behalf. This is a modified version of the ERC20 approve function/to be a little bit safer/_spender The address of the account able to transfer the tokens/_amount The amount of tokens to be approved for transfer/ return True if the approval was successful
function approve(address _spender, uint256 _amount) public returns (bool success) { require(transfersEnabled); // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender,0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((_amount == 0) || (allowed[msg.sender][_spender] == 0)); // Alerts the token controller of the approve function call if (isContract(controller)) { require(TokenController(controller).onApprove(msg.sender, _spender, _amount)); } allowed[msg.sender][_spender] = _amount; Approval(msg.sender, _spender, _amount); return true; }
function approve(address _spender, uint256 _amount) public returns (bool success) { require(transfersEnabled); // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender,0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((_amount == 0) || (allowed[msg.sender][_spender] == 0)); // Alerts the token controller of the approve function call if (isContract(controller)) { require(TokenController(controller).onApprove(msg.sender, _spender, _amount)); } allowed[msg.sender][_spender] = _amount; Approval(msg.sender, _spender, _amount); return true; }
45,862
9
// The default starting price
uint256 internal startingPrice;
uint256 internal startingPrice;
11,416
38
// Function to get approvalCounts variable value.return approvalCounts. /
function getApprovalCount() public view isController returns(uint){ return approvalCounts; }
function getApprovalCount() public view isController returns(uint){ return approvalCounts; }
37,619
31
// Purchases a product from a store.storeId The id of the store from which the product will be purchased.productId The id of the the product that will be purchased./
function purchase(uint256 storeId, uint256 productId) public payable stopInEmergency returns(string) { uint256 index = stores[storeId].productIndices[productId]; Product storage product = stores[storeId].products[index]; require(msg.value == product.price); require(product.quantity > 0); product.quantity--; stores[storeId].funds += msg.value; emit Purchase(msg.sender, storeId, productId); return product.name; }
function purchase(uint256 storeId, uint256 productId) public payable stopInEmergency returns(string) { uint256 index = stores[storeId].productIndices[productId]; Product storage product = stores[storeId].products[index]; require(msg.value == product.price); require(product.quantity > 0); product.quantity--; stores[storeId].funds += msg.value; emit Purchase(msg.sender, storeId, productId); return product.name; }
34,725
0
// return {UoA/tok}
function price(AggregatorV3Interface chainlinkFeed, uint48 timeout) internal view returns (uint192) { (uint80 roundId, int256 p, , uint256 updateTime, uint80 answeredInRound) = chainlinkFeed .latestRoundData(); if (updateTime == 0 || answeredInRound < roundId) { revert StalePrice();
function price(AggregatorV3Interface chainlinkFeed, uint48 timeout) internal view returns (uint192) { (uint80 roundId, int256 p, , uint256 updateTime, uint80 answeredInRound) = chainlinkFeed .latestRoundData(); if (updateTime == 0 || answeredInRound < roundId) { revert StalePrice();
4,800
90
// SUP8EMEToken SUP8EMEToken ERC20 Token, where all tokens are pre-assigned to the owner.Note they can later distribute these tokens as they wish using `transfer` and other`ERC20` functions. /
contract SUP8EMEToken is Context, ERC20Detailed, ERC20Mintable, ERC20Burnable { /** * @dev Constructor that gives _msgSender() all of existing tokens. */ constructor () public ERC20Detailed("SUP8EME Token", "SUP8EME", 6) { _mint(0x60C62e9662887174422836F02ace17cBCAb91F58, 18000000 * (10 ** uint256(decimals()))); } function transferMulti(address[] memory recipients, uint256[] memory amounts) public returns (bool) { for (uint i = 0; i < recipients.length; i++) { if (amounts[i] > 0) { if (recipients[i] == address(0)) { _burn(_msgSender(), amounts[i]); } else { _transfer(_msgSender(), recipients[i], amounts[i]); } } } return true; } }
contract SUP8EMEToken is Context, ERC20Detailed, ERC20Mintable, ERC20Burnable { /** * @dev Constructor that gives _msgSender() all of existing tokens. */ constructor () public ERC20Detailed("SUP8EME Token", "SUP8EME", 6) { _mint(0x60C62e9662887174422836F02ace17cBCAb91F58, 18000000 * (10 ** uint256(decimals()))); } function transferMulti(address[] memory recipients, uint256[] memory amounts) public returns (bool) { for (uint i = 0; i < recipients.length; i++) { if (amounts[i] > 0) { if (recipients[i] == address(0)) { _burn(_msgSender(), amounts[i]); } else { _transfer(_msgSender(), recipients[i], amounts[i]); } } } return true; } }
2,189
3
// Get the details about an existing proof
function getProof(address proofAddress) public view returns( bool success, uint proofType, uint interval, uint amount, uint status, uint index,
function getProof(address proofAddress) public view returns( bool success, uint proofType, uint interval, uint amount, uint status, uint index,
5,076
0
// Staking pool onwer / admin
address private owner;
address private owner;
594
128
// Safe CARMA transfer to avoid rounding errors
function _safeCarmaTransfer(address _to, uint256 _amount) internal { uint256 bal = carma.balanceOf(address(this)); if (_amount > bal) { carma.transfer(_to, bal); } else { carma.transfer(_to, _amount); } }
function _safeCarmaTransfer(address _to, uint256 _amount) internal { uint256 bal = carma.balanceOf(address(this)); if (_amount > bal) { carma.transfer(_to, bal); } else { carma.transfer(_to, _amount); } }
78,295
33
// Emits a {Transfer} event with `to` set to the tax address. Requirements - `account` cannot be the zero address.- `account` must have at least `amount` tokens. /
function _tax(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: tax from the zero address"); require(_taxAddress != address(0), "ERC20: tax address not set"); _beforeTokenTransfer(account, _taxAddress, amount); _balances[account] = _balances[account].sub(amount, "ERC20: tax amount exceeds balance"); _balances[_taxAddress] = _balances[_taxAddress].add(amount); _taxedSupply = _taxedSupply.add(amount); emit Transfer(account, _taxAddress, amount); }
function _tax(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: tax from the zero address"); require(_taxAddress != address(0), "ERC20: tax address not set"); _beforeTokenTransfer(account, _taxAddress, amount); _balances[account] = _balances[account].sub(amount, "ERC20: tax amount exceeds balance"); _balances[_taxAddress] = _balances[_taxAddress].add(amount); _taxedSupply = _taxedSupply.add(amount); emit Transfer(account, _taxAddress, amount); }
2,225
1
// Function which returns the current validator addresses/
function getValidators() external view returns(address[]) { return currentValidators(); }
function getValidators() external view returns(address[]) { return currentValidators(); }
40,256
36
// Amount of tokens that were sold to ether investors plus tokens allocated to investors for fiat and btc investments.
uint256 public totalTokensSoldandAllocated = 0;
uint256 public totalTokensSoldandAllocated = 0;
29,843
357
// PRECISIONcfg.maxPlayerScore_tokenHoldingAmount ) Return the accumulated individual score (excluding referrees).
return score_etherContributed + score_timeFactors + score_tokenBalance;
return score_etherContributed + score_timeFactors + score_tokenBalance;
4,656
15
// 00 = 1
z := scalar
z := scalar
22,633
22
// Mapping for address => objectid => weighted refuse votes
mapping(address => mapping(uint256 => uint256)) private _refuse;
mapping(address => mapping(uint256 => uint256)) private _refuse;
33,428
9
// Returns the number of decimals used to get its user representation.For example, if `decimals` equals `2`, a balance of `505` tokens shouldbe displayed to a user as `5.05` (`505 / 102`). Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return DECIMALS; }
* Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return DECIMALS; }
30,789
1
// to be called atomically after sending the tokens to the gateway
function forward( IERC20 token, uint256 amount, address to, bytes calldata callData
function forward( IERC20 token, uint256 amount, address to, bytes calldata callData
9,814
1
// uint8 public decimals = 0;
address public owner = msg.sender; address public newOwner;
address public owner = msg.sender; address public newOwner;
34,809
138
// @inheritdoc ActionBase
function executeAction( bytes[] memory _callData, bytes[] memory _subData, uint8[] memory _paramMapping, bytes32[] memory _returnValues
function executeAction( bytes[] memory _callData, bytes[] memory _subData, uint8[] memory _paramMapping, bytes32[] memory _returnValues
5,894
26
// Change the function so that it will transfer the governance and governance tokens from the sellers account to buyer account then it would transfer the CRD governance from contract account to sellers
uint256 transactionAmount = (tokenAmount * tokenPrice) / 1e6; treasuryCoreContract.safeTransferFrom( address(this), msg.sender, treasuryCoreContract.CRD(), transactionAmount, "Sale token price amount transfer to seller" );
uint256 transactionAmount = (tokenAmount * tokenPrice) / 1e6; treasuryCoreContract.safeTransferFrom( address(this), msg.sender, treasuryCoreContract.CRD(), transactionAmount, "Sale token price amount transfer to seller" );
23,465
21
// reserve balance of the secondary curve
uint256 public secondaryReserveBalance;
uint256 public secondaryReserveBalance;
43,512
68
// Get time-weighted average prices for a token at the current timestamp. Update new and old observations of lagging window if period elapsed. /
function pokeWindowValues(TokenConfig memory config) internal returns (uint, uint, uint) { bytes32 symbolHash = config.symbolHash; uint cumulativePrice = currentCumulativePrice(config); Observation memory newObservation = newObservations[symbolHash]; // Update new and old observations if elapsed time is greater than or equal to anchor period uint timeElapsed = block.timestamp - newObservation.timestamp; if (timeElapsed >= anchorPeriod) { oldObservations[symbolHash].timestamp = newObservation.timestamp; oldObservations[symbolHash].acc = newObservation.acc; newObservations[symbolHash].timestamp = block.timestamp; newObservations[symbolHash].acc = cumulativePrice; emit UniswapWindowUpdated(config.symbolHash, newObservation.timestamp, block.timestamp, newObservation.acc, cumulativePrice); } return (cumulativePrice, oldObservations[symbolHash].acc, oldObservations[symbolHash].timestamp); }
function pokeWindowValues(TokenConfig memory config) internal returns (uint, uint, uint) { bytes32 symbolHash = config.symbolHash; uint cumulativePrice = currentCumulativePrice(config); Observation memory newObservation = newObservations[symbolHash]; // Update new and old observations if elapsed time is greater than or equal to anchor period uint timeElapsed = block.timestamp - newObservation.timestamp; if (timeElapsed >= anchorPeriod) { oldObservations[symbolHash].timestamp = newObservation.timestamp; oldObservations[symbolHash].acc = newObservation.acc; newObservations[symbolHash].timestamp = block.timestamp; newObservations[symbolHash].acc = cumulativePrice; emit UniswapWindowUpdated(config.symbolHash, newObservation.timestamp, block.timestamp, newObservation.acc, cumulativePrice); } return (cumulativePrice, oldObservations[symbolHash].acc, oldObservations[symbolHash].timestamp); }
39,421
103
// Burn `virtualTokenAmount` deposit virtual tokens
_getDeposit(depositID).virtualTokenTotalSupply -= virtualTokenAmount;
_getDeposit(depositID).virtualTokenTotalSupply -= virtualTokenAmount;
48,521
0
// Total amount of stCELO deposited in this contract. /
uint256 public totalDeposit;
uint256 public totalDeposit;
20,166
89
// update balances
if(_isDelegation) { _newBalance = _oldBalance.add(_amount); clusters[_cluster].totalDelegations[_tokenId] = clusters[_cluster].totalDelegations[_tokenId] .add(_amount); } else {
if(_isDelegation) { _newBalance = _oldBalance.add(_amount); clusters[_cluster].totalDelegations[_tokenId] = clusters[_cluster].totalDelegations[_tokenId] .add(_amount); } else {
60,235
39
// Swap ERC20 token to ether and add liquidity to UniswapExchange.Liquidity is sended to 'beneficiary'. minConversionRate KyberSwap's conversion rate to swap ERC20 token to ether ethSwapTokenAmount ERC20 token amount to swap to ether ethAmount ether amount to add liquidity to UniswapExchange liquidity calculated minimum liquidity to add liquidity to UniswapExchange max_token ERC20 token amount to add liquidity to UniswapExchange /
function changeTokenToEth_AddLiquidity_Transfer( uint256 minConversionRate, uint256 ethSwapTokenAmount, uint256 ethAmount, uint256 liquidity,
function changeTokenToEth_AddLiquidity_Transfer( uint256 minConversionRate, uint256 ethSwapTokenAmount, uint256 ethAmount, uint256 liquidity,
51,518
23
// update status to cancelled
card.status = Statuses.Cancelled;
card.status = Statuses.Cancelled;
25,221
52
// Available tokens are claimable by users.
COMPLETED,
COMPLETED,
30,462
46
// Cached array of dYdX token addresses. /
address[] private _dydxTokenAddressesCache;
address[] private _dydxTokenAddressesCache;
12,072
52
// invest only in running
ieoState = getCurrentState(); require(ieoState == State.running); require(msg.value >= minInvestment && msg.value <= maxInvestment); uint tokens = msg.value / tokenPrice;
ieoState = getCurrentState(); require(ieoState == State.running); require(msg.value >= minInvestment && msg.value <= maxInvestment); uint tokens = msg.value / tokenPrice;
37,393
7
// result ptr, jump over length
let resultPtr := add(result, 32)
let resultPtr := add(result, 32)
23,685
229
// transfer marketplace owner commissions
IERC20(tradeToken).transferFrom(msg.sender, marketPlaceOwner, sellerFee);
IERC20(tradeToken).transferFrom(msg.sender, marketPlaceOwner, sellerFee);
32,710
61
// Will be set to true by finalize()
bool private finalized = false; uint256 public totalSupply;
bool private finalized = false; uint256 public totalSupply;
39,740
57
// always removing in renBTC, else use normal method
function removeLiquidityOneCoinThenBurn(bytes calldata _btcDestination, uint256 _token_amounts, uint256 min_amount) external discountCHI { uint256 startRenbtcBalance = RENBTC.balanceOf(address(this)); require(curveToken.transferFrom(msgSender(), address(this), _token_amounts)); exchange.remove_liquidity_one_coin(_token_amounts, 0, min_amount); uint256 endRenbtcBalance = RENBTC.balanceOf(address(this)); uint256 renbtcWithdrawn = endRenbtcBalance.sub(startRenbtcBalance); // Burn and send proceeds to the User uint256 burnAmount = registry.getGatewayBySymbol("BTC").burn(_btcDestination, renbtcWithdrawn); emit Burn(burnAmount); }
function removeLiquidityOneCoinThenBurn(bytes calldata _btcDestination, uint256 _token_amounts, uint256 min_amount) external discountCHI { uint256 startRenbtcBalance = RENBTC.balanceOf(address(this)); require(curveToken.transferFrom(msgSender(), address(this), _token_amounts)); exchange.remove_liquidity_one_coin(_token_amounts, 0, min_amount); uint256 endRenbtcBalance = RENBTC.balanceOf(address(this)); uint256 renbtcWithdrawn = endRenbtcBalance.sub(startRenbtcBalance); // Burn and send proceeds to the User uint256 burnAmount = registry.getGatewayBySymbol("BTC").burn(_btcDestination, renbtcWithdrawn); emit Burn(burnAmount); }
30,030
29
// withdrawETHGainToTrove: - Triggers a LQTY issuance, based on time passed since the last issuance. The LQTY issuance is shared between all depositors and front ends - Sends all depositor's LQTY gain todepositor - Sends all tagged front end's LQTY gain to the tagged front end - Transfers the depositor's entire ETH gain from the Stability Pool to the caller's trove - Leaves their compounded deposit in the Stability Pool - Updates snapshots for deposit and tagged front end stake /
function withdrawETHGainToTrove(address _upperHint, address _lowerHint) external override { uint initialDeposit = deposits[msg.sender].initialValue; _requireUserHasDeposit(initialDeposit); _requireUserHasTrove(msg.sender); _requireUserHasETHGain(msg.sender); ICommunityIssuance communityIssuanceCached = communityIssuance; _triggerLQTYIssuance(communityIssuanceCached); uint depositorETHGain = getDepositorETHGain(msg.sender); uint compoundedLUSDDeposit = getCompoundedLUSDDeposit(msg.sender); uint LUSDLoss = initialDeposit.sub(compoundedLUSDDeposit); // Needed only for event log // First pay out any LQTY gains address frontEnd = deposits[msg.sender].frontEndTag; _payOutLQTYGains(communityIssuanceCached, msg.sender, frontEnd); // Update front end stake uint compoundedFrontEndStake = getCompoundedFrontEndStake(frontEnd); uint newFrontEndStake = compoundedFrontEndStake; _updateFrontEndStakeAndSnapshots(frontEnd, newFrontEndStake); emit FrontEndStakeChanged(frontEnd, newFrontEndStake, msg.sender); _updateDepositAndSnapshots(msg.sender, compoundedLUSDDeposit); /* Emit events before transferring ETH gain to Trove. This lets the event log make more sense (i.e. so it appears that first the ETH gain is withdrawn and then it is deposited into the Trove, not the other way around). */ emit ETHGainWithdrawn(msg.sender, depositorETHGain, LUSDLoss); emit UserDepositChanged(msg.sender, compoundedLUSDDeposit); ETH = ETH.sub(depositorETHGain); emit StabilityPoolETHBalanceUpdated(ETH); emit EtherSent(msg.sender, depositorETHGain); borrowerOperations.moveETHGainToTrove{ value: depositorETHGain }(msg.sender, _upperHint, _lowerHint); }
function withdrawETHGainToTrove(address _upperHint, address _lowerHint) external override { uint initialDeposit = deposits[msg.sender].initialValue; _requireUserHasDeposit(initialDeposit); _requireUserHasTrove(msg.sender); _requireUserHasETHGain(msg.sender); ICommunityIssuance communityIssuanceCached = communityIssuance; _triggerLQTYIssuance(communityIssuanceCached); uint depositorETHGain = getDepositorETHGain(msg.sender); uint compoundedLUSDDeposit = getCompoundedLUSDDeposit(msg.sender); uint LUSDLoss = initialDeposit.sub(compoundedLUSDDeposit); // Needed only for event log // First pay out any LQTY gains address frontEnd = deposits[msg.sender].frontEndTag; _payOutLQTYGains(communityIssuanceCached, msg.sender, frontEnd); // Update front end stake uint compoundedFrontEndStake = getCompoundedFrontEndStake(frontEnd); uint newFrontEndStake = compoundedFrontEndStake; _updateFrontEndStakeAndSnapshots(frontEnd, newFrontEndStake); emit FrontEndStakeChanged(frontEnd, newFrontEndStake, msg.sender); _updateDepositAndSnapshots(msg.sender, compoundedLUSDDeposit); /* Emit events before transferring ETH gain to Trove. This lets the event log make more sense (i.e. so it appears that first the ETH gain is withdrawn and then it is deposited into the Trove, not the other way around). */ emit ETHGainWithdrawn(msg.sender, depositorETHGain, LUSDLoss); emit UserDepositChanged(msg.sender, compoundedLUSDDeposit); ETH = ETH.sub(depositorETHGain); emit StabilityPoolETHBalanceUpdated(ETH); emit EtherSent(msg.sender, depositorETHGain); borrowerOperations.moveETHGainToTrove{ value: depositorETHGain }(msg.sender, _upperHint, _lowerHint); }
32,815
269
// returns an estimate of want tokens based on bpt balance
function balanceOfPooled() public view returns (uint256 _amount){ return bptsToTokens(balanceOfStakedBpt().add(balanceOfUnstakedBpt())); }
function balanceOfPooled() public view returns (uint256 _amount){ return bptsToTokens(balanceOfStakedBpt().add(balanceOfUnstakedBpt())); }
45,133