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 |
|---|---|---|---|---|
145 | // Flash swap types | enum FlashSwapType {
FlashSwapWETHForExactTokens
}
| enum FlashSwapType {
FlashSwapWETHForExactTokens
}
| 16,553 |
3 | // setter to set the position of an implementation from the implementation position onwards | function _setImplementation(address _newImplementation) internal {
require(msg.sender == proxyOwner());
bytes32 position = implementationPosition;
assembly {
sstore(position, _newImplementation)
}
}
| function _setImplementation(address _newImplementation) internal {
require(msg.sender == proxyOwner());
bytes32 position = implementationPosition;
assembly {
sstore(position, _newImplementation)
}
}
| 42,135 |
19 | // on stake axion gets burned | IToken(addresses.mainToken).burn(msg.sender, amount);
| IToken(addresses.mainToken).burn(msg.sender, amount);
| 50,996 |
6 | // some helper functions for demo purposes (not required) | function getMyLockedFunds() public view returns (uint x) {
return accounts[msg.sender].balance;
}
| function getMyLockedFunds() public view returns (uint x) {
return accounts[msg.sender].balance;
}
| 39,553 |
11 | // Will evaluate if an array of addresses are past their subscription date and set their payment status to false .array of address. | function resetUserPaidStatus(address[] memory _address) public onlyOwner {
for (uint256 i = 0; i < _address.length; i++) {
if (userPastExpiration(_address[i])) {
UserRegistion[_address[i]].isPaid = false;
}
}
}
| function resetUserPaidStatus(address[] memory _address) public onlyOwner {
for (uint256 i = 0; i < _address.length; i++) {
if (userPastExpiration(_address[i])) {
UserRegistion[_address[i]].isPaid = false;
}
}
}
| 33,837 |
43 | // Fallback functions allowing to perform a delegatecall to the given implementation.This function will return whatever the implementation call returns / | fallback() external payable {
proxyCall();
}
| fallback() external payable {
proxyCall();
}
| 6,558 |
130 | // Sells can't exceed the sell limit(50.000 Tokens at start, can be updated to circulating supply) | if(amount>sellLimit) {
triedToDump.push(sender);
}
| if(amount>sellLimit) {
triedToDump.push(sender);
}
| 40,287 |
25 | // Fonskyionların public/private ları ayarlanacak, Contract ikinci oyuncuyu kabul etmiyorEğer kimse kazanamazsa bir sistem kur / | contract PickTheNumber is VRFConsumerBase {
//Chainlink değişkenleri
uint256 public vrf_fee = 0.005 ether; //VRF Coordinatorüne gönderdiğimiz ücret.
bytes32 public keyHash; //Coordinator ve aramızda yapılan bağıntı.
uint public _entryFee = 0.005 ether; // Oyuncular oyuna katılmak için ödemeliler.
mapping(uint256 => Game) public games; // Game değişkenlerini tutan mapping.
uint256[] keysOfGames; // Arayüzde kolayca "games" mapping değişkenlerini çekebilmek için
// keylerini burada listeliyoruz böylece kolayca bir döngüyle Game verilerini çekebileceğiz.
uint256 private gameCounter = 1; // gameCounter, her Game değişkeninin gameID'sine eşittir
// Her oyun bittiğinde gameCounter +1 artar.
// Toplam kaç oyun oynandığın gösterir.
//Hali hazırda Oynanan oyunun verileri, bunlar oyun bittikten sonra "Game" değişkenine atanıp
// "games" mappinginde depolanacak ve sonrasında yeni oyun için sıfırlanacak.
address[] public gameParticipants; //Katılımcıların listesi
uint public gameParticipantsCounter = 0; //Katılımcı sayısı
uint public luckyNumber; // 0-9 arası rastegele seçilmiş 16 sayı
address[] public winners; // Girişte en çok tekrar eden sayıyı bulanlar
uint public totalReward; // Oynanmakta olan oyunun ödül havuzu
bool public isGameStarted;
uint8 public constant maxPlayers = 2;
// 1 => [0x1, 0x2 ,0x3] böylece bir sayı kazandığında
// bu addreslerin hepsine ödül göndericez.
// winnersı buradan çekicez.
mapping(uint => address[]) public playersAndSelectedNumbers; // 0-9 olan sayıları seçen address listeleri
constructor(
address _vrfCoordinator,
address linkToken,
bytes32 _keyHash
) VRFConsumerBase(_vrfCoordinator, linkToken) {
keyHash = _keyHash;
isGameStarted = false;
}
struct Game {
uint gameID; // Her oyunun özel ID'si var. Bu gameCounter ile belirleniyor.
uint luckyNumber; // Rastgele seçilen 16 rakam.
address[] participants; // Oyun katılımcıları, oyun bittiğinde atanır ve depolanır. Max 20 kişi.
uint totalReward; // Oyunun ödül havuzu
address[] winners; // Oyunun kazananları
}
event EnterTheGame(uint indexed gameID, address participant);
event GameStart(uint indexed gameID);
event GameEnd(uint indexed gameID, uint luckyNumber, address[] winners);
event PickedTheNumber(uint indexed gameID, address player, uint number);
//HAZIRLIK EVRESİ
/**
@dev Kullanıcı, entryFee yi öder ve bir sayı seçerek oyuna giriş yapar.
*/
function enterGame(uint _selectedNumber) external payable {
require(!isGameStarted, "Game is not started yet");
require(gameParticipants.length < maxPlayers, "Game is full");
require(msg.value == _entryFee, "Entry fee is 0.005 Ether !");
gameParticipants.push(msg.sender);
gameParticipantsCounter++;
playersAndSelectedNumbers[_selectedNumber].push(msg.sender);
emit PickedTheNumber(gameCounter, msg.sender, _selectedNumber);
emit EnterTheGame(gameCounter, msg.sender);
if (gameParticipants.length == maxPlayers) {
startGame();
}
}
//OYUN
/*
@dev Oyunu başlatır. İlk olarak Chainlink aracılığıyla 0-15 arasında 16 tane numara rastgele olarak seçilir.
Bu rastgele üretilen sayılardan en fazla tekrar edeni bulunur.
*/
function startGame() public {
isGameStarted = true;
emit GameStart(gameCounter);
getLuckyNumberFromChainlink();
}
function getLuckyNumberFromChainlink() public returns (bytes32 requestId) {
require(LINK.balanceOf(address(this)) >= vrf_fee, "Not enough LINK");
return requestRandomness(keyHash, vrf_fee);
}
//OYNANIŞ PİPELİNE
/**
* @dev randomness bize 77 digitlik bir random uin256 sayısı veriyor. Biz bunun ilk 16 basamağını alacağız.
* @dev override fonksiyon
*/
function fulfillRandomness(bytes32 requestId, uint256 randomness)
internal
virtual
override
{
uint256 winnerNumber = randomness / 10**76; // İlk digitni aldık.
luckyNumber = winnerNumber;
setWinners(winnerNumber);
}
/**
* @dev Winner Number'ı seçenleri winner listesine atıyoruz.
*/
function setWinners(uint _winnerNumber) public {
winners = playersAndSelectedNumbers[_winnerNumber];
sendRewards();
}
/**
* @dev Ödül havuzunu kazanan liste uzunluğuna bölüyoruz ve kişi başı kazanılan ödülü hesaplıyoruz
* winner listesinde olan her kişiye sıra sıra bu ödülü gönderiyoruz.
*/
function sendRewards() internal {
uint rewardForEach = totalReward / winners.length;
for (uint i = 0; i < winners.length; i++) {
(bool sent, ) = winners[i].call{value: rewardForEach}("");
require(sent, "Failed to send reward");
}
finishTheGameAndStoreGameData();
}
//BİTİŞ
function finishTheGameAndStoreGameData() private {
Game memory finishedGame = Game({ //GAME STRUCT kayıt olarak kullanılacak. Oyun bittikten sonra oluşturulacak.
gameID: gameCounter,
luckyNumber: luckyNumber,
participants: gameParticipants, //Get participants from function as array
totalReward: getTotalReward(),
winners: winners // getWinners()
});
games[gameCounter] = finishedGame;
keysOfGames.push(gameCounter);
gameCounter++;
emit GameEnd(gameCounter, luckyNumber, winners);
beReadyToNewGame();
}
/**
* @dev Reset the game and ready to start new game.
*/
function beReadyToNewGame() internal {
for (uint i = 0; i < gameParticipantsCounter; i++) {
delete gameParticipants[i];
}
delete gameParticipants; //Katılımcıların listesi
delete gameParticipantsCounter; //Katılımcı sayısı
delete luckyNumber; // 0-9 arası rastegele seçilmiş rastgele bir sayı
delete winners; // Girişte en çok tekrar eden sayıyı bulanlar
delete totalReward; // Oynanmakta olan oyunun ödül havuzu
delete isGameStarted;
isGameStarted = false;
}
/*
@@@@@ GETTERS
*/
function getTotalReward() public view returns (uint) {
return getPlayerList().length * _entryFee;
}
function getWinners() public view returns (address[] memory) {
return winners;
}
function getLuckyNumber() public view returns (uint) {
return luckyNumber;
}
function getPlayerList() public view returns (address[] memory) {
return gameParticipants;
}
function totalPlayersCurrentGame() public view returns (uint) {
return gameParticipantsCounter;
}
function getLinkBalance() public view returns (uint){
return LINK.balanceOf(address(this));
}
receive() external payable {}
fallback() external payable {}
}
| contract PickTheNumber is VRFConsumerBase {
//Chainlink değişkenleri
uint256 public vrf_fee = 0.005 ether; //VRF Coordinatorüne gönderdiğimiz ücret.
bytes32 public keyHash; //Coordinator ve aramızda yapılan bağıntı.
uint public _entryFee = 0.005 ether; // Oyuncular oyuna katılmak için ödemeliler.
mapping(uint256 => Game) public games; // Game değişkenlerini tutan mapping.
uint256[] keysOfGames; // Arayüzde kolayca "games" mapping değişkenlerini çekebilmek için
// keylerini burada listeliyoruz böylece kolayca bir döngüyle Game verilerini çekebileceğiz.
uint256 private gameCounter = 1; // gameCounter, her Game değişkeninin gameID'sine eşittir
// Her oyun bittiğinde gameCounter +1 artar.
// Toplam kaç oyun oynandığın gösterir.
//Hali hazırda Oynanan oyunun verileri, bunlar oyun bittikten sonra "Game" değişkenine atanıp
// "games" mappinginde depolanacak ve sonrasında yeni oyun için sıfırlanacak.
address[] public gameParticipants; //Katılımcıların listesi
uint public gameParticipantsCounter = 0; //Katılımcı sayısı
uint public luckyNumber; // 0-9 arası rastegele seçilmiş 16 sayı
address[] public winners; // Girişte en çok tekrar eden sayıyı bulanlar
uint public totalReward; // Oynanmakta olan oyunun ödül havuzu
bool public isGameStarted;
uint8 public constant maxPlayers = 2;
// 1 => [0x1, 0x2 ,0x3] böylece bir sayı kazandığında
// bu addreslerin hepsine ödül göndericez.
// winnersı buradan çekicez.
mapping(uint => address[]) public playersAndSelectedNumbers; // 0-9 olan sayıları seçen address listeleri
constructor(
address _vrfCoordinator,
address linkToken,
bytes32 _keyHash
) VRFConsumerBase(_vrfCoordinator, linkToken) {
keyHash = _keyHash;
isGameStarted = false;
}
struct Game {
uint gameID; // Her oyunun özel ID'si var. Bu gameCounter ile belirleniyor.
uint luckyNumber; // Rastgele seçilen 16 rakam.
address[] participants; // Oyun katılımcıları, oyun bittiğinde atanır ve depolanır. Max 20 kişi.
uint totalReward; // Oyunun ödül havuzu
address[] winners; // Oyunun kazananları
}
event EnterTheGame(uint indexed gameID, address participant);
event GameStart(uint indexed gameID);
event GameEnd(uint indexed gameID, uint luckyNumber, address[] winners);
event PickedTheNumber(uint indexed gameID, address player, uint number);
//HAZIRLIK EVRESİ
/**
@dev Kullanıcı, entryFee yi öder ve bir sayı seçerek oyuna giriş yapar.
*/
function enterGame(uint _selectedNumber) external payable {
require(!isGameStarted, "Game is not started yet");
require(gameParticipants.length < maxPlayers, "Game is full");
require(msg.value == _entryFee, "Entry fee is 0.005 Ether !");
gameParticipants.push(msg.sender);
gameParticipantsCounter++;
playersAndSelectedNumbers[_selectedNumber].push(msg.sender);
emit PickedTheNumber(gameCounter, msg.sender, _selectedNumber);
emit EnterTheGame(gameCounter, msg.sender);
if (gameParticipants.length == maxPlayers) {
startGame();
}
}
//OYUN
/*
@dev Oyunu başlatır. İlk olarak Chainlink aracılığıyla 0-15 arasında 16 tane numara rastgele olarak seçilir.
Bu rastgele üretilen sayılardan en fazla tekrar edeni bulunur.
*/
function startGame() public {
isGameStarted = true;
emit GameStart(gameCounter);
getLuckyNumberFromChainlink();
}
function getLuckyNumberFromChainlink() public returns (bytes32 requestId) {
require(LINK.balanceOf(address(this)) >= vrf_fee, "Not enough LINK");
return requestRandomness(keyHash, vrf_fee);
}
//OYNANIŞ PİPELİNE
/**
* @dev randomness bize 77 digitlik bir random uin256 sayısı veriyor. Biz bunun ilk 16 basamağını alacağız.
* @dev override fonksiyon
*/
function fulfillRandomness(bytes32 requestId, uint256 randomness)
internal
virtual
override
{
uint256 winnerNumber = randomness / 10**76; // İlk digitni aldık.
luckyNumber = winnerNumber;
setWinners(winnerNumber);
}
/**
* @dev Winner Number'ı seçenleri winner listesine atıyoruz.
*/
function setWinners(uint _winnerNumber) public {
winners = playersAndSelectedNumbers[_winnerNumber];
sendRewards();
}
/**
* @dev Ödül havuzunu kazanan liste uzunluğuna bölüyoruz ve kişi başı kazanılan ödülü hesaplıyoruz
* winner listesinde olan her kişiye sıra sıra bu ödülü gönderiyoruz.
*/
function sendRewards() internal {
uint rewardForEach = totalReward / winners.length;
for (uint i = 0; i < winners.length; i++) {
(bool sent, ) = winners[i].call{value: rewardForEach}("");
require(sent, "Failed to send reward");
}
finishTheGameAndStoreGameData();
}
//BİTİŞ
function finishTheGameAndStoreGameData() private {
Game memory finishedGame = Game({ //GAME STRUCT kayıt olarak kullanılacak. Oyun bittikten sonra oluşturulacak.
gameID: gameCounter,
luckyNumber: luckyNumber,
participants: gameParticipants, //Get participants from function as array
totalReward: getTotalReward(),
winners: winners // getWinners()
});
games[gameCounter] = finishedGame;
keysOfGames.push(gameCounter);
gameCounter++;
emit GameEnd(gameCounter, luckyNumber, winners);
beReadyToNewGame();
}
/**
* @dev Reset the game and ready to start new game.
*/
function beReadyToNewGame() internal {
for (uint i = 0; i < gameParticipantsCounter; i++) {
delete gameParticipants[i];
}
delete gameParticipants; //Katılımcıların listesi
delete gameParticipantsCounter; //Katılımcı sayısı
delete luckyNumber; // 0-9 arası rastegele seçilmiş rastgele bir sayı
delete winners; // Girişte en çok tekrar eden sayıyı bulanlar
delete totalReward; // Oynanmakta olan oyunun ödül havuzu
delete isGameStarted;
isGameStarted = false;
}
/*
@@@@@ GETTERS
*/
function getTotalReward() public view returns (uint) {
return getPlayerList().length * _entryFee;
}
function getWinners() public view returns (address[] memory) {
return winners;
}
function getLuckyNumber() public view returns (uint) {
return luckyNumber;
}
function getPlayerList() public view returns (address[] memory) {
return gameParticipants;
}
function totalPlayersCurrentGame() public view returns (uint) {
return gameParticipantsCounter;
}
function getLinkBalance() public view returns (uint){
return LINK.balanceOf(address(this));
}
receive() external payable {}
fallback() external payable {}
}
| 6,672 |
2 | // pragma solidity ^0.8.0; //Provides information about the current execution context, including the sender of the transaction and its data. While these are generally available via msg.sender and msg.data, they should not be accessed in such a direct manner, since when dealing with meta-transactions the account sending and paying for execution may not be the actual sender (as far as an application is concerned). This contract is only required for intermediate, library-like contracts./ | abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
| abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
| 8,531 |
89 | // Calculate the pure black-scholes premium for given params | function _getPurePremium(
uint secondsToExpiry,
uint vol,
uint spotPrice,
uint strikePrice
| function _getPurePremium(
uint secondsToExpiry,
uint vol,
uint spotPrice,
uint strikePrice
| 15,675 |
52 | // Insert the leaf | stateTree.insertLeaf(hashedLeaf);
| stateTree.insertLeaf(hashedLeaf);
| 21,009 |
18 | // Returns the amount of `debtShares` owned by `owner`.owner to check balance / | function balanceOfDebtShares(address owner) external view returns (uint256 debtShares);
| function balanceOfDebtShares(address owner) external view returns (uint256 debtShares);
| 13,635 |
3 | // Retrieves data of a randomization request that got successfully posted to the WRB within a given block./Returns zero values if no randomness request was actually posted within a given block./_block Block number whose randomness request is being queried for./ return _from Address from which the latest randomness request was posted./ return _id Unique request identifier as provided by the WRB./ return _prevBlock Block number in which a randomness request got posted just before this one. 0 if none./ return _nextBlock Block number in which a randomness request got posted just after this one, 0 if none. | function getRandomizeData(uint256 _block)
external view returns (address _from, uint256 _id, uint256 _prevBlock, uint256 _nextBlock);
| function getRandomizeData(uint256 _block)
external view returns (address _from, uint256 _id, uint256 _prevBlock, uint256 _nextBlock);
| 14,058 |
27 | // do the actual transfer | balances[from] -= value;
balances[to] += value;
CheckBest(balances[to], to);
| balances[from] -= value;
balances[to] += value;
CheckBest(balances[to], to);
| 28,704 |
32 | // Payout half to ownerPayee and half to updaterPayee | if (propertyOwnerPayee != 0) {
balances[propertyOwnerPayee] += payout / 2;
}
| if (propertyOwnerPayee != 0) {
balances[propertyOwnerPayee] += payout / 2;
}
| 50,473 |
164 | // Store the Advocate/Listener/Speaker information | require (_nameTAOPosition.initialize(nameId, nameId, nameId, nameId));
| require (_nameTAOPosition.initialize(nameId, nameId, nameId, nameId));
| 47,101 |
141 | // _newAmount : amount of underlying tokens that needs to be minted with this rebalance _clientProtocolAmounts : client side calculated amounts to put on each lending protocolreturn : whether has rebalanced or not / | function rebalance(uint256 _newAmount, uint256[] calldata _clientProtocolAmounts) external returns (bool);
| function rebalance(uint256 _newAmount, uint256[] calldata _clientProtocolAmounts) external returns (bool);
| 37,564 |
33 | // Pixel / | function testGetNonExistingPixel() public {
uint256 mintTax = 10 * (10**uint256(currency.decimals()));
_setMintTax(mintTax);
ITheSpaceRegistry.Pixel memory pixel = thespace.getPixel(PIXEL_ID);
assertEq(pixel.price, mintTax);
assertEq(pixel.color, 0);
assertEq(pixel.owner, address(0));
}
| function testGetNonExistingPixel() public {
uint256 mintTax = 10 * (10**uint256(currency.decimals()));
_setMintTax(mintTax);
ITheSpaceRegistry.Pixel memory pixel = thespace.getPixel(PIXEL_ID);
assertEq(pixel.price, mintTax);
assertEq(pixel.color, 0);
assertEq(pixel.owner, address(0));
}
| 19,519 |
20 | // Construct a new Tribe token account The initial account to grant all the tokens minter_ The account with minting ability / | constructor(address account, address minter_) public {
balances[account] = uint96(totalSupply);
emit Transfer(address(0), account, totalSupply);
minter = minter_;
emit MinterChanged(address(0), minter);
}
| constructor(address account, address minter_) public {
balances[account] = uint96(totalSupply);
emit Transfer(address(0), account, totalSupply);
minter = minter_;
emit MinterChanged(address(0), minter);
}
| 67,473 |
150 | // If the reserve has been met, then bidding will end in 24 hours if we are near the end, we have bids, then extend the bidding end | bool isCountDownTriggered = originalBiddingEnd > 0;
if (msg.value >= reserveAuction.reservePrice && !isCountDownTriggered) {
reserveAuction.biddingEnd = uint128(block.timestamp) + reserveAuctionLengthOnceReserveMet;
}
| bool isCountDownTriggered = originalBiddingEnd > 0;
if (msg.value >= reserveAuction.reservePrice && !isCountDownTriggered) {
reserveAuction.biddingEnd = uint128(block.timestamp) + reserveAuctionLengthOnceReserveMet;
}
| 23,950 |
68 | // Try to deal a new limit order or insert it into orderbook its suggested order id is 'id' and suggested positions are in 'prevKey' prevKey points to 3 existing orders in the single-linked list the order's sender is 'sender'. the order's amount is amountstockUnit, which is the stock amount to be sold or bought. the order's price is 'price32', which is decimal floating point value. | function addLimitOrder(bool isBuy, address sender, uint64 amount, uint32 price32, uint32 id, uint72 prevKey) external payable;
| function addLimitOrder(bool isBuy, address sender, uint64 amount, uint32 price32, uint32 id, uint72 prevKey) external payable;
| 38,740 |
128 | // Returns the addition of two unsigned integers, with an overflow flag. _Available since v3.4._/ | function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
| function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
| 28,182 |
21 | // Supply caps enforced by mintAllowed for each kToken address. Defaults to zero which corresponds to unlimited supplying. | mapping(address => uint) public supplyCaps;
| mapping(address => uint) public supplyCaps;
| 28,530 |
160 | // globalConstraintsCount return the global constraint pre and post count return uint globalConstraintsPre count. return uint globalConstraintsPost count./ | function globalConstraintsCount(address _avatar)
external
isAvatarValid(_avatar)
view
returns(uint,uint)
| function globalConstraintsCount(address _avatar)
external
isAvatarValid(_avatar)
view
returns(uint,uint)
| 35,341 |
40 | // Queries the amount of unclaimed rewards for the pool member in a given epoch and feeHandlerreturn 0 if PoolMaster has not called claimRewardMasterreturn 0 if PoolMember has previously claimed reward for the epochreturn 0 if PoolMember has not stake for the epochreturn 0 if PoolMember has not delegated it stake to this contract for the epoch _poolMember address of pool member _epoch for which epoch the member is querying unclaimed reward _feeHandler FeeHandler address / | function getUnclaimedRewardsMember(
address _poolMember,
uint256 _epoch,
address _feeHandler
| function getUnclaimedRewardsMember(
address _poolMember,
uint256 _epoch,
address _feeHandler
| 25,055 |
35 | // There cannot be an owner with address 0. | address lastOwner = address(0);
address currentOwner;
uint8 v;
bytes32 r;
bytes32 s;
uint256 i;
for (i = 0; i < requiredSignatures; i++) {
(v, r, s) = signatureSplit(signatures, i);
if (v == 0) {
| address lastOwner = address(0);
address currentOwner;
uint8 v;
bytes32 r;
bytes32 s;
uint256 i;
for (i = 0; i < requiredSignatures; i++) {
(v, r, s) = signatureSplit(signatures, i);
if (v == 0) {
| 40,681 |
39 | // count confirmation | uint256 remaining;
| uint256 remaining;
| 40,025 |
3 | // value used to divide collateral to adjust the decimal places | uint256 public immutable collateralDecimalsAdjustmentFactor;
| uint256 public immutable collateralDecimalsAdjustmentFactor;
| 34,404 |
179 | // We know if the first token in the batch doesn't exist, the other ones don't as well, because of serial ordering. | require(!_exists(startTokenId), "ERC721A: token already minted");
require(quantity <= maxBatchSize, "ERC721A: quantity to mint too high");
_beforeTokenTransfers(address(0), to, startTokenId, quantity);
AddressData memory addressData = _addressData[to];
_addressData[to] = AddressData(
addressData.balance + uint128(quantity),
addressData.numberMinted + uint128(quantity)
);
| require(!_exists(startTokenId), "ERC721A: token already minted");
require(quantity <= maxBatchSize, "ERC721A: quantity to mint too high");
_beforeTokenTransfers(address(0), to, startTokenId, quantity);
AddressData memory addressData = _addressData[to];
_addressData[to] = AddressData(
addressData.balance + uint128(quantity),
addressData.numberMinted + uint128(quantity)
);
| 872 |
75 | // pause/unpause entire protocol, including mint/redeem/borrow/seize/transfer Admin function, only owner and pauseGuardian can call this _paused whether to pause or unpause / | function _setProtocolPaused(bool _paused)
external
override
checkPauser(_paused)
| function _setProtocolPaused(bool _paused)
external
override
checkPauser(_paused)
| 57,758 |
115 | // remove stake | orderPool.salesRate[orderId] = 0;
| orderPool.salesRate[orderId] = 0;
| 35,124 |
37 | // try to choose a sacrifice in an already full stage (finalize a stage) | tryFinalizeStage();
| tryFinalizeStage();
| 27,623 |
24 | // Triggered on set SELL order | event Order_sell(address indexed _owner, uint256 _max_amount, uint256 _price);
| event Order_sell(address indexed _owner, uint256 _max_amount, uint256 _price);
| 47,609 |
2 | // Emitted when a `severity` is aggregated for a given `season` + `region` | event SeverityAggregated(
uint16 indexed season,
bytes32 region,
Common.Severity severity,
address indexed keeper
);
| event SeverityAggregated(
uint16 indexed season,
bytes32 region,
Common.Severity severity,
address indexed keeper
);
| 11,047 |
91 | // See README.md for updgrade plan | contractsGrantedAccess[_v2Address] = true;
| contractsGrantedAccess[_v2Address] = true;
| 1,727 |
4 | // Returns the average of two numbers. The result is rounded towardszero. / | function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
| function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
| 21,017 |
38 | // Moves tokens `amount` from `sender` to `recipient`. This is internal function is equivalent to `transfer`, and can be used toe.g. implement automatic token fees, slashing mechanisms, etc. Emits a `Transfer` event. Requirements: - `sender` cannot be the zero address.- `recipient` cannot be the zero address.- `sender` must have a balance of at least `amount`. / | function _transfer(address sender, address recipient, uint256 amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(sender != _jailedAddress, "Address jailed");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount);
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
| function _transfer(address sender, address recipient, uint256 amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(sender != _jailedAddress, "Address jailed");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount);
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
| 16,430 |
119 | // Function selector for ERC721Receiver.onERC721Received 0x150b7a02 | bytes4 constant internal ERC721_RECEIVED = bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"));
| bytes4 constant internal ERC721_RECEIVED = bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"));
| 23,983 |
47 | // allowMinting | mintingEnabled=enable;
| mintingEnabled=enable;
| 9,422 |
10 | // TODO: tranfer cUSD to _user, using _unitspricePerUnit | emit CheckpointOpportunity(_id, _units, _user);
| emit CheckpointOpportunity(_id, _units, _user);
| 2,756 |
33 | // Removing a bit of dust to avoid rounding errorsrepayAmount = maxClose - 1e1; | repayAmount = maxClose;
| repayAmount = maxClose;
| 31,934 |
69 | // Transfer the token from the caller and revert on failure. | _transferInToken(tokenProvided, msg.sender, tokenProvidedAmount);
totalTokensSold = _tradeTokenForToken(
msg.sender,
tokenProvided,
tokenReceived,
tokenProvidedAmount,
quotedTokenReceivedAmount,
deadline,
routeThroughEther
| _transferInToken(tokenProvided, msg.sender, tokenProvidedAmount);
totalTokensSold = _tradeTokenForToken(
msg.sender,
tokenProvided,
tokenReceived,
tokenProvidedAmount,
quotedTokenReceivedAmount,
deadline,
routeThroughEther
| 78,151 |
7 | // Transfer tokens to attacker | token.transferFrom(address(wallet), owner(), 10 ether);
| token.transferFrom(address(wallet), owner(), 10 ether);
| 38,598 |
267 | // https:docs.synthetix.io/contracts/source/contracts/binaryoptionmarket | contract BinaryOptionMarket is Owned, MixinResolver, IBinaryOptionMarket {
/* ========== LIBRARIES ========== */
using SafeMath for uint;
using SafeDecimalMath for uint;
/* ========== TYPES ========== */
struct Options {
BinaryOption long;
BinaryOption short;
}
struct Prices {
uint long;
uint short;
}
struct Times {
uint biddingEnd;
uint maturity;
uint expiry;
}
struct OracleDetails {
bytes32 key;
uint strikePrice;
uint finalPrice;
}
/* ========== STATE VARIABLES ========== */
Options public options;
Prices public prices;
Times public times;
OracleDetails public oracleDetails;
BinaryOptionMarketManager.Fees public fees;
BinaryOptionMarketManager.CreatorLimits public creatorLimits;
// `deposited` tracks the sum of open bids on short and long, plus withheld refund fees.
// This must explicitly be kept, in case tokens are transferred to the contract directly.
uint public deposited;
address public creator;
bool public resolved;
bool public refundsEnabled;
uint internal _feeMultiplier;
/* ---------- Address Resolver Configuration ---------- */
bytes32 internal constant CONTRACT_SYSTEMSTATUS = "SystemStatus";
bytes32 internal constant CONTRACT_EXRATES = "ExchangeRates";
bytes32 internal constant CONTRACT_SYNTHSUSD = "SynthsUSD";
bytes32 internal constant CONTRACT_FEEPOOL = "FeePool";
/* ========== CONSTRUCTOR ========== */
constructor(
address _owner,
address _creator,
address _resolver,
uint[2] memory _creatorLimits, // [capitalRequirement, skewLimit]
bytes32 _oracleKey,
uint _strikePrice,
bool _refundsEnabled,
uint[3] memory _times, // [biddingEnd, maturity, expiry]
uint[2] memory _bids, // [longBid, shortBid]
uint[3] memory _fees // [poolFee, creatorFee, refundFee]
) public Owned(_owner) MixinResolver(_resolver) {
creator = _creator;
creatorLimits = BinaryOptionMarketManager.CreatorLimits(_creatorLimits[0], _creatorLimits[1]);
oracleDetails = OracleDetails(_oracleKey, _strikePrice, 0);
times = Times(_times[0], _times[1], _times[2]);
refundsEnabled = _refundsEnabled;
(uint longBid, uint shortBid) = (_bids[0], _bids[1]);
_checkCreatorLimits(longBid, shortBid);
emit Bid(Side.Long, _creator, longBid);
emit Bid(Side.Short, _creator, shortBid);
// Note that the initial deposit of synths must be made by the manager, otherwise the contract's assumed
// deposits will fall out of sync with its actual balance. Similarly the total system deposits must be updated in the manager.
// A balance check isn't performed here since the manager doesn't know the address of the new contract until after it is created.
uint initialDeposit = longBid.add(shortBid);
deposited = initialDeposit;
(uint poolFee, uint creatorFee) = (_fees[0], _fees[1]);
fees = BinaryOptionMarketManager.Fees(poolFee, creatorFee, _fees[2]);
_feeMultiplier = SafeDecimalMath.unit().sub(poolFee.add(creatorFee));
// Compute the prices now that the fees and deposits have been set.
_updatePrices(longBid, shortBid, initialDeposit);
// Instantiate the options themselves
options.long = new BinaryOption(_creator, longBid);
options.short = new BinaryOption(_creator, shortBid);
}
/* ========== VIEWS ========== */
function resolverAddressesRequired() public view returns (bytes32[] memory addresses) {
addresses = new bytes32[](4);
addresses[0] = CONTRACT_SYSTEMSTATUS;
addresses[1] = CONTRACT_EXRATES;
addresses[2] = CONTRACT_SYNTHSUSD;
addresses[3] = CONTRACT_FEEPOOL;
}
/* ---------- External Contracts ---------- */
function _systemStatus() internal view returns (ISystemStatus) {
return ISystemStatus(requireAndGetAddress(CONTRACT_SYSTEMSTATUS));
}
function _exchangeRates() internal view returns (IExchangeRates) {
return IExchangeRates(requireAndGetAddress(CONTRACT_EXRATES));
}
function _sUSD() internal view returns (IERC20) {
return IERC20(requireAndGetAddress(CONTRACT_SYNTHSUSD));
}
function _feePool() internal view returns (IFeePool) {
return IFeePool(requireAndGetAddress(CONTRACT_FEEPOOL));
}
function _manager() internal view returns (BinaryOptionMarketManager) {
return BinaryOptionMarketManager(owner);
}
/* ---------- Phases ---------- */
function _biddingEnded() internal view returns (bool) {
return times.biddingEnd < now;
}
function _matured() internal view returns (bool) {
return times.maturity < now;
}
function _expired() internal view returns (bool) {
return resolved && (times.expiry < now || deposited == 0);
}
function phase() external view returns (Phase) {
if (!_biddingEnded()) {
return Phase.Bidding;
}
if (!_matured()) {
return Phase.Trading;
}
if (!_expired()) {
return Phase.Maturity;
}
return Phase.Expiry;
}
/* ---------- Market Resolution ---------- */
function _oraclePriceAndTimestamp() internal view returns (uint price, uint updatedAt) {
return _exchangeRates().rateAndUpdatedTime(oracleDetails.key);
}
function oraclePriceAndTimestamp() external view returns (uint price, uint updatedAt) {
return _oraclePriceAndTimestamp();
}
function _isFreshPriceUpdateTime(uint timestamp) internal view returns (bool) {
(uint maxOraclePriceAge, , ) = _manager().durations();
return (times.maturity.sub(maxOraclePriceAge)) <= timestamp;
}
function canResolve() external view returns (bool) {
(, uint updatedAt) = _oraclePriceAndTimestamp();
return !resolved && _matured() && _isFreshPriceUpdateTime(updatedAt);
}
function _result() internal view returns (Side) {
uint price;
if (resolved) {
price = oracleDetails.finalPrice;
} else {
(price, ) = _oraclePriceAndTimestamp();
}
return oracleDetails.strikePrice <= price ? Side.Long : Side.Short;
}
function result() external view returns (Side) {
return _result();
}
/* ---------- Option Prices ---------- */
function _computePrices(
uint longBids,
uint shortBids,
uint _deposited
) internal view returns (uint long, uint short) {
require(longBids != 0 && shortBids != 0, "Bids must be nonzero");
uint optionsPerSide = _exercisableDeposits(_deposited);
// The math library rounds up on an exact half-increment -- the price on one side may be an increment too high,
// but this only implies a tiny extra quantity will go to fees.
return (longBids.divideDecimalRound(optionsPerSide), shortBids.divideDecimalRound(optionsPerSide));
}
function senderPriceAndExercisableDeposits() external view returns (uint price, uint exercisable) {
// When the market is not yet resolved, both sides might be able to exercise all the options.
// On the other hand, if the market has resolved, then only the winning side may exercise.
exercisable = 0;
if (!resolved || address(_option(_result())) == msg.sender) {
exercisable = _exercisableDeposits(deposited);
}
// Send the correct price for each side of the market.
if (msg.sender == address(options.long)) {
price = prices.long;
} else if (msg.sender == address(options.short)) {
price = prices.short;
} else {
revert("Sender is not an option");
}
}
function pricesAfterBidOrRefund(
Side side,
uint value,
bool refund
) external view returns (uint long, uint short) {
(uint longTotalBids, uint shortTotalBids) = _totalBids();
// prettier-ignore
function(uint, uint) pure returns (uint) operation = refund ? SafeMath.sub : SafeMath.add;
if (side == Side.Long) {
longTotalBids = operation(longTotalBids, value);
} else {
shortTotalBids = operation(shortTotalBids, value);
}
if (refund) {
value = value.multiplyDecimalRound(SafeDecimalMath.unit().sub(fees.refundFee));
}
return _computePrices(longTotalBids, shortTotalBids, operation(deposited, value));
}
// Returns zero if the result would be negative. See the docs for the formulae this implements.
function bidOrRefundForPrice(
Side bidSide,
Side priceSide,
uint price,
bool refund
) external view returns (uint) {
uint adjustedPrice = price.multiplyDecimalRound(_feeMultiplier);
uint bids = _option(priceSide).totalBids();
uint _deposited = deposited;
uint unit = SafeDecimalMath.unit();
uint refundFeeMultiplier = unit.sub(fees.refundFee);
if (bidSide == priceSide) {
uint depositedByPrice = _deposited.multiplyDecimalRound(adjustedPrice);
// For refunds, the numerator is the negative of the bid case and,
// in the denominator the adjusted price has an extra factor of (1 - the refundFee).
if (refund) {
(depositedByPrice, bids) = (bids, depositedByPrice);
adjustedPrice = adjustedPrice.multiplyDecimalRound(refundFeeMultiplier);
}
// The adjusted price is guaranteed to be less than 1: all its factors are also less than 1.
return _subToZero(depositedByPrice, bids).divideDecimalRound(unit.sub(adjustedPrice));
} else {
uint bidsPerPrice = bids.divideDecimalRound(adjustedPrice);
// For refunds, the numerator is the negative of the bid case.
if (refund) {
(bidsPerPrice, _deposited) = (_deposited, bidsPerPrice);
}
uint value = _subToZero(bidsPerPrice, _deposited);
return refund ? value.divideDecimalRound(refundFeeMultiplier) : value;
}
}
/* ---------- Option Balances and Bids ---------- */
function _bidsOf(address account) internal view returns (uint long, uint short) {
return (options.long.bidOf(account), options.short.bidOf(account));
}
function bidsOf(address account) external view returns (uint long, uint short) {
return _bidsOf(account);
}
function _totalBids() internal view returns (uint long, uint short) {
return (options.long.totalBids(), options.short.totalBids());
}
function totalBids() external view returns (uint long, uint short) {
return _totalBids();
}
function _claimableBalancesOf(address account) internal view returns (uint long, uint short) {
return (options.long.claimableBalanceOf(account), options.short.claimableBalanceOf(account));
}
function claimableBalancesOf(address account) external view returns (uint long, uint short) {
return _claimableBalancesOf(account);
}
function totalClaimableSupplies() external view returns (uint long, uint short) {
return (options.long.totalClaimableSupply(), options.short.totalClaimableSupply());
}
function _balancesOf(address account) internal view returns (uint long, uint short) {
return (options.long.balanceOf(account), options.short.balanceOf(account));
}
function balancesOf(address account) external view returns (uint long, uint short) {
return _balancesOf(account);
}
function totalSupplies() external view returns (uint long, uint short) {
return (options.long.totalSupply(), options.short.totalSupply());
}
function _exercisableDeposits(uint _deposited) internal view returns (uint) {
// Fees are deducted at resolution, so remove them if we're still bidding or trading.
return resolved ? _deposited : _deposited.multiplyDecimalRound(_feeMultiplier);
}
function exercisableDeposits() external view returns (uint) {
return _exercisableDeposits(deposited);
}
/* ---------- Utilities ---------- */
function _chooseSide(
Side side,
uint longValue,
uint shortValue
) internal pure returns (uint) {
if (side == Side.Long) {
return longValue;
}
return shortValue;
}
function _option(Side side) internal view returns (BinaryOption) {
if (side == Side.Long) {
return options.long;
}
return options.short;
}
// Returns zero if the result would be negative.
function _subToZero(uint a, uint b) internal pure returns (uint) {
return a < b ? 0 : a.sub(b);
}
function _checkCreatorLimits(uint longBid, uint shortBid) internal view {
uint totalBid = longBid.add(shortBid);
require(creatorLimits.capitalRequirement <= totalBid, "Insufficient capital");
uint skewLimit = creatorLimits.skewLimit;
require(
skewLimit <= longBid.divideDecimal(totalBid) && skewLimit <= shortBid.divideDecimal(totalBid),
"Bids too skewed"
);
}
function _incrementDeposited(uint value) internal returns (uint _deposited) {
_deposited = deposited.add(value);
deposited = _deposited;
_manager().incrementTotalDeposited(value);
}
function _decrementDeposited(uint value) internal returns (uint _deposited) {
_deposited = deposited.sub(value);
deposited = _deposited;
_manager().decrementTotalDeposited(value);
}
function _requireManagerNotPaused() internal view {
require(!_manager().paused(), "This action cannot be performed while the contract is paused");
}
function requireActiveAndUnpaused() external view {
_systemStatus().requireSystemActive();
_requireManagerNotPaused();
}
/* ========== MUTATIVE FUNCTIONS ========== */
/* ---------- Bidding and Refunding ---------- */
function _updatePrices(
uint longBids,
uint shortBids,
uint _deposited
) internal {
(uint256 longPrice, uint256 shortPrice) = _computePrices(longBids, shortBids, _deposited);
prices = Prices(longPrice, shortPrice);
emit PricesUpdated(longPrice, shortPrice);
}
function bid(Side side, uint value) external duringBidding {
if (value == 0) {
return;
}
_option(side).bid(msg.sender, value);
emit Bid(side, msg.sender, value);
uint _deposited = _incrementDeposited(value);
_sUSD().transferFrom(msg.sender, address(this), value);
(uint longTotalBids, uint shortTotalBids) = _totalBids();
_updatePrices(longTotalBids, shortTotalBids, _deposited);
}
function refund(Side side, uint value) external duringBidding returns (uint refundMinusFee) {
require(refundsEnabled, "Refunds disabled");
if (value == 0) {
return 0;
}
// Require the market creator to leave sufficient capital in the market.
if (msg.sender == creator) {
(uint thisBid, uint thatBid) = _bidsOf(msg.sender);
if (side == Side.Short) {
(thisBid, thatBid) = (thatBid, thisBid);
}
_checkCreatorLimits(thisBid.sub(value), thatBid);
}
// Safe subtraction here and in related contracts will fail if either the
// total supply, deposits, or wallet balance are too small to support the refund.
refundMinusFee = value.multiplyDecimalRound(SafeDecimalMath.unit().sub(fees.refundFee));
_option(side).refund(msg.sender, value);
emit Refund(side, msg.sender, refundMinusFee, value.sub(refundMinusFee));
uint _deposited = _decrementDeposited(refundMinusFee);
_sUSD().transfer(msg.sender, refundMinusFee);
(uint longTotalBids, uint shortTotalBids) = _totalBids();
_updatePrices(longTotalBids, shortTotalBids, _deposited);
}
/* ---------- Market Resolution ---------- */
function resolve() external onlyOwner afterMaturity systemActive managerNotPaused {
require(!resolved, "Market already resolved");
// We don't need to perform stale price checks, so long as the price was
// last updated recently enough before the maturity date.
(uint price, uint updatedAt) = _oraclePriceAndTimestamp();
require(_isFreshPriceUpdateTime(updatedAt), "Price is stale");
oracleDetails.finalPrice = price;
resolved = true;
// Now remit any collected fees.
// Since the constructor enforces that creatorFee + poolFee < 1, the balance
// in the contract will be sufficient to cover these transfers.
IERC20 sUSD = _sUSD();
uint _deposited = deposited;
uint poolFees = _deposited.multiplyDecimalRound(fees.poolFee);
uint creatorFees = _deposited.multiplyDecimalRound(fees.creatorFee);
_decrementDeposited(creatorFees.add(poolFees));
sUSD.transfer(_feePool().FEE_ADDRESS(), poolFees);
sUSD.transfer(creator, creatorFees);
emit MarketResolved(_result(), price, updatedAt, deposited, poolFees, creatorFees);
}
/* ---------- Claiming and Exercising Options ---------- */
function _claimOptions()
internal
systemActive
managerNotPaused
afterBidding
returns (uint longClaimed, uint shortClaimed)
{
uint exercisable = _exercisableDeposits(deposited);
Side outcome = _result();
bool _resolved = resolved;
// Only claim options if we aren't resolved, and only claim the winning side.
uint longOptions;
uint shortOptions;
if (!_resolved || outcome == Side.Long) {
longOptions = options.long.claim(msg.sender, prices.long, exercisable);
}
if (!_resolved || outcome == Side.Short) {
shortOptions = options.short.claim(msg.sender, prices.short, exercisable);
}
require(longOptions != 0 || shortOptions != 0, "Nothing to claim");
emit OptionsClaimed(msg.sender, longOptions, shortOptions);
return (longOptions, shortOptions);
}
function claimOptions() external returns (uint longClaimed, uint shortClaimed) {
return _claimOptions();
}
function exerciseOptions() external returns (uint) {
// The market must be resolved if it has not been.
if (!resolved) {
_manager().resolveMarket(address(this));
}
// If there are options to be claimed, claim them and proceed.
(uint claimableLong, uint claimableShort) = _claimableBalancesOf(msg.sender);
if (claimableLong != 0 || claimableShort != 0) {
_claimOptions();
}
// If the account holds no options, revert.
(uint longBalance, uint shortBalance) = _balancesOf(msg.sender);
require(longBalance != 0 || shortBalance != 0, "Nothing to exercise");
// Each option only needs to be exercised if the account holds any of it.
if (longBalance != 0) {
options.long.exercise(msg.sender);
}
if (shortBalance != 0) {
options.short.exercise(msg.sender);
}
// Only pay out the side that won.
uint payout = _chooseSide(_result(), longBalance, shortBalance);
emit OptionsExercised(msg.sender, payout);
if (payout != 0) {
_decrementDeposited(payout);
_sUSD().transfer(msg.sender, payout);
}
return payout;
}
/* ---------- Market Expiry ---------- */
function _selfDestruct(address payable beneficiary) internal {
uint _deposited = deposited;
if (_deposited != 0) {
_decrementDeposited(_deposited);
}
// Transfer the balance rather than the deposit value in case there are any synths left over
// from direct transfers.
IERC20 sUSD = _sUSD();
uint balance = sUSD.balanceOf(address(this));
if (balance != 0) {
sUSD.transfer(beneficiary, balance);
}
// Destroy the option tokens before destroying the market itself.
options.long.expire(beneficiary);
options.short.expire(beneficiary);
selfdestruct(beneficiary);
}
function cancel(address payable beneficiary) external onlyOwner duringBidding {
(uint longTotalBids, uint shortTotalBids) = _totalBids();
(uint creatorLongBids, uint creatorShortBids) = _bidsOf(creator);
bool cancellable = longTotalBids == creatorLongBids && shortTotalBids == creatorShortBids;
require(cancellable, "Not cancellable");
_selfDestruct(beneficiary);
}
function expire(address payable beneficiary) external onlyOwner {
require(_expired(), "Unexpired options remaining");
_selfDestruct(beneficiary);
}
/* ========== MODIFIERS ========== */
modifier duringBidding() {
require(!_biddingEnded(), "Bidding inactive");
_;
}
modifier afterBidding() {
require(_biddingEnded(), "Bidding incomplete");
_;
}
modifier afterMaturity() {
require(_matured(), "Not yet mature");
_;
}
modifier systemActive() {
_systemStatus().requireSystemActive();
_;
}
modifier managerNotPaused() {
_requireManagerNotPaused();
_;
}
/* ========== EVENTS ========== */
event Bid(Side side, address indexed account, uint value);
event Refund(Side side, address indexed account, uint value, uint fee);
event PricesUpdated(uint longPrice, uint shortPrice);
event MarketResolved(
Side result,
uint oraclePrice,
uint oracleTimestamp,
uint deposited,
uint poolFees,
uint creatorFees
);
event OptionsClaimed(address indexed account, uint longOptions, uint shortOptions);
event OptionsExercised(address indexed account, uint value);
}
| contract BinaryOptionMarket is Owned, MixinResolver, IBinaryOptionMarket {
/* ========== LIBRARIES ========== */
using SafeMath for uint;
using SafeDecimalMath for uint;
/* ========== TYPES ========== */
struct Options {
BinaryOption long;
BinaryOption short;
}
struct Prices {
uint long;
uint short;
}
struct Times {
uint biddingEnd;
uint maturity;
uint expiry;
}
struct OracleDetails {
bytes32 key;
uint strikePrice;
uint finalPrice;
}
/* ========== STATE VARIABLES ========== */
Options public options;
Prices public prices;
Times public times;
OracleDetails public oracleDetails;
BinaryOptionMarketManager.Fees public fees;
BinaryOptionMarketManager.CreatorLimits public creatorLimits;
// `deposited` tracks the sum of open bids on short and long, plus withheld refund fees.
// This must explicitly be kept, in case tokens are transferred to the contract directly.
uint public deposited;
address public creator;
bool public resolved;
bool public refundsEnabled;
uint internal _feeMultiplier;
/* ---------- Address Resolver Configuration ---------- */
bytes32 internal constant CONTRACT_SYSTEMSTATUS = "SystemStatus";
bytes32 internal constant CONTRACT_EXRATES = "ExchangeRates";
bytes32 internal constant CONTRACT_SYNTHSUSD = "SynthsUSD";
bytes32 internal constant CONTRACT_FEEPOOL = "FeePool";
/* ========== CONSTRUCTOR ========== */
constructor(
address _owner,
address _creator,
address _resolver,
uint[2] memory _creatorLimits, // [capitalRequirement, skewLimit]
bytes32 _oracleKey,
uint _strikePrice,
bool _refundsEnabled,
uint[3] memory _times, // [biddingEnd, maturity, expiry]
uint[2] memory _bids, // [longBid, shortBid]
uint[3] memory _fees // [poolFee, creatorFee, refundFee]
) public Owned(_owner) MixinResolver(_resolver) {
creator = _creator;
creatorLimits = BinaryOptionMarketManager.CreatorLimits(_creatorLimits[0], _creatorLimits[1]);
oracleDetails = OracleDetails(_oracleKey, _strikePrice, 0);
times = Times(_times[0], _times[1], _times[2]);
refundsEnabled = _refundsEnabled;
(uint longBid, uint shortBid) = (_bids[0], _bids[1]);
_checkCreatorLimits(longBid, shortBid);
emit Bid(Side.Long, _creator, longBid);
emit Bid(Side.Short, _creator, shortBid);
// Note that the initial deposit of synths must be made by the manager, otherwise the contract's assumed
// deposits will fall out of sync with its actual balance. Similarly the total system deposits must be updated in the manager.
// A balance check isn't performed here since the manager doesn't know the address of the new contract until after it is created.
uint initialDeposit = longBid.add(shortBid);
deposited = initialDeposit;
(uint poolFee, uint creatorFee) = (_fees[0], _fees[1]);
fees = BinaryOptionMarketManager.Fees(poolFee, creatorFee, _fees[2]);
_feeMultiplier = SafeDecimalMath.unit().sub(poolFee.add(creatorFee));
// Compute the prices now that the fees and deposits have been set.
_updatePrices(longBid, shortBid, initialDeposit);
// Instantiate the options themselves
options.long = new BinaryOption(_creator, longBid);
options.short = new BinaryOption(_creator, shortBid);
}
/* ========== VIEWS ========== */
function resolverAddressesRequired() public view returns (bytes32[] memory addresses) {
addresses = new bytes32[](4);
addresses[0] = CONTRACT_SYSTEMSTATUS;
addresses[1] = CONTRACT_EXRATES;
addresses[2] = CONTRACT_SYNTHSUSD;
addresses[3] = CONTRACT_FEEPOOL;
}
/* ---------- External Contracts ---------- */
function _systemStatus() internal view returns (ISystemStatus) {
return ISystemStatus(requireAndGetAddress(CONTRACT_SYSTEMSTATUS));
}
function _exchangeRates() internal view returns (IExchangeRates) {
return IExchangeRates(requireAndGetAddress(CONTRACT_EXRATES));
}
function _sUSD() internal view returns (IERC20) {
return IERC20(requireAndGetAddress(CONTRACT_SYNTHSUSD));
}
function _feePool() internal view returns (IFeePool) {
return IFeePool(requireAndGetAddress(CONTRACT_FEEPOOL));
}
function _manager() internal view returns (BinaryOptionMarketManager) {
return BinaryOptionMarketManager(owner);
}
/* ---------- Phases ---------- */
function _biddingEnded() internal view returns (bool) {
return times.biddingEnd < now;
}
function _matured() internal view returns (bool) {
return times.maturity < now;
}
function _expired() internal view returns (bool) {
return resolved && (times.expiry < now || deposited == 0);
}
function phase() external view returns (Phase) {
if (!_biddingEnded()) {
return Phase.Bidding;
}
if (!_matured()) {
return Phase.Trading;
}
if (!_expired()) {
return Phase.Maturity;
}
return Phase.Expiry;
}
/* ---------- Market Resolution ---------- */
function _oraclePriceAndTimestamp() internal view returns (uint price, uint updatedAt) {
return _exchangeRates().rateAndUpdatedTime(oracleDetails.key);
}
function oraclePriceAndTimestamp() external view returns (uint price, uint updatedAt) {
return _oraclePriceAndTimestamp();
}
function _isFreshPriceUpdateTime(uint timestamp) internal view returns (bool) {
(uint maxOraclePriceAge, , ) = _manager().durations();
return (times.maturity.sub(maxOraclePriceAge)) <= timestamp;
}
function canResolve() external view returns (bool) {
(, uint updatedAt) = _oraclePriceAndTimestamp();
return !resolved && _matured() && _isFreshPriceUpdateTime(updatedAt);
}
function _result() internal view returns (Side) {
uint price;
if (resolved) {
price = oracleDetails.finalPrice;
} else {
(price, ) = _oraclePriceAndTimestamp();
}
return oracleDetails.strikePrice <= price ? Side.Long : Side.Short;
}
function result() external view returns (Side) {
return _result();
}
/* ---------- Option Prices ---------- */
function _computePrices(
uint longBids,
uint shortBids,
uint _deposited
) internal view returns (uint long, uint short) {
require(longBids != 0 && shortBids != 0, "Bids must be nonzero");
uint optionsPerSide = _exercisableDeposits(_deposited);
// The math library rounds up on an exact half-increment -- the price on one side may be an increment too high,
// but this only implies a tiny extra quantity will go to fees.
return (longBids.divideDecimalRound(optionsPerSide), shortBids.divideDecimalRound(optionsPerSide));
}
function senderPriceAndExercisableDeposits() external view returns (uint price, uint exercisable) {
// When the market is not yet resolved, both sides might be able to exercise all the options.
// On the other hand, if the market has resolved, then only the winning side may exercise.
exercisable = 0;
if (!resolved || address(_option(_result())) == msg.sender) {
exercisable = _exercisableDeposits(deposited);
}
// Send the correct price for each side of the market.
if (msg.sender == address(options.long)) {
price = prices.long;
} else if (msg.sender == address(options.short)) {
price = prices.short;
} else {
revert("Sender is not an option");
}
}
function pricesAfterBidOrRefund(
Side side,
uint value,
bool refund
) external view returns (uint long, uint short) {
(uint longTotalBids, uint shortTotalBids) = _totalBids();
// prettier-ignore
function(uint, uint) pure returns (uint) operation = refund ? SafeMath.sub : SafeMath.add;
if (side == Side.Long) {
longTotalBids = operation(longTotalBids, value);
} else {
shortTotalBids = operation(shortTotalBids, value);
}
if (refund) {
value = value.multiplyDecimalRound(SafeDecimalMath.unit().sub(fees.refundFee));
}
return _computePrices(longTotalBids, shortTotalBids, operation(deposited, value));
}
// Returns zero if the result would be negative. See the docs for the formulae this implements.
function bidOrRefundForPrice(
Side bidSide,
Side priceSide,
uint price,
bool refund
) external view returns (uint) {
uint adjustedPrice = price.multiplyDecimalRound(_feeMultiplier);
uint bids = _option(priceSide).totalBids();
uint _deposited = deposited;
uint unit = SafeDecimalMath.unit();
uint refundFeeMultiplier = unit.sub(fees.refundFee);
if (bidSide == priceSide) {
uint depositedByPrice = _deposited.multiplyDecimalRound(adjustedPrice);
// For refunds, the numerator is the negative of the bid case and,
// in the denominator the adjusted price has an extra factor of (1 - the refundFee).
if (refund) {
(depositedByPrice, bids) = (bids, depositedByPrice);
adjustedPrice = adjustedPrice.multiplyDecimalRound(refundFeeMultiplier);
}
// The adjusted price is guaranteed to be less than 1: all its factors are also less than 1.
return _subToZero(depositedByPrice, bids).divideDecimalRound(unit.sub(adjustedPrice));
} else {
uint bidsPerPrice = bids.divideDecimalRound(adjustedPrice);
// For refunds, the numerator is the negative of the bid case.
if (refund) {
(bidsPerPrice, _deposited) = (_deposited, bidsPerPrice);
}
uint value = _subToZero(bidsPerPrice, _deposited);
return refund ? value.divideDecimalRound(refundFeeMultiplier) : value;
}
}
/* ---------- Option Balances and Bids ---------- */
function _bidsOf(address account) internal view returns (uint long, uint short) {
return (options.long.bidOf(account), options.short.bidOf(account));
}
function bidsOf(address account) external view returns (uint long, uint short) {
return _bidsOf(account);
}
function _totalBids() internal view returns (uint long, uint short) {
return (options.long.totalBids(), options.short.totalBids());
}
function totalBids() external view returns (uint long, uint short) {
return _totalBids();
}
function _claimableBalancesOf(address account) internal view returns (uint long, uint short) {
return (options.long.claimableBalanceOf(account), options.short.claimableBalanceOf(account));
}
function claimableBalancesOf(address account) external view returns (uint long, uint short) {
return _claimableBalancesOf(account);
}
function totalClaimableSupplies() external view returns (uint long, uint short) {
return (options.long.totalClaimableSupply(), options.short.totalClaimableSupply());
}
function _balancesOf(address account) internal view returns (uint long, uint short) {
return (options.long.balanceOf(account), options.short.balanceOf(account));
}
function balancesOf(address account) external view returns (uint long, uint short) {
return _balancesOf(account);
}
function totalSupplies() external view returns (uint long, uint short) {
return (options.long.totalSupply(), options.short.totalSupply());
}
function _exercisableDeposits(uint _deposited) internal view returns (uint) {
// Fees are deducted at resolution, so remove them if we're still bidding or trading.
return resolved ? _deposited : _deposited.multiplyDecimalRound(_feeMultiplier);
}
function exercisableDeposits() external view returns (uint) {
return _exercisableDeposits(deposited);
}
/* ---------- Utilities ---------- */
function _chooseSide(
Side side,
uint longValue,
uint shortValue
) internal pure returns (uint) {
if (side == Side.Long) {
return longValue;
}
return shortValue;
}
function _option(Side side) internal view returns (BinaryOption) {
if (side == Side.Long) {
return options.long;
}
return options.short;
}
// Returns zero if the result would be negative.
function _subToZero(uint a, uint b) internal pure returns (uint) {
return a < b ? 0 : a.sub(b);
}
function _checkCreatorLimits(uint longBid, uint shortBid) internal view {
uint totalBid = longBid.add(shortBid);
require(creatorLimits.capitalRequirement <= totalBid, "Insufficient capital");
uint skewLimit = creatorLimits.skewLimit;
require(
skewLimit <= longBid.divideDecimal(totalBid) && skewLimit <= shortBid.divideDecimal(totalBid),
"Bids too skewed"
);
}
function _incrementDeposited(uint value) internal returns (uint _deposited) {
_deposited = deposited.add(value);
deposited = _deposited;
_manager().incrementTotalDeposited(value);
}
function _decrementDeposited(uint value) internal returns (uint _deposited) {
_deposited = deposited.sub(value);
deposited = _deposited;
_manager().decrementTotalDeposited(value);
}
function _requireManagerNotPaused() internal view {
require(!_manager().paused(), "This action cannot be performed while the contract is paused");
}
function requireActiveAndUnpaused() external view {
_systemStatus().requireSystemActive();
_requireManagerNotPaused();
}
/* ========== MUTATIVE FUNCTIONS ========== */
/* ---------- Bidding and Refunding ---------- */
function _updatePrices(
uint longBids,
uint shortBids,
uint _deposited
) internal {
(uint256 longPrice, uint256 shortPrice) = _computePrices(longBids, shortBids, _deposited);
prices = Prices(longPrice, shortPrice);
emit PricesUpdated(longPrice, shortPrice);
}
function bid(Side side, uint value) external duringBidding {
if (value == 0) {
return;
}
_option(side).bid(msg.sender, value);
emit Bid(side, msg.sender, value);
uint _deposited = _incrementDeposited(value);
_sUSD().transferFrom(msg.sender, address(this), value);
(uint longTotalBids, uint shortTotalBids) = _totalBids();
_updatePrices(longTotalBids, shortTotalBids, _deposited);
}
function refund(Side side, uint value) external duringBidding returns (uint refundMinusFee) {
require(refundsEnabled, "Refunds disabled");
if (value == 0) {
return 0;
}
// Require the market creator to leave sufficient capital in the market.
if (msg.sender == creator) {
(uint thisBid, uint thatBid) = _bidsOf(msg.sender);
if (side == Side.Short) {
(thisBid, thatBid) = (thatBid, thisBid);
}
_checkCreatorLimits(thisBid.sub(value), thatBid);
}
// Safe subtraction here and in related contracts will fail if either the
// total supply, deposits, or wallet balance are too small to support the refund.
refundMinusFee = value.multiplyDecimalRound(SafeDecimalMath.unit().sub(fees.refundFee));
_option(side).refund(msg.sender, value);
emit Refund(side, msg.sender, refundMinusFee, value.sub(refundMinusFee));
uint _deposited = _decrementDeposited(refundMinusFee);
_sUSD().transfer(msg.sender, refundMinusFee);
(uint longTotalBids, uint shortTotalBids) = _totalBids();
_updatePrices(longTotalBids, shortTotalBids, _deposited);
}
/* ---------- Market Resolution ---------- */
function resolve() external onlyOwner afterMaturity systemActive managerNotPaused {
require(!resolved, "Market already resolved");
// We don't need to perform stale price checks, so long as the price was
// last updated recently enough before the maturity date.
(uint price, uint updatedAt) = _oraclePriceAndTimestamp();
require(_isFreshPriceUpdateTime(updatedAt), "Price is stale");
oracleDetails.finalPrice = price;
resolved = true;
// Now remit any collected fees.
// Since the constructor enforces that creatorFee + poolFee < 1, the balance
// in the contract will be sufficient to cover these transfers.
IERC20 sUSD = _sUSD();
uint _deposited = deposited;
uint poolFees = _deposited.multiplyDecimalRound(fees.poolFee);
uint creatorFees = _deposited.multiplyDecimalRound(fees.creatorFee);
_decrementDeposited(creatorFees.add(poolFees));
sUSD.transfer(_feePool().FEE_ADDRESS(), poolFees);
sUSD.transfer(creator, creatorFees);
emit MarketResolved(_result(), price, updatedAt, deposited, poolFees, creatorFees);
}
/* ---------- Claiming and Exercising Options ---------- */
function _claimOptions()
internal
systemActive
managerNotPaused
afterBidding
returns (uint longClaimed, uint shortClaimed)
{
uint exercisable = _exercisableDeposits(deposited);
Side outcome = _result();
bool _resolved = resolved;
// Only claim options if we aren't resolved, and only claim the winning side.
uint longOptions;
uint shortOptions;
if (!_resolved || outcome == Side.Long) {
longOptions = options.long.claim(msg.sender, prices.long, exercisable);
}
if (!_resolved || outcome == Side.Short) {
shortOptions = options.short.claim(msg.sender, prices.short, exercisable);
}
require(longOptions != 0 || shortOptions != 0, "Nothing to claim");
emit OptionsClaimed(msg.sender, longOptions, shortOptions);
return (longOptions, shortOptions);
}
function claimOptions() external returns (uint longClaimed, uint shortClaimed) {
return _claimOptions();
}
function exerciseOptions() external returns (uint) {
// The market must be resolved if it has not been.
if (!resolved) {
_manager().resolveMarket(address(this));
}
// If there are options to be claimed, claim them and proceed.
(uint claimableLong, uint claimableShort) = _claimableBalancesOf(msg.sender);
if (claimableLong != 0 || claimableShort != 0) {
_claimOptions();
}
// If the account holds no options, revert.
(uint longBalance, uint shortBalance) = _balancesOf(msg.sender);
require(longBalance != 0 || shortBalance != 0, "Nothing to exercise");
// Each option only needs to be exercised if the account holds any of it.
if (longBalance != 0) {
options.long.exercise(msg.sender);
}
if (shortBalance != 0) {
options.short.exercise(msg.sender);
}
// Only pay out the side that won.
uint payout = _chooseSide(_result(), longBalance, shortBalance);
emit OptionsExercised(msg.sender, payout);
if (payout != 0) {
_decrementDeposited(payout);
_sUSD().transfer(msg.sender, payout);
}
return payout;
}
/* ---------- Market Expiry ---------- */
function _selfDestruct(address payable beneficiary) internal {
uint _deposited = deposited;
if (_deposited != 0) {
_decrementDeposited(_deposited);
}
// Transfer the balance rather than the deposit value in case there are any synths left over
// from direct transfers.
IERC20 sUSD = _sUSD();
uint balance = sUSD.balanceOf(address(this));
if (balance != 0) {
sUSD.transfer(beneficiary, balance);
}
// Destroy the option tokens before destroying the market itself.
options.long.expire(beneficiary);
options.short.expire(beneficiary);
selfdestruct(beneficiary);
}
function cancel(address payable beneficiary) external onlyOwner duringBidding {
(uint longTotalBids, uint shortTotalBids) = _totalBids();
(uint creatorLongBids, uint creatorShortBids) = _bidsOf(creator);
bool cancellable = longTotalBids == creatorLongBids && shortTotalBids == creatorShortBids;
require(cancellable, "Not cancellable");
_selfDestruct(beneficiary);
}
function expire(address payable beneficiary) external onlyOwner {
require(_expired(), "Unexpired options remaining");
_selfDestruct(beneficiary);
}
/* ========== MODIFIERS ========== */
modifier duringBidding() {
require(!_biddingEnded(), "Bidding inactive");
_;
}
modifier afterBidding() {
require(_biddingEnded(), "Bidding incomplete");
_;
}
modifier afterMaturity() {
require(_matured(), "Not yet mature");
_;
}
modifier systemActive() {
_systemStatus().requireSystemActive();
_;
}
modifier managerNotPaused() {
_requireManagerNotPaused();
_;
}
/* ========== EVENTS ========== */
event Bid(Side side, address indexed account, uint value);
event Refund(Side side, address indexed account, uint value, uint fee);
event PricesUpdated(uint longPrice, uint shortPrice);
event MarketResolved(
Side result,
uint oraclePrice,
uint oracleTimestamp,
uint deposited,
uint poolFees,
uint creatorFees
);
event OptionsClaimed(address indexed account, uint longOptions, uint shortOptions);
event OptionsExercised(address indexed account, uint value);
}
| 30,151 |
22 | // Check if point is the neutral of the curve / | function ecZZ_IsZero (uint x0, uint y0, uint zz0, uint zzz0) internal pure returns (bool)
| function ecZZ_IsZero (uint x0, uint y0, uint zz0, uint zzz0) internal pure returns (bool)
| 22,080 |
2 | // 0.75 $RAD / day | uint256 constant MED = 0.75 ether;
| uint256 constant MED = 0.75 ether;
| 28,031 |
155 | // ERC1363Spender interface Interface for any contract that wants to support `approveAndCall` from ERC1363 token contracts. / | interface IERC1363Spender {
/*
* Note: the ERC-165 identifier for this interface is 0.8.04a2d0.
* 0.8.04a2d0 === bytes4(keccak256("onApprovalReceived(address,uint256,bytes)"))
*/
/**
* @notice Handle the approval of ERC1363 tokens
* @dev Any ERC1363 smart contract calls this function on the recipient
* after an `approve`. This function MAY throw to revert and reject the
* approval. Return of other than the magic value MUST result in the
* transaction being reverted.
* Note: the token contract address is always the message sender.
* @param owner address The address which called `approveAndCall` function
* @param value uint256 The amount of tokens to be spent
* @param data bytes Additional data with no specified format
* @return `bytes4(keccak256("onApprovalReceived(address,uint256,bytes)"))`
* unless throwing
*/
function onApprovalReceived(address owner, uint256 value, bytes calldata data) external returns (bytes4);
}
| interface IERC1363Spender {
/*
* Note: the ERC-165 identifier for this interface is 0.8.04a2d0.
* 0.8.04a2d0 === bytes4(keccak256("onApprovalReceived(address,uint256,bytes)"))
*/
/**
* @notice Handle the approval of ERC1363 tokens
* @dev Any ERC1363 smart contract calls this function on the recipient
* after an `approve`. This function MAY throw to revert and reject the
* approval. Return of other than the magic value MUST result in the
* transaction being reverted.
* Note: the token contract address is always the message sender.
* @param owner address The address which called `approveAndCall` function
* @param value uint256 The amount of tokens to be spent
* @param data bytes Additional data with no specified format
* @return `bytes4(keccak256("onApprovalReceived(address,uint256,bytes)"))`
* unless throwing
*/
function onApprovalReceived(address owner, uint256 value, bytes calldata data) external returns (bytes4);
}
| 19,492 |
0 | // Represents the deposit of an NFT | struct Deposit {
address owner;
uint128 liquidity;
address token0;
address token1;
}
| struct Deposit {
address owner;
uint128 liquidity;
address token0;
address token1;
}
| 57,022 |
26 | // unpackMessage will revert if anything else other than XChainMsgType.XFER is in the _payload to support additional message types in the future implement something like if (xchainMsgType == XChainMsgType.XFER) ... | IPortfolio.XFER memory xfer = unpackXFerMessage(msgdata);
xfer.symbol = getSymbolForId(xfer.symbol);
return (xfer.trader, xfer.symbol, xfer.quantity);
| IPortfolio.XFER memory xfer = unpackXFerMessage(msgdata);
xfer.symbol = getSymbolForId(xfer.symbol);
return (xfer.trader, xfer.symbol, xfer.quantity);
| 34,676 |
283 | // Mints tokens/ | function mintDoges(uint256 numberOfTokens) external payable {
require(saleIsActive, "Sale must be active to mint");
require(numberOfTokens <= maxToMint, "Invalid amount to mint per once");
require(mintAmount.add(numberOfTokens).add(MAX_CLAIM) <= MAX_DOGE_SUPPLY, "Purchase would exceed max supply");
require(mintPrice.mul(numberOfTokens) <= msg.value, "Ether value sent is not correct");
for(uint256 i = 0; i < numberOfTokens; i++) {
_safeMint(msg.sender, MAX_CLAIM.add(mintAmount));
mintAmount++;
}
// If we haven't set the starting index and this is either
// 1) the last saleable token or 2) the first token to be sold after
// the reveal time, set the starting index block
if (startingIndexBlock == 0 && (totalSupply() == MAX_DOGE_SUPPLY || block.timestamp >= REVEAL_TIMESTAMP)) {
startingIndexBlock = block.number;
}
}
| function mintDoges(uint256 numberOfTokens) external payable {
require(saleIsActive, "Sale must be active to mint");
require(numberOfTokens <= maxToMint, "Invalid amount to mint per once");
require(mintAmount.add(numberOfTokens).add(MAX_CLAIM) <= MAX_DOGE_SUPPLY, "Purchase would exceed max supply");
require(mintPrice.mul(numberOfTokens) <= msg.value, "Ether value sent is not correct");
for(uint256 i = 0; i < numberOfTokens; i++) {
_safeMint(msg.sender, MAX_CLAIM.add(mintAmount));
mintAmount++;
}
// If we haven't set the starting index and this is either
// 1) the last saleable token or 2) the first token to be sold after
// the reveal time, set the starting index block
if (startingIndexBlock == 0 && (totalSupply() == MAX_DOGE_SUPPLY || block.timestamp >= REVEAL_TIMESTAMP)) {
startingIndexBlock = block.number;
}
}
| 34,035 |
7 | // Here we don't have enough money so partially pay to investor | dep.depositor.send(money); // Send to him everything we have
dep.payout += money; // Update the payout amount
break; // Exit cycle
| dep.depositor.send(money); // Send to him everything we have
dep.payout += money; // Update the payout amount
break; // Exit cycle
| 14,745 |
8 | // Test helper for STQCrowdsale, DONT use it in production! | contract STQCrowdsaleTestHelper is STQCrowdsale {
function STQCrowdsaleTestHelper(address[] _owners, address _token, address _funds, address _teamTokens)
STQCrowdsale(_owners, _token, _funds, _teamTokens)
{
}
function getCurrentTime() internal constant returns (uint) {
return m_time;
}
function setTime(uint time) external onlyowner {
m_time = time;
}
function getMinFunds() internal constant returns (uint) {
return 100 finney;
}
function getMaximumFunds() internal constant returns (uint) {
return 400 finney;
}
function getTotalInvested() internal constant returns (uint) {
return m_funds.totalInvested().add(2 finney);
}
function getLastMaxInvestments() internal constant returns (uint) {
return m_maxLastInvestments;
}
function setLastMaxInvestments(uint value) external onlyowner {
m_maxLastInvestments = value;
}
uint m_time;
uint m_maxLastInvestments = c_maxLastInvestments;
}
| contract STQCrowdsaleTestHelper is STQCrowdsale {
function STQCrowdsaleTestHelper(address[] _owners, address _token, address _funds, address _teamTokens)
STQCrowdsale(_owners, _token, _funds, _teamTokens)
{
}
function getCurrentTime() internal constant returns (uint) {
return m_time;
}
function setTime(uint time) external onlyowner {
m_time = time;
}
function getMinFunds() internal constant returns (uint) {
return 100 finney;
}
function getMaximumFunds() internal constant returns (uint) {
return 400 finney;
}
function getTotalInvested() internal constant returns (uint) {
return m_funds.totalInvested().add(2 finney);
}
function getLastMaxInvestments() internal constant returns (uint) {
return m_maxLastInvestments;
}
function setLastMaxInvestments(uint value) external onlyowner {
m_maxLastInvestments = value;
}
uint m_time;
uint m_maxLastInvestments = c_maxLastInvestments;
}
| 2,033 |
28 | // Update the number of decimals for the token newDecimals The new number of decimals for the token / | function _setDecimals(uint8 newDecimals) internal {
_decimals = newDecimals;
}
| function _setDecimals(uint8 newDecimals) internal {
_decimals = newDecimals;
}
| 4,649 |
36 | // The `order` must be verified by calling `Orders.verifyOrder` before calling this function. | function executeDeposit(Orders.Order calldata order) internal {
uint256 gasStart = gasleft();
orders.dequeueOrder(order.orderId);
(bool executionSuccess, bytes memory data) = address(this).call{
gas: order.gasLimit.sub(
Orders.ORDER_BASE_COST.add(orders.transferGasCosts[order.token0]).add(
orders.transferGasCosts[order.token1]
)
)
}(abi.encodeWithSelector(this._executeDeposit.selector, order));
bool refundSuccess = true;
if (!executionSuccess) {
refundSuccess = refundTokens(
order.to,
order.token0,
order.value0,
order.token1,
order.value1,
order.unwrap
);
}
finalizeOrder(refundSuccess);
(uint256 gasUsed, uint256 ethRefund) = refund(order.gasLimit, order.gasPrice, gasStart, order.to);
emit OrderExecuted(orders.lastProcessedOrderId, executionSuccess, data, gasUsed, ethRefund);
}
| function executeDeposit(Orders.Order calldata order) internal {
uint256 gasStart = gasleft();
orders.dequeueOrder(order.orderId);
(bool executionSuccess, bytes memory data) = address(this).call{
gas: order.gasLimit.sub(
Orders.ORDER_BASE_COST.add(orders.transferGasCosts[order.token0]).add(
orders.transferGasCosts[order.token1]
)
)
}(abi.encodeWithSelector(this._executeDeposit.selector, order));
bool refundSuccess = true;
if (!executionSuccess) {
refundSuccess = refundTokens(
order.to,
order.token0,
order.value0,
order.token1,
order.value1,
order.unwrap
);
}
finalizeOrder(refundSuccess);
(uint256 gasUsed, uint256 ethRefund) = refund(order.gasLimit, order.gasPrice, gasStart, order.to);
emit OrderExecuted(orders.lastProcessedOrderId, executionSuccess, data, gasUsed, ethRefund);
}
| 28,495 |
274 | // Increase the withdrawable funds for the given address owner Address of the account to add withdrawable funds to / | function increaseWithdrawableFunds(address owner, uint256 amount) internal {
_withdrawableFunds[owner] = _withdrawableFunds[owner].add(amount);
}
| function increaseWithdrawableFunds(address owner, uint256 amount) internal {
_withdrawableFunds[owner] = _withdrawableFunds[owner].add(amount);
}
| 35,857 |
217 | // Returns tax as a proper fraction for the given country, defined by `_tokenId` _tokenId country id to query tax forreturn tax as a proper fraction (tuple containing nominator and denominator) / | function getTax(uint256 _tokenId) public constant returns(uint8, uint8) {
// obtain token's tax as packed fraction
uint16 tax = getTaxPacked(_tokenId);
// return tax as a proper fraction
return (tax.getNominator(), tax.getDenominator());
}
| function getTax(uint256 _tokenId) public constant returns(uint8, uint8) {
// obtain token's tax as packed fraction
uint16 tax = getTaxPacked(_tokenId);
// return tax as a proper fraction
return (tax.getNominator(), tax.getDenominator());
}
| 32,393 |
12 | // return true if the account is the owner of the contract. / | function isOwner(address account) public view returns(bool) {
return account == _owner;
}
| function isOwner(address account) public view returns(bool) {
return account == _owner;
}
| 10,195 |
17 | // Get the approved address for a single NFT. Throws if `_tokenId` is not a valid NFT. _tokenId The NFT to find the approved address for.return Address that _tokenId is approved for. / | function getApproved(uint256 _tokenId) public view returns (address) {
address _owner = owners[_tokenId];
require(_owner != address(0));
address _approved = approveds[_tokenId];
return _approved;
}
| function getApproved(uint256 _tokenId) public view returns (address) {
address _owner = owners[_tokenId];
require(_owner != address(0));
address _approved = approveds[_tokenId];
return _approved;
}
| 26,114 |
18 | // Sets the siloed borrowing flag for the reserve. When this flag is set to true, users borrowing this asset will not be allowed to borrow any other asset. self The reserve configuration siloed True if the asset is siloed / | {
self.data =
(self.data & SILOED_BORROWING_MASK) |
(uint256(siloed ? 1 : 0) << SILOED_BORROWING_START_BIT_POSITION);
}
| {
self.data =
(self.data & SILOED_BORROWING_MASK) |
(uint256(siloed ? 1 : 0) << SILOED_BORROWING_START_BIT_POSITION);
}
| 36,435 |
16 | // This basically means if a minter burns more than its usedAllownace,there will be tokens left unburned,and some other minter will have to burn it. / | bool burningMoreThanUsedAllowance = (usedAllowance < amount);
| bool burningMoreThanUsedAllowance = (usedAllowance < amount);
| 30,263 |
24 | // We always want to assess for the most recently past nextDueTime. So if the recalculation above sets the nextDueTime into the future, then ensure we pass in the one just before this. | if (timeToAssess > currentTime()) {
uint256 secondsPerPeriod = paymentPeriodInDays.mul(SECONDS_PER_DAY);
timeToAssess = timeToAssess.sub(secondsPerPeriod);
}
| if (timeToAssess > currentTime()) {
uint256 secondsPerPeriod = paymentPeriodInDays.mul(SECONDS_PER_DAY);
timeToAssess = timeToAssess.sub(secondsPerPeriod);
}
| 6,041 |
11 | // Add Emergency pause/_pause to set Emergency Pause ON/OFF/_by to set who Start/Stop EP | function addEmergencyPause(bool _pause, bytes4 _by) public {
require(_by == "AB" || _by == "AUT","Invalid call.");
require(msg.sender == getLatestAddress("P1") || msg.sender == getLatestAddress("GV"),"Callable by P1 and GV only.");
emergencyPaused.push(EmergencyPause(_pause, now, _by));
if (_pause == false) {
Claims c1 = Claims(allContractVersions["CL"]);
c1.submitClaimAfterEPOff(); // Process claims submitted while EP was on
c1.startAllPendingClaimsVoting(); // Resume voting on all pending claims
}
}
| function addEmergencyPause(bool _pause, bytes4 _by) public {
require(_by == "AB" || _by == "AUT","Invalid call.");
require(msg.sender == getLatestAddress("P1") || msg.sender == getLatestAddress("GV"),"Callable by P1 and GV only.");
emergencyPaused.push(EmergencyPause(_pause, now, _by));
if (_pause == false) {
Claims c1 = Claims(allContractVersions["CL"]);
c1.submitClaimAfterEPOff(); // Process claims submitted while EP was on
c1.startAllPendingClaimsVoting(); // Resume voting on all pending claims
}
}
| 36,595 |
153 | // uint remainingAmount = amountAfterFee.sub(_75Percent); |
depositedTokens[msg.sender] = depositedTokens[msg.sender].add(amountAfterFee);
holders.add(msg.sender);
if (referrals[msg.sender] == address(0)) {
referrals[msg.sender] = referrer;
}
|
depositedTokens[msg.sender] = depositedTokens[msg.sender].add(amountAfterFee);
holders.add(msg.sender);
if (referrals[msg.sender] == address(0)) {
referrals[msg.sender] = referrer;
}
| 3,721 |
16 | // path = remoteAddress + localAddress | require(
chainAddressSize != 0 && _path.length == 20 + chainAddressSize,
"LayerZero: incorrect remote address size"
);
address srcInPath;
bytes memory path = _path; // copy to memory
assembly {
srcInPath := mload(add(add(path, 20), chainAddressSize)) // chainAddressSize + 20
}
| require(
chainAddressSize != 0 && _path.length == 20 + chainAddressSize,
"LayerZero: incorrect remote address size"
);
address srcInPath;
bytes memory path = _path; // copy to memory
assembly {
srcInPath := mload(add(add(path, 20), chainAddressSize)) // chainAddressSize + 20
}
| 25,963 |
10 | // modify internal contract state before transfering funds | delete _entries;
| delete _entries;
| 3,476 |
128 | // toogle market pair status | function setMarketPairStatus(address account, bool newValue) public onlyOwner {
isMarketPair[account] = newValue;
}
| function setMarketPairStatus(address account, bool newValue) public onlyOwner {
isMarketPair[account] = newValue;
}
| 23,092 |
0 | // should access position of caller using delegatecall | function shouldBuy(Position memory position, uint _reserve0, uint _reserve1) external pure override returns(uint){
return position.blockTimestamp == 0 ? position.amount : 0 ;
}
| function shouldBuy(Position memory position, uint _reserve0, uint _reserve1) external pure override returns(uint){
return position.blockTimestamp == 0 ? position.amount : 0 ;
}
| 3,796 |
6 | // find the corresponding request of the letter: | string memory letterStudentId = letters[_letterId].studentId;
string memory letterRecommenderId = letters[_letterId].recommenderId;
string memory letterProgramId = letters[_letterId].schoolProgramId;
for (uint i = 0; i < requests.length; i++) {
if ( (keccak256(requests[i].studentId) == keccak256(letterStudentId)) &&
(keccak256(requests[i].recommenderId) == keccak256(letterRecommenderId)) &&
(keccak256(requests[i].schoolProgramId) == keccak256(letterProgramId))) {
if(_status == 1) requests[i].status = State.Created;
break;
}
| string memory letterStudentId = letters[_letterId].studentId;
string memory letterRecommenderId = letters[_letterId].recommenderId;
string memory letterProgramId = letters[_letterId].schoolProgramId;
for (uint i = 0; i < requests.length; i++) {
if ( (keccak256(requests[i].studentId) == keccak256(letterStudentId)) &&
(keccak256(requests[i].recommenderId) == keccak256(letterRecommenderId)) &&
(keccak256(requests[i].schoolProgramId) == keccak256(letterProgramId))) {
if(_status == 1) requests[i].status = State.Created;
break;
}
| 42,645 |
107 | // removes all fee from transaction if takefee is set to false / | function removeAllFee() private {
if(_totalFee == 0) return;
_previousTotalFee = _totalFee;
_totalFee = 0;
}
| function removeAllFee() private {
if(_totalFee == 0) return;
_previousTotalFee = _totalFee;
_totalFee = 0;
}
| 57,457 |
49 | // Wrapper around addLiquidity() and optionStake() tokenIds The tokenIds of the nfts to send to the sudoswap pool. minPrice The min price to lp at. maxPrice The max price to lp at. termIndex Index into the terms array which tells how long to stake for. / | function addLiquidityAndOptionStake(
uint256[] calldata tokenIds,
uint256 minPrice,
uint256 maxPrice,
uint256 termIndex
)
public
payable
returns (uint256 tokenId)
| function addLiquidityAndOptionStake(
uint256[] calldata tokenIds,
uint256 minPrice,
uint256 maxPrice,
uint256 termIndex
)
public
payable
returns (uint256 tokenId)
| 20,850 |
128 | // Process withdrawal fee | uint256 _fee = _processWithdrawalFee(_toWithdraw);
| uint256 _fee = _processWithdrawalFee(_toWithdraw);
| 34,046 |
85 | // Pancake Profile is requested | bool public pancakeProfileIsRequested;
| bool public pancakeProfileIsRequested;
| 39,179 |
26 | // sets the executor address/_executorAddress the address of the executor contract | function setExecutor(address _executorAddress) external onlyOwner {
executor = IExecutor(_executorAddress);
emit ExecutorSet(_executorAddress);
}
| function setExecutor(address _executorAddress) external onlyOwner {
executor = IExecutor(_executorAddress);
emit ExecutorSet(_executorAddress);
}
| 18,337 |
315 | // Jackpot holding contract. This accepts token payouts from a game for every player loss, and on a win, pays out half of the jackpot to the winner. Jackpot payout should only be called from the game./ | contract JackpotHolding is ERC223Receiving {
/****************************
* FIELDS
****************************/
// How many times we've paid out the jackpot
uint public payOutNumber = 0;
// The amount to divide the token balance by for a pay out (defaults to half the token balance)
uint public payOutDivisor = 2;
// Holds the bankroll controller info
ZethrBankrollControllerInterface controller;
// Zethr contract
Zethr zethr;
/****************************
* CONSTRUCTOR
****************************/
constructor (address _controllerAddress, address _zethrAddress) public {
controller = ZethrBankrollControllerInterface(_controllerAddress);
zethr = Zethr(_zethrAddress);
}
function() public payable {}
function tokenFallback(address /*_from*/, uint /*_amountOfTokens*/, bytes/*_data*/)
public
returns (bool)
{
// Do nothing, we can track the jackpot by this balance
}
/****************************
* VIEWS
****************************/
function getJackpotBalance()
public view
returns (uint)
{
// Half of this balance + half of jackpotBalance in each token bankroll
uint tempBalance;
for (uint i=0; i<7; i++) {
tempBalance += controller.tokenBankrolls(i).jackpotBalance() > 0 ? controller.tokenBankrolls(i).jackpotBalance() / payOutDivisor : 0;
}
tempBalance += zethr.balanceOf(address(this)) > 0 ? zethr.balanceOf(address(this)) / payOutDivisor : 0;
return tempBalance;
}
/****************************
* OWNER FUNCTIONS
****************************/
/** @dev Sets the pay out divisor
* @param _divisor The value to set the new divisor to
*/
function ownerSetPayOutDivisor(uint _divisor)
public
ownerOnly
{
require(_divisor != 0);
payOutDivisor = _divisor;
}
/** @dev Sets the address of the game controller
* @param _controllerAddress The new address of the controller
*/
function ownerSetControllerAddress(address _controllerAddress)
public
ownerOnly
{
controller = ZethrBankrollControllerInterface(_controllerAddress);
}
/** @dev Transfers the jackpot to _to
* @param _to Address to send the jackpot tokens to
*/
function ownerWithdrawZth(address _to)
public
ownerOnly
{
uint balance = zethr.balanceOf(address(this));
zethr.transfer(_to, balance);
}
/** @dev Transfers any ETH received from dividends to _to
* @param _to Address to send the ETH to
*/
function ownerWithdrawEth(address _to)
public
ownerOnly
{
_to.transfer(address(this).balance);
}
/****************************
* GAME FUNCTIONS
****************************/
function gamePayOutWinner(address _winner)
public
gameOnly
{
// Call the payout function on all 7 token bankrolls
for (uint i=0; i<7; i++) {
controller.tokenBankrolls(i).payJackpotToWinner(_winner, payOutDivisor);
}
uint payOutAmount;
// Calculate pay out & pay out
if (zethr.balanceOf(address(this)) >= 1e10) {
payOutAmount = zethr.balanceOf(address(this)) / payOutDivisor;
}
if (payOutAmount >= 1e10) {
zethr.transfer(_winner, payOutAmount);
}
// Increment the statistics fields
payOutNumber += 1;
// Emit jackpot event
emit JackpotPayOut(_winner, payOutNumber);
}
/****************************
* EVENTS
****************************/
event JackpotPayOut(
address winner,
uint payOutNumber
);
/****************************
* MODIFIERS
****************************/
// Only an owner can call this method (controller is always an owner)
modifier ownerOnly()
{
require(msg.sender == address(controller) || controller.multiSigWallet().isOwner(msg.sender));
_;
}
// Only a game can call this method
modifier gameOnly()
{
require(controller.validGameAddresses(msg.sender));
_;
}
} | contract JackpotHolding is ERC223Receiving {
/****************************
* FIELDS
****************************/
// How many times we've paid out the jackpot
uint public payOutNumber = 0;
// The amount to divide the token balance by for a pay out (defaults to half the token balance)
uint public payOutDivisor = 2;
// Holds the bankroll controller info
ZethrBankrollControllerInterface controller;
// Zethr contract
Zethr zethr;
/****************************
* CONSTRUCTOR
****************************/
constructor (address _controllerAddress, address _zethrAddress) public {
controller = ZethrBankrollControllerInterface(_controllerAddress);
zethr = Zethr(_zethrAddress);
}
function() public payable {}
function tokenFallback(address /*_from*/, uint /*_amountOfTokens*/, bytes/*_data*/)
public
returns (bool)
{
// Do nothing, we can track the jackpot by this balance
}
/****************************
* VIEWS
****************************/
function getJackpotBalance()
public view
returns (uint)
{
// Half of this balance + half of jackpotBalance in each token bankroll
uint tempBalance;
for (uint i=0; i<7; i++) {
tempBalance += controller.tokenBankrolls(i).jackpotBalance() > 0 ? controller.tokenBankrolls(i).jackpotBalance() / payOutDivisor : 0;
}
tempBalance += zethr.balanceOf(address(this)) > 0 ? zethr.balanceOf(address(this)) / payOutDivisor : 0;
return tempBalance;
}
/****************************
* OWNER FUNCTIONS
****************************/
/** @dev Sets the pay out divisor
* @param _divisor The value to set the new divisor to
*/
function ownerSetPayOutDivisor(uint _divisor)
public
ownerOnly
{
require(_divisor != 0);
payOutDivisor = _divisor;
}
/** @dev Sets the address of the game controller
* @param _controllerAddress The new address of the controller
*/
function ownerSetControllerAddress(address _controllerAddress)
public
ownerOnly
{
controller = ZethrBankrollControllerInterface(_controllerAddress);
}
/** @dev Transfers the jackpot to _to
* @param _to Address to send the jackpot tokens to
*/
function ownerWithdrawZth(address _to)
public
ownerOnly
{
uint balance = zethr.balanceOf(address(this));
zethr.transfer(_to, balance);
}
/** @dev Transfers any ETH received from dividends to _to
* @param _to Address to send the ETH to
*/
function ownerWithdrawEth(address _to)
public
ownerOnly
{
_to.transfer(address(this).balance);
}
/****************************
* GAME FUNCTIONS
****************************/
function gamePayOutWinner(address _winner)
public
gameOnly
{
// Call the payout function on all 7 token bankrolls
for (uint i=0; i<7; i++) {
controller.tokenBankrolls(i).payJackpotToWinner(_winner, payOutDivisor);
}
uint payOutAmount;
// Calculate pay out & pay out
if (zethr.balanceOf(address(this)) >= 1e10) {
payOutAmount = zethr.balanceOf(address(this)) / payOutDivisor;
}
if (payOutAmount >= 1e10) {
zethr.transfer(_winner, payOutAmount);
}
// Increment the statistics fields
payOutNumber += 1;
// Emit jackpot event
emit JackpotPayOut(_winner, payOutNumber);
}
/****************************
* EVENTS
****************************/
event JackpotPayOut(
address winner,
uint payOutNumber
);
/****************************
* MODIFIERS
****************************/
// Only an owner can call this method (controller is always an owner)
modifier ownerOnly()
{
require(msg.sender == address(controller) || controller.multiSigWallet().isOwner(msg.sender));
_;
}
// Only a game can call this method
modifier gameOnly()
{
require(controller.validGameAddresses(msg.sender));
_;
}
} | 76,644 |
328 | // DepositCollateralDelegator dYdX Interface that smart contracts must implement in order to let other addresses deposit heldTokensinto a position owned by the smart contract. NOTE: Any contract implementing this interface should also use OnlyMargin to control accessto these functions / | interface DepositCollateralDelegator {
// ============ Public Interface functions ============
/**
* Function a contract must implement in order to let other addresses call depositCollateral().
*
* @param depositor Address of the caller of the depositCollateral() function
* @param positionId Unique ID of the position
* @param amount Requested deposit amount
* @return This address to accept, a different address to ask that contract
*/
function depositCollateralOnBehalfOf(
address depositor,
bytes32 positionId,
uint256 amount
)
external
/* onlyMargin */
returns (address);
}
| interface DepositCollateralDelegator {
// ============ Public Interface functions ============
/**
* Function a contract must implement in order to let other addresses call depositCollateral().
*
* @param depositor Address of the caller of the depositCollateral() function
* @param positionId Unique ID of the position
* @param amount Requested deposit amount
* @return This address to accept, a different address to ask that contract
*/
function depositCollateralOnBehalfOf(
address depositor,
bytes32 positionId,
uint256 amount
)
external
/* onlyMargin */
returns (address);
}
| 5,744 |
58 | // it worked, _sender placed a bid | lastAuction.highestBidder = _sender;
zoneFactory.fillCurrentZoneBidder(_sender);
zoneFactory.emitBid(geohash, _sender, currentAuctionId, _dthAmount);
| lastAuction.highestBidder = _sender;
zoneFactory.fillCurrentZoneBidder(_sender);
zoneFactory.emitBid(geohash, _sender, currentAuctionId, _dthAmount);
| 10,120 |
3 | // Verifies if the given value is valid as a move for the givennamespace.If it is not, the function throws.If it is, the fee thatshould be charged is returned. Note that the function does not know the exact name.This ensures thatthe policy cannot be abused to censor specific names (and the associatedgame assets) after they have already been accepted for registration. / | function checkMove (string memory ns, string memory mv)
external returns (uint256);
| function checkMove (string memory ns, string memory mv)
external returns (uint256);
| 6,451 |
8 | // --- gift | function freeMint(uint256 quantity) external {
require(giftedList[msg.sender], "NOT_WHITELISTED");
require(quantity <= GIFT_PER_ADDRESS, "ONLY_ONE_GIFT");
require(giftedAmount + quantity <= GIFT_LIMIT, "SUPPLY_LIMIT_EXPIRED");
require(totalMinted() + quantity <= MAX_SUPPLY, "TOKENS_EXPIRED");
giftedAmount += quantity;
giftedList[msg.sender] = false;
_safeMint(msg.sender, quantity);
}
| function freeMint(uint256 quantity) external {
require(giftedList[msg.sender], "NOT_WHITELISTED");
require(quantity <= GIFT_PER_ADDRESS, "ONLY_ONE_GIFT");
require(giftedAmount + quantity <= GIFT_LIMIT, "SUPPLY_LIMIT_EXPIRED");
require(totalMinted() + quantity <= MAX_SUPPLY, "TOKENS_EXPIRED");
giftedAmount += quantity;
giftedList[msg.sender] = false;
_safeMint(msg.sender, quantity);
}
| 16,083 |
160 | // globalConstraintsCount return the global constraint pre and post count return uint globalConstraintsPre count. return uint globalConstraintsPost count./ | function globalConstraintsCount(address _avatar)
external
isAvatarValid(_avatar)
view
returns(uint,uint)
| function globalConstraintsCount(address _avatar)
external
isAvatarValid(_avatar)
view
returns(uint,uint)
| 8,080 |
14 | // Multiplies two numbers, throws on overflow./ | function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
// Gas optimization: this is cheaper than asserting 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
| function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
// Gas optimization: this is cheaper than asserting 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
| 13,110 |
130 | // Cannot recover the staking token or the rewards token | require(tokenAddress != address(stakingToken) && tokenAddress != address(sporeToken), "Cannot withdraw the staking or rewards tokens");
| require(tokenAddress != address(stakingToken) && tokenAddress != address(sporeToken), "Cannot withdraw the staking or rewards tokens");
| 11,546 |
284 | // the creator of the contract is the initial CEO | ceoAddress = msg.sender;
| ceoAddress = msg.sender;
| 8,207 |
3 | // Event emitted when a Burner role is granted to an address./beneficiary The address that is granted the Burner role./caller The address that performed the role grant operation. | event BurnerRoleGranted(
address indexed beneficiary,
address indexed caller
);
| event BurnerRoleGranted(
address indexed beneficiary,
address indexed caller
);
| 33,247 |
360 | // What percentage of the debt will they be left with? | uint newDebt = existingDebt.sub(debtToRemove);
uint newTotalDebtIssued = totalDebtIssued.sub(debtToRemove);
uint newDebtPercentage = newDebt.divideDecimalRoundPrecise(newTotalDebtIssued);
| uint newDebt = existingDebt.sub(debtToRemove);
uint newTotalDebtIssued = totalDebtIssued.sub(debtToRemove);
uint newDebtPercentage = newDebt.divideDecimalRoundPrecise(newTotalDebtIssued);
| 6,219 |
2 | // 任务完成的评价(viewers mark) | int8 result;
| int8 result;
| 42,305 |
2 | // Emitted when the allowance of a `spender` for an `owner` is set by | * a call to {approve}. `value` is the new allowance.
*/
event QuantizedTokenGenerated(address account, address indexed token, uint256 amount);
}
| * a call to {approve}. `value` is the new allowance.
*/
event QuantizedTokenGenerated(address account, address indexed token, uint256 amount);
}
| 7,223 |
220 | // amountSpecified (Exact input: positive) (Exact output: negative) | int256 amountSpecified = -1 * int256(_amountOut);
uint160 sqrtPriceLimitX96 = (zeroForOne ? 4295128740 : 1461446703485210103287273052203988822378723970341);
| int256 amountSpecified = -1 * int256(_amountOut);
uint160 sqrtPriceLimitX96 = (zeroForOne ? 4295128740 : 1461446703485210103287273052203988822378723970341);
| 16,597 |
5 | // Returns the amount of tokens in existence. / |
function totalSupply() external view returns (uint256);
|
function totalSupply() external view returns (uint256);
| 613 |
257 | // 创建新的拍卖 | function createAuction(
uint256 _tokenId,
uint256 _startingPrice,
uint256 _endingPrice,
uint256 _duration,
address _seller
) external {
require(_startingPrice == uint256(uint128(_startingPrice)));
require(_endingPrice == uint256(uint128(_endingPrice)));
require(_duration == uint256(uint64(_duration)));
| function createAuction(
uint256 _tokenId,
uint256 _startingPrice,
uint256 _endingPrice,
uint256 _duration,
address _seller
) external {
require(_startingPrice == uint256(uint128(_startingPrice)));
require(_endingPrice == uint256(uint128(_endingPrice)));
require(_duration == uint256(uint64(_duration)));
| 44,134 |
6 | // Super simple bridge that bridges Eth from Mainnet and Optimism. | contract Bridge {
address public owner;
event BridgeEth(uint256 amount, uint256 targetChain);
constructor(address _owner) {
owner = _owner;
}
function verifyChain(uint256 targetChain) public pure returns (bool) {
// optimism = 420
// mainnet = 1
if (targetChain == 420 || targetChain == 1) return true;
return false;
}
function withdraw(uint256 amount) external {
require(msg.sender == owner);
(bool success,) = owner.call{value: amount}("");
require(success, "transfer failed");
}
function thisChain() public view returns (uint256) {
return block.chainid;
}
function bridgeEth(uint256 targetChain) external payable {
require(verifyChain(targetChain), "invalid chain");
emit BridgeEth(msg.value, targetChain);
}
}
| contract Bridge {
address public owner;
event BridgeEth(uint256 amount, uint256 targetChain);
constructor(address _owner) {
owner = _owner;
}
function verifyChain(uint256 targetChain) public pure returns (bool) {
// optimism = 420
// mainnet = 1
if (targetChain == 420 || targetChain == 1) return true;
return false;
}
function withdraw(uint256 amount) external {
require(msg.sender == owner);
(bool success,) = owner.call{value: amount}("");
require(success, "transfer failed");
}
function thisChain() public view returns (uint256) {
return block.chainid;
}
function bridgeEth(uint256 targetChain) external payable {
require(verifyChain(targetChain), "invalid chain");
emit BridgeEth(msg.value, targetChain);
}
}
| 24,149 |
3 | // Ownership Marketplace library. / | library Ownership {
bytes32 public constant SPLIT_TYPEHASH = keccak256("Split(address account,uint96 shares)");
struct Split {
address payable account;
uint96 shares;
}
struct Royalties {
Split[] splits;
uint96 percentage;
}
function hash(Split memory split) internal pure returns (bytes32) {
return keccak256(abi.encode(SPLIT_TYPEHASH, split.account, split.shares));
}
}
| library Ownership {
bytes32 public constant SPLIT_TYPEHASH = keccak256("Split(address account,uint96 shares)");
struct Split {
address payable account;
uint96 shares;
}
struct Royalties {
Split[] splits;
uint96 percentage;
}
function hash(Split memory split) internal pure returns (bytes32) {
return keccak256(abi.encode(SPLIT_TYPEHASH, split.account, split.shares));
}
}
| 28,516 |
17 | // this function is called by buyer to finalize the transaction/ | function releaseFunds(bytes32 escrowID) external onlyBuyer(escrowID) {
require(
escrowTransactions[escrowID].status == EscrowStatus.Delivered,
"Can't release funds"
);
escrowTransactions[escrowID].status = EscrowStatus.Released;
if (escrowTransactions[escrowID].escrow_type == EscrowType.BuyEscrow) {
address payable seller = payable(escrowTransactions[escrowID].seller);
seller.transfer(escrowTransactions[escrowID].price);
} else if (
escrowTransactions[escrowID].escrow_type == EscrowType.SellEscrow
) {
address payable seller = payable(escrowTransactions[escrowID].seller);
seller.transfer((escrowTransactions[escrowID].price / 1025) * 1000);
}
emit EscrowReleased(escrowID);
}
| function releaseFunds(bytes32 escrowID) external onlyBuyer(escrowID) {
require(
escrowTransactions[escrowID].status == EscrowStatus.Delivered,
"Can't release funds"
);
escrowTransactions[escrowID].status = EscrowStatus.Released;
if (escrowTransactions[escrowID].escrow_type == EscrowType.BuyEscrow) {
address payable seller = payable(escrowTransactions[escrowID].seller);
seller.transfer(escrowTransactions[escrowID].price);
} else if (
escrowTransactions[escrowID].escrow_type == EscrowType.SellEscrow
) {
address payable seller = payable(escrowTransactions[escrowID].seller);
seller.transfer((escrowTransactions[escrowID].price / 1025) * 1000);
}
emit EscrowReleased(escrowID);
}
| 12,122 |
25 | // set the Oracle to be used by this UA for LayerZero messages | function setOracle(uint16 dstChainId, address oracle) external {
// should technically be onlyOwner but this is a mock
uint TYPE_ORACLE = 6; // from UltraLightNode
// set the Oracle
// uint16 _version, uint16 _chainId, uint _configType, bytes calldata _config
endpoint.setConfig(endpoint.getSendVersion(address(this)), dstChainId, TYPE_ORACLE, abi.encode(oracle));
}
| function setOracle(uint16 dstChainId, address oracle) external {
// should technically be onlyOwner but this is a mock
uint TYPE_ORACLE = 6; // from UltraLightNode
// set the Oracle
// uint16 _version, uint16 _chainId, uint _configType, bytes calldata _config
endpoint.setConfig(endpoint.getSendVersion(address(this)), dstChainId, TYPE_ORACLE, abi.encode(oracle));
}
| 27,450 |
130 | // Emits a {Approval} event | function _approve(address _owner, address _spender, uint96 amount) internal {
require(_owner != address(0), "ERC20: approve from the zero address");
require(_spender != address(0), "ERC20: approve to the zero address");
allowances[_owner][_spender] = amount;
emit Approval(_owner, _spender, amount);
}
| function _approve(address _owner, address _spender, uint96 amount) internal {
require(_owner != address(0), "ERC20: approve from the zero address");
require(_spender != address(0), "ERC20: approve to the zero address");
allowances[_owner][_spender] = amount;
emit Approval(_owner, _spender, amount);
}
| 58,383 |
6,366 | // 3185 | entry "reduplicatively" : ENG_ADVERB
| entry "reduplicatively" : ENG_ADVERB
| 24,021 |
155 | // mint_amount = token_supply(D2 - D0) / D0 | mint_amount = totalSupply().mul(D2.sub(D0)).div(D0);
| mint_amount = totalSupply().mul(D2.sub(D0)).div(D0);
| 52,790 |
20 | // Store the persons details into the arrays | for(uint i = 0; i<personCount; i++){
NationalIDArray[i] = PersonsArray[i];
FirstNameArray[i] = PersonMap[PersonsArray[i]].FirstName;
LastNameArray[i] = PersonMap[PersonsArray[i]].LastName;
GenderArray[i] = PersonMap[PersonsArray[i]].Gender;
DateOfBirthArray[i] = PersonMap[PersonsArray[i]].DateOfBirth;
ImageLinkArray[i] = PersonMap[PersonsArray[i]].ImageLink;
AddressArray[i] = PersonMap[PersonsArray[i]].PersonAddress;
}
| for(uint i = 0; i<personCount; i++){
NationalIDArray[i] = PersonsArray[i];
FirstNameArray[i] = PersonMap[PersonsArray[i]].FirstName;
LastNameArray[i] = PersonMap[PersonsArray[i]].LastName;
GenderArray[i] = PersonMap[PersonsArray[i]].Gender;
DateOfBirthArray[i] = PersonMap[PersonsArray[i]].DateOfBirth;
ImageLinkArray[i] = PersonMap[PersonsArray[i]].ImageLink;
AddressArray[i] = PersonMap[PersonsArray[i]].PersonAddress;
}
| 32,449 |
230 | // Verify signature | bytes32 signedMessageHash = hashForSignature(
_symbol,
_recipient,
_amount,
msg.sender,
_nHash
);
require(
status[signedMessageHash] == false,
"Gateway: nonce hash already spent"
| bytes32 signedMessageHash = hashForSignature(
_symbol,
_recipient,
_amount,
msg.sender,
_nHash
);
require(
status[signedMessageHash] == false,
"Gateway: nonce hash already spent"
| 9,985 |
187 | // Maximum number of premium and ultra premium mints | uint256 public constant MAXIMUM_PREMIUM_MINTS = 2000;
uint256 public constant MAXIMUM_ULTRA_PREMIUM_MINTS = 500;
| uint256 public constant MAXIMUM_PREMIUM_MINTS = 2000;
uint256 public constant MAXIMUM_ULTRA_PREMIUM_MINTS = 500;
| 20,094 |
54 | // Calculates sqrt(a), following the selected rounding direction. / | function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = sqrt(a);
return result + (rounding == Rounding.Up && result * result < a ? 1 : 0);
}
}
| function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = sqrt(a);
return result + (rounding == Rounding.Up && result * result < a ? 1 : 0);
}
}
| 440 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.