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
195
// require(canClaim(destination, amount, merkleProof), "I");
if (!canClaim(destination, amount, merkleProof)) { revert NoClaimExists(); }
if (!canClaim(destination, amount, merkleProof)) { revert NoClaimExists(); }
22,294
85
// The number of tokens burned.
uint256 internal _burnCounter;
uint256 internal _burnCounter;
16,284
54
// Execute options during the ICO token purchase. Priority: GVOT30 -> GVOT20 -> GVOT10
function executeOptions(address buyer, uint usdCents, string txHash) icoOnly
function executeOptions(address buyer, uint usdCents, string txHash) icoOnly
53,801
154
// something about rate, account, total amount / Currency of the game machine, like AZUKI, WETH, Chianbinders.
IERC20 public currencyToken; IMomijiToken public momijiToken; uint256 public playOncePrice; address public administrator; event AddCard(uint256 cardId, uint256 amount, uint256 cardAmount); event RemoveCard(uint256 card, uint256 removeAmount, uint256 cardAmount); event RunMachineSuccessfully(address account, uint256 times, uint256 playFee);
IERC20 public currencyToken; IMomijiToken public momijiToken; uint256 public playOncePrice; address public administrator; event AddCard(uint256 cardId, uint256 amount, uint256 cardAmount); event RemoveCard(uint256 card, uint256 removeAmount, uint256 cardAmount); event RunMachineSuccessfully(address account, uint256 times, uint256 playFee);
12,446
1
// Reference to the Gearbox creditFacade contract for the primary token of this vault.
function creditFacade() external view returns (ICreditFacade);
function creditFacade() external view returns (ICreditFacade);
31,596
23
// Check if about 50% of airlines approve registration of new airline
if ( votings >= registeredAirlines.div(2) ) { airLines[id] = AirLine({ id: id, isRegistered: true, isAdmin: 0 });
if ( votings >= registeredAirlines.div(2) ) { airLines[id] = AirLine({ id: id, isRegistered: true, isAdmin: 0 });
11,429
44
// MathHelpers dYdX This library helps with common math functions in Solidity /
library MathHelpers { using SafeMath for uint256; /** * Calculates partial value given a numerator and denominator. * * @param numerator Numerator * @param denominator Denominator * @param target Value to calculate partial of * @return target * numerator / denominator */ function getPartialAmount( uint256 numerator, uint256 denominator, uint256 target ) internal pure returns (uint256) { return numerator.mul(target).div(denominator); } /** * Calculates partial value given a numerator and denominator, rounded up. * * @param numerator Numerator * @param denominator Denominator * @param target Value to calculate partial of * @return Rounded-up result of target * numerator / denominator */ function getPartialAmountRoundedUp( uint256 numerator, uint256 denominator, uint256 target ) internal pure returns (uint256) { return divisionRoundedUp(numerator.mul(target), denominator); } /** * Calculates division given a numerator and denominator, rounded up. * * @param numerator Numerator. * @param denominator Denominator. * @return Rounded-up result of numerator / denominator */ function divisionRoundedUp( uint256 numerator, uint256 denominator ) internal pure returns (uint256) { assert(denominator != 0); // coverage-enable-line if (numerator == 0) { return 0; } return numerator.sub(1).div(denominator).add(1); } /** * Calculates and returns the maximum value for a uint256 in solidity * * @return The maximum value for uint256 */ function maxUint256( ) internal pure returns (uint256) { return 2 ** 256 - 1; } /** * Calculates and returns the maximum value for a uint256 in solidity * * @return The maximum value for uint256 */ function maxUint32( ) internal pure returns (uint32) { return 2 ** 32 - 1; } /** * Returns the number of bits in a uint256. That is, the lowest number, x, such that n >> x == 0 * * @param n The uint256 to get the number of bits in * @return The number of bits in n */ function getNumBits( uint256 n ) internal pure returns (uint256) { uint256 first = 0; uint256 last = 256; while (first < last) { uint256 check = (first + last) / 2; if ((n >> check) == 0) { last = check; } else { first = check + 1; } } assert(first <= 256); return first; } }
library MathHelpers { using SafeMath for uint256; /** * Calculates partial value given a numerator and denominator. * * @param numerator Numerator * @param denominator Denominator * @param target Value to calculate partial of * @return target * numerator / denominator */ function getPartialAmount( uint256 numerator, uint256 denominator, uint256 target ) internal pure returns (uint256) { return numerator.mul(target).div(denominator); } /** * Calculates partial value given a numerator and denominator, rounded up. * * @param numerator Numerator * @param denominator Denominator * @param target Value to calculate partial of * @return Rounded-up result of target * numerator / denominator */ function getPartialAmountRoundedUp( uint256 numerator, uint256 denominator, uint256 target ) internal pure returns (uint256) { return divisionRoundedUp(numerator.mul(target), denominator); } /** * Calculates division given a numerator and denominator, rounded up. * * @param numerator Numerator. * @param denominator Denominator. * @return Rounded-up result of numerator / denominator */ function divisionRoundedUp( uint256 numerator, uint256 denominator ) internal pure returns (uint256) { assert(denominator != 0); // coverage-enable-line if (numerator == 0) { return 0; } return numerator.sub(1).div(denominator).add(1); } /** * Calculates and returns the maximum value for a uint256 in solidity * * @return The maximum value for uint256 */ function maxUint256( ) internal pure returns (uint256) { return 2 ** 256 - 1; } /** * Calculates and returns the maximum value for a uint256 in solidity * * @return The maximum value for uint256 */ function maxUint32( ) internal pure returns (uint32) { return 2 ** 32 - 1; } /** * Returns the number of bits in a uint256. That is, the lowest number, x, such that n >> x == 0 * * @param n The uint256 to get the number of bits in * @return The number of bits in n */ function getNumBits( uint256 n ) internal pure returns (uint256) { uint256 first = 0; uint256 last = 256; while (first < last) { uint256 check = (first + last) / 2; if ((n >> check) == 0) { last = check; } else { first = check + 1; } } assert(first <= 256); return first; } }
41,346
444
// ================================= MUTATIVE FUNCTIONS ====================== /
function transfer(address to, uint256 value) public override returns (bool) { uint256 gonValue = value.mul(_gonsPerFragment); _gonBalances[ msg.sender ] = _gonBalances[ msg.sender ].sub(gonValue); _gonBalances[ to ] = _gonBalances[ to ].add(gonValue); emit Transfer(msg.sender, to, value); return true; }
function transfer(address to, uint256 value) public override returns (bool) { uint256 gonValue = value.mul(_gonsPerFragment); _gonBalances[ msg.sender ] = _gonBalances[ msg.sender ].sub(gonValue); _gonBalances[ to ] = _gonBalances[ to ].add(gonValue); emit Transfer(msg.sender, to, value); return true; }
32,914
29
// there are non-ascii characters – we have to crash
revert NotAscii();
revert NotAscii();
37,600
6
// `SignatureType.Wallet` callback, so that this bridge can be the maker/and sign for itself in orders. Always succeeds./ return magicValue Magic success bytes, always.
function isValidSignature( bytes32, bytes calldata ) external view returns (bytes4 magicValue)
function isValidSignature( bytes32, bytes calldata ) external view returns (bytes4 magicValue)
7,926
136
// roll 3 turns
for (uint256 i = 0; i < 3; i++){ uint256 winNr = Helper.getRandom(_seed, weightRange);
for (uint256 i = 0; i < 3; i++){ uint256 winNr = Helper.getRandom(_seed, weightRange);
15,818
4,466
// 2235
entry "exackly" : ENG_ADVERB
entry "exackly" : ENG_ADVERB
23,071
9
// GET the PRICE in the case of PRESALE and PUBLICSALE
price = 0;
price = 0;
17,215
179
// Remove any current role bearer for a given role and emit a`RoleModified` event if a role holder was previously set. Only the ownermay call this function. role The role that the account will be removed from. Permitted rolesare operator (0), recoverer (1), canceller (2), disabler (3), andpauser (4). /
function removeRole(Role role) external onlyOwner { _setRole(role, address(0)); }
function removeRole(Role role) external onlyOwner { _setRole(role, address(0)); }
5,879
47
// next we need to allow the uniswapv2 router to spend the token we just sent to this contractby calling IERC20 approve you allow the uniswap contract to spend the tokens in this contract
IERC20(_tokenIn).approve(_router, _amountIn);
IERC20(_tokenIn).approve(_router, _amountIn);
5,914
42
// only owner address can set owner address / function ownerChangeOwner(address newOwner) public onlyOwner
// { // owner = newOwner; // }
// { // owner = newOwner; // }
12,295
8
// Returns true if an account is an operator of `tokenHolder`.Operators can send and burn tokens on behalf of their owners. Allaccounts are their own operator. See {operatorSend} and {operatorBurn}. /
function isOperatorFor(address operator, address tokenHolder) external view returns (bool);
function isOperatorFor(address operator, address tokenHolder) external view returns (bool);
20,161
221
// contracts/libraries/Silo.sol/ pragma solidity ^0.8.10; // import "@openzeppelin/contracts/utils/Address.sol"; // import "contracts/interfaces/ISilo.sol"; /
library Silo { using Address for address; function delegate_poke(ISilo silo) internal { address(silo).functionDelegateCall(abi.encodeWithSelector(silo.poke.selector)); } function delegate_deposit(ISilo silo, uint256 amount) internal { address(silo).functionDelegateCall(abi.encodeWithSelector(silo.deposit.selector, amount)); } function delegate_withdraw(ISilo silo, uint256 amount) internal { address(silo).functionDelegateCall(abi.encodeWithSelector(silo.withdraw.selector, amount)); } }
library Silo { using Address for address; function delegate_poke(ISilo silo) internal { address(silo).functionDelegateCall(abi.encodeWithSelector(silo.poke.selector)); } function delegate_deposit(ISilo silo, uint256 amount) internal { address(silo).functionDelegateCall(abi.encodeWithSelector(silo.deposit.selector, amount)); } function delegate_withdraw(ISilo silo, uint256 amount) internal { address(silo).functionDelegateCall(abi.encodeWithSelector(silo.withdraw.selector, amount)); } }
57,846
34
// Transfer redemption fee to humanityCashAddress
erc20Token.transfer(humanityCashAddress, redemptionFeeAmount); burnAmount = burnAmount - redemptionFeeAmount; emit RedemptionFee(humanityCashAddress, redemptionFeeAmount);
erc20Token.transfer(humanityCashAddress, redemptionFeeAmount); burnAmount = burnAmount - redemptionFeeAmount; emit RedemptionFee(humanityCashAddress, redemptionFeeAmount);
24,706
27
// Standard function transfer similar to ERC20 ERC223 transfer with no _data . Added due to backwards compatibility reasons .transfer token for a user or another contract addressfor ERC20 and ERC223_to The user address or contract address to transfer to._value The amount to be transferred./
function transfer(address _to, uint256 _value) public returns (bool) { //standard function transfer similar to ERC20 transfer with no _data //added due to backwards compatibility reasons bytes memory empty; if(isContract(_to)) { return transferToContract(_to, _value, empty); } else { return transferToAddress(_to, _value, empty); } }
function transfer(address _to, uint256 _value) public returns (bool) { //standard function transfer similar to ERC20 transfer with no _data //added due to backwards compatibility reasons bytes memory empty; if(isContract(_to)) { return transferToContract(_to, _value, empty); } else { return transferToAddress(_to, _value, empty); } }
53,463
202
// Check credentials
require(workerPoolHub.isWorkerPoolRegistered(msg.sender));
require(workerPoolHub.isWorkerPoolRegistered(msg.sender));
22,901
264
// Extension of the ERC721Enumerable contract that integrates a marketplace so that simple lazy-salesand auctions do not have to be done on another contract. This saves gas fees on secondary sales becausebuyers will not have to pay a gas fee to setApprovalForAll for another marketplace contract after buying. Easely will help power the lazy-selling and auctions as well as lazy minting that take place on directly on the collection, which is why we take a cut of these transactions. Our cut can be publically seen in the connected EaselyPayout contract. /
abstract contract EaselyMarketplaceCollection is ERC721Enumerable, Ownable { using ECDSA for bytes32; using Strings for uint256; /** * @dev Auction structure that includes: * * @param address topBidder - Current top bidder who has already paid the price param below. Is * initialized with address(0) when there have been no bids. When a bidder gets outBid, * the old topBidder will get the price they paid returned. * @param uint256 price - Current top price paid by the topBidder. * @param uint256 startTimestamp - When the auction can start getting bidded on. * @param uint256 endTimestamp - When the auction can no longer get bid on. * @param uint256 minBidIncrement - The minimum each new bid has to be greater than the previous * bid in order to be the next topBidder. * @param uint256 minLastBidDuration - The minimum time each bid must hold the highest price before * the auction can settle. If people keep bidding, the auction can last for much longer than * the initial endTimestamp, and endTimestamp will continually be updated. */ struct Auction { address topBidder; uint256 tokenId; uint256 price; uint256 startTimestamp; uint256 endTimestamp; uint256 minBidIncrement; uint256 minLastBidDuration; } /* see {IEaselyPayout} for more */ address public payoutContractAddress; /* Let's the owner enable another address to lazy mint */ address public alternateSignerAddress; uint256 internal nextAuctionId; uint256 public timePerDecrement; uint256 public constant maxRoyaltiesBPS = 9500; /* Optional basis points for the owner for secondary sales of this collection */ uint256 public constant maxSecondaryBPS = 1000; /* Optional basis points for the owner for secondary sales of this collection */ uint256 public secondaryOwnerBPS; /* Optional addresses to distribute royalties for primary sales of this collection */ address[] public royalties; /* Optional basis points for above royalties addresses for primary sales of this collection */ uint256[] public royaltiesBPS; /* Mapping if a tokenId has an active auction or not */ mapping(uint256 => uint256) private _tokenIdToAuctionId; /* Mapping for all auctions that have happened. */ mapping(uint256 => Auction) private _auctionIdToAuction; /* Mapping to the active version for all signed transactions */ mapping(address => uint256) internal _addressToActiveVersion; /* Cancelled or finalized sales by hash to determine buyabliity */ mapping(bytes32 => bool) internal _cancelledOrFinalizedSales; // Events related to an auction event AuctionCreated(uint256 indexed auctionId, uint256 indexed tokenId, uint256 startingPrice, uint256 startingTimestamp, uint256 endingTimestamp, uint256 minBidIncrement, uint256 minLastBidDuration, address indexed seller); event AuctionTimeAltered(uint256 indexed auctionId, uint256 indexed tokenId, uint256 startTime, uint256 endTime, address indexed seller); event AuctionCancelled(uint256 indexed auctionId, uint256 indexed tokenId, address indexed seller); event AuctionBidded(uint256 indexed auctionId, uint256 indexed tokenId, uint256 newPrice, uint256 timestamp, address indexed bidder); event AuctionSettled(uint256 indexed auctionId, uint256 indexed tokenId, uint256 price, address buyer, address indexed seller); // Events related to lazy selling event SaleCancelled(address indexed seller, bytes32 hash); event SaleCompleted(uint256 indexed tokenId, uint256 price, address indexed seller, address indexed buyer, bytes32 hash); // Miscellaneous events event VersionChanged(address indexed seller, uint256 version); event AltSignerChanged(address newSigner); /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || interfaceId == type(Ownable).interfaceId || interfaceId == type(IERC2981).interfaceId || super.supportsInterface(interfaceId); } /** * @dev see {IERC2981-supportsInterface} */ function royaltyInfo(uint256 _tokenId, uint256 _salePrice) external view returns (address receiver, uint256 royaltyAmount) { uint256 royalty = _salePrice * secondaryOwnerBPS / 10000; return (owner(), royalty); } /** * @dev Returns the current auction variables for a tokenId if the auction is present */ function getAuctionForTokenId(uint256 tokenId) external view returns (Auction memory) { // _getAuctionId will error if token is not on an auction uint256 auctionId = _getAuctionId(tokenId); return _auctionIdToAuction[auctionId]; } /** * @dev See {_getAuctionId} */ function getAuctionId(uint256 tokenId) external view returns (uint256) { return _getAuctionId(tokenId); } /** * @dev Returns the current auction variables for a tokenId if the auction is present */ function getAuction(uint256 auctionId) external view returns (Auction memory) { require(_auctionIdToAuction[auctionId].minBidIncrement != 0, "This auction does not exist"); return _auctionIdToAuction[auctionId]; } /** * @dev See {_currentPrice} */ function getCurrentPrice(uint256[4] memory pricesAndTimestamps) external view returns (uint256) { return _currentPrice(pricesAndTimestamps); } /** * @dev Returns the current activeVersion of an address both used to create signatures * and to verify signatures of {buyToken} and {buyNewToken} */ function getActiveVersion(address address_) external view returns (uint256) { return _addressToActiveVersion[address_]; } /** * @dev Allows the owner to change who the alternate signer is */ function setAltSigner(address alt) external onlyOwner { alternateSignerAddress = alt; emit AltSignerChanged(alt); } /** * @dev see {_setRoyalties} */ function setRoyalties(address[4] memory newRoyalties, uint256[4] memory bps) external onlyOwner { _setRoyalties(newRoyalties, bps); } /** * @dev see {_setSecondary} */ function setSecondaryBPS(uint256 bps) external onlyOwner() { _setSecondary(bps); } /** * @dev Usable by any user to update the version that they want their signatures to check. This is helpful if * an address wants to mass invalidate their signatures without having to call cancelSale on each one. */ function updateVersion(uint256 version) external { _addressToActiveVersion[_msgSender()] = version; emit VersionChanged(_msgSender(), version); } /** * @dev Creates an auction for a token and locks it from being transferred until the auction ends * the auction can end if the endTimestamp has been reached and can be cancelled prematurely if * there has been no bids yet. * * @param tokenId uint256 for the token to put on auction. Must exist and be on the auction already * @param startingPrice uint256 for the starting price an interested owner must bid * @param startingTimestamp uint256 for when the auction can start taking bids * @param endingTimestamp uint256 for when the auction has concluded and can no longer take bids * @param minBidIncrement uint256 the minimum each interested owner must bid over the latest bid * @param minLastBidDuration uint256 the minimum time a bid needs to be live before the auction can end. * this means that an auction can extend past its original endingTimestamp */ function createAuction( uint256 tokenId, uint256 startingPrice, uint256 startingTimestamp, uint256 endingTimestamp, uint256 minBidIncrement, uint256 minLastBidDuration ) external { require(endingTimestamp > block.timestamp, "Cannot create an auction in the past"); require(!_onAuction(tokenId), "Token is already on auction"); require(minBidIncrement > 0, "Min bid must be a positive number"); require(_msgSender() == ownerOf(tokenId), "Must own token to create auction"); Auction memory auction = Auction(address(0), tokenId, startingPrice, startingTimestamp, endingTimestamp, minBidIncrement, minLastBidDuration); // This locks the token from being sold _tokenIdToAuctionId[tokenId] = nextAuctionId; _auctionIdToAuction[nextAuctionId] = auction; emit AuctionCreated(nextAuctionId, tokenId, startingPrice, startingTimestamp, endingTimestamp, minBidIncrement, minLastBidDuration, ownerOf(tokenId)); nextAuctionId += 1; } /** * @dev Lets the token owner alter the start and end time of an auction in case they want to * end an auction early, extend the auction, or start it early. * * Changes to endTime can only be made when the auction is not within a minLastBidDuration from ending. * Changes to startTime can only be made when the auction has not yet started. */ function alterAuctionTime(uint256 tokenId, uint256 startTime, uint256 endTime) external { // _getAuctionId will error if token is not on an auction uint256 auctionId = _getAuctionId(tokenId); uint256 time = block.timestamp; require(_msgSender() == ownerOf(tokenId), "Only token owner can alter end time"); Auction memory auction = _auctionIdToAuction[auctionId]; require(auction.endTimestamp > time + auction.minLastBidDuration, "Auction has ended or is close to ending"); // if the auction has already started we cannot change the start time if (auction.startTimestamp > time) { auction.startTimestamp = startTime; } auction.endTimestamp = endTime; _auctionIdToAuction[auctionId] = auction; emit AuctionTimeAltered(auctionId, tokenId, startTime, endTime, ownerOf(tokenId)); } /** * @dev Allows the token owner to cancel an auction that does not yet have a bid. */ function cancelAuction(uint256 tokenId) external { // _getAuctionId will error if token is not on an auction uint256 auctionId = _getAuctionId(tokenId); require(_msgSender() == ownerOf(tokenId), "Only token owner can cancel auction"); require(_auctionIdToAuction[auctionId].topBidder == address(0), "Cannot cancel an auction with a bid"); _tokenIdToAuctionId[tokenId] = 0; emit AuctionCancelled(auctionId, tokenId, ownerOf(tokenId)); } /** * @dev Method that anyone can call to settle the auction. It is available to everyone * because the settlement is not dependent on the message sender, and will allow either * the buyer, the seller, or a third party to cover the gas fees to settle. The burdern of * the auction to settle should be on the seller, but in case there are issues with * the seller settling we will not be locked from settling. * * If the seller is the contract owner, this is considered a primary sale and royalties will * be paid to primiary royalties. If the seller is a user then it is a secondary sale and * the contract owner will get a secondary sale cut. */ function settleAuction(uint256 tokenId) external { // _getAuctionId will error if token is not on an auction uint256 auctionId = _getAuctionId(tokenId); Auction memory auction = _auctionIdToAuction[auctionId]; address tokenOwner = ownerOf(tokenId); require(block.timestamp > auction.endTimestamp, "Auction must end to be settled"); require(auction.topBidder != address(0), "No bidder, cancel the auction instead"); // This will allow transfers again _tokenIdToAuctionId[tokenId] = 0; _transfer(tokenOwner, auction.topBidder, tokenId); if (tokenOwner == owner()) { IEaselyPayout(payoutContractAddress).splitPayable{ value: auction.price }(tokenOwner, royalties, royaltiesBPS); } else { address[] memory ownerRoyalties = new address[](1); uint256[] memory ownerBPS = new uint256[](1); ownerRoyalties[0] = owner(); ownerBPS[0] = secondaryOwnerBPS; IEaselyPayout(payoutContractAddress).splitPayable{ value: auction.price }(tokenOwner, ownerRoyalties, ownerBPS); } emit AuctionSettled(auctionId, tokenId, auction.price, auction.topBidder, tokenOwner); } /** * @dev Allows any potential buyer to submit a bid on a token with an auction. When outbidding the current topBidder * the contract returns the value that the previous bidder had escrowed to the contract. */ function bidOnAuction(uint256 tokenId) external payable { // _getAuctionId will error if token is not on an auction uint256 auctionId = _getAuctionId(tokenId); uint256 timestamp = block.timestamp; Auction memory auction = _auctionIdToAuction[auctionId]; uint256 msgValue = msg.value; address prevBidder = auction.topBidder; uint256 prevPrice = auction.price; // Tokens that are not on auction always have an endTimestamp of 0 require(timestamp <= auction.endTimestamp, "Auction has already ended"); require(timestamp >= auction.startTimestamp, "Auction has not started yet"); uint256 minPrice = prevPrice + auction.minBidIncrement; if (prevBidder == address(0)) { minPrice = prevPrice; } require(msgValue >= minPrice, "Bid is too small"); uint256 endTime = auction.endTimestamp; if (endTime < auction.minLastBidDuration + timestamp) { endTime = timestamp + auction.minLastBidDuration; } auction.endTimestamp = endTime; auction.price = msgValue; auction.topBidder = _msgSender(); _auctionIdToAuction[auctionId] = auction; if (prevBidder != address(0)) { // Give the old top bidder their money back payable(prevBidder).transfer(prevPrice); } emit AuctionBidded(auctionId, tokenId, auction.price, timestamp, auction.topBidder); } /** * @dev Usable by the owner of any token initiate a sale for their token. This does not * lock the tokenId and the owner can freely trade their token because unlike auctions * sales would be immediate. */ function hashToSignToSellToken( uint256 version, uint256 nonce, uint256 tokenId, uint256[4] memory pricesAndTimestamps ) external view returns (bytes32) { require(_msgSender() == ownerOf(tokenId), "Not the owner of the token"); return _hashForSale(_msgSender(), version, nonce, tokenId, pricesAndTimestamps); } /** * @dev With a hash signed by the method {hashToSignToSellToken} any user sending enough value can buy * the token from the seller. These are all considered secondary sales and will give a cut to the * owner of the contract based on the secondaryOwnerBPS. */ function buyToken( address seller, uint256 version, uint256 nonce, uint256 tokenId, uint256[4] memory pricesAndTimestamps, bytes memory signature ) external payable { uint256 currentPrice = _currentPrice(pricesAndTimestamps); require(_addressToActiveVersion[seller] == version, "Incorrect signature version"); require(msg.value >= currentPrice, "Not enough ETH to buy"); _markHashSold(seller, version, nonce, tokenId, pricesAndTimestamps, currentPrice, signature); _transfer(seller, _msgSender(), tokenId); IEaselyPayout(payoutContractAddress).splitPayable{ value: currentPrice }(seller, _ownerRoyalties(), _ownerBPS()); payable(_msgSender()).transfer(msg.value - currentPrice); } /** * @dev Usable to cancel hashes generated from {hashToSignToSellToken} */ function cancelSale( uint256 version, uint256 nonce, uint256 tokenId, uint256[4] memory pricesAndTimestamps ) external { bytes32 hash = _hashToCheckForSale(_msgSender(), version, nonce, tokenId, pricesAndTimestamps); _cancelledOrFinalizedSales[hash] = true; emit SaleCancelled(_msgSender(), hash); } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual override returns (string memory) { return "ipfs://"; } /** * @dev Changing _beforeTokenTransfer to lock tokens that are in an auction so * that owner cannot transfer the token as people are bidding on it. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { require(!_onAuction(tokenId), "Cannot transfer a token in an auction"); super._beforeTokenTransfer(from, to, tokenId); } /** * @dev checks if a token is in an auction or not. We make sure that no active auction can * have an endTimestamp of 0. */ function _onAuction(uint256 tokenId) internal view returns (bool) { return _tokenIdToAuctionId[tokenId] != 0; } /** * @dev returns the auctionId of a tokenId if the token is on auction. */ function _getAuctionId(uint256 tokenId) internal view returns (uint256) { require(_onAuction(tokenId), "This token is not on auction"); return _tokenIdToAuctionId[tokenId]; } /** * @dev helper method get ownerRoyalties into an array form */ function _ownerRoyalties() internal view returns (address[] memory) { address[] memory ownerRoyalties = new address[](1); ownerRoyalties[0] = owner(); return ownerRoyalties; } /** * @dev helper method get secondary BPS into array form */ function _ownerBPS() internal view returns (uint256[] memory) { uint256[] memory ownerBPS = new uint256[](1); ownerBPS[0] = secondaryOwnerBPS; return ownerBPS; } /** * @dev Current price for a sale which is calculated for the case of a descending auction. So * the ending price must be less than the starting price and the auction must have already started. * Standard single fare sales will have a matching starting and ending price. */ function _currentPrice(uint256[4] memory pricesAndTimestamps) internal view returns (uint256) { uint256 startingPrice = pricesAndTimestamps[0]; uint256 endingPrice = pricesAndTimestamps[1]; uint256 startingTimestamp = pricesAndTimestamps[2]; uint256 endingTimestamp = pricesAndTimestamps[3]; uint256 currTime = block.timestamp; require(currTime >= startingTimestamp, "Has not started yet"); require(startingTimestamp < endingTimestamp, "Must end after it starts"); require(startingPrice >= endingPrice, "Ending price cannot be bigger"); if (startingPrice == endingPrice || currTime > endingTimestamp) { return endingPrice; } uint256 diff = startingPrice - endingPrice; uint256 decrements = (currTime - startingTimestamp) / timePerDecrement; if (decrements == 0) { return startingPrice; } // decrements will equal 0 before totalDecrements does so we will not divide by 0 uint256 totalDecrements = (endingTimestamp - startingTimestamp) / timePerDecrement; return startingPrice - diff / totalDecrements * decrements; } /** * @dev Sets secondary BPS amount */ function _setSecondary(uint256 secondary) internal { secondaryOwnerBPS = secondary; require(secondaryOwnerBPS <= maxSecondaryBPS, "Cannot take more than 10% of secondaries"); } /** * @dev Sets primary royalties */ function _setRoyalties(address[4] memory newRoyalties, uint256[4] memory bps) internal { require(bps[0] + bps[1] + bps[2] + bps[3] <= maxRoyaltiesBPS, "Royalties too high"); royalties = newRoyalties; royaltiesBPS = bps; } /** * @dev Checks if an address is either the owner, or the approved alternate signer. */ function _checkValidSigner(address signer) internal view { require(signer == owner() || signer == alternateSignerAddress, "Not valid signer."); } /** * toEthSignedMessageHash * @dev prefix a bytes32 value with "\x19Ethereum Signed Message:" * and hash the result */ function _toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } /** * @dev First checks if a sale is valid by checking that the hash has not been cancelled or already completed * and that the correct address has given the signature. If both checks pass we mark the hash as complete and * emit an event. */ function _markHashSold( address owner, uint256 version, uint256 nonce, uint256 tokenId, uint256[4] memory pricesAndTimestamps, uint256 salePrice, bytes memory signature ) internal { bytes32 hash = _hashToCheckForSale(owner, version, nonce, tokenId, pricesAndTimestamps); require(!_cancelledOrFinalizedSales[hash], "Sale no longer active"); require(hash.recover(signature) == owner, "Not signed by current token owner"); _cancelledOrFinalizedSales[hash] = true; emit SaleCompleted(tokenId, salePrice, owner, _msgSender(), hash); } /** * @dev Hash an order, returning the hash that a client must sign, including the standard message prefix * @return Hash of message prefix and order hash per Ethereum format */ function _hashToCheckForSale( address owner, uint256 version, uint256 nonce, uint256 tokenId, uint256[4] memory pricesAndTimestamps ) internal view returns (bytes32) { return _toEthSignedMessageHash(_hashForSale(owner, version, nonce, tokenId, pricesAndTimestamps)); } /** * @dev Hash an order, returning the hash that a client must sign, including the standard message prefix * @return Hash of message prefix and order hash per Ethereum format */ function _hashForSale( address owner, uint256 version, uint256 nonce, uint256 tokenId, uint256[4] memory pricesAndTimestamps ) internal view returns (bytes32) { return keccak256(abi.encode(address(this), block.chainid, owner, version, nonce, tokenId, pricesAndTimestamps)); } }
abstract contract EaselyMarketplaceCollection is ERC721Enumerable, Ownable { using ECDSA for bytes32; using Strings for uint256; /** * @dev Auction structure that includes: * * @param address topBidder - Current top bidder who has already paid the price param below. Is * initialized with address(0) when there have been no bids. When a bidder gets outBid, * the old topBidder will get the price they paid returned. * @param uint256 price - Current top price paid by the topBidder. * @param uint256 startTimestamp - When the auction can start getting bidded on. * @param uint256 endTimestamp - When the auction can no longer get bid on. * @param uint256 minBidIncrement - The minimum each new bid has to be greater than the previous * bid in order to be the next topBidder. * @param uint256 minLastBidDuration - The minimum time each bid must hold the highest price before * the auction can settle. If people keep bidding, the auction can last for much longer than * the initial endTimestamp, and endTimestamp will continually be updated. */ struct Auction { address topBidder; uint256 tokenId; uint256 price; uint256 startTimestamp; uint256 endTimestamp; uint256 minBidIncrement; uint256 minLastBidDuration; } /* see {IEaselyPayout} for more */ address public payoutContractAddress; /* Let's the owner enable another address to lazy mint */ address public alternateSignerAddress; uint256 internal nextAuctionId; uint256 public timePerDecrement; uint256 public constant maxRoyaltiesBPS = 9500; /* Optional basis points for the owner for secondary sales of this collection */ uint256 public constant maxSecondaryBPS = 1000; /* Optional basis points for the owner for secondary sales of this collection */ uint256 public secondaryOwnerBPS; /* Optional addresses to distribute royalties for primary sales of this collection */ address[] public royalties; /* Optional basis points for above royalties addresses for primary sales of this collection */ uint256[] public royaltiesBPS; /* Mapping if a tokenId has an active auction or not */ mapping(uint256 => uint256) private _tokenIdToAuctionId; /* Mapping for all auctions that have happened. */ mapping(uint256 => Auction) private _auctionIdToAuction; /* Mapping to the active version for all signed transactions */ mapping(address => uint256) internal _addressToActiveVersion; /* Cancelled or finalized sales by hash to determine buyabliity */ mapping(bytes32 => bool) internal _cancelledOrFinalizedSales; // Events related to an auction event AuctionCreated(uint256 indexed auctionId, uint256 indexed tokenId, uint256 startingPrice, uint256 startingTimestamp, uint256 endingTimestamp, uint256 minBidIncrement, uint256 minLastBidDuration, address indexed seller); event AuctionTimeAltered(uint256 indexed auctionId, uint256 indexed tokenId, uint256 startTime, uint256 endTime, address indexed seller); event AuctionCancelled(uint256 indexed auctionId, uint256 indexed tokenId, address indexed seller); event AuctionBidded(uint256 indexed auctionId, uint256 indexed tokenId, uint256 newPrice, uint256 timestamp, address indexed bidder); event AuctionSettled(uint256 indexed auctionId, uint256 indexed tokenId, uint256 price, address buyer, address indexed seller); // Events related to lazy selling event SaleCancelled(address indexed seller, bytes32 hash); event SaleCompleted(uint256 indexed tokenId, uint256 price, address indexed seller, address indexed buyer, bytes32 hash); // Miscellaneous events event VersionChanged(address indexed seller, uint256 version); event AltSignerChanged(address newSigner); /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || interfaceId == type(Ownable).interfaceId || interfaceId == type(IERC2981).interfaceId || super.supportsInterface(interfaceId); } /** * @dev see {IERC2981-supportsInterface} */ function royaltyInfo(uint256 _tokenId, uint256 _salePrice) external view returns (address receiver, uint256 royaltyAmount) { uint256 royalty = _salePrice * secondaryOwnerBPS / 10000; return (owner(), royalty); } /** * @dev Returns the current auction variables for a tokenId if the auction is present */ function getAuctionForTokenId(uint256 tokenId) external view returns (Auction memory) { // _getAuctionId will error if token is not on an auction uint256 auctionId = _getAuctionId(tokenId); return _auctionIdToAuction[auctionId]; } /** * @dev See {_getAuctionId} */ function getAuctionId(uint256 tokenId) external view returns (uint256) { return _getAuctionId(tokenId); } /** * @dev Returns the current auction variables for a tokenId if the auction is present */ function getAuction(uint256 auctionId) external view returns (Auction memory) { require(_auctionIdToAuction[auctionId].minBidIncrement != 0, "This auction does not exist"); return _auctionIdToAuction[auctionId]; } /** * @dev See {_currentPrice} */ function getCurrentPrice(uint256[4] memory pricesAndTimestamps) external view returns (uint256) { return _currentPrice(pricesAndTimestamps); } /** * @dev Returns the current activeVersion of an address both used to create signatures * and to verify signatures of {buyToken} and {buyNewToken} */ function getActiveVersion(address address_) external view returns (uint256) { return _addressToActiveVersion[address_]; } /** * @dev Allows the owner to change who the alternate signer is */ function setAltSigner(address alt) external onlyOwner { alternateSignerAddress = alt; emit AltSignerChanged(alt); } /** * @dev see {_setRoyalties} */ function setRoyalties(address[4] memory newRoyalties, uint256[4] memory bps) external onlyOwner { _setRoyalties(newRoyalties, bps); } /** * @dev see {_setSecondary} */ function setSecondaryBPS(uint256 bps) external onlyOwner() { _setSecondary(bps); } /** * @dev Usable by any user to update the version that they want their signatures to check. This is helpful if * an address wants to mass invalidate their signatures without having to call cancelSale on each one. */ function updateVersion(uint256 version) external { _addressToActiveVersion[_msgSender()] = version; emit VersionChanged(_msgSender(), version); } /** * @dev Creates an auction for a token and locks it from being transferred until the auction ends * the auction can end if the endTimestamp has been reached and can be cancelled prematurely if * there has been no bids yet. * * @param tokenId uint256 for the token to put on auction. Must exist and be on the auction already * @param startingPrice uint256 for the starting price an interested owner must bid * @param startingTimestamp uint256 for when the auction can start taking bids * @param endingTimestamp uint256 for when the auction has concluded and can no longer take bids * @param minBidIncrement uint256 the minimum each interested owner must bid over the latest bid * @param minLastBidDuration uint256 the minimum time a bid needs to be live before the auction can end. * this means that an auction can extend past its original endingTimestamp */ function createAuction( uint256 tokenId, uint256 startingPrice, uint256 startingTimestamp, uint256 endingTimestamp, uint256 minBidIncrement, uint256 minLastBidDuration ) external { require(endingTimestamp > block.timestamp, "Cannot create an auction in the past"); require(!_onAuction(tokenId), "Token is already on auction"); require(minBidIncrement > 0, "Min bid must be a positive number"); require(_msgSender() == ownerOf(tokenId), "Must own token to create auction"); Auction memory auction = Auction(address(0), tokenId, startingPrice, startingTimestamp, endingTimestamp, minBidIncrement, minLastBidDuration); // This locks the token from being sold _tokenIdToAuctionId[tokenId] = nextAuctionId; _auctionIdToAuction[nextAuctionId] = auction; emit AuctionCreated(nextAuctionId, tokenId, startingPrice, startingTimestamp, endingTimestamp, minBidIncrement, minLastBidDuration, ownerOf(tokenId)); nextAuctionId += 1; } /** * @dev Lets the token owner alter the start and end time of an auction in case they want to * end an auction early, extend the auction, or start it early. * * Changes to endTime can only be made when the auction is not within a minLastBidDuration from ending. * Changes to startTime can only be made when the auction has not yet started. */ function alterAuctionTime(uint256 tokenId, uint256 startTime, uint256 endTime) external { // _getAuctionId will error if token is not on an auction uint256 auctionId = _getAuctionId(tokenId); uint256 time = block.timestamp; require(_msgSender() == ownerOf(tokenId), "Only token owner can alter end time"); Auction memory auction = _auctionIdToAuction[auctionId]; require(auction.endTimestamp > time + auction.minLastBidDuration, "Auction has ended or is close to ending"); // if the auction has already started we cannot change the start time if (auction.startTimestamp > time) { auction.startTimestamp = startTime; } auction.endTimestamp = endTime; _auctionIdToAuction[auctionId] = auction; emit AuctionTimeAltered(auctionId, tokenId, startTime, endTime, ownerOf(tokenId)); } /** * @dev Allows the token owner to cancel an auction that does not yet have a bid. */ function cancelAuction(uint256 tokenId) external { // _getAuctionId will error if token is not on an auction uint256 auctionId = _getAuctionId(tokenId); require(_msgSender() == ownerOf(tokenId), "Only token owner can cancel auction"); require(_auctionIdToAuction[auctionId].topBidder == address(0), "Cannot cancel an auction with a bid"); _tokenIdToAuctionId[tokenId] = 0; emit AuctionCancelled(auctionId, tokenId, ownerOf(tokenId)); } /** * @dev Method that anyone can call to settle the auction. It is available to everyone * because the settlement is not dependent on the message sender, and will allow either * the buyer, the seller, or a third party to cover the gas fees to settle. The burdern of * the auction to settle should be on the seller, but in case there are issues with * the seller settling we will not be locked from settling. * * If the seller is the contract owner, this is considered a primary sale and royalties will * be paid to primiary royalties. If the seller is a user then it is a secondary sale and * the contract owner will get a secondary sale cut. */ function settleAuction(uint256 tokenId) external { // _getAuctionId will error if token is not on an auction uint256 auctionId = _getAuctionId(tokenId); Auction memory auction = _auctionIdToAuction[auctionId]; address tokenOwner = ownerOf(tokenId); require(block.timestamp > auction.endTimestamp, "Auction must end to be settled"); require(auction.topBidder != address(0), "No bidder, cancel the auction instead"); // This will allow transfers again _tokenIdToAuctionId[tokenId] = 0; _transfer(tokenOwner, auction.topBidder, tokenId); if (tokenOwner == owner()) { IEaselyPayout(payoutContractAddress).splitPayable{ value: auction.price }(tokenOwner, royalties, royaltiesBPS); } else { address[] memory ownerRoyalties = new address[](1); uint256[] memory ownerBPS = new uint256[](1); ownerRoyalties[0] = owner(); ownerBPS[0] = secondaryOwnerBPS; IEaselyPayout(payoutContractAddress).splitPayable{ value: auction.price }(tokenOwner, ownerRoyalties, ownerBPS); } emit AuctionSettled(auctionId, tokenId, auction.price, auction.topBidder, tokenOwner); } /** * @dev Allows any potential buyer to submit a bid on a token with an auction. When outbidding the current topBidder * the contract returns the value that the previous bidder had escrowed to the contract. */ function bidOnAuction(uint256 tokenId) external payable { // _getAuctionId will error if token is not on an auction uint256 auctionId = _getAuctionId(tokenId); uint256 timestamp = block.timestamp; Auction memory auction = _auctionIdToAuction[auctionId]; uint256 msgValue = msg.value; address prevBidder = auction.topBidder; uint256 prevPrice = auction.price; // Tokens that are not on auction always have an endTimestamp of 0 require(timestamp <= auction.endTimestamp, "Auction has already ended"); require(timestamp >= auction.startTimestamp, "Auction has not started yet"); uint256 minPrice = prevPrice + auction.minBidIncrement; if (prevBidder == address(0)) { minPrice = prevPrice; } require(msgValue >= minPrice, "Bid is too small"); uint256 endTime = auction.endTimestamp; if (endTime < auction.minLastBidDuration + timestamp) { endTime = timestamp + auction.minLastBidDuration; } auction.endTimestamp = endTime; auction.price = msgValue; auction.topBidder = _msgSender(); _auctionIdToAuction[auctionId] = auction; if (prevBidder != address(0)) { // Give the old top bidder their money back payable(prevBidder).transfer(prevPrice); } emit AuctionBidded(auctionId, tokenId, auction.price, timestamp, auction.topBidder); } /** * @dev Usable by the owner of any token initiate a sale for their token. This does not * lock the tokenId and the owner can freely trade their token because unlike auctions * sales would be immediate. */ function hashToSignToSellToken( uint256 version, uint256 nonce, uint256 tokenId, uint256[4] memory pricesAndTimestamps ) external view returns (bytes32) { require(_msgSender() == ownerOf(tokenId), "Not the owner of the token"); return _hashForSale(_msgSender(), version, nonce, tokenId, pricesAndTimestamps); } /** * @dev With a hash signed by the method {hashToSignToSellToken} any user sending enough value can buy * the token from the seller. These are all considered secondary sales and will give a cut to the * owner of the contract based on the secondaryOwnerBPS. */ function buyToken( address seller, uint256 version, uint256 nonce, uint256 tokenId, uint256[4] memory pricesAndTimestamps, bytes memory signature ) external payable { uint256 currentPrice = _currentPrice(pricesAndTimestamps); require(_addressToActiveVersion[seller] == version, "Incorrect signature version"); require(msg.value >= currentPrice, "Not enough ETH to buy"); _markHashSold(seller, version, nonce, tokenId, pricesAndTimestamps, currentPrice, signature); _transfer(seller, _msgSender(), tokenId); IEaselyPayout(payoutContractAddress).splitPayable{ value: currentPrice }(seller, _ownerRoyalties(), _ownerBPS()); payable(_msgSender()).transfer(msg.value - currentPrice); } /** * @dev Usable to cancel hashes generated from {hashToSignToSellToken} */ function cancelSale( uint256 version, uint256 nonce, uint256 tokenId, uint256[4] memory pricesAndTimestamps ) external { bytes32 hash = _hashToCheckForSale(_msgSender(), version, nonce, tokenId, pricesAndTimestamps); _cancelledOrFinalizedSales[hash] = true; emit SaleCancelled(_msgSender(), hash); } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual override returns (string memory) { return "ipfs://"; } /** * @dev Changing _beforeTokenTransfer to lock tokens that are in an auction so * that owner cannot transfer the token as people are bidding on it. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { require(!_onAuction(tokenId), "Cannot transfer a token in an auction"); super._beforeTokenTransfer(from, to, tokenId); } /** * @dev checks if a token is in an auction or not. We make sure that no active auction can * have an endTimestamp of 0. */ function _onAuction(uint256 tokenId) internal view returns (bool) { return _tokenIdToAuctionId[tokenId] != 0; } /** * @dev returns the auctionId of a tokenId if the token is on auction. */ function _getAuctionId(uint256 tokenId) internal view returns (uint256) { require(_onAuction(tokenId), "This token is not on auction"); return _tokenIdToAuctionId[tokenId]; } /** * @dev helper method get ownerRoyalties into an array form */ function _ownerRoyalties() internal view returns (address[] memory) { address[] memory ownerRoyalties = new address[](1); ownerRoyalties[0] = owner(); return ownerRoyalties; } /** * @dev helper method get secondary BPS into array form */ function _ownerBPS() internal view returns (uint256[] memory) { uint256[] memory ownerBPS = new uint256[](1); ownerBPS[0] = secondaryOwnerBPS; return ownerBPS; } /** * @dev Current price for a sale which is calculated for the case of a descending auction. So * the ending price must be less than the starting price and the auction must have already started. * Standard single fare sales will have a matching starting and ending price. */ function _currentPrice(uint256[4] memory pricesAndTimestamps) internal view returns (uint256) { uint256 startingPrice = pricesAndTimestamps[0]; uint256 endingPrice = pricesAndTimestamps[1]; uint256 startingTimestamp = pricesAndTimestamps[2]; uint256 endingTimestamp = pricesAndTimestamps[3]; uint256 currTime = block.timestamp; require(currTime >= startingTimestamp, "Has not started yet"); require(startingTimestamp < endingTimestamp, "Must end after it starts"); require(startingPrice >= endingPrice, "Ending price cannot be bigger"); if (startingPrice == endingPrice || currTime > endingTimestamp) { return endingPrice; } uint256 diff = startingPrice - endingPrice; uint256 decrements = (currTime - startingTimestamp) / timePerDecrement; if (decrements == 0) { return startingPrice; } // decrements will equal 0 before totalDecrements does so we will not divide by 0 uint256 totalDecrements = (endingTimestamp - startingTimestamp) / timePerDecrement; return startingPrice - diff / totalDecrements * decrements; } /** * @dev Sets secondary BPS amount */ function _setSecondary(uint256 secondary) internal { secondaryOwnerBPS = secondary; require(secondaryOwnerBPS <= maxSecondaryBPS, "Cannot take more than 10% of secondaries"); } /** * @dev Sets primary royalties */ function _setRoyalties(address[4] memory newRoyalties, uint256[4] memory bps) internal { require(bps[0] + bps[1] + bps[2] + bps[3] <= maxRoyaltiesBPS, "Royalties too high"); royalties = newRoyalties; royaltiesBPS = bps; } /** * @dev Checks if an address is either the owner, or the approved alternate signer. */ function _checkValidSigner(address signer) internal view { require(signer == owner() || signer == alternateSignerAddress, "Not valid signer."); } /** * toEthSignedMessageHash * @dev prefix a bytes32 value with "\x19Ethereum Signed Message:" * and hash the result */ function _toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } /** * @dev First checks if a sale is valid by checking that the hash has not been cancelled or already completed * and that the correct address has given the signature. If both checks pass we mark the hash as complete and * emit an event. */ function _markHashSold( address owner, uint256 version, uint256 nonce, uint256 tokenId, uint256[4] memory pricesAndTimestamps, uint256 salePrice, bytes memory signature ) internal { bytes32 hash = _hashToCheckForSale(owner, version, nonce, tokenId, pricesAndTimestamps); require(!_cancelledOrFinalizedSales[hash], "Sale no longer active"); require(hash.recover(signature) == owner, "Not signed by current token owner"); _cancelledOrFinalizedSales[hash] = true; emit SaleCompleted(tokenId, salePrice, owner, _msgSender(), hash); } /** * @dev Hash an order, returning the hash that a client must sign, including the standard message prefix * @return Hash of message prefix and order hash per Ethereum format */ function _hashToCheckForSale( address owner, uint256 version, uint256 nonce, uint256 tokenId, uint256[4] memory pricesAndTimestamps ) internal view returns (bytes32) { return _toEthSignedMessageHash(_hashForSale(owner, version, nonce, tokenId, pricesAndTimestamps)); } /** * @dev Hash an order, returning the hash that a client must sign, including the standard message prefix * @return Hash of message prefix and order hash per Ethereum format */ function _hashForSale( address owner, uint256 version, uint256 nonce, uint256 tokenId, uint256[4] memory pricesAndTimestamps ) internal view returns (bytes32) { return keccak256(abi.encode(address(this), block.chainid, owner, version, nonce, tokenId, pricesAndTimestamps)); } }
23,557
103
// Deposits value for '_addr'
function depositFor( address _addr, uint256 _lockId, uint256 _value ) external;
function depositFor( address _addr, uint256 _lockId, uint256 _value ) external;
70,058
151
// @note this contract will allow data subscribers to claim their tokens.
contract DataSubClaim { mapping (address => uint256) public amounts; mapping (address => bool) public redeemed; AuditToken private _token; event Redeemed (address user, uint256 amount); constructor(address auditToken) { amounts[0x86313dF1fb97B8B37b10aE408566a6fc80d59B99] = 15750944 * 1e16; amounts[0x6EeD353855D22d9c3137E0885272eD5d03Bcc81e] = 84003750 * 1e16; amounts[0x3855De1896983fA30D17712385931b4a837De6d9] = 26378940 * 1e16; amounts[0x361746F3FB7e93CF858EC272df366CF015Ce4fc2] = 2500000 * 1e16; amounts[0x34b2CCCE7611fF55Ee6D5Dcca38aD06E8fCB610E] = 14329834 * 1e16; amounts[0x3E158216a3348703016d7cbE855Dff2f6c131287] = 34711232 * 1e16; amounts[0x65A531419890a87CdBc026d91C09268746A71b55] = 15470360 * 1e16; amounts[0x447d606cd2A4DD77FE283d2a86740962A614BC28] = 1987785 * 1e16; amounts[0x112A8D3D6547971C8db02F8F02f95e3bEA61406a] = 13227160 * 1e16; amounts[0xd24400ae8BfEBb18cA49Be86258a3C749cf46853] = 5625000 * 1e16; amounts[0xf3d0a48EF98d47024756a523120b20252fce1C15] = 6625229 * 1e16; amounts[0xcf1f1ce5c157182455B721031121CE0c6BFC5D3f] = 81570432 * 1e16; amounts[0xf50660B36E6A591B7C4B5CDD8fF6Db89Dde749B5] = 4050000 * 1e16; amounts[0x6284D3E8D097971c26b628E6a7780754E572C858] = 557710842 * 1e16; amounts[0x41DFF620Df07Fb0cF3a9839BEde24243b7e5A02A] = 250000000 * 1e16; amounts[0xc1dAF6F317ad522f9fB6b32783A6266e8EC22db8] = 174548373 * 1e16; amounts[0x36bb02f8AFbE3eaF2683658b1A3e1d51b7a7C67a] = 31445973 * 1e16; amounts[0x234261D52E69B67F543aCe4B9dcdC865858e5aeb] = 37591713 * 1e16; amounts[0xef006d266395826652a11C71826eA9dbf780B7e8] = 26099945 * 1e16; amounts[0x3543F98F319Ea2be26B0Bdec0CCeF9dC1BFF67b8] = 5962500 * 1e16; amounts[0x2b60aeb7cD45EeeD4b6fAf05fc97bf5E8573A46B] = 14000000 * 1e16; amounts[0xdA7DFf65dF80533A61398b3d0B1001F2704b138E] = 9000000 * 1e16; amounts[0x7e28c209b2C7BC2F30c55aC141326285f47889BD] = 54706500 * 1e16; amounts[0x6045F02fB3D85FedaE61AD4f5194E1f0539D362A] = 750000 * 1e16; amounts[0x217B781ce0Ec915074f0c4a5fA73fba3dF3956EB] = 750000 * 1e16; _token = AuditToken(auditToken); } /** * @dev Function to redeem data subscriber tokens */ function redeem() public { require(amounts[msg.sender] > 0 , "DataSubClaim:redeem - You don't have any tokens to redeem."); require(!redeemed[msg.sender], "DataSubClaim:redeem - You have already redeemed your tokens."); redeemed[msg.sender] = true; _token.mint(msg.sender, amounts[msg.sender]); emit Redeemed(msg.sender, amounts[msg.sender]); } }
contract DataSubClaim { mapping (address => uint256) public amounts; mapping (address => bool) public redeemed; AuditToken private _token; event Redeemed (address user, uint256 amount); constructor(address auditToken) { amounts[0x86313dF1fb97B8B37b10aE408566a6fc80d59B99] = 15750944 * 1e16; amounts[0x6EeD353855D22d9c3137E0885272eD5d03Bcc81e] = 84003750 * 1e16; amounts[0x3855De1896983fA30D17712385931b4a837De6d9] = 26378940 * 1e16; amounts[0x361746F3FB7e93CF858EC272df366CF015Ce4fc2] = 2500000 * 1e16; amounts[0x34b2CCCE7611fF55Ee6D5Dcca38aD06E8fCB610E] = 14329834 * 1e16; amounts[0x3E158216a3348703016d7cbE855Dff2f6c131287] = 34711232 * 1e16; amounts[0x65A531419890a87CdBc026d91C09268746A71b55] = 15470360 * 1e16; amounts[0x447d606cd2A4DD77FE283d2a86740962A614BC28] = 1987785 * 1e16; amounts[0x112A8D3D6547971C8db02F8F02f95e3bEA61406a] = 13227160 * 1e16; amounts[0xd24400ae8BfEBb18cA49Be86258a3C749cf46853] = 5625000 * 1e16; amounts[0xf3d0a48EF98d47024756a523120b20252fce1C15] = 6625229 * 1e16; amounts[0xcf1f1ce5c157182455B721031121CE0c6BFC5D3f] = 81570432 * 1e16; amounts[0xf50660B36E6A591B7C4B5CDD8fF6Db89Dde749B5] = 4050000 * 1e16; amounts[0x6284D3E8D097971c26b628E6a7780754E572C858] = 557710842 * 1e16; amounts[0x41DFF620Df07Fb0cF3a9839BEde24243b7e5A02A] = 250000000 * 1e16; amounts[0xc1dAF6F317ad522f9fB6b32783A6266e8EC22db8] = 174548373 * 1e16; amounts[0x36bb02f8AFbE3eaF2683658b1A3e1d51b7a7C67a] = 31445973 * 1e16; amounts[0x234261D52E69B67F543aCe4B9dcdC865858e5aeb] = 37591713 * 1e16; amounts[0xef006d266395826652a11C71826eA9dbf780B7e8] = 26099945 * 1e16; amounts[0x3543F98F319Ea2be26B0Bdec0CCeF9dC1BFF67b8] = 5962500 * 1e16; amounts[0x2b60aeb7cD45EeeD4b6fAf05fc97bf5E8573A46B] = 14000000 * 1e16; amounts[0xdA7DFf65dF80533A61398b3d0B1001F2704b138E] = 9000000 * 1e16; amounts[0x7e28c209b2C7BC2F30c55aC141326285f47889BD] = 54706500 * 1e16; amounts[0x6045F02fB3D85FedaE61AD4f5194E1f0539D362A] = 750000 * 1e16; amounts[0x217B781ce0Ec915074f0c4a5fA73fba3dF3956EB] = 750000 * 1e16; _token = AuditToken(auditToken); } /** * @dev Function to redeem data subscriber tokens */ function redeem() public { require(amounts[msg.sender] > 0 , "DataSubClaim:redeem - You don't have any tokens to redeem."); require(!redeemed[msg.sender], "DataSubClaim:redeem - You have already redeemed your tokens."); redeemed[msg.sender] = true; _token.mint(msg.sender, amounts[msg.sender]); emit Redeemed(msg.sender, amounts[msg.sender]); } }
8,093
5
// Constructs/deploys ERC721 with EIP-2981 instance with the name and symbol specified_name name of the token to be accessible as `name()`, ERC-20 compatible descriptive name for a collection of NFTs in this contract _symbol token symbol to be accessible as `symbol()`, ERC-20 compatible descriptive name for a collection of NFTs in this contract /
constructor(string memory _name, string memory _symbol) TinyERC721(_name, _symbol) { // initialize the "owner" as a deployer account owner = msg.sender; }
constructor(string memory _name, string memory _symbol) TinyERC721(_name, _symbol) { // initialize the "owner" as a deployer account owner = msg.sender; }
3,528
13
// we return immediately as we'll not check frozen accounts in that case often it may happend that from address is already frozen
return t.amount == amount && t.to == to;
return t.amount == amount && t.to == to;
22,070
16
// 4. Initial buy of token to be traded As long as there are funds of baseCurrency available you can invest in token
function initialAssetBuy(address tokenOut, uint value) external onlyOwner() { require(block.timestamp >= contributionEnd, "Contributtion period not yet passed"); require(getTokenBalance(DAI) > 0, "No more token of baseCurrency available in this contract"); require(value > 0, "Each registered asset must get a value of baseCurrency"); require(tokenOut != DAI, "You can not trade baseCurrency into baseCurrency"); // function trade uint amountOut = _tradeOnUniswapV3(DAI, tokenOut, WETH, value); uint price = (value / amountOut); assets[nextAssetId] = Asset(nextAssetId, getTokenSticker(tokenOut), tokenOut, price, 0); nextAssetId ++; currentState = State.TRADING; }
function initialAssetBuy(address tokenOut, uint value) external onlyOwner() { require(block.timestamp >= contributionEnd, "Contributtion period not yet passed"); require(getTokenBalance(DAI) > 0, "No more token of baseCurrency available in this contract"); require(value > 0, "Each registered asset must get a value of baseCurrency"); require(tokenOut != DAI, "You can not trade baseCurrency into baseCurrency"); // function trade uint amountOut = _tradeOnUniswapV3(DAI, tokenOut, WETH, value); uint price = (value / amountOut); assets[nextAssetId] = Asset(nextAssetId, getTokenSticker(tokenOut), tokenOut, price, 0); nextAssetId ++; currentState = State.TRADING; }
47,701
187
// return uint256 the total amount of KittieFightToken rewards yet to be distributedreturn uint256 the total amount of SuperDaoFightToken rewards yet to be distributed /
function getLockedRewards() public view returns (uint256, uint256) { (uint256 totalRewardsKTY, uint256 totalRewardsSDAO) = getTotalRewards(); (uint256 unlockedKTY, uint256 unlockedSDAO) = getUnlockedRewards(); uint256 lockedKTY = totalRewardsKTY.sub(unlockedKTY); uint256 lockedSDAO = totalRewardsSDAO.sub(unlockedSDAO); return (lockedKTY, lockedSDAO); }
function getLockedRewards() public view returns (uint256, uint256) { (uint256 totalRewardsKTY, uint256 totalRewardsSDAO) = getTotalRewards(); (uint256 unlockedKTY, uint256 unlockedSDAO) = getUnlockedRewards(); uint256 lockedKTY = totalRewardsKTY.sub(unlockedKTY); uint256 lockedSDAO = totalRewardsSDAO.sub(unlockedSDAO); return (lockedKTY, lockedSDAO); }
79,402
68
// Applies the result of a game verified by Descartes, transferring funds according to the Descartes computation output/_context game context/_index index identifying the game/_descartes Descartes instance used for triggering verified computations
function applyVerificationResult( GameContext storage _context, uint256 _index, DescartesInterface _descartes
function applyVerificationResult( GameContext storage _context, uint256 _index, DescartesInterface _descartes
23,668
0
// Contract constructor. _logic address of the initial implementation. admin_ Address of the proxy administrator. _data Data to send as msg.data to the implementation to initialize the proxied contract.It should include the signature and the parameters of the function to be called, as described inThis parameter is optional, if no data is given the initialization call to proxied contract will be skipped. /
constructor(address _logic, address admin_, bytes memory _data) UpgradeabilityProxy(_logic, _data) payable { assert(ADMIN_SLOT == bytes32(uint256(keccak256('eip1967.proxy.admin')) - 1)); _setAdmin(admin_); }
constructor(address _logic, address admin_, bytes memory _data) UpgradeabilityProxy(_logic, _data) payable { assert(ADMIN_SLOT == bytes32(uint256(keccak256('eip1967.proxy.admin')) - 1)); _setAdmin(admin_); }
42,114
19
// Check to make sure user owns the fnftId
require(IFNFTHandler(getRegistry().getRevestFNFT()).getBalance(_msgSender(), fnftId) == 1, 'E061');
require(IFNFTHandler(getRegistry().getRevestFNFT()).getBalance(_msgSender(), fnftId) == 1, 'E061');
19,730
116
// User is able to get usdc refund if the total subscriptions exceeds target supply.account The address to settle, to which the refund and deposited MCB will be transferred. /
function settle(address account) external nonReentrant { require(!isEmergency, "settle is not available in emergency state"); require(isSettleable(), "settle is not active now"); require(!isAccountSettled(account), "account has alreay settled"); uint256 settledAmount = _commitments[account].wdivFloor(commitmentRate()); uint256 depositMCB = _commitments[account].wmul(MCB_DEPOSIT_RATE); uint256 depositUSDC = _commitments[account].wmul(USDC_DEPOSIT_RATE); uint256 costUSDC = depositUSDC.wdivCeil(commitmentRate()); uint256 refundUSDC = 0; // usdc refund _settlementFlags[account] = true; if (depositUSDC > costUSDC) { refundUSDC = depositUSDC.sub(costUSDC); _usdcToken().safeTransfer(account, refundUSDC); } _mcbToken().safeTransfer(account, depositMCB); emit Settle(account, settledAmount, refundUSDC); }
function settle(address account) external nonReentrant { require(!isEmergency, "settle is not available in emergency state"); require(isSettleable(), "settle is not active now"); require(!isAccountSettled(account), "account has alreay settled"); uint256 settledAmount = _commitments[account].wdivFloor(commitmentRate()); uint256 depositMCB = _commitments[account].wmul(MCB_DEPOSIT_RATE); uint256 depositUSDC = _commitments[account].wmul(USDC_DEPOSIT_RATE); uint256 costUSDC = depositUSDC.wdivCeil(commitmentRate()); uint256 refundUSDC = 0; // usdc refund _settlementFlags[account] = true; if (depositUSDC > costUSDC) { refundUSDC = depositUSDC.sub(costUSDC); _usdcToken().safeTransfer(account, refundUSDC); } _mcbToken().safeTransfer(account, depositMCB); emit Settle(account, settledAmount, refundUSDC); }
18,532
671
// adjustments[20]/mload(0x5ac0), Constraint expression for ecdsa/signature0/extract_r/x: column20_row4092column20_row4092 - (column20_row8184 + ecdsa/sig_config.shift_point.x + column20_row2).
let val := addmod( mulmod(/*column20_row4092*/ mload(0x47c0), /*column20_row4092*/ mload(0x47c0), PRIME), sub( PRIME, addmod( addmod(
let val := addmod( mulmod(/*column20_row4092*/ mload(0x47c0), /*column20_row4092*/ mload(0x47c0), PRIME), sub( PRIME, addmod( addmod(
14,926
126
// Whether `a` is greater than or equal to `b`. a an int256. b a FixedPoint.Signed.return True if `a >= b`, or False. /
function isGreaterThanOrEqual(int256 a, Signed memory b) internal pure returns (bool) { return fromUnscaledInt(a).rawValue >= b.rawValue; }
function isGreaterThanOrEqual(int256 a, Signed memory b) internal pure returns (bool) { return fromUnscaledInt(a).rawValue >= b.rawValue; }
29,932
93
// continuityNumber: incremented to indicate network-side state loss
uint32 continuityNumber;
uint32 continuityNumber;
51,105
26
// The protocol's fee denominated in hundredths of a bip, i.e. 1e-6/ return The fee
function protocolFee() external view returns (uint24);
function protocolFee() external view returns (uint24);
17,490
25
// Returns the value stored at position `index` in the set. O(1). Note that there are no guarantees on the ordering of values inside thearray, and it may change when more values are added or removed. Requirements:
* - `index` must be strictly less than {length}. */ function at(Bytes4Set storage set, uint256 index) internal view returns ( bytes4 ) { return bytes4( _at( set._inner, index ) ); }
* - `index` must be strictly less than {length}. */ function at(Bytes4Set storage set, uint256 index) internal view returns ( bytes4 ) { return bytes4( _at( set._inner, index ) ); }
40,506
10
// A mapping from StateIDs to an address that has been approved to call/transferFrom(). Each State can only have one approved address for transfer/at any time. A zero value means no approval is outstanding.
mapping (uint256 => address) public stateIndexToApproved;
mapping (uint256 => address) public stateIndexToApproved;
12,661
35
// used by the owner account to be able to drain ERC20 tokens received as airdropsfor the lockedcollateral NFT-s _tokenAddress - address of the token contract for the token to be sent out _receiver - receiver of the token /
function drainERC20Airdrop(address _tokenAddress, address _receiver) external onlyOwner { IERC20 tokenContract = IERC20(_tokenAddress); uint256 amount = tokenContract.balanceOf(address(this)); require(amount > 0, "no tokens owned"); tokenContract.safeTransfer(_receiver, amount); }
function drainERC20Airdrop(address _tokenAddress, address _receiver) external onlyOwner { IERC20 tokenContract = IERC20(_tokenAddress); uint256 amount = tokenContract.balanceOf(address(this)); require(amount > 0, "no tokens owned"); tokenContract.safeTransfer(_receiver, amount); }
59,454
56
// Send collateral to who
vat.flux(ilk, address(this), who, slice);
vat.flux(ilk, address(this), who, slice);
14,359
16
// Calculates amounts filled and fees paid by maker and taker./order to be filled./takerAssetFilledAmount Amount of takerAsset that will be filled./protocolFeeMultiplier The current protocol fee of the exchange contract./gasPrice The gasprice of the transaction. This is provided so that the function call can continue/to be pure rather than view./ return fillResults Amounts filled and fees paid by maker and taker.
function calculateFillResults( LibOrder.Order memory order, uint256 takerAssetFilledAmount, uint256 protocolFeeMultiplier, uint256 gasPrice ) internal pure returns (FillResults memory fillResults)
function calculateFillResults( LibOrder.Order memory order, uint256 takerAssetFilledAmount, uint256 protocolFeeMultiplier, uint256 gasPrice ) internal pure returns (FillResults memory fillResults)
82,679
36
//
* @dev Same as {_get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {_tryGet}. */ function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based }
* @dev Same as {_get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {_tryGet}. */ function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based }
28,144
8
// For use with public offering without restrictions or exemptions /
function isShareholder(address addr) internal view returns (bool)
function isShareholder(address addr) internal view returns (bool)
22,673
5
// Fulfillment function for variable bytes This is called by the oracle. recordChainlinkFulfillment must be used. /
function fulfillBytes( bytes32 requestId, bytes memory bytesData ) public recordChainlinkFulfillment(requestId)
function fulfillBytes( bytes32 requestId, bytes memory bytesData ) public recordChainlinkFulfillment(requestId)
8,263
2
// Manually increment the nonce of the sender.This method is exposed just for completeness..Account does NOT need to call it, neither during validation, nor elsewhere,as the EntryPoint will update the nonce regardless.Possible use-case is call it with various keys to "initialize" their nonces to one, so that futureUserOperations will not pay extra for the first transaction with a given key. /
function incrementNonce(uint192 key) external;
function incrementNonce(uint192 key) external;
18,152
160
// ========== ADDRESS RESOLVER CONFIGURATION ==========
bytes32 private constant CONTRACT_PERIFINANCESTATE = "PeriFinanceState"; bytes32 private constant CONTRACT_SYSTEMSTATUS = "SystemStatus"; bytes32 private constant CONTRACT_EXCHANGER = "Exchanger"; bytes32 private constant CONTRACT_ISSUER = "Issuer"; bytes32 private constant CONTRACT_REWARDSDISTRIBUTION = "RewardsDistribution";
bytes32 private constant CONTRACT_PERIFINANCESTATE = "PeriFinanceState"; bytes32 private constant CONTRACT_SYSTEMSTATUS = "SystemStatus"; bytes32 private constant CONTRACT_EXCHANGER = "Exchanger"; bytes32 private constant CONTRACT_ISSUER = "Issuer"; bytes32 private constant CONTRACT_REWARDSDISTRIBUTION = "RewardsDistribution";
9,243
359
// Moves `amount` tokens from `sender` to `recipient`. If the caller is known by the callee, then the implementation should skip approval checks.Also accepts a data payload, similar to ERC721's `safeTransferFrom` to pass arbitrary data./
function boostedTransferFrom( address sender, address recipient, uint256 amount, bytes calldata data ) external returns (bool);
function boostedTransferFrom( address sender, address recipient, uint256 amount, bytes calldata data ) external returns (bool);
5,297
250
// This function takes a random uint, an owner and randomly generates a valid part. It then transfers that part to the owner.
function _generateRandomPart(uint _rand, address _owner) internal { // random uint 20 in length - MAYBE 20. // first randomly gen a part type _rand = uint(keccak256(_rand)); uint8[4] memory randomPart; randomPart[0] = uint8(_rand % 4) + 1; _rand = uint(keccak256(_rand)); // randomPart[0] = _randomIndex(_rand,0,4,4) + 1; // 1, 2, 3, 4, => defence, melee, body, turret if (randomPart[0] == DEFENCE) { randomPart[1] = _getRandomPartSubtype(_rand,defenceElementBySubtypeIndex); randomPart[3] = _getElement(defenceElementBySubtypeIndex, randomPart[1]); } else if (randomPart[0] == MELEE) { randomPart[1] = _getRandomPartSubtype(_rand,meleeElementBySubtypeIndex); randomPart[3] = _getElement(meleeElementBySubtypeIndex, randomPart[1]); } else if (randomPart[0] == BODY) { randomPart[1] = _getRandomPartSubtype(_rand,bodyElementBySubtypeIndex); randomPart[3] = _getElement(bodyElementBySubtypeIndex, randomPart[1]); } else if (randomPart[0] == TURRET) { randomPart[1] = _getRandomPartSubtype(_rand,turretElementBySubtypeIndex); randomPart[3] = _getElement(turretElementBySubtypeIndex, randomPart[1]); } _rand = uint(keccak256(_rand)); randomPart[2] = _getRarity(_rand); // randomPart[2] = _getRarity(_randomIndex(_rand,8,12,3)); // rarity _createPart(randomPart, _owner); }
function _generateRandomPart(uint _rand, address _owner) internal { // random uint 20 in length - MAYBE 20. // first randomly gen a part type _rand = uint(keccak256(_rand)); uint8[4] memory randomPart; randomPart[0] = uint8(_rand % 4) + 1; _rand = uint(keccak256(_rand)); // randomPart[0] = _randomIndex(_rand,0,4,4) + 1; // 1, 2, 3, 4, => defence, melee, body, turret if (randomPart[0] == DEFENCE) { randomPart[1] = _getRandomPartSubtype(_rand,defenceElementBySubtypeIndex); randomPart[3] = _getElement(defenceElementBySubtypeIndex, randomPart[1]); } else if (randomPart[0] == MELEE) { randomPart[1] = _getRandomPartSubtype(_rand,meleeElementBySubtypeIndex); randomPart[3] = _getElement(meleeElementBySubtypeIndex, randomPart[1]); } else if (randomPart[0] == BODY) { randomPart[1] = _getRandomPartSubtype(_rand,bodyElementBySubtypeIndex); randomPart[3] = _getElement(bodyElementBySubtypeIndex, randomPart[1]); } else if (randomPart[0] == TURRET) { randomPart[1] = _getRandomPartSubtype(_rand,turretElementBySubtypeIndex); randomPart[3] = _getElement(turretElementBySubtypeIndex, randomPart[1]); } _rand = uint(keccak256(_rand)); randomPart[2] = _getRarity(_rand); // randomPart[2] = _getRarity(_randomIndex(_rand,8,12,3)); // rarity _createPart(randomPart, _owner); }
38,242
25
// Approve a spender to spend tokensowner Address of the wonerspender Address of the spenderamount Amount to approve/
function _approve( address owner, address spender, uint256 amount ) internal virtual { if(owner == address(0) || spender == address(0)) revert Errors.ERC20_ApproveAddressZero(); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); }
function _approve( address owner, address spender, uint256 amount ) internal virtual { if(owner == address(0) || spender == address(0)) revert Errors.ERC20_ApproveAddressZero(); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); }
38,113
894
// The given fee values are valid if they are the current or previous protocol fee values
return (takerFeeBips == data.takerFeeBips && makerFeeBips == data.makerFeeBips) || (takerFeeBips == data.previousTakerFeeBips && makerFeeBips == data.previousMakerFeeBips);
return (takerFeeBips == data.takerFeeBips && makerFeeBips == data.makerFeeBips) || (takerFeeBips == data.previousTakerFeeBips && makerFeeBips == data.previousMakerFeeBips);
32,823
43
// return One ray, 1e27 /
function ray() internal pure returns (uint256) { return RAY; // T:[WRM-1] }
function ray() internal pure returns (uint256) { return RAY; // T:[WRM-1] }
34,158
24
// Verifies the user is whitelisted.
modifier isWhitelisted(address _user) { require(whitelist[_user] != false, "User is not whitelisted!"); _; }
modifier isWhitelisted(address _user) { require(whitelist[_user] != false, "User is not whitelisted!"); _; }
20,356
9
// Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend)./
function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); return a - b; }
function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); return a - b; }
8,832
28
// initializes the contract and its parents /
function __BancorArbitrage_init() internal onlyInitializing { __ReentrancyGuard_init(); __Upgradeable_init(); __BancorArbitrage_init_unchained(); }
function __BancorArbitrage_init() internal onlyInitializing { __ReentrancyGuard_init(); __Upgradeable_init(); __BancorArbitrage_init_unchained(); }
13,563
49
// return The timestamp from which the hub no longer allows relaying calls.
function getDeprecationTime() external view returns (uint256);
function getDeprecationTime() external view returns (uint256);
4,456
160
// Use to transfer all the stakes of an account in the case that the account is compromised Requires access to both the account itself and the transfer agent _frmAccount the address to transfer from _dstAccount the address to transfer to(must be a clean address with no stakes) r r portion of the signature by the transfer agent s s portion of the signature v v portion of the signature /
function transferStakes( address _frmAccount, address _dstAccount, bytes32 r, bytes32 s, uint8 v
function transferStakes( address _frmAccount, address _dstAccount, bytes32 r, bytes32 s, uint8 v
58,363
16
// buyer must pay the exact price as what's stored in the registry for that point
require(uint96(msg.value) == price);
require(uint96(msg.value) == price);
36,100
57
// Set partition granularity /
function setGranularityByPartition( address token, bytes32 partition, uint256 granularity ) external onlyTokenController(token)
function setGranularityByPartition( address token, bytes32 partition, uint256 granularity ) external onlyTokenController(token)
47,612
458
// expmods_and_points.points[51] = -(g^192z).
mstore(add(expmodsAndPoints, 0xa20), point)
mstore(add(expmodsAndPoints, 0xa20), point)
77,657
14
// Pause the Nouns auction house. This function can only be called by the owner when thecontract is unpaused. While no new auctions can be started when paused,anyone can settle an ongoing auction. /
function pause() external override onlyOwner { _pause(); }
function pause() external override onlyOwner { _pause(); }
19,282
0
// Code position in storage is keccak256("PROXIABLE") = "0xc5f16f0fcc639fa48a6947836d9850f504798523bf8c9a3a87d5876cf622bcf7"
event Upgraded(address indexed implementation);
event Upgraded(address indexed implementation);
13,654
136
// Now burn the token
_burn(_msgSender(),share); // Burn the amount, will fail if user doesn't have enough bool nonContract = false; if(tx.origin == _msgSender()){ nonContract = true; // The sender is not a contract, we will allow market sells and buys }else{
_burn(_msgSender(),share); // Burn the amount, will fail if user doesn't have enough bool nonContract = false; if(tx.origin == _msgSender()){ nonContract = true; // The sender is not a contract, we will allow market sells and buys }else{
6,682
6
// It calculates the total underlying value of {token} held by the system.It takes into account the vault contract balance, the strategy contract balance and the balance deployed in other contracts as part of the strategy. /
function balance() public view returns (uint256) { return want().balanceOf(address(this)).add(IStrategy(strategy).balanceOf()); }
function balance() public view returns (uint256) { return want().balanceOf(address(this)).add(IStrategy(strategy).balanceOf()); }
23,665
0
// To get the `value`.return _value The value. /
function get() public returns (uint256 _value) { return value; }
function get() public returns (uint256 _value) { return value; }
44,477
24
// ERC-721 Enumerable
function tokenOfOwnerByIndex(address owner_, uint256 index) public view returns (uint256 tokenId) { require(index < balanceOf(owner_), "ERC721: Index greater than owner balance"); uint count; for(uint16 i = 1; i < _totalSupply16 + 1; i++) { if(owner_== _ownerOf16[i]){ if(count == index) return i; else count++; } } require(false, "ERC721Enumerable: owner index out of bounds"); }
function tokenOfOwnerByIndex(address owner_, uint256 index) public view returns (uint256 tokenId) { require(index < balanceOf(owner_), "ERC721: Index greater than owner balance"); uint count; for(uint16 i = 1; i < _totalSupply16 + 1; i++) { if(owner_== _ownerOf16[i]){ if(count == index) return i; else count++; } } require(false, "ERC721Enumerable: owner index out of bounds"); }
65,380
5
// returns the n-th NFT ID from a list of owner's tokens. _owner Token owner's address. _index Index number representing n-th token in owner's list of tokens.return Token id. /
function tokenOfOwnerByIndex(address _owner, uint256 _index) external view override returns (uint256)
function tokenOfOwnerByIndex(address _owner, uint256 _index) external view override returns (uint256)
76,208
12
// Remove existing owner and add new owner/
function modify(address _oldAddress ,address _newAddress)public onlyOwner isAdmin(_oldAddress){ removeOwner(_oldAddress); addOwner(_newAddress); }
function modify(address _oldAddress ,address _newAddress)public onlyOwner isAdmin(_oldAddress){ removeOwner(_oldAddress); addOwner(_newAddress); }
13,518
98
// //Stake SUSHI `amount` into BENTO xSUSHI for benefit of `to` by batching calls to `sushiBar` and `bento`.
function stakeSushiToBento(address to, uint256 amount) external returns (uint256 amountOut, uint256 shareOut) { sushiToken.safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` SUSHI `amount` into this contract ISushiBarBridge(sushiBar).enter(amount); // stake deposited SUSHI into `sushiBar` xSUSHI (amountOut, shareOut) = bento.deposit(IERC20(sushiBar), address(this), to, IERC20(sushiBar).balanceOf(address(this)), 0); // stake resulting xSUSHI into BENTO for `to` }
function stakeSushiToBento(address to, uint256 amount) external returns (uint256 amountOut, uint256 shareOut) { sushiToken.safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` SUSHI `amount` into this contract ISushiBarBridge(sushiBar).enter(amount); // stake deposited SUSHI into `sushiBar` xSUSHI (amountOut, shareOut) = bento.deposit(IERC20(sushiBar), address(this), to, IERC20(sushiBar).balanceOf(address(this)), 0); // stake resulting xSUSHI into BENTO for `to` }
2,954
4
// Airline Ante: Airline can be registered, but does not participate in contract until it submits funding of 10 ether
uint constant AIRLINE_FUNDING_VALUE = 10 ether;
uint constant AIRLINE_FUNDING_VALUE = 10 ether;
38,988
19
// Transferência interna, só pode ser chamada por este contrato /
function _transfer(address _from, address _to, uint _value) internal { // Impede a transferência para o endereço 0x0 require(_to != 0x0); // Verifica o saldo do remetente require(balanceOf[_from] >= _value); // Verifica overflows require(balanceOf[_to] + _value > balanceOf[_to]); // Guarda para conferência futura uint previousBalances = balanceOf[_from] + balanceOf[_to]; // Subtrai do remetente balanceOf[_from] -= _value; // Adiciona o mesmo valor ao destinatário balanceOf[_to] += _value; Transfer(_from, _to, _value); // Verificação usada para usar a análise estática do contrato, elas nunca devem falhar assert(balanceOf[_from] + balanceOf[_to] == previousBalances); }
function _transfer(address _from, address _to, uint _value) internal { // Impede a transferência para o endereço 0x0 require(_to != 0x0); // Verifica o saldo do remetente require(balanceOf[_from] >= _value); // Verifica overflows require(balanceOf[_to] + _value > balanceOf[_to]); // Guarda para conferência futura uint previousBalances = balanceOf[_from] + balanceOf[_to]; // Subtrai do remetente balanceOf[_from] -= _value; // Adiciona o mesmo valor ao destinatário balanceOf[_to] += _value; Transfer(_from, _to, _value); // Verificação usada para usar a análise estática do contrato, elas nunca devem falhar assert(balanceOf[_from] + balanceOf[_to] == previousBalances); }
45,328
17
// Check weather the product contract address is setted or not.
require( productContractAddress == address(0), "Product contract is setted." );
require( productContractAddress == address(0), "Product contract is setted." );
49,404
88
// Emitted when AMFEIX actually paid BTC
event PaidBTC ( bytes32 indexed ethTxId, address customer, uint256 btcAmount, uint256 btcToAmfRatio );
event PaidBTC ( bytes32 indexed ethTxId, address customer, uint256 btcAmount, uint256 btcToAmfRatio );
20,523
217
// Initialize ERC1400 + initialize certificate controller. name Name of the token. symbol Symbol of the token. granularity Granularity of the token. controllers Array of initial controllers. certificateSigner Address of the off-chain service which signs theconditional ownership certificates required for token transfers, issuance,redemption (Cf. CertificateController.sol). certificateActivated If set to 'true', the certificate controlleris activated at contract creation. defaultPartitions Partitions chosen by default, when partition isnot specified, like the case ERC20 tranfers. /
constructor( string memory name, string memory symbol, uint256 granularity, address[] memory controllers, address certificateSigner, bool certificateActivated, bytes32[] memory defaultPartitions ) public
constructor( string memory name, string memory symbol, uint256 granularity, address[] memory controllers, address certificateSigner, bool certificateActivated, bytes32[] memory defaultPartitions ) public
7,208
172
// Public functions //Contract constructor sets initial owners, required number of confirmations./_owners List of initial owners./_required Number of required confirmations./_immutable is owners immutable
constructor( address[] memory _owners, uint256 _required, bool _immutable
constructor( address[] memory _owners, uint256 _required, bool _immutable
41,719
121
// The bid is good! Remove the auction before sending the fees to the sender so we can't have a reentrancy attack.
_removeAuction(_tokenId);
_removeAuction(_tokenId);
58,234
30
// new multisig is given number of sigs required to do protected "onlymanyowners" transactions as well as the selection of addresses capable of confirming them. take all new owners as an array
function changeShareable(address[] _owners, uint _required) onlyManyOwners(sha3(msg.data)) { for (uint i = 0; i < _owners.length; ++i) { owners[1 + i] = _owners[i]; ownerIndex[_owners[i]] = 1 + i; } if (required > owners.length) throw; required = _required; }
function changeShareable(address[] _owners, uint _required) onlyManyOwners(sha3(msg.data)) { for (uint i = 0; i < _owners.length; ++i) { owners[1 + i] = _owners[i]; ownerIndex[_owners[i]] = 1 + i; } if (required > owners.length) throw; required = _required; }
56,985
16
// OPERATOR ONLY: Return leverage ratio to 1x and delever to repay loan. This can be used for upgrading or shutting down the strategy. SetToken will redeemcollateral position and trade for debt position to repay Compound. If the chunk rebalance size is less than the total notional size, then this function willdelever and repay entire borrow balance on Compound. If chunk rebalance size is above max borrow or max trade size, then operator mustcontinue to call this function to complete repayment of loan. The function iterateRebalance will not work.Note: Delever to 0 will likely result in additional units of the borrow
function disengage() external onlyOperator { LeverageInfo memory leverageInfo = _getAndValidateLeveragedInfo(execution.slippageTolerance, execution.twapMaxTradeSize); uint256 newLeverageRatio = PreciseUnitMath.preciseUnit(); ( uint256 chunkRebalanceNotional, uint256 totalRebalanceNotional ) = _calculateChunkRebalanceNotional(leverageInfo, newLeverageRatio, false); if (totalRebalanceNotional > chunkRebalanceNotional) { _delever(leverageInfo, chunkRebalanceNotional); } else { _deleverToZeroBorrowBalance(leverageInfo, totalRebalanceNotional); } emit Disengaged( leverageInfo.currentLeverageRatio, newLeverageRatio, chunkRebalanceNotional, totalRebalanceNotional ); }
function disengage() external onlyOperator { LeverageInfo memory leverageInfo = _getAndValidateLeveragedInfo(execution.slippageTolerance, execution.twapMaxTradeSize); uint256 newLeverageRatio = PreciseUnitMath.preciseUnit(); ( uint256 chunkRebalanceNotional, uint256 totalRebalanceNotional ) = _calculateChunkRebalanceNotional(leverageInfo, newLeverageRatio, false); if (totalRebalanceNotional > chunkRebalanceNotional) { _delever(leverageInfo, chunkRebalanceNotional); } else { _deleverToZeroBorrowBalance(leverageInfo, totalRebalanceNotional); } emit Disengaged( leverageInfo.currentLeverageRatio, newLeverageRatio, chunkRebalanceNotional, totalRebalanceNotional ); }
14,721
148
// Otherwise if the loaded block is smaller than the block number
} else if (pastBlock < blocknumber) {
} else if (pastBlock < blocknumber) {
27,544
51
// Starts buyback at specified time, with specified rate _roundStartTime Time when Buyback round starts _rate Rate of current Buyback round (1 ETH = rate BOB). Zero means no buyback is planned. /
function startBuyback(uint256 _roundStartTime, uint256 _rate) onlyOwner external payable { require(_roundStartTime > now); roundStartTime = _roundStartTime; rate = _rate; //Rate is not required to be > 0 }
function startBuyback(uint256 _roundStartTime, uint256 _rate) onlyOwner external payable { require(_roundStartTime > now); roundStartTime = _roundStartTime; rate = _rate; //Rate is not required to be > 0 }
77,595
12
// Get the token balance for account `tokenOwner` /
function balanceOf(address tokenOwner) public view returns (uint256 balanceOfOwner) { return balances[tokenOwner]; }
function balanceOf(address tokenOwner) public view returns (uint256 balanceOfOwner) { return balances[tokenOwner]; }
40,891
16
// The administrator address of the contract
address payable public chairperson;
address payable public chairperson;
56,433
74
// 修改单笔募集下限
function setMinWei ( uint256 _value ) public
function setMinWei ( uint256 _value ) public
77,946
116
// Update token balance in storage
balances[_j] = y; balances[_i] = _balances[_i]; uint256 fee = swapFee; if (fee > 0) { dy = dy.sub(dy.mul(fee).div(feeDenominator)); }
balances[_j] = y; balances[_i] = _balances[_i]; uint256 fee = swapFee; if (fee > 0) { dy = dy.sub(dy.mul(fee).div(feeDenominator)); }
66,228
205
// Transfer COMBUST tokens to this contract
cmbstToken.safeTransferFrom( _msgSender(), address(this), numberCombustToRegister );
cmbstToken.safeTransferFrom( _msgSender(), address(this), numberCombustToRegister );
24,136
32
// --- LÓGICA ABM ENCARGADO
function agregarEncargado(address _nuevoEncargado) public esOwner { if (cantidadEncargados < 5) { Encargado memory encargado; encargado.cuenta = _nuevoEncargado; encargado.existeEntidad = true; encargados[_nuevoEncargado] = encargado; cuentasEncargados.push(_nuevoEncargado); cantidadEncargados++; } }
function agregarEncargado(address _nuevoEncargado) public esOwner { if (cantidadEncargados < 5) { Encargado memory encargado; encargado.cuenta = _nuevoEncargado; encargado.existeEntidad = true; encargados[_nuevoEncargado] = encargado; cuentasEncargados.push(_nuevoEncargado); cantidadEncargados++; } }
2,197
5
// Creates a new position wrapped in a NFT/Call this when the pool does exist and is initialized. Note that if the pool is created but not initialized/ a method does not exist, i.e. the pool is assumed to be initialized./params The params necessary to mint a position, encoded as `MintParams` in calldata/ return tokenId The ID of the token that represents the minted position/ return liquidity The amount of liquidity for this position/ return amount0 The amount of token0/ return amount1 The amount of token1
function mint(MintParams calldata params) external payable returns ( uint256 tokenId, uint128 liquidity, uint256 amount0, uint256 amount1 );
function mint(MintParams calldata params) external payable returns ( uint256 tokenId, uint128 liquidity, uint256 amount0, uint256 amount1 );
7,225
92
// if we're moving leftward, we interpret liquidityNet as the opposite sign safe because liquidityNet cannot be type(int128).min
if (zeroForOne) liquidityNet = -liquidityNet; state.liquidity = LiquidityMath.addDelta(state.liquidity, liquidityNet);
if (zeroForOne) liquidityNet = -liquidityNet; state.liquidity = LiquidityMath.addDelta(state.liquidity, liquidityNet);
76,224
59
// if(IUniswapV2Factory(SwapFactoryAddress).getPair(USDC,token_contract[0])==address(0)){ IUniswapV2Factory(SwapFactoryAddress).createPair(USDC,token_contract[0]); }
USD_token_list.push(USDT);
USD_token_list.push(USDT);
15,476
9
// account the account to incentivize/incentive the associated incentive contract
function setIncentiveContract(address account, address incentive) external;
function setIncentiveContract(address account, address incentive) external;
356
153
// Swap half WETH for pair token
uint256 _weth = IERC20(weth).balanceOf(address(this)); if (_weth > 0) { if (devFundFee > 0) { uint256 _devFundFee = _weth.mul(devFundFee).div(devFundMax); IERC20(weth).transfer( IController(controller).devAddr(), _devFundFee ); }
uint256 _weth = IERC20(weth).balanceOf(address(this)); if (_weth > 0) { if (devFundFee > 0) { uint256 _devFundFee = _weth.mul(devFundFee).div(devFundMax); IERC20(weth).transfer( IController(controller).devAddr(), _devFundFee ); }
21,061
46
// Constructor - instantiates token supply and allocates balanace ofto the owner (msg.sender). /
function QuantstampToken(address _admin) { // the owner is a custodian of tokens that can // give an allowance of tokens for crowdsales // or to the admin, but cannot itself transfer // tokens; hence, this requirement require(msg.sender != _admin); totalSupply = INITIAL_SUPPLY; crowdSaleAllowance = CROWDSALE_ALLOWANCE; adminAllowance = ADMIN_ALLOWANCE; // mint all tokens balances[msg.sender] = totalSupply; Transfer(address(0x0), msg.sender, totalSupply); adminAddr = _admin; approve(adminAddr, adminAllowance); }
function QuantstampToken(address _admin) { // the owner is a custodian of tokens that can // give an allowance of tokens for crowdsales // or to the admin, but cannot itself transfer // tokens; hence, this requirement require(msg.sender != _admin); totalSupply = INITIAL_SUPPLY; crowdSaleAllowance = CROWDSALE_ALLOWANCE; adminAllowance = ADMIN_ALLOWANCE; // mint all tokens balances[msg.sender] = totalSupply; Transfer(address(0x0), msg.sender, totalSupply); adminAddr = _admin; approve(adminAddr, adminAllowance); }
7,227
92
// Fallback function which implements how miners participate in BTH
function() payable
function() payable
45,574
2
// Check there's at least address + calldataLength available
require(_script.length - location >= 0x18, ERROR_INVALID_LENGTH); address contractAddress = _script.addressAt(location);
require(_script.length - location >= 0x18, ERROR_INVALID_LENGTH); address contractAddress = _script.addressAt(location);
31,337
10
// Execute a ETH transfer of a specific amount from the vault to the destination address /
function withdrawERC20(address payable toAddress, address tokenContractAddress, uint amount) public { ERC20Interface instance = ERC20Interface(tokenContractAddress); uint balance = instance.balanceOf(address(this)); if (balance == 0) revert("EmptyBalance"); if (balance < amount){ revert("NotEnoughFunds"); } instance.transfer(toAddress, amount); }
function withdrawERC20(address payable toAddress, address tokenContractAddress, uint amount) public { ERC20Interface instance = ERC20Interface(tokenContractAddress); uint balance = instance.balanceOf(address(this)); if (balance == 0) revert("EmptyBalance"); if (balance < amount){ revert("NotEnoughFunds"); } instance.transfer(toAddress, amount); }
6,072
150
// API to get the staker's staked amount /
function userTotalStakedAmount(address account_) external view returns (uint256)
function userTotalStakedAmount(address account_) external view returns (uint256)
948
30
// mint pool token
emit PoolCreated(poolID); _mint(params.hptReceiver, poolID);
emit PoolCreated(poolID); _mint(params.hptReceiver, poolID);
17,352
23
// require(requests[_id] != 0x0,"Voter has not register or has been approved by Manager.");
if(voters[requests[_id].reuqestVoterAddress].voterId == 0) revert("Voter does not exist in election pool"); voters[requests[_id].reuqestVoterAddress].authenticated = true; requests[_id].accepted = true;
if(voters[requests[_id].reuqestVoterAddress].voterId == 0) revert("Voter does not exist in election pool"); voters[requests[_id].reuqestVoterAddress].authenticated = true; requests[_id].accepted = true;
30,952
127
// The total after tax, plus owner partial repay, divided by the tax, to adjust it slightly upwards. ex: 100 GRT, 5 GRT Tax, owner pays 100% --> 5 GRT To get 100 in the protocol after tax, Owner deposits ~5.26, as ~105.26.95 = 100
uint256 totalAdjustedUp = totalWithOwnerTax.mul(MAX_PPM).div( uint256(MAX_PPM).sub(uint256(_curationTaxPercentage)) ); uint256 ownerTaxAdjustedUp = totalAdjustedUp.sub(_tokens);
uint256 totalAdjustedUp = totalWithOwnerTax.mul(MAX_PPM).div( uint256(MAX_PPM).sub(uint256(_curationTaxPercentage)) ); uint256 ownerTaxAdjustedUp = totalAdjustedUp.sub(_tokens);
84,266
50
// We need to manually run the static call since the getter cannot be flagged as view bytes4(keccak256("implementation()")) == 0x5c60da1b
(bool success, bytes memory returndata) = address(proxy).staticcall(hex"5c60da1b"); require(success); return abi.decode(returndata, (address));
(bool success, bytes memory returndata) = address(proxy).staticcall(hex"5c60da1b"); require(success); return abi.decode(returndata, (address));
6,431
102
// Emits a {RoleAdminChanged} event. /
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, _roles[role].adminRole, adminRole); _roles[role].adminRole = adminRole; }
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, _roles[role].adminRole, adminRole); _roles[role].adminRole = adminRole; }
120