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
23
// εˆ€ζ–·ζζ‘ˆζ˜―ε¦η‚ΊREJECTEDη‹€ζ…‹
modifier isProposalRejected(uint256 _proposalIndex){ require(proposals[_proposalIndex].proposalPhase == ProposalPhase.REJECTED, "not at REJECTED phase."); _; }
modifier isProposalRejected(uint256 _proposalIndex){ require(proposals[_proposalIndex].proposalPhase == ProposalPhase.REJECTED, "not at REJECTED phase."); _; }
15,029
41
// enable trading
tradingActive = true; swapEnabled = true;
tradingActive = true; swapEnabled = true;
28,840
311
// Internal utility function to initiate pve battle, assumes that all battle/requirements have been checked.
function _triggerPVEStart(uint256 _warriorId) internal { // Grab a reference to the warrior from storage. DataTypes.Warrior storage warrior = warriors[_warriorId]; // Set warrior current action to pve battle warrior.action = uint16(PVE_BATTLE); // Set battle duration warrior.cooldownEndBlock = uint64((getPVEDuration(warrior.level) / secondsPerBlock) + block.number); // Emit the pve battle start event. PVEStarted(msg.sender, warrior.dungeonIndex, _warriorId, warrior.cooldownEndBlock); }
function _triggerPVEStart(uint256 _warriorId) internal { // Grab a reference to the warrior from storage. DataTypes.Warrior storage warrior = warriors[_warriorId]; // Set warrior current action to pve battle warrior.action = uint16(PVE_BATTLE); // Set battle duration warrior.cooldownEndBlock = uint64((getPVEDuration(warrior.level) / secondsPerBlock) + block.number); // Emit the pve battle start event. PVEStarted(msg.sender, warrior.dungeonIndex, _warriorId, warrior.cooldownEndBlock); }
78,879
313
// burn staked tokens
(, address scAddress) = qd.getscAddressOfCover(coverId); uint tokenPrice = pool.getTokenPrice(asset);
(, address scAddress) = qd.getscAddressOfCover(coverId); uint tokenPrice = pool.getTokenPrice(asset);
54,580
1
// Address of soldier contract
address soldierContractAddress;
address soldierContractAddress;
45,416
23
// Unset all boosts for the staked team.
NTSUserManager.StakeTeam memory _inStakedteam = userStorage.getInStakedTeam(_staketeam); uint16[] memory _boostIds = _inStakedteam.boostIds; for(uint16 i = 0; i < _boostIds.length; i++) { uint16 _boostId = _boostIds[i]; if(momoToken.ownerOf(_boostId) == msg.sender) {
NTSUserManager.StakeTeam memory _inStakedteam = userStorage.getInStakedTeam(_staketeam); uint16[] memory _boostIds = _inStakedteam.boostIds; for(uint16 i = 0; i < _boostIds.length; i++) { uint16 _boostId = _boostIds[i]; if(momoToken.ownerOf(_boostId) == msg.sender) {
29,349
19
// Blacklist an extension /
function _blacklistExtension(address extension) internal { require(extension != address(this), "Cannot blacklist yourself"); if (_extensions.contains(extension)) { emit ExtensionUnregistered(extension, msg.sender); _extensions.remove(extension); } if (!_blacklistedExtensions.contains(extension)) { emit ExtensionBlacklisted(extension, msg.sender); _blacklistedExtensions.add(extension); } }
function _blacklistExtension(address extension) internal { require(extension != address(this), "Cannot blacklist yourself"); if (_extensions.contains(extension)) { emit ExtensionUnregistered(extension, msg.sender); _extensions.remove(extension); } if (!_blacklistedExtensions.contains(extension)) { emit ExtensionBlacklisted(extension, msg.sender); _blacklistedExtensions.add(extension); } }
21,028
25
// GlobalToken Interface
contract GlobalCryptoFund is Owned, GlobalToken { using SafeMath for uint256; /* Public variables of the token */ string public name; string public symbol; uint8 public decimals; uint256 public totalSupply; address public minter; /* This creates an array with all balances */ mapping (address => uint256) public balanceOf; modifier onlyMinter { require(msg.sender == minter); _; } function setMinter(address _addressMinter) onlyOwner { minter = _addressMinter; } /* Initializes contract with initial supply tokens to the creator of the contract */ function GlobalCryptoFund() { name = "GlobalCryptoFund"; // Set the name for display purposes symbol = "GCF"; // Set the symbol for display purposes decimals = 18; // Amount of decimals for display purposes totalSupply = 0; // Update total supply balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens } function balanceOf(address _owner) constant returns (uint256 balance){ return balanceOf[_owner]; } /* Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint256 _value) internal { require (_to != 0x0); // Prevent transfer to 0x0 address. Use burn() instead require (balanceOf[_from] >= _value); // Check if the sender has enough require (balanceOf[_to].add(_value) >= balanceOf[_to]); // Check for overflows require(_to != address(this)); balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the sender balanceOf[_to] = balanceOf[_to].add(_value); // Add the same to the recipient Transfer(_from, _to, _value); } function transfer(address _to, uint256 _value) onlyPayloadSize(2) returns (bool) { _transfer(msg.sender, _to, _value); return true; } event Mint(address indexed from, uint256 value); function mintToken(address target, uint256 mintedAmount) onlyMinter { balanceOf[target] = balanceOf[target].add(mintedAmount); totalSupply = totalSupply.add(mintedAmount); Transfer(0, this, mintedAmount); Transfer(this, target, mintedAmount); Mint(target, mintedAmount); } event Burn(address indexed from, uint256 value); function burn(uint256 _value) onlyMinter returns (bool success) { require (balanceOf[msg.sender] >= _value); // Check if the sender has enough balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value); // Subtract from the sender totalSupply = totalSupply.sub(_value); // Updates totalSupply Burn(msg.sender, _value); return true; } function kill() onlyOwner { selfdestruct(owner); } function contractVersion() constant returns(uint256) { /* contractVersion identifies as 200YYYYMMDDHHMM */ return 200201712010000; } }
contract GlobalCryptoFund is Owned, GlobalToken { using SafeMath for uint256; /* Public variables of the token */ string public name; string public symbol; uint8 public decimals; uint256 public totalSupply; address public minter; /* This creates an array with all balances */ mapping (address => uint256) public balanceOf; modifier onlyMinter { require(msg.sender == minter); _; } function setMinter(address _addressMinter) onlyOwner { minter = _addressMinter; } /* Initializes contract with initial supply tokens to the creator of the contract */ function GlobalCryptoFund() { name = "GlobalCryptoFund"; // Set the name for display purposes symbol = "GCF"; // Set the symbol for display purposes decimals = 18; // Amount of decimals for display purposes totalSupply = 0; // Update total supply balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens } function balanceOf(address _owner) constant returns (uint256 balance){ return balanceOf[_owner]; } /* Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint256 _value) internal { require (_to != 0x0); // Prevent transfer to 0x0 address. Use burn() instead require (balanceOf[_from] >= _value); // Check if the sender has enough require (balanceOf[_to].add(_value) >= balanceOf[_to]); // Check for overflows require(_to != address(this)); balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the sender balanceOf[_to] = balanceOf[_to].add(_value); // Add the same to the recipient Transfer(_from, _to, _value); } function transfer(address _to, uint256 _value) onlyPayloadSize(2) returns (bool) { _transfer(msg.sender, _to, _value); return true; } event Mint(address indexed from, uint256 value); function mintToken(address target, uint256 mintedAmount) onlyMinter { balanceOf[target] = balanceOf[target].add(mintedAmount); totalSupply = totalSupply.add(mintedAmount); Transfer(0, this, mintedAmount); Transfer(this, target, mintedAmount); Mint(target, mintedAmount); } event Burn(address indexed from, uint256 value); function burn(uint256 _value) onlyMinter returns (bool success) { require (balanceOf[msg.sender] >= _value); // Check if the sender has enough balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value); // Subtract from the sender totalSupply = totalSupply.sub(_value); // Updates totalSupply Burn(msg.sender, _value); return true; } function kill() onlyOwner { selfdestruct(owner); } function contractVersion() constant returns(uint256) { /* contractVersion identifies as 200YYYYMMDDHHMM */ return 200201712010000; } }
31,002
209
// setting initial roles
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _setupRole(MINTER_ROLE, _msgSender()); _setupRole(PAUSER_ROLE, _msgSender()); _setupRole(FREEZER_ROLE, _msgSender());
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _setupRole(MINTER_ROLE, _msgSender()); _setupRole(PAUSER_ROLE, _msgSender()); _setupRole(FREEZER_ROLE, _msgSender());
11,752
46
// Event emitted when comptroller is changed /
event NewComptroller(ComptrollerInterface oldComptroller, ComptrollerInterface newComptroller);
event NewComptroller(ComptrollerInterface oldComptroller, ComptrollerInterface newComptroller);
19,307
113
// Calculate prizes in CAKE for each bracket by starting from the highest one
for (uint32 i = 0; i < numbersCount; i++) { uint32 j = numbersCount - 1 - i; uint32 transformedWinningNumber = _bracketCalculator[j] + (finalNumber % (uint32(10)**(j + 1))); _lotteries[_lotteryId].countWinnersPerBracket[j] = _numberTicketsPerLotteryId[_lotteryId][transformedWinningNumber] - numberAddressesInPreviousBracket;
for (uint32 i = 0; i < numbersCount; i++) { uint32 j = numbersCount - 1 - i; uint32 transformedWinningNumber = _bracketCalculator[j] + (finalNumber % (uint32(10)**(j + 1))); _lotteries[_lotteryId].countWinnersPerBracket[j] = _numberTicketsPerLotteryId[_lotteryId][transformedWinningNumber] - numberAddressesInPreviousBracket;
46,672
58
// Only for the owner of the contract. Adds commission to the owner's pending withdrawals./
function addCommissionToPendingWithdrawals(uint32 _canvasId) external onlyOwner stateOwned(_canvasId)
function addCommissionToPendingWithdrawals(uint32 _canvasId) external onlyOwner stateOwned(_canvasId)
4,639
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)); } }
37,309
22
// Attach retirement events to an NFT./tokenId The id of the NFT to attach events to./retirementEventIds An array of event ids to associate with the NFT.
function attachRetirementEvents( uint256 tokenId, uint256[] calldata retirementEventIds
function attachRetirementEvents( uint256 tokenId, uint256[] calldata retirementEventIds
21,727
51
// Transfers asset balance between holders wallets._fromId holder id to take from. _toId holder id to give to. _value amount to transfer. _symbol asset symbol. /
function _transferDirect(uint _fromId, uint _toId, uint _value, bytes32 _symbol) internal { assets[_symbol].wallets[_fromId].balance -= _value; assets[_symbol].wallets[_toId].balance += _value; }
function _transferDirect(uint _fromId, uint _toId, uint _value, bytes32 _symbol) internal { assets[_symbol].wallets[_fromId].balance -= _value; assets[_symbol].wallets[_toId].balance += _value; }
29,019
5
// only execute if there's an active season set
modifier requireActiveSeason() { require(seasons.length > 0, 'Series: No active season'); _; }
modifier requireActiveSeason() { require(seasons.length > 0, 'Series: No active season'); _; }
27,239
25
// execute a HTLC
function executeHTLC(uint256 htlcid, string memory hashkey) public { // getting htlc HTLC memory htlc = htlcs[htlcid]; // hashkey must be correct require(htlc.hashlock == sha256(abi.encodePacked(hashkey)), "password is wrong"); // timestamp must be in the future require(block.number <= htlc.timelock, "timelock already activated"); // get cbdc structure IERC20 cbdc = IERC20(htlc.cbdcAddress); // transfer to the recipient cbdc.transfer( htlc.toAddress, htlc.amount ); // raise event emit HTLCexecute( htlcid, htlc.hashlock, htlc.cbdcAddress, htlc.fromAddress, htlc.toAddress, htlc.amount); }
function executeHTLC(uint256 htlcid, string memory hashkey) public { // getting htlc HTLC memory htlc = htlcs[htlcid]; // hashkey must be correct require(htlc.hashlock == sha256(abi.encodePacked(hashkey)), "password is wrong"); // timestamp must be in the future require(block.number <= htlc.timelock, "timelock already activated"); // get cbdc structure IERC20 cbdc = IERC20(htlc.cbdcAddress); // transfer to the recipient cbdc.transfer( htlc.toAddress, htlc.amount ); // raise event emit HTLCexecute( htlcid, htlc.hashlock, htlc.cbdcAddress, htlc.fromAddress, htlc.toAddress, htlc.amount); }
43,548
30
// Increment the funds that can withdrawn for sustainability.
sustainabilityPool[w] = sustainabilityPool[w].add(sustainabilityAmount);
sustainabilityPool[w] = sustainabilityPool[w].add(sustainabilityAmount);
18,961
90
// SPDX-License-Identifier: MIT/ Wrappers over Solidity's arithmetic operations with added overflowchecks. note that this is a stripped down version of open zeppelin's safemath /
contract SafeMath { /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return _sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function _sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } }
contract SafeMath { /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return _sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function _sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } }
66,967
8
// Event emitted when point list is deployed.
event PointListDeployed(address indexed operator, address indexed addr, address pointList, address owner);
event PointListDeployed(address indexed operator, address indexed addr, address pointList, address owner);
25,300
25
// Updates the minimum and maximum number of validators that can be elected. min The minimum number of validators that can be elected. max The maximum number of validators that can be elected.return True upon success. /
function setElectableValidators(uint256 min, uint256 max) public onlyOwner returns (bool) { require(0 < min, "Minimum electable validators cannot be zero"); require(min <= max, "Maximum electable validators cannot be smaller than minimum"); require( min != electableValidators.min || max != electableValidators.max, "Electable validators not changed" ); electableValidators = ElectableValidators(min, max); emit ElectableValidatorsSet(min, max); return true;
function setElectableValidators(uint256 min, uint256 max) public onlyOwner returns (bool) { require(0 < min, "Minimum electable validators cannot be zero"); require(min <= max, "Maximum electable validators cannot be smaller than minimum"); require( min != electableValidators.min || max != electableValidators.max, "Electable validators not changed" ); electableValidators = ElectableValidators(min, max); emit ElectableValidatorsSet(min, max); return true;
16,888
4
// stores royalties for token contract, set in setRoyaltiesByToken() method
mapping(address => RoyaltiesSet) public royaltiesByToken;
mapping(address => RoyaltiesSet) public royaltiesByToken;
1,521
10
// --- Dependency setters ---
function setAddresses( address _priceAggregatorAddress, address _tellorCallerAddress ) external onlyOwner
function setAddresses( address _priceAggregatorAddress, address _tellorCallerAddress ) external onlyOwner
4,318
59
// Storage /
OMIToken public token; OMITokenLock public tokenLock;
OMIToken public token; OMITokenLock public tokenLock;
32,859
18
// If we're checking for an allowlist quantity restriction, ignore the general quantity restriction.
require( _quantity > 0 && (!verifyMaxQuantityPerTransaction || _quantity <= currentClaimPhase.quantityLimitPerTransaction), "invalid quantity." ); require( currentClaimPhase.supplyClaimed + _quantity <= currentClaimPhase.maxClaimableSupply, "exceed max claimable supply." );
require( _quantity > 0 && (!verifyMaxQuantityPerTransaction || _quantity <= currentClaimPhase.quantityLimitPerTransaction), "invalid quantity." ); require( currentClaimPhase.supplyClaimed + _quantity <= currentClaimPhase.maxClaimableSupply, "exceed max claimable supply." );
20,554
4
// Private Functions//Computes the secure counterpart to a key. _key Key to get a secure key from.return _secureKey Secure version of the key. /
function _getSecureKey(bytes memory _key) private pure returns (bytes memory _secureKey) { return abi.encodePacked(keccak256(_key)); }
function _getSecureKey(bytes memory _key) private pure returns (bytes memory _secureKey) { return abi.encodePacked(keccak256(_key)); }
28,769
383
// Calculate denominator for row 76: x - g^76z.
let denominator := add(shiftedEvalPoint, mload(add(expmodsAndPoints, 0x660))) mstore(add(productsPtr, 0x3c0), partialProduct) mstore(add(valuesPtr, 0x3c0), denominator) partialProduct := mulmod(partialProduct, denominator, PRIME)
let denominator := add(shiftedEvalPoint, mload(add(expmodsAndPoints, 0x660))) mstore(add(productsPtr, 0x3c0), partialProduct) mstore(add(valuesPtr, 0x3c0), denominator) partialProduct := mulmod(partialProduct, denominator, PRIME)
47,246
119
// Adds a new bundle to array/Can only be called by auth addresses if it's not open to public/Strategies need to have the same number of triggers and ids exists/_strategyIds Array of strategyIds that go into a bundle
function createBundle( uint64[] memory _strategyIds
function createBundle( uint64[] memory _strategyIds
41,058
78
// OPERATOR ONLY: Toggle whether anyone can call function, bypassing the callAllowlist _status Boolean indicating whether to allow anyone call /
function updateAnyoneCallable(bool _status) external onlyOperator { anyoneCallable = _status; emit AnyoneCallableUpdated(_status); }
function updateAnyoneCallable(bool _status) external onlyOperator { anyoneCallable = _status; emit AnyoneCallableUpdated(_status); }
11,016
192
// Reset the Rampp surcharge total to zero regardless of value on contract currently./
function resetRamppSurchargeBalance() public isRampp { ramppSurchargeBalance = 0 ether; }
function resetRamppSurchargeBalance() public isRampp { ramppSurchargeBalance = 0 ether; }
6,399
7
// basic info
contract Newuser { struct User { bytes32 name; } struct Message{ bytes32 content; address writtenBy; uint256 timestamp; } // Each address is linked to a user with name, occupation and bio mapping(address => User) public userInfo; // The messages that each address has written mapping(address => Message[]) public userMessages; // All the messages ever written Message[] public messages; function setCreateUser(bytes32 _name) public { User memory user = User(_name ); userInfo[msg.sender] = user; } // Adds a new message function writeMessage(bytes32 _content) public { Message memory message = Message(_content, msg.sender, now); userMessages[msg.sender].push(message); messages.push(message); } }
contract Newuser { struct User { bytes32 name; } struct Message{ bytes32 content; address writtenBy; uint256 timestamp; } // Each address is linked to a user with name, occupation and bio mapping(address => User) public userInfo; // The messages that each address has written mapping(address => Message[]) public userMessages; // All the messages ever written Message[] public messages; function setCreateUser(bytes32 _name) public { User memory user = User(_name ); userInfo[msg.sender] = user; } // Adds a new message function writeMessage(bytes32 _content) public { Message memory message = Message(_content, msg.sender, now); userMessages[msg.sender].push(message); messages.push(message); } }
19,760
1
// >>>>>>>>>>>>>>>>>>>>>>>STATE<<<<<<<<<<<<<<<<<<<<<<<<<< /
IQuantumKeyRing private _keyRing;
IQuantumKeyRing private _keyRing;
67,857
9
// Emitted when a new message is dispatched via Optics leafIndex Index of message's leaf in merkle tree destinationAndNonce Destination and destination-specificnonce combined in single field ((destination << 32) & nonce) messageHash Hash of message; the leaf inserted to the Merkle tree for the message committedRoot the latest notarized root submitted in the last signed Update message Raw bytes of message /
event Dispatch( bytes32 indexed messageHash, uint256 indexed leafIndex, uint64 indexed destinationAndNonce, bytes32 committedRoot, bytes message );
event Dispatch( bytes32 indexed messageHash, uint256 indexed leafIndex, uint64 indexed destinationAndNonce, bytes32 committedRoot, bytes message );
4,766
1
// Simulate blockers action. /
function blockerAction() external onlyBlocker { BlockerAction = true; emit BlockerCalled(msg.sender, BlockerAction); }
function blockerAction() external onlyBlocker { BlockerAction = true; emit BlockerCalled(msg.sender, BlockerAction); }
45,814
108
// Withdraws the beneficiary's funds. /
function beneficiaryWithdraw() public { require(_state == State.Closed); _beneficiary.transfer(address(this).balance); }
function beneficiaryWithdraw() public { require(_state == State.Closed); _beneficiary.transfer(address(this).balance); }
33,406
85
// Contract address of the Token contract mints and sends out to compensate losses
IToken public outToken;
IToken public outToken;
25,403
53
// vSPYClaimE18 = ( msg.value /weiDebtCounterVault[_targetCounterVault])vSPYAssetCounterVaultE18[_targetCounterVault];
vSPYClaimE18 = msg.value.mul( vSPYAssetCounterVaultE18[_targetCounterVault] ).div( weiDebtCounterVault[_targetCounterVault] ); require(vSPYClaimE18 <= vSPYAssetCounterVaultE18[_targetCounterVault], "Code Error Branch 1 if you reached this point");
vSPYClaimE18 = msg.value.mul( vSPYAssetCounterVaultE18[_targetCounterVault] ).div( weiDebtCounterVault[_targetCounterVault] ); require(vSPYClaimE18 <= vSPYAssetCounterVaultE18[_targetCounterVault], "Code Error Branch 1 if you reached this point");
64,696
140
//
currentAveragePrices.cumulativeLast20Blocks = currentAveragePrices.cumulativeLast20Blocks.sub(currentAveragePrices.price[i]); currentAveragePrices.price[i] = outTokenFor1WETH; currentAveragePrices.cumulativeLast20Blocks = currentAveragePrices.cumulativeLast20Blocks.add(outTokenFor1WETH); currentAveragePrices.lastAddedHead++; if(currentAveragePrices.lastAddedHead > 19) { currentAveragePrices.lastAddedHead = 0; currentAveragePrices.arrayFull = true; }
currentAveragePrices.cumulativeLast20Blocks = currentAveragePrices.cumulativeLast20Blocks.sub(currentAveragePrices.price[i]); currentAveragePrices.price[i] = outTokenFor1WETH; currentAveragePrices.cumulativeLast20Blocks = currentAveragePrices.cumulativeLast20Blocks.add(outTokenFor1WETH); currentAveragePrices.lastAddedHead++; if(currentAveragePrices.lastAddedHead > 19) { currentAveragePrices.lastAddedHead = 0; currentAveragePrices.arrayFull = true; }
80,446
136
// Max amount that can be swapped based on amount of liquidityAsset in the Balancer Pool
uint256 maxSwapOut = tokenBalanceOut.mul(bPool.MAX_OUT_RATIO()).div(WAD); return tokenAmountOut <= maxSwapOut ? tokenAmountOut : maxSwapOut;
uint256 maxSwapOut = tokenBalanceOut.mul(bPool.MAX_OUT_RATIO()).div(WAD); return tokenAmountOut <= maxSwapOut ? tokenAmountOut : maxSwapOut;
6,011
1
// constants // Position of message bus in the storage. //Penalty in bounty amount percentage charged to staker on revert stake. /
uint8 constant REVOCATION_PENALTY = 150;
uint8 constant REVOCATION_PENALTY = 150;
49,903
3
// Checks if a borrow is allowed borrower Address of the borrower lenderVault Address of the lender vault generalQuoteInfo General quote info (see DataTypesPeerToPeer.sol) quoteTuple Quote tuple (see DataTypesPeerToPeer.sol)return _isAllowed Flag to indicate if the borrow is allowedreturn minNumOfSignersOverwrite Overwrite of minimum number of signers (if zero ignored in quote handler) /
function isAllowed(
function isAllowed(
38,362
168
// PlaceBidLibrary Set Protocol Default implementation of Rebalancing Set Token placeBid function /
library PlaceBidLibrary { using SafeMath for uint256; /* ============ Internal Functions ============ */ /* * Place bid during rebalance auction. Can only be called by Core. * * @param _quantity The amount of currentSet to be rebalanced * @param _coreAddress Core address * @param _biddingParameters Struct containing relevant data for calculating token flows * @return inflowUnitArray Array of amount of tokens inserted into system in bid * @return outflowUnitArray Array of amount of tokens taken out of system in bid */ function validatePlaceBid( uint256 _quantity, address _coreAddress, RebalancingLibrary.BiddingParameters memory _biddingParameters ) public view returns (uint256) { // Make sure sender is a module require( ICore(_coreAddress).validModules(msg.sender), "RebalancingSetToken.placeBid: Sender must be approved module" ); // Make sure that bid amount is greater than zero require( _quantity > 0, "RebalancingSetToken.placeBid: Bid must be > 0" ); // Make sure that bid amount is multiple of minimum bid amount require( _quantity.mod(_biddingParameters.minimumBid) == 0, "RebalancingSetToken.placeBid: Must bid multiple of minimum bid" ); // Make sure that bid Amount is less than remainingCurrentSets require( _quantity <= _biddingParameters.remainingCurrentSets, "RebalancingSetToken.placeBid: Bid exceeds remaining current sets" ); } /* * Get token inflows and outflows required for bid. Also the amount of Rebalancing * Sets that would be generated. * * @param _quantity The amount of currentSet to be rebalanced * @param _auctionLibrary Auction library used in rebalance * @param _biddingParameters Struct containing relevant data for calculating token flows * @param _auctionPriceParameters Struct containing auction price curve parameters * @param _rebalanceState State of rebalancing set token * @return inflowUnitArray Array of amount of tokens inserted into system in bid * @return outflowUnitArray Array of amount of tokens taken out of system in bid */ function getBidPrice( uint256 _quantity, address _auctionLibrary, RebalancingLibrary.BiddingParameters memory _biddingParameters, RebalancingLibrary.AuctionPriceParameters memory _auctionPriceParameters, uint8 _rebalanceState ) public view returns (uint256[] memory, uint256[] memory) { // Confirm in Rebalance State require( _rebalanceState == uint8(RebalancingLibrary.State.Rebalance), "RebalancingSetToken.getBidPrice: State must be Rebalance" ); // Get bid conversion price, currently static placeholder for calling auctionlibrary uint256 priceNumerator; uint256 priceDivisor; (priceNumerator, priceDivisor) = IAuctionPriceCurve(_auctionLibrary).getCurrentPrice( _auctionPriceParameters ); // Normalized quantity amount uint256 unitsMultiplier = _quantity.div(_biddingParameters.minimumBid).mul(priceDivisor); // Calculate token flow arrays return createTokenFlowArrays( unitsMultiplier, priceNumerator, priceDivisor, _biddingParameters ); } /* * Creates arrays of token inflows and outflows * * @param _unitsMultiplier Bid amount normalized to number of standard bid amounts * @param _priceNumerator The numerator of the price ratio * @param _priceDivisor The denominator of the price ratio * @param _biddingParameters Struct containing relevant data for calculating token flows * @return inflowUnitArray Array of amount of tokens inserted into system in bid * @return outflowUnitArray Array of amount of tokens taken out of system in bid */ function createTokenFlowArrays( uint256 _unitsMultiplier, uint256 _priceNumerator, uint256 _priceDivisor, RebalancingLibrary.BiddingParameters memory _biddingParameters ) public pure returns (uint256[] memory, uint256[] memory) { // Declare unit arrays in memory uint256 combinedTokenCount = _biddingParameters.combinedTokenArray.length; uint256[] memory inflowUnitArray = new uint256[](combinedTokenCount); uint256[] memory outflowUnitArray = new uint256[](combinedTokenCount); // Cycle through each token in combinedTokenArray, calculate inflow/outflow and store // result in array for (uint256 i = 0; i < combinedTokenCount; i++) { ( inflowUnitArray[i], outflowUnitArray[i] ) = calculateTokenFlows( _biddingParameters.combinedCurrentUnits[i], _biddingParameters.combinedNextSetUnits[i], _unitsMultiplier, _priceNumerator, _priceDivisor ); } return (inflowUnitArray, outflowUnitArray); } /* * Calculates token inflow/outflow for single component in combinedTokenArray * * @param _currentUnit Amount of token i in currentSet per minimum bid amount * @param _nextSetUnit Amount of token i in nextSet per minimum bid amount * @param _unitsMultiplier Bid amount normalized to number of minimum bid amounts * @param _priceNumerator The numerator of the price ratio * @param _priceDivisor The denominator of the price ratio * @return inflowUnit Amount of token i transferred into the system * @return outflowUnit Amount of token i transferred to the bidder */ function calculateTokenFlows( uint256 _currentUnit, uint256 _nextSetUnit, uint256 _unitsMultiplier, uint256 _priceNumerator, uint256 _priceDivisor ) public pure returns (uint256, uint256) { /* * Below is a mathematically simplified formula for calculating token inflows and * outflows, the following is it's derivation: * token_flow = (bidQuantity/price)*(nextUnit - price*currentUnit) * * Where, * 1) price = (priceNumerator/priceDivisor), * 2) nextUnit and currentUnit are the amount of component i needed for a * standardAmount of sets to be rebalanced where one standardAmount = * max(natural unit nextSet, natural unit currentSet), and * 3) bidQuantity is a normalized amount in terms of the standardAmount used * to calculate nextUnit and currentUnit. This is represented by the unitsMultiplier * variable. * * Given these definitions we can derive the below formula as follows: * token_flow = (unitsMultiplier/(priceNumerator/priceDivisor))* * (nextUnit - (priceNumerator/priceDivisor)*currentUnit) * * We can then multiply this equation by (priceDivisor/priceDivisor) * which simplifies the above equation to: * * (unitsMultiplier/priceNumerator)* (nextUnit*priceDivisor - currentUnit*priceNumerator) * * This is the equation seen below, but since unsigned integers are used we must check to see if * nextUnit*priceDivisor > currentUnit*priceNumerator, otherwise those two terms must be * flipped in the equation. */ uint256 inflowUnit; uint256 outflowUnit; // Use if statement to check if token inflow or outflow if (_nextSetUnit.mul(_priceDivisor) > _currentUnit.mul(_priceNumerator)) { // Calculate inflow amount inflowUnit = _unitsMultiplier.mul( _nextSetUnit.mul(_priceDivisor).sub(_currentUnit.mul(_priceNumerator)) ).div(_priceNumerator); // Set outflow amount to 0 for component i, since tokens need to be injected in rebalance outflowUnit = 0; } else { // Calculate outflow amount outflowUnit = _unitsMultiplier.mul( _currentUnit.mul(_priceNumerator).sub(_nextSetUnit.mul(_priceDivisor)) ).div(_priceNumerator); // Set inflow amount to 0 for component i, since tokens need to be returned in rebalance inflowUnit = 0; } return (inflowUnit, outflowUnit); } }
library PlaceBidLibrary { using SafeMath for uint256; /* ============ Internal Functions ============ */ /* * Place bid during rebalance auction. Can only be called by Core. * * @param _quantity The amount of currentSet to be rebalanced * @param _coreAddress Core address * @param _biddingParameters Struct containing relevant data for calculating token flows * @return inflowUnitArray Array of amount of tokens inserted into system in bid * @return outflowUnitArray Array of amount of tokens taken out of system in bid */ function validatePlaceBid( uint256 _quantity, address _coreAddress, RebalancingLibrary.BiddingParameters memory _biddingParameters ) public view returns (uint256) { // Make sure sender is a module require( ICore(_coreAddress).validModules(msg.sender), "RebalancingSetToken.placeBid: Sender must be approved module" ); // Make sure that bid amount is greater than zero require( _quantity > 0, "RebalancingSetToken.placeBid: Bid must be > 0" ); // Make sure that bid amount is multiple of minimum bid amount require( _quantity.mod(_biddingParameters.minimumBid) == 0, "RebalancingSetToken.placeBid: Must bid multiple of minimum bid" ); // Make sure that bid Amount is less than remainingCurrentSets require( _quantity <= _biddingParameters.remainingCurrentSets, "RebalancingSetToken.placeBid: Bid exceeds remaining current sets" ); } /* * Get token inflows and outflows required for bid. Also the amount of Rebalancing * Sets that would be generated. * * @param _quantity The amount of currentSet to be rebalanced * @param _auctionLibrary Auction library used in rebalance * @param _biddingParameters Struct containing relevant data for calculating token flows * @param _auctionPriceParameters Struct containing auction price curve parameters * @param _rebalanceState State of rebalancing set token * @return inflowUnitArray Array of amount of tokens inserted into system in bid * @return outflowUnitArray Array of amount of tokens taken out of system in bid */ function getBidPrice( uint256 _quantity, address _auctionLibrary, RebalancingLibrary.BiddingParameters memory _biddingParameters, RebalancingLibrary.AuctionPriceParameters memory _auctionPriceParameters, uint8 _rebalanceState ) public view returns (uint256[] memory, uint256[] memory) { // Confirm in Rebalance State require( _rebalanceState == uint8(RebalancingLibrary.State.Rebalance), "RebalancingSetToken.getBidPrice: State must be Rebalance" ); // Get bid conversion price, currently static placeholder for calling auctionlibrary uint256 priceNumerator; uint256 priceDivisor; (priceNumerator, priceDivisor) = IAuctionPriceCurve(_auctionLibrary).getCurrentPrice( _auctionPriceParameters ); // Normalized quantity amount uint256 unitsMultiplier = _quantity.div(_biddingParameters.minimumBid).mul(priceDivisor); // Calculate token flow arrays return createTokenFlowArrays( unitsMultiplier, priceNumerator, priceDivisor, _biddingParameters ); } /* * Creates arrays of token inflows and outflows * * @param _unitsMultiplier Bid amount normalized to number of standard bid amounts * @param _priceNumerator The numerator of the price ratio * @param _priceDivisor The denominator of the price ratio * @param _biddingParameters Struct containing relevant data for calculating token flows * @return inflowUnitArray Array of amount of tokens inserted into system in bid * @return outflowUnitArray Array of amount of tokens taken out of system in bid */ function createTokenFlowArrays( uint256 _unitsMultiplier, uint256 _priceNumerator, uint256 _priceDivisor, RebalancingLibrary.BiddingParameters memory _biddingParameters ) public pure returns (uint256[] memory, uint256[] memory) { // Declare unit arrays in memory uint256 combinedTokenCount = _biddingParameters.combinedTokenArray.length; uint256[] memory inflowUnitArray = new uint256[](combinedTokenCount); uint256[] memory outflowUnitArray = new uint256[](combinedTokenCount); // Cycle through each token in combinedTokenArray, calculate inflow/outflow and store // result in array for (uint256 i = 0; i < combinedTokenCount; i++) { ( inflowUnitArray[i], outflowUnitArray[i] ) = calculateTokenFlows( _biddingParameters.combinedCurrentUnits[i], _biddingParameters.combinedNextSetUnits[i], _unitsMultiplier, _priceNumerator, _priceDivisor ); } return (inflowUnitArray, outflowUnitArray); } /* * Calculates token inflow/outflow for single component in combinedTokenArray * * @param _currentUnit Amount of token i in currentSet per minimum bid amount * @param _nextSetUnit Amount of token i in nextSet per minimum bid amount * @param _unitsMultiplier Bid amount normalized to number of minimum bid amounts * @param _priceNumerator The numerator of the price ratio * @param _priceDivisor The denominator of the price ratio * @return inflowUnit Amount of token i transferred into the system * @return outflowUnit Amount of token i transferred to the bidder */ function calculateTokenFlows( uint256 _currentUnit, uint256 _nextSetUnit, uint256 _unitsMultiplier, uint256 _priceNumerator, uint256 _priceDivisor ) public pure returns (uint256, uint256) { /* * Below is a mathematically simplified formula for calculating token inflows and * outflows, the following is it's derivation: * token_flow = (bidQuantity/price)*(nextUnit - price*currentUnit) * * Where, * 1) price = (priceNumerator/priceDivisor), * 2) nextUnit and currentUnit are the amount of component i needed for a * standardAmount of sets to be rebalanced where one standardAmount = * max(natural unit nextSet, natural unit currentSet), and * 3) bidQuantity is a normalized amount in terms of the standardAmount used * to calculate nextUnit and currentUnit. This is represented by the unitsMultiplier * variable. * * Given these definitions we can derive the below formula as follows: * token_flow = (unitsMultiplier/(priceNumerator/priceDivisor))* * (nextUnit - (priceNumerator/priceDivisor)*currentUnit) * * We can then multiply this equation by (priceDivisor/priceDivisor) * which simplifies the above equation to: * * (unitsMultiplier/priceNumerator)* (nextUnit*priceDivisor - currentUnit*priceNumerator) * * This is the equation seen below, but since unsigned integers are used we must check to see if * nextUnit*priceDivisor > currentUnit*priceNumerator, otherwise those two terms must be * flipped in the equation. */ uint256 inflowUnit; uint256 outflowUnit; // Use if statement to check if token inflow or outflow if (_nextSetUnit.mul(_priceDivisor) > _currentUnit.mul(_priceNumerator)) { // Calculate inflow amount inflowUnit = _unitsMultiplier.mul( _nextSetUnit.mul(_priceDivisor).sub(_currentUnit.mul(_priceNumerator)) ).div(_priceNumerator); // Set outflow amount to 0 for component i, since tokens need to be injected in rebalance outflowUnit = 0; } else { // Calculate outflow amount outflowUnit = _unitsMultiplier.mul( _currentUnit.mul(_priceNumerator).sub(_nextSetUnit.mul(_priceDivisor)) ).div(_priceNumerator); // Set inflow amount to 0 for component i, since tokens need to be returned in rebalance inflowUnit = 0; } return (inflowUnit, outflowUnit); } }
17,384
1
// This event emits when the metadata of a token is changed./ So that the third-party platforms such as NFT market could/ timely update the images and related attributes of the NFT.
event MetadataUpdate(uint256 _tokenId);
event MetadataUpdate(uint256 _tokenId);
1,864
29
// Check loan amount
require(_loanAmount > 0 && _expectedDurationQty > 0, "1");
require(_loanAmount > 0 && _expectedDurationQty > 0, "1");
40,414
85
// Grants `role` to `account`.
* If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant"); _grantRole(role, account); }
* If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant"); _grantRole(role, account); }
1,330
16
// Iterate through all frax pools and calculate all value of collateral in all pools globally
function globalCollateralValue() public view returns (uint256) { uint256 total_collateral_value_d18 = 0; for (uint i = 0; i < frax_pools_array.length; i++){ // Exclude null addresses if (frax_pools_array[i] != address(0)){ total_collateral_value_d18 = total_collateral_value_d18.add(FraxPool(frax_pools_array[i]).collatDollarBalance()); } } return total_collateral_value_d18; }
function globalCollateralValue() public view returns (uint256) { uint256 total_collateral_value_d18 = 0; for (uint i = 0; i < frax_pools_array.length; i++){ // Exclude null addresses if (frax_pools_array[i] != address(0)){ total_collateral_value_d18 = total_collateral_value_d18.add(FraxPool(frax_pools_array[i]).collatDollarBalance()); } } return total_collateral_value_d18; }
33,515
70
// Returns all tokens registered with the Allocator.return the tokens /
function tokens() external view override returns (IERC20[] memory) { return _tokens; }
function tokens() external view override returns (IERC20[] memory) { return _tokens; }
8,978
126
// Gets previous block in which a randomness request was posted before the given one./_block Block number from which the search will start./ return First block found before the given one, or `0` otherwise.
function getRandomnessPrevBlock(uint256 _block) external view returns (uint256);
function getRandomnessPrevBlock(uint256 _block) external view returns (uint256);
19,734
57
// Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}by `operator` from `from`, this function is called. It must return its Solidity selector to confirm the token transfer.If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. /
function onERC721Received( address operator, address from, uint256 tokenId,
function onERC721Received( address operator, address from, uint256 tokenId,
1,238
114
// Safely mints `tokenId` and transfers it to `to`. Requirements: - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); }
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); }
1,682
19
// If we find an issue with people trying to join games that are in progress, we can change the logic to not allow this and they can only join before a game starts
allowInPlayJoining = !allowInPlayJoining;
allowInPlayJoining = !allowInPlayJoining;
22,567
72
// Allow the contract to approve the mint restart(Voting will be essential in these actions)
function restartMinting() onlyContract cantMint public returns (bool) { mintingFinished = false; MintRestarted(); // Notify the blockchain that the coin minting was restarted return true; }
function restartMinting() onlyContract cantMint public returns (bool) { mintingFinished = false; MintRestarted(); // Notify the blockchain that the coin minting was restarted return true; }
52,849
228
// ========== EVENTS ==========
event PynthExchange( address indexed account, bytes32 fromCurrencyKey, uint256 fromAmount, bytes32 toCurrencyKey, uint256 toAmount, address toAddress ); bytes32 internal constant PYNTHEXCHANGE_SIG = keccak256("PynthExchange(address,bytes32,uint256,bytes32,uint256,address)");
event PynthExchange( address indexed account, bytes32 fromCurrencyKey, uint256 fromAmount, bytes32 toCurrencyKey, uint256 toAmount, address toAddress ); bytes32 internal constant PYNTHEXCHANGE_SIG = keccak256("PynthExchange(address,bytes32,uint256,bytes32,uint256,address)");
15,990
88
// |/ Will emit default URI log event for corresponding token _id _tokenIDs Array of IDs of tokens to log default URI /
function _logURIs(uint256[] memory _tokenIDs) internal { string memory baseURL = baseMetadataURI; string memory tokenURI; for (uint256 i = 0; i < _tokenIDs.length; i++) { tokenURI = string(abi.encodePacked(baseURL, _uint2str(_tokenIDs[i]), ".json")); emit URI(tokenURI, _tokenIDs[i]); } }
function _logURIs(uint256[] memory _tokenIDs) internal { string memory baseURL = baseMetadataURI; string memory tokenURI; for (uint256 i = 0; i < _tokenIDs.length; i++) { tokenURI = string(abi.encodePacked(baseURL, _uint2str(_tokenIDs[i]), ".json")); emit URI(tokenURI, _tokenIDs[i]); } }
11,546
26
// : Peggy : Peg zone contract for testing one-way transfers from Ethereum to Cosmos, facilitated by a trusted relayer. This contract is NOT intended to be used in production and users are empowered to withdraw their locked funds at any time. /
contract Peggy is Processor { bool public active; address public relayer; mapping(bytes32 => bool) public ids; event LogLock( bytes32 _id, address _from, bytes _to, address _token, uint256 _value, uint256 _nonce ); event LogUnlock( bytes32 _id, address _to, address _token, uint256 _value, uint256 _nonce ); event LogWithdraw( bytes32 _id, address _to, address _token, uint256 _value, uint256 _nonce ); event LogLockingPaused( uint256 _time ); event LogLockingActivated( uint256 _time ); /* * @dev: Modifier to restrict access to the relayer. * */ modifier onlyRelayer() { require( msg.sender == relayer, 'Must be the specified relayer.' ); _; } /* * @dev: Modifier which restricts lock functionality when paused. * */ modifier whileActive() { require( active == true, 'Lock functionality is currently paused.' ); _; } /* * @dev: Constructor, initalizes relayer and active status. * */ constructor() public { relayer = msg.sender; active = true; emit LogLockingActivated(now); } /* * @dev: Locks received funds and creates new items. * * @param _recipient: bytes representation of destination address. * @param _token: token address in origin chain (0x0 if ethereum) * @param _amount: value of item */ function lock( bytes memory _recipient, address _token, uint256 _amount ) public payable availableNonce() whileActive() returns(bytes32 _id) { //Actions based on token address type if (msg.value != 0) { require(_token == address(0)); require(msg.value == _amount); } else { require(ERC20(_token).transferFrom(msg.sender, address(this), _amount)); } //Create an item with a unique key. bytes32 id = create( msg.sender, _recipient, _token, _amount ); emit LogLock( id, msg.sender, _recipient, _token, _amount, getNonce() ); return id; } /* * @dev: Unlocks ethereum/erc20 tokens, called by relayer. * * This is a shortcut utility method for testing purposes. * In the future bidirectional system, unlocking functionality * will be guarded by validator signatures. * * @param _id: Unique key of the item. */ function unlock( bytes32 _id ) onlyRelayer canDeliver(_id) external returns (bool) { require(isLocked(_id)); // Transfer item's funds and unlock it (address payable sender, address token, uint256 amount, uint256 uniqueNonce) = complete(_id); //Emit unlock event emit LogUnlock( _id, sender, token, amount, uniqueNonce ); return true; } /* * @dev: Withdraws ethereum/erc20 tokens, called original sender. * * This is a backdoor utility method included for testing, * purposes, allowing users to withdraw their funds. This * functionality will be removed in production. * * @param _id: Unique key of the item. */ function withdraw( bytes32 _id ) onlySender(_id) canDeliver(_id) external returns (bool) { require(isLocked(_id)); // Transfer item's funds and unlock it (address payable sender, address token, uint256 amount, uint256 uniqueNonce) = complete(_id); //Emit withdraw event emit LogWithdraw( _id, sender, token, amount, uniqueNonce ); return true; } /* * @dev: Exposes an item's current status. * * @param _id: The item in question. * @return: Boolean indicating the lock status. */ function getStatus( bytes32 _id ) public view returns(bool) { return isLocked(_id); } /* * @dev: Allows access to an item's information via its unique identifier. * * @param _id: The item to be viewed. * @return: Original sender's address. * @return: Intended receiver's address in bytes. * @return: The token's address. * @return: The amount locked in the item. * @return: The item's unique nonce. */ function viewItem( bytes32 _id ) public view returns(address, bytes memory, address, uint256, uint256) { return getItem(_id); } /* * @dev: Relayer can pause fund locking without impacting other functionality. */ function pauseLocking() public onlyRelayer { require(active); active = false; emit LogLockingPaused(now); } /* * @dev: Relayer can activate fund locking without impacting other functionality. */ function activateLocking() public onlyRelayer { require(!active); active = true; emit LogLockingActivated(now); } }
contract Peggy is Processor { bool public active; address public relayer; mapping(bytes32 => bool) public ids; event LogLock( bytes32 _id, address _from, bytes _to, address _token, uint256 _value, uint256 _nonce ); event LogUnlock( bytes32 _id, address _to, address _token, uint256 _value, uint256 _nonce ); event LogWithdraw( bytes32 _id, address _to, address _token, uint256 _value, uint256 _nonce ); event LogLockingPaused( uint256 _time ); event LogLockingActivated( uint256 _time ); /* * @dev: Modifier to restrict access to the relayer. * */ modifier onlyRelayer() { require( msg.sender == relayer, 'Must be the specified relayer.' ); _; } /* * @dev: Modifier which restricts lock functionality when paused. * */ modifier whileActive() { require( active == true, 'Lock functionality is currently paused.' ); _; } /* * @dev: Constructor, initalizes relayer and active status. * */ constructor() public { relayer = msg.sender; active = true; emit LogLockingActivated(now); } /* * @dev: Locks received funds and creates new items. * * @param _recipient: bytes representation of destination address. * @param _token: token address in origin chain (0x0 if ethereum) * @param _amount: value of item */ function lock( bytes memory _recipient, address _token, uint256 _amount ) public payable availableNonce() whileActive() returns(bytes32 _id) { //Actions based on token address type if (msg.value != 0) { require(_token == address(0)); require(msg.value == _amount); } else { require(ERC20(_token).transferFrom(msg.sender, address(this), _amount)); } //Create an item with a unique key. bytes32 id = create( msg.sender, _recipient, _token, _amount ); emit LogLock( id, msg.sender, _recipient, _token, _amount, getNonce() ); return id; } /* * @dev: Unlocks ethereum/erc20 tokens, called by relayer. * * This is a shortcut utility method for testing purposes. * In the future bidirectional system, unlocking functionality * will be guarded by validator signatures. * * @param _id: Unique key of the item. */ function unlock( bytes32 _id ) onlyRelayer canDeliver(_id) external returns (bool) { require(isLocked(_id)); // Transfer item's funds and unlock it (address payable sender, address token, uint256 amount, uint256 uniqueNonce) = complete(_id); //Emit unlock event emit LogUnlock( _id, sender, token, amount, uniqueNonce ); return true; } /* * @dev: Withdraws ethereum/erc20 tokens, called original sender. * * This is a backdoor utility method included for testing, * purposes, allowing users to withdraw their funds. This * functionality will be removed in production. * * @param _id: Unique key of the item. */ function withdraw( bytes32 _id ) onlySender(_id) canDeliver(_id) external returns (bool) { require(isLocked(_id)); // Transfer item's funds and unlock it (address payable sender, address token, uint256 amount, uint256 uniqueNonce) = complete(_id); //Emit withdraw event emit LogWithdraw( _id, sender, token, amount, uniqueNonce ); return true; } /* * @dev: Exposes an item's current status. * * @param _id: The item in question. * @return: Boolean indicating the lock status. */ function getStatus( bytes32 _id ) public view returns(bool) { return isLocked(_id); } /* * @dev: Allows access to an item's information via its unique identifier. * * @param _id: The item to be viewed. * @return: Original sender's address. * @return: Intended receiver's address in bytes. * @return: The token's address. * @return: The amount locked in the item. * @return: The item's unique nonce. */ function viewItem( bytes32 _id ) public view returns(address, bytes memory, address, uint256, uint256) { return getItem(_id); } /* * @dev: Relayer can pause fund locking without impacting other functionality. */ function pauseLocking() public onlyRelayer { require(active); active = false; emit LogLockingPaused(now); } /* * @dev: Relayer can activate fund locking without impacting other functionality. */ function activateLocking() public onlyRelayer { require(!active); active = true; emit LogLockingActivated(now); } }
44,490
167
// set price update for current hourly bucket l storage layout struct timestamp timestamp to update price64x64 64x64 fixed point representation of price /
function setPriceUpdate( Layout storage l, uint256 timestamp, int128 price64x64
function setPriceUpdate( Layout storage l, uint256 timestamp, int128 price64x64
23,344
23
// A library for performing overflow-/underflow-safe addition and subtraction on uint128.
library BoringMath128 { function add(uint128 a, uint128 b) internal pure returns (uint128 c) { require((c = a + b) >= b, "BoringMath: Add Overflow"); } function sub(uint128 a, uint128 b) internal pure returns (uint128 c) { require((c = a - b) <= a, "BoringMath: Underflow"); } }
library BoringMath128 { function add(uint128 a, uint128 b) internal pure returns (uint128 c) { require((c = a + b) >= b, "BoringMath: Add Overflow"); } function sub(uint128 a, uint128 b) internal pure returns (uint128 c) { require((c = a - b) <= a, "BoringMath: Underflow"); } }
4,855
22
// Accept ownership of another contract by this contractownable The address of the contract that is getting it's ownership transferred
function acceptOwnership(address ownable) external onlyAdmin { IOwnable(ownable).acceptOwnership(); }
function acceptOwnership(address ownable) external onlyAdmin { IOwnable(ownable).acceptOwnership(); }
24,131
2
// Checks whether a given address (possibleOwner) owns a given token by given contract addresses and the token id itself.This method can only check contracts implementing the ERC721 standard and in addition the CryptoPunks contract(with a custom implementation because it does not implement the ERC721 standard).Does not throw errors but returns false if the real token owner could not be found or the token does not exist.Returns an array with the results at the given index of the array. Sample contract addresses on MainnetCryptoPunks: 0x3C6D0C0d7c818474A93a8A271e0BBdb2e52E71d8 Bored Ape Yacht Club:0xBC4CA0EdA7647A8aB7C2061c2E118A18a936f13DCool Cats: 0x1A92f7381B9F03921564a437210bB9396471050CCrypToadz: 0x1CB1A5e65610AEFF2551A50f76a87a7d3fB649C6 /
function ownsTokenOfContracts(address possibleOwner, address[] calldata contractAddresses, uint256 tokenId) public view returns (bool[] memory) { bool[] memory result = new bool[](contractAddresses.length); for (uint256 i = 0; i < contractAddresses.length; i++) { result[i] = ownsTokenOfContract(possibleOwner, contractAddresses[i], tokenId); } return result; }
function ownsTokenOfContracts(address possibleOwner, address[] calldata contractAddresses, uint256 tokenId) public view returns (bool[] memory) { bool[] memory result = new bool[](contractAddresses.length); for (uint256 i = 0; i < contractAddresses.length; i++) { result[i] = ownsTokenOfContract(possibleOwner, contractAddresses[i], tokenId); } return result; }
33,762
21
// Prepares this contract to validate a signature./hash The hash./dataType The data type associated with the hash./action Action to take./signatureHash keccak256 of the expected signature data.
function prepare( bytes32 hash, DataType dataType, ValidatorAction action, bytes32 signatureHash ) external
function prepare( bytes32 hash, DataType dataType, ValidatorAction action, bytes32 signatureHash ) external
30,488
2
// 62%
winAmount[msg.sender] += 0 ether; return "LOST TURN";
winAmount[msg.sender] += 0 ether; return "LOST TURN";
19,671
190
// enable
_autoSwapAndLiquifyEnabled = true; setTaxLiquify(taxLiquify_, taxLiquifyDecimals_); emit EnabledAutoSwapAndLiquify();
_autoSwapAndLiquifyEnabled = true; setTaxLiquify(taxLiquify_, taxLiquifyDecimals_); emit EnabledAutoSwapAndLiquify();
20,828
495
// All that remains is storing the new Pool balances.
PoolSpecialization specialization = _getPoolSpecialization(poolId); if (specialization == PoolSpecialization.TWO_TOKEN) { _setTwoTokenPoolCashBalances(poolId, tokens[0], finalBalances[0], tokens[1], finalBalances[1]); } else if (specialization == PoolSpecialization.MINIMAL_SWAP_INFO) {
PoolSpecialization specialization = _getPoolSpecialization(poolId); if (specialization == PoolSpecialization.TWO_TOKEN) { _setTwoTokenPoolCashBalances(poolId, tokens[0], finalBalances[0], tokens[1], finalBalances[1]); } else if (specialization == PoolSpecialization.MINIMAL_SWAP_INFO) {
82,094
37
// setCost() periodically sets the cost of calling the contract
function setCost(uint _cost) public onlyAdmin(msg.sender) returns(bool) { // check for gas cost changes gas = updateGasPrice(); // no need to check for price change...just update and notifiy gas_price = gas; PriceChange(_cost, gas_price); // fire event to notify price has change cost = _cost; // change the cost of the contract return true; }
function setCost(uint _cost) public onlyAdmin(msg.sender) returns(bool) { // check for gas cost changes gas = updateGasPrice(); // no need to check for price change...just update and notifiy gas_price = gas; PriceChange(_cost, gas_price); // fire event to notify price has change cost = _cost; // change the cost of the contract return true; }
54,868
576
// NOTE: We don't use SafeMath (or similar) in this function because _currentBank max is equal ~ 20000000 finney, and (tournamentOwnersCut + tournamentIncentiveCut) <= 10000 (see the require() statement in the Tournament constructor). The result of this function is always guaranteed to be <= _currentBank.
return _currentBank * _incentiveCut / 10000;
return _currentBank * _incentiveCut / 10000;
41,052
5
// Returns the multiplication of two unsigned integers, reverting on overflow. Counterpart to Solidity's `` operator. Requirements:- Multiplication cannot overflow. /
function mul(uint a, uint b) internal pure returns (uint) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint c = a * b; require(c / a == b, "mul: *"); return c; }
function mul(uint a, uint b) internal pure returns (uint) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint c = a * b; require(c / a == b, "mul: *"); return c; }
15,620
212
// Function get value by provied key hash. Keys hashes can be found in Sync event emitted by Registry.sol contract. keyHash The key to query the value of. tokenId The token id to set.return Key and value. /
function getByHash(uint256 keyHash, uint256 tokenId) public view whenResolver(tokenId) returns (string memory key, string memory value) { key = hashToKey(keyHash); value = get(key, tokenId); }
function getByHash(uint256 keyHash, uint256 tokenId) public view whenResolver(tokenId) returns (string memory key, string memory value) { key = hashToKey(keyHash); value = get(key, tokenId); }
30,290
69
// safeApprove should only be called when setting an initial allowance,or when resetting it to zero. To increase and decrease it, use'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require((value == 0) || (token.allowance(msg.sender, spender) == 0)); require(token.approve(spender, value));
require((value == 0) || (token.allowance(msg.sender, spender) == 0)); require(token.approve(spender, value));
19,748
101
// -----------------------------------------------------------------------------/LockToken contract/defines token locking and unlocking functionality.-----------------------------------------------------------------------------
contract LockToken is BurnToken { //------------------------------------------------------------------------- /// @dev Emits when PLAY tokens become locked for any number of years by /// any mechanism. //------------------------------------------------------------------------- event Lock (address indexed tokenOwner, uint tokens); //------------------------------------------------------------------------- /// @dev Emits when PLAY tokens become unlocked by any mechanism. //------------------------------------------------------------------------- event Unlock (address indexed tokenOwner, uint tokens); // Unix Timestamp for 1-1-2018 at 00:00:00. // Used to calculate years since release. uint constant FIRST_YEAR_TIMESTAMP = 1514764800; // Tracks years since release. Starts at 0 and increments every 365 days. uint public currentYear; // Maximum number of years into the future locked tokens can be recovered. uint public maximumLockYears = 10; // Locked token balances by unlock year mapping (address => mapping(uint => uint)) tokensLockedUntilYear; //------------------------------------------------------------------------- /// @notice Lock `(tokens/1000000000000000000).fixed(0,18)` PLAY for /// `numberOfYears` years. /// @dev Throws if amount to lock is zero. Throws if numberOfYears is zero /// or greater than maximumLockYears. Throws if `msg.sender` has /// insufficient balance to lock. /// @param numberOfYears The number of years the tokens will be locked. /// @param tokens The number of tokens to lock (in pWei). //------------------------------------------------------------------------- function lock(uint numberOfYears, uint tokens) public notZero(tokens) sufficientFunds(msg.sender, tokens) returns(bool) { // number of years must be a valid amount. require ( numberOfYears > 0 && numberOfYears <= maximumLockYears, "Invalid number of years" ); // subtract amount from sender playBalances[msg.sender] -= tokens; // add amount to sender's locked token balance tokensLockedUntilYear[msg.sender][currentYear+numberOfYears] += tokens; // emit lock event emit Lock(msg.sender, tokens); return true; } //------------------------------------------------------------------------- /// @notice Lock `(tokens/1000000000000000000).fixed(0,18)` PLAY from /// `from` for `numberOfYears` years. /// @dev Throws if amount to lock is zero. Throws if numberOfYears is zero /// or greater than maximumLockYears. Throws if `msg.sender` has /// insufficient allowance to lock. Throws if `from` has insufficient /// balance to lock. /// @param from The token owner whose PLAY is being locked. Sender must be /// an approved spender. /// @param numberOfYears The number of years the tokens will be locked. /// @param tokens The number of tokens to lock (in pWei). //------------------------------------------------------------------------- function lockFrom(address from, uint numberOfYears, uint tokens) external notZero(tokens) sufficientFunds(from, tokens) sufficientAllowance(from, msg.sender, tokens) returns(bool) { // number of years must be a valid amount. require ( numberOfYears > 0 && numberOfYears <= maximumLockYears, "Invalid number of years" ); // subtract amount from sender's allowance allowances[from][msg.sender] -= tokens; // subtract amount from token owner's balance playBalances[from] -= tokens; // add amount to token owner's locked token balance tokensLockedUntilYear[from][currentYear + numberOfYears] += tokens; // emit lock event emit Lock(from, tokens); return true; } //------------------------------------------------------------------------- /// @notice Send `(tokens/1000000000000000000).fixed(0,18)` PLAY to `to`, /// then lock for `numberOfYears` years. /// @dev Throws if amount to send is zero. Throws if `msg.sender` has /// insufficient balance for transfer. Throws if `to` is the zero /// address. Emits transfer and lock events. /// @param to The address to where PLAY is being sent and locked. /// @param numberOfYears The number of years the tokens will be locked. /// @param tokens The number of tokens to send (in pWei). //------------------------------------------------------------------------- function transferAndLock( address to, uint numberOfYears, uint tokens ) external { // Transfer will fail if sender's balance is too low or "to" is zero transfer(to, tokens); // subtract amount from token receiver's balance playBalances[to] -= tokens; // add amount to token receiver's locked token balance tokensLockedUntilYear[to][currentYear + numberOfYears] += tokens; // emit lock event emit Lock(msg.sender, tokens); } //------------------------------------------------------------------------- /// @notice Send `(tokens/1000000000000000000).fixed(0,18)` PLAY from /// `from` to `to`, then lock for `numberOfYears` years. /// @dev Throws if amount to send is zero. Throws if `msg.sender` has /// insufficient allowance for transfer. Throws if `from` has /// insufficient balance for transfer. Throws if `to` is the zero /// address. Emits transfer and lock events. /// @param from The token owner whose PLAY is being sent. Sender must be /// an approved spender. /// @param to The address to where PLAY is being sent and locked. /// @param tokens The number of tokens to send (in pWei). //------------------------------------------------------------------------- function transferFromAndLock( address from, address to, uint numberOfYears, uint tokens ) external { // Initiate transfer. Transfer will fail if sender's allowance is too // low, token owner's balance is too low, or "to" is zero transferFrom(from, to, tokens); // subtract amount from token owner's balance playBalances[to] -= tokens; // add amount to token receiver's locked token balance tokensLockedUntilYear[to][currentYear + numberOfYears] += tokens; // emit lock event emit Lock(msg.sender, tokens); } //------------------------------------------------------------------------- /// @notice Unlock all qualifying tokens for `tokenOwner`. Sender must /// either be tokenOwner or an approved address. /// @dev If tokenOwner is empty, tokenOwner is set to msg.sender. Throws /// if sender is not tokenOwner or an approved spender (allowance > 0). /// @param tokenOwner The token owner whose tokens will unlock. //------------------------------------------------------------------------- function unlockAll(address tokenOwner) external { // create local variable for token owner address addressToUnlock = tokenOwner; // if tokenOwner parameter is empty, set tokenOwner to sender if (addressToUnlock == address(0)) { addressToUnlock = msg.sender; } // sender must either be tokenOwner or an approved address if (msg.sender != addressToUnlock) { require ( allowances[addressToUnlock][msg.sender] > 0, "Not authorized to unlock for this address" ); } // create local variable for unlock total uint tokensToUnlock; // check each year starting from 1 year after release for (uint i = 1; i <= currentYear; ++i) { // add qualifying tokens to tokens to unlock variable tokensToUnlock += tokensLockedUntilYear[addressToUnlock][i]; // set locked token balance of year i to 0 tokensLockedUntilYear[addressToUnlock][i] = 0; } // add qualifying tokens back to token owner's account balance playBalances[addressToUnlock] += tokensToUnlock; // emit unlock event emit Unlock (addressToUnlock, tokensToUnlock); } //------------------------------------------------------------------------- /// @notice Unlock all tokens locked until `year` years since 2018 for /// `tokenOwner`. Sender must be tokenOwner or an approved address. /// @dev If tokenOwner is empty, tokenOwner is set to msg.sender. Throws /// if sender is not tokenOwner or an approved spender (allowance > 0). /// @param tokenOwner The token owner whose tokens will unlock. /// @param year Number of years since 2018 the tokens were locked until. //------------------------------------------------------------------------- function unlockByYear(address tokenOwner, uint year) external { // create local variable for token owner address addressToUnlock = tokenOwner; // if tokenOwner parameter is empty, set tokenOwner to sender if (addressToUnlock == address(0)) { addressToUnlock = msg.sender; } // sender must either be tokenOwner or an approved address if (msg.sender != addressToUnlock) { require ( allowances[addressToUnlock][msg.sender] > 0, "Not authorized to unlock for this address" ); } // year of locked tokens must be less than or equal to current year require ( currentYear >= year, "Tokens from this year cannot be unlocked yet" ); // create local variable for unlock amount uint tokensToUnlock = tokensLockedUntilYear[addressToUnlock][year]; // set locked token balance of year to 0 tokensLockedUntilYear[addressToUnlock][year] = 0; // add qualifying tokens back to token owner's account balance playBalances[addressToUnlock] += tokensToUnlock; // emit unlock event emit Unlock(addressToUnlock, tokensToUnlock); } //------------------------------------------------------------------------- /// @notice Update the current year. /// @dev Throws if less than 365 days has passed since currentYear. //------------------------------------------------------------------------- function updateYearsSinceRelease() external { // check if years since first year is greater than the currentYear uint secondsSinceRelease = block.timestamp - FIRST_YEAR_TIMESTAMP; require ( currentYear < secondsSinceRelease / (365 * 1 days), "Cannot update year yet" ); // increment years since release ++currentYear; } //------------------------------------------------------------------------- /// @notice Get the total locked token holdings of `tokenOwner`. /// @param tokenOwner The locked token owner. /// @return Total locked token holdings of an address. //------------------------------------------------------------------------- function getTotalLockedTokens( address tokenOwner ) public view returns (uint lockedTokens) { for (uint i = 1; i < currentYear + maximumLockYears; ++i) { lockedTokens += tokensLockedUntilYear[tokenOwner][i]; } } //------------------------------------------------------------------------- /// @notice Get the locked token holdings of `tokenOwner` unlockable in /// `(year + 2018)`. /// @param tokenOwner The locked token owner. /// @param year Years since 2018 the tokens are locked until. /// @return Locked token holdings of an address for `(year + 2018)`. //------------------------------------------------------------------------- function getLockedTokensByYear( address tokenOwner, uint year ) external view returns (uint) { return tokensLockedUntilYear[tokenOwner][year]; } }
contract LockToken is BurnToken { //------------------------------------------------------------------------- /// @dev Emits when PLAY tokens become locked for any number of years by /// any mechanism. //------------------------------------------------------------------------- event Lock (address indexed tokenOwner, uint tokens); //------------------------------------------------------------------------- /// @dev Emits when PLAY tokens become unlocked by any mechanism. //------------------------------------------------------------------------- event Unlock (address indexed tokenOwner, uint tokens); // Unix Timestamp for 1-1-2018 at 00:00:00. // Used to calculate years since release. uint constant FIRST_YEAR_TIMESTAMP = 1514764800; // Tracks years since release. Starts at 0 and increments every 365 days. uint public currentYear; // Maximum number of years into the future locked tokens can be recovered. uint public maximumLockYears = 10; // Locked token balances by unlock year mapping (address => mapping(uint => uint)) tokensLockedUntilYear; //------------------------------------------------------------------------- /// @notice Lock `(tokens/1000000000000000000).fixed(0,18)` PLAY for /// `numberOfYears` years. /// @dev Throws if amount to lock is zero. Throws if numberOfYears is zero /// or greater than maximumLockYears. Throws if `msg.sender` has /// insufficient balance to lock. /// @param numberOfYears The number of years the tokens will be locked. /// @param tokens The number of tokens to lock (in pWei). //------------------------------------------------------------------------- function lock(uint numberOfYears, uint tokens) public notZero(tokens) sufficientFunds(msg.sender, tokens) returns(bool) { // number of years must be a valid amount. require ( numberOfYears > 0 && numberOfYears <= maximumLockYears, "Invalid number of years" ); // subtract amount from sender playBalances[msg.sender] -= tokens; // add amount to sender's locked token balance tokensLockedUntilYear[msg.sender][currentYear+numberOfYears] += tokens; // emit lock event emit Lock(msg.sender, tokens); return true; } //------------------------------------------------------------------------- /// @notice Lock `(tokens/1000000000000000000).fixed(0,18)` PLAY from /// `from` for `numberOfYears` years. /// @dev Throws if amount to lock is zero. Throws if numberOfYears is zero /// or greater than maximumLockYears. Throws if `msg.sender` has /// insufficient allowance to lock. Throws if `from` has insufficient /// balance to lock. /// @param from The token owner whose PLAY is being locked. Sender must be /// an approved spender. /// @param numberOfYears The number of years the tokens will be locked. /// @param tokens The number of tokens to lock (in pWei). //------------------------------------------------------------------------- function lockFrom(address from, uint numberOfYears, uint tokens) external notZero(tokens) sufficientFunds(from, tokens) sufficientAllowance(from, msg.sender, tokens) returns(bool) { // number of years must be a valid amount. require ( numberOfYears > 0 && numberOfYears <= maximumLockYears, "Invalid number of years" ); // subtract amount from sender's allowance allowances[from][msg.sender] -= tokens; // subtract amount from token owner's balance playBalances[from] -= tokens; // add amount to token owner's locked token balance tokensLockedUntilYear[from][currentYear + numberOfYears] += tokens; // emit lock event emit Lock(from, tokens); return true; } //------------------------------------------------------------------------- /// @notice Send `(tokens/1000000000000000000).fixed(0,18)` PLAY to `to`, /// then lock for `numberOfYears` years. /// @dev Throws if amount to send is zero. Throws if `msg.sender` has /// insufficient balance for transfer. Throws if `to` is the zero /// address. Emits transfer and lock events. /// @param to The address to where PLAY is being sent and locked. /// @param numberOfYears The number of years the tokens will be locked. /// @param tokens The number of tokens to send (in pWei). //------------------------------------------------------------------------- function transferAndLock( address to, uint numberOfYears, uint tokens ) external { // Transfer will fail if sender's balance is too low or "to" is zero transfer(to, tokens); // subtract amount from token receiver's balance playBalances[to] -= tokens; // add amount to token receiver's locked token balance tokensLockedUntilYear[to][currentYear + numberOfYears] += tokens; // emit lock event emit Lock(msg.sender, tokens); } //------------------------------------------------------------------------- /// @notice Send `(tokens/1000000000000000000).fixed(0,18)` PLAY from /// `from` to `to`, then lock for `numberOfYears` years. /// @dev Throws if amount to send is zero. Throws if `msg.sender` has /// insufficient allowance for transfer. Throws if `from` has /// insufficient balance for transfer. Throws if `to` is the zero /// address. Emits transfer and lock events. /// @param from The token owner whose PLAY is being sent. Sender must be /// an approved spender. /// @param to The address to where PLAY is being sent and locked. /// @param tokens The number of tokens to send (in pWei). //------------------------------------------------------------------------- function transferFromAndLock( address from, address to, uint numberOfYears, uint tokens ) external { // Initiate transfer. Transfer will fail if sender's allowance is too // low, token owner's balance is too low, or "to" is zero transferFrom(from, to, tokens); // subtract amount from token owner's balance playBalances[to] -= tokens; // add amount to token receiver's locked token balance tokensLockedUntilYear[to][currentYear + numberOfYears] += tokens; // emit lock event emit Lock(msg.sender, tokens); } //------------------------------------------------------------------------- /// @notice Unlock all qualifying tokens for `tokenOwner`. Sender must /// either be tokenOwner or an approved address. /// @dev If tokenOwner is empty, tokenOwner is set to msg.sender. Throws /// if sender is not tokenOwner or an approved spender (allowance > 0). /// @param tokenOwner The token owner whose tokens will unlock. //------------------------------------------------------------------------- function unlockAll(address tokenOwner) external { // create local variable for token owner address addressToUnlock = tokenOwner; // if tokenOwner parameter is empty, set tokenOwner to sender if (addressToUnlock == address(0)) { addressToUnlock = msg.sender; } // sender must either be tokenOwner or an approved address if (msg.sender != addressToUnlock) { require ( allowances[addressToUnlock][msg.sender] > 0, "Not authorized to unlock for this address" ); } // create local variable for unlock total uint tokensToUnlock; // check each year starting from 1 year after release for (uint i = 1; i <= currentYear; ++i) { // add qualifying tokens to tokens to unlock variable tokensToUnlock += tokensLockedUntilYear[addressToUnlock][i]; // set locked token balance of year i to 0 tokensLockedUntilYear[addressToUnlock][i] = 0; } // add qualifying tokens back to token owner's account balance playBalances[addressToUnlock] += tokensToUnlock; // emit unlock event emit Unlock (addressToUnlock, tokensToUnlock); } //------------------------------------------------------------------------- /// @notice Unlock all tokens locked until `year` years since 2018 for /// `tokenOwner`. Sender must be tokenOwner or an approved address. /// @dev If tokenOwner is empty, tokenOwner is set to msg.sender. Throws /// if sender is not tokenOwner or an approved spender (allowance > 0). /// @param tokenOwner The token owner whose tokens will unlock. /// @param year Number of years since 2018 the tokens were locked until. //------------------------------------------------------------------------- function unlockByYear(address tokenOwner, uint year) external { // create local variable for token owner address addressToUnlock = tokenOwner; // if tokenOwner parameter is empty, set tokenOwner to sender if (addressToUnlock == address(0)) { addressToUnlock = msg.sender; } // sender must either be tokenOwner or an approved address if (msg.sender != addressToUnlock) { require ( allowances[addressToUnlock][msg.sender] > 0, "Not authorized to unlock for this address" ); } // year of locked tokens must be less than or equal to current year require ( currentYear >= year, "Tokens from this year cannot be unlocked yet" ); // create local variable for unlock amount uint tokensToUnlock = tokensLockedUntilYear[addressToUnlock][year]; // set locked token balance of year to 0 tokensLockedUntilYear[addressToUnlock][year] = 0; // add qualifying tokens back to token owner's account balance playBalances[addressToUnlock] += tokensToUnlock; // emit unlock event emit Unlock(addressToUnlock, tokensToUnlock); } //------------------------------------------------------------------------- /// @notice Update the current year. /// @dev Throws if less than 365 days has passed since currentYear. //------------------------------------------------------------------------- function updateYearsSinceRelease() external { // check if years since first year is greater than the currentYear uint secondsSinceRelease = block.timestamp - FIRST_YEAR_TIMESTAMP; require ( currentYear < secondsSinceRelease / (365 * 1 days), "Cannot update year yet" ); // increment years since release ++currentYear; } //------------------------------------------------------------------------- /// @notice Get the total locked token holdings of `tokenOwner`. /// @param tokenOwner The locked token owner. /// @return Total locked token holdings of an address. //------------------------------------------------------------------------- function getTotalLockedTokens( address tokenOwner ) public view returns (uint lockedTokens) { for (uint i = 1; i < currentYear + maximumLockYears; ++i) { lockedTokens += tokensLockedUntilYear[tokenOwner][i]; } } //------------------------------------------------------------------------- /// @notice Get the locked token holdings of `tokenOwner` unlockable in /// `(year + 2018)`. /// @param tokenOwner The locked token owner. /// @param year Years since 2018 the tokens are locked until. /// @return Locked token holdings of an address for `(year + 2018)`. //------------------------------------------------------------------------- function getLockedTokensByYear( address tokenOwner, uint year ) external view returns (uint) { return tokensLockedUntilYear[tokenOwner][year]; } }
14,379
121
// Token information tokenId % 1,000,000 = index of token (i.e. how many were minted before this token) (tokenId / 1,000,000) % 100 = week in which sacrificed occured (from game start) (tokenId / 100,000,000) = number of cultists remaining after sacrifice
let countdown := mod(div(tokenId, 1000000), 100)
let countdown := mod(div(tokenId, 1000000), 100)
17,599
117
// we can accept 0 as minimum because this is called only by a trusted role
uint256 minimum = 0; uint256[4] memory coinAmounts = wrapCoinAmount(yBalance); ICurveFi(curve).add_liquidity( coinAmounts, minimum );
uint256 minimum = 0; uint256[4] memory coinAmounts = wrapCoinAmount(yBalance); ICurveFi(curve).add_liquidity( coinAmounts, minimum );
9,466
113
// Transitively inherit reflection over the same ancestor.
c.reflectOver = midline.reflectOver; circles[nextCircle].reflectOver = midline.reflectOver;
c.reflectOver = midline.reflectOver; circles[nextCircle].reflectOver = midline.reflectOver;
39,189
2
// Hash table size. - Size should be prime for a good average distribution. - Space is preallocated, for efficiency. - Specific value was selected based on gas and averageof collisions.
uint256 constant HASH_TABLE_SIZE = 313;
uint256 constant HASH_TABLE_SIZE = 313;
40,626
5
// Allowances structureWallet addr1 allows addr2 to transfer until 10 tokens[addr1][addr2] = 10 /
mapping( address => mapping(address => uint256) ) private _allowances;
mapping( address => mapping(address => uint256) ) private _allowances;
21,273
132
// The timestamp on and after which the transfer restriction must be lifted.
uint256 public immutable TRANSFER_RESTRICTION_LIFTED_NO_LATER_THAN;
uint256 public immutable TRANSFER_RESTRICTION_LIFTED_NO_LATER_THAN;
65,993
64
// The superior Distributor contract /
Distributor public superior;
Distributor public superior;
53,209
6
// Factory for deploying BlacklistManager module /
contract BlacklistTransferManagerFactory is ModuleFactory { /** * @notice Constructor * @param _polyAddress Address of the polytoken * @param _setupCost Setup cost of the module * @param _usageCost Usage cost of the module * @param _subscriptionCost Subscription cost of the module */ constructor (address _polyAddress, uint256 _setupCost, uint256 _usageCost, uint256 _subscriptionCost) public ModuleFactory(_polyAddress, _setupCost, _usageCost, _subscriptionCost) { version = "2.1.0"; name = "BlacklistTransferManager"; title = "Blacklist Transfer Manager"; description = "Automate blacklist to restrict selling"; compatibleSTVersionRange["lowerBound"] = VersionUtils.pack(uint8(0), uint8(0), uint8(0)); compatibleSTVersionRange["upperBound"] = VersionUtils.pack(uint8(0), uint8(0), uint8(0)); } /** * @notice used to launch the Module with the help of factory * @return address Contract address of the Module */ function deploy(bytes /* _data */) external returns(address) { if (setupCost > 0) require(polyToken.transferFrom(msg.sender, owner, setupCost), "Failed transferFrom because of sufficent Allowance is not provided"); address blacklistTransferManager = new BlacklistTransferManager(msg.sender, address(polyToken)); /*solium-disable-next-line security/no-block-members*/ emit GenerateModuleFromFactory(address(blacklistTransferManager), getName(), address(this), msg.sender, setupCost, now); return address(blacklistTransferManager); } /** * @notice Type of the Module factory */ function getTypes() external view returns(uint8[]) { uint8[] memory res = new uint8[](1); res[0] = 2; return res; } /** * @notice Get the Instructions that helped to used the module */ function getInstructions() public view returns(string) { return "Allows an issuer to blacklist the addresses."; } /** * @notice Get the tags related to the module factory */ function getTags() public view returns(bytes32[]) { bytes32[] memory availableTags = new bytes32[](2); availableTags[0] = "Blacklist"; availableTags[1] = "Restricted transfer"; return availableTags; } }
contract BlacklistTransferManagerFactory is ModuleFactory { /** * @notice Constructor * @param _polyAddress Address of the polytoken * @param _setupCost Setup cost of the module * @param _usageCost Usage cost of the module * @param _subscriptionCost Subscription cost of the module */ constructor (address _polyAddress, uint256 _setupCost, uint256 _usageCost, uint256 _subscriptionCost) public ModuleFactory(_polyAddress, _setupCost, _usageCost, _subscriptionCost) { version = "2.1.0"; name = "BlacklistTransferManager"; title = "Blacklist Transfer Manager"; description = "Automate blacklist to restrict selling"; compatibleSTVersionRange["lowerBound"] = VersionUtils.pack(uint8(0), uint8(0), uint8(0)); compatibleSTVersionRange["upperBound"] = VersionUtils.pack(uint8(0), uint8(0), uint8(0)); } /** * @notice used to launch the Module with the help of factory * @return address Contract address of the Module */ function deploy(bytes /* _data */) external returns(address) { if (setupCost > 0) require(polyToken.transferFrom(msg.sender, owner, setupCost), "Failed transferFrom because of sufficent Allowance is not provided"); address blacklistTransferManager = new BlacklistTransferManager(msg.sender, address(polyToken)); /*solium-disable-next-line security/no-block-members*/ emit GenerateModuleFromFactory(address(blacklistTransferManager), getName(), address(this), msg.sender, setupCost, now); return address(blacklistTransferManager); } /** * @notice Type of the Module factory */ function getTypes() external view returns(uint8[]) { uint8[] memory res = new uint8[](1); res[0] = 2; return res; } /** * @notice Get the Instructions that helped to used the module */ function getInstructions() public view returns(string) { return "Allows an issuer to blacklist the addresses."; } /** * @notice Get the tags related to the module factory */ function getTags() public view returns(bytes32[]) { bytes32[] memory availableTags = new bytes32[](2); availableTags[0] = "Blacklist"; availableTags[1] = "Restricted transfer"; return availableTags; } }
26,243
256
// Make as much capital as possible "free" for the Vault to take. Some slippageis allowed, since when this method is called the strategist is no longer receivingtheir performance fee. The goal is for the strategy to divest as quickly as possiblewhile not suffering exorbitant losses. This function is used during emergency exitinstead of `prepareReturn()`. This method returns any realized losses incurred, andshould also return the amount of `want` tokens available to repay outstanding debtto the Vault. /
function exitPosition() internal virtual returns (uint256 _loss, uint256 _debtPayment);
function exitPosition() internal virtual returns (uint256 _loss, uint256 _debtPayment);
42,673
0
// Creates `_amount` token to `_to`. Must only be called by the owner (WanSwapFarm).
function mint(address _to, uint256 _amount) public onlyOwner { _mint(_to, _amount); }
function mint(address _to, uint256 _amount) public onlyOwner { _mint(_to, _amount); }
10,532
360
// Updates user's fees reward
function _updateFeesReward(address account) internal { uint liquidity = pool.positionLiquidity(tickLower, tickUpper); if (liquidity == 0) return; // we can't poke when liquidity is zero (uint256 collect0, uint256 collect1) = _earnFees(); token0PerShareStored = _tokenPerShare(collect0, token0PerShareStored); token1PerShareStored = _tokenPerShare(collect1, token1PerShareStored); if (account != address(0)) { UserInfo storage user = userInfo[msg.sender]; user.token0Rewards = _fee0Earned(account, token0PerShareStored); user.token0PerSharePaid = token0PerShareStored; user.token1Rewards = _fee1Earned(account, token1PerShareStored); user.token1PerSharePaid = token1PerShareStored; } }
function _updateFeesReward(address account) internal { uint liquidity = pool.positionLiquidity(tickLower, tickUpper); if (liquidity == 0) return; // we can't poke when liquidity is zero (uint256 collect0, uint256 collect1) = _earnFees(); token0PerShareStored = _tokenPerShare(collect0, token0PerShareStored); token1PerShareStored = _tokenPerShare(collect1, token1PerShareStored); if (account != address(0)) { UserInfo storage user = userInfo[msg.sender]; user.token0Rewards = _fee0Earned(account, token0PerShareStored); user.token0PerSharePaid = token0PerShareStored; user.token1Rewards = _fee1Earned(account, token1PerShareStored); user.token1PerSharePaid = token1PerShareStored; } }
32,787
181
// Private function to invoke {IERC721Receiver-onERC721Received} on a target contract. `from` - Previous owner of the given token ID.`to` - Target address that will receive the token.`tokenId` - Token ID to be transferred.`_data` - Optional data to send along with the call. Returns whether the call correctly returned the expected magic value. /
function _checkContractOnERC721Received(
function _checkContractOnERC721Received(
8,746
22
// struct for exchange data /
struct linkedBook { uint256 amount; address nextUser; }
struct linkedBook { uint256 amount; address nextUser; }
24,359
14
// Emitted when a studio badge holder claimstheir Age of Valor tokens /
event AgeOfValorClaimedByStudioBadge(
event AgeOfValorClaimedByStudioBadge(
23,746
109
// Transfers all fees or slippage collected by the router to the treasury address/token The address of the token we want to transfer from the router
function sweep(address token) external onlyOwner { if (token == NATIVE_TOKEN) { // transfer native token out of contract (bool success, ) = feeTreasury.call{value: address(this).balance}( "" ); require(success, "transfer failed in sweep"); } else { // transfer ERC20 contract TransferHelper.safeTransfer( token, feeTreasury, IERC20(token).balanceOf(address(this)) ); } }
function sweep(address token) external onlyOwner { if (token == NATIVE_TOKEN) { // transfer native token out of contract (bool success, ) = feeTreasury.call{value: address(this).balance}( "" ); require(success, "transfer failed in sweep"); } else { // transfer ERC20 contract TransferHelper.safeTransfer( token, feeTreasury, IERC20(token).balanceOf(address(this)) ); } }
21,897
11
// See {ERC721AQueryable-tokensOfOwnerIn} for splitting the scan intomultiple smaller scans if the collection is large enough to causean out-of-gas error (10K pfp collections should be fine). /
function tokensOfOwner(address owner) external view returns (uint256[] memory) { unchecked { uint256 tokenIdsIdx; address currOwnershipAddr; uint256 tokenIdsLength = balanceOf(owner); uint256[] memory tokenIds = new uint256[](tokenIdsLength); TokenOwnership memory ownership; for (uint256 i = _startTokenId(); tokenIdsIdx != tokenIdsLength; ++i) { ownership = _ownerships[i]; if (ownership.burned) {
function tokensOfOwner(address owner) external view returns (uint256[] memory) { unchecked { uint256 tokenIdsIdx; address currOwnershipAddr; uint256 tokenIdsLength = balanceOf(owner); uint256[] memory tokenIds = new uint256[](tokenIdsLength); TokenOwnership memory ownership; for (uint256 i = _startTokenId(); tokenIdsIdx != tokenIdsLength; ++i) { ownership = _ownerships[i]; if (ownership.burned) {
39,385
175
// Checks for a valid signature authorizing the migration of an account to a new address. This is shared by both the FNDNFT721 and FNDNFTMarket, and the same signature authorizes both. /
abstract contract AccountMigration is FoundationOperatorRole { // From https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v4.1.0/contracts/utils/cryptography function _isValidSignatureNow( address signer, bytes32 hash, bytes memory signature ) private view returns (bool) { if (Address.isContract(signer)) { try IERC1271(signer).isValidSignature(hash, signature) returns (bytes4 magicValue) { return magicValue == IERC1271(signer).isValidSignature.selector; } catch { return false; } } else { return ECDSA.recover(hash, signature) == signer; } } // From https://ethereum.stackexchange.com/questions/8346/convert-address-to-string function _toAsciiString(address x) private pure returns (string memory) { bytes memory s = new bytes(42); s[0] = "0"; s[1] = "x"; for (uint256 i = 0; i < 20; i++) { bytes1 b = bytes1(uint8(uint256(uint160(x)) / (2**(8 * (19 - i))))); bytes1 hi = bytes1(uint8(b) / 16); bytes1 lo = bytes1(uint8(b) - 16 * uint8(hi)); s[2 * i + 2] = _char(hi); s[2 * i + 3] = _char(lo); } return string(s); } function _char(bytes1 b) private pure returns (bytes1 c) { if (uint8(b) < 10) return bytes1(uint8(b) + 0x30); else return bytes1(uint8(b) + 0x57); } // From https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v4.1.0/contracts/utils/cryptography/ECDSA.sol // Modified to accept messages (instead of the message hash) function _toEthSignedMessage(bytes memory message) private pure returns (bytes32) { return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(message.length), message)); } /** * @dev Confirms the msg.sender is a Foundation operator and that the signature provided is valid. * @param signature Message `I authorize Foundation to migrate my account to ${newAccount.address.toLowerCase()}` * signed by the original account. */ modifier onlyAuthorizedAccountMigration( address originalAddress, address newAddress, bytes memory signature ) { require(_isFoundationOperator(), "AccountMigration: Caller is not an operator"); require(originalAddress != newAddress, "AccountMigration: Cannot migrate to the same account"); bytes32 hash = _toEthSignedMessage( abi.encodePacked("I authorize Foundation to migrate my account to ", _toAsciiString(newAddress)) ); require( _isValidSignatureNow(originalAddress, hash, signature), "AccountMigration: Signature must be from the original account" ); _; } }
abstract contract AccountMigration is FoundationOperatorRole { // From https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v4.1.0/contracts/utils/cryptography function _isValidSignatureNow( address signer, bytes32 hash, bytes memory signature ) private view returns (bool) { if (Address.isContract(signer)) { try IERC1271(signer).isValidSignature(hash, signature) returns (bytes4 magicValue) { return magicValue == IERC1271(signer).isValidSignature.selector; } catch { return false; } } else { return ECDSA.recover(hash, signature) == signer; } } // From https://ethereum.stackexchange.com/questions/8346/convert-address-to-string function _toAsciiString(address x) private pure returns (string memory) { bytes memory s = new bytes(42); s[0] = "0"; s[1] = "x"; for (uint256 i = 0; i < 20; i++) { bytes1 b = bytes1(uint8(uint256(uint160(x)) / (2**(8 * (19 - i))))); bytes1 hi = bytes1(uint8(b) / 16); bytes1 lo = bytes1(uint8(b) - 16 * uint8(hi)); s[2 * i + 2] = _char(hi); s[2 * i + 3] = _char(lo); } return string(s); } function _char(bytes1 b) private pure returns (bytes1 c) { if (uint8(b) < 10) return bytes1(uint8(b) + 0x30); else return bytes1(uint8(b) + 0x57); } // From https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v4.1.0/contracts/utils/cryptography/ECDSA.sol // Modified to accept messages (instead of the message hash) function _toEthSignedMessage(bytes memory message) private pure returns (bytes32) { return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(message.length), message)); } /** * @dev Confirms the msg.sender is a Foundation operator and that the signature provided is valid. * @param signature Message `I authorize Foundation to migrate my account to ${newAccount.address.toLowerCase()}` * signed by the original account. */ modifier onlyAuthorizedAccountMigration( address originalAddress, address newAddress, bytes memory signature ) { require(_isFoundationOperator(), "AccountMigration: Caller is not an operator"); require(originalAddress != newAddress, "AccountMigration: Cannot migrate to the same account"); bytes32 hash = _toEthSignedMessage( abi.encodePacked("I authorize Foundation to migrate my account to ", _toAsciiString(newAddress)) ); require( _isValidSignatureNow(originalAddress, hash, signature), "AccountMigration: Signature must be from the original account" ); _; } }
78,385
40
// β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•— β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•— β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•— β–ˆβ–ˆβ•”β•β•β•β•β•β•šβ•β•β–ˆβ–ˆβ•”β•β•β•β–ˆβ–ˆβ•”β•β•β–ˆβ–ˆβ•—β•šβ•β•β–ˆβ–ˆβ•”β•β•β•β–ˆβ–ˆβ•”β•β•β•β•β• β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•— β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•— β•šβ•β•β•β•β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•”β•β•β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•”β•β•β• β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•— β•šβ•β•β•β•β•β•β• β•šβ•β• β•šβ•β•β•šβ•β• β•šβ•β• β•šβ•β•β•β•β•β•β• amount of raised money in wei
uint public weiRaised;
uint public weiRaised;
78,916
7
// to add a new user to the contract to make guesses
function makeUser() public{ users[msg.sender].userAddress = msg.sender; users[msg.sender].tokensBought = 0; userAddresses.push(msg.sender); }
function makeUser() public{ users[msg.sender].userAddress = msg.sender; users[msg.sender].tokensBought = 0; userAddresses.push(msg.sender); }
46,589
1
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> FILE STORAGE: IPFS<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ S T A T E @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@/ Account used to deploy contract
address private contractOwner;
address private contractOwner;
1,837
25
// Update the total ownership and ensure it's valid
totalOwnership += founderPct;
totalOwnership += founderPct;
14,744
119
// call notifyRewardAmount for all staking tokens.
function notifyRewardAmounts() public { require( stakingTokens.length > 0, "StakingRewardsFactory::notifyRewardAmounts: called before any deploys" ); for (uint256 i = 0; i < stakingTokens.length; i++) { notifyRewardAmount(stakingTokens[i]); } }
function notifyRewardAmounts() public { require( stakingTokens.length > 0, "StakingRewardsFactory::notifyRewardAmounts: called before any deploys" ); for (uint256 i = 0; i < stakingTokens.length; i++) { notifyRewardAmount(stakingTokens[i]); } }
28,611
20
// Increment token count
tokenCount++;
tokenCount++;
6,839
131
// @nonce Returns provider's share in WBTC account Provider's addressreturn Provider's share in WBTC /
function shareOf(address user) external view returns (uint256 share) { uint supply = totalSupply(); if (supply > 0) share = totalBalance().mul(balanceOf(user)).div(supply); else share = 0; }
function shareOf(address user) external view returns (uint256 share) { uint supply = totalSupply(); if (supply > 0) share = totalBalance().mul(balanceOf(user)).div(supply); else share = 0; }
12,668
40
// mustWithdraw (wrapper) tries to subtracts any deposited collateral token from the contract and reverts on failure.
function mustWithdraw(address _token, uint256 _amount) public nonReentrant { // make the attempt uint256 result = _withdraw(_token, _amount); // check zero amount condition require(result != ERR_ZERO_AMOUNT, "non-zero amount expected"); // check low balance condition require(result != ERR_LOW_BALANCE, "insufficient collateral balance"); // check no value condition require(result != ERR_NO_VALUE, "token has no value"); // check low balance condition require(result != ERR_LOW_COLLATERAL_RATIO, "insufficient collateral value remains"); // sanity check for any non-covered condition require(result == ERR_NO_ERROR, "unexpected failure"); }
function mustWithdraw(address _token, uint256 _amount) public nonReentrant { // make the attempt uint256 result = _withdraw(_token, _amount); // check zero amount condition require(result != ERR_ZERO_AMOUNT, "non-zero amount expected"); // check low balance condition require(result != ERR_LOW_BALANCE, "insufficient collateral balance"); // check no value condition require(result != ERR_NO_VALUE, "token has no value"); // check low balance condition require(result != ERR_LOW_COLLATERAL_RATIO, "insufficient collateral value remains"); // sanity check for any non-covered condition require(result == ERR_NO_ERROR, "unexpected failure"); }
29,520
5
// Claimable Methods Implementation of the claiming utils that can be useful for withdrawing accidentally sent tokens that are not used in bridge operations.@custom:a w3box.com /
contract Claimable is Context { using SafeERC20 for IERC20; /** * @dev Withdraws the erc20 tokens or native coins from this contract. * Caller should additionally check that the claimed token is not a part of bridge operations (i.e. that token != erc20token()). * @param _token address of the claimed token or address(0) for native coins. * @param _to address of the tokens/coins receiver. */ function _claimValues(address _token, address _to) internal { if (_token == address(0)) { _claimNativeCoins(_to); } else { _claimErc20Tokens(_token, _to); } } /** * @dev Internal function for withdrawing all native coins from the contract. * @param _to address of the coins receiver. */ function _claimNativeCoins(address _to) internal { uint256 amount = address(this).balance; // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = _to.call{ value: amount }(""); require(success, "ERC20: Address: unable to send value, recipient may have reverted"); } /** * @dev Internal function for withdrawing all tokens of some particular ERC20 contract from this contract. * @param _token address of the claimed ERC20 token. * @param _to address of the tokens receiver. */ function _claimErc20Tokens(address _token, address _to) internal { IERC20 token = IERC20(_token); uint256 balance = token.balanceOf(address(this)); token.safeTransfer(_to, balance); } /** * @dev Internal function for withdrawing all tokens of some particular ERC721 contract from this contract. * @param _token address of the claimed ERC721 token. * @param _to address of the tokens receiver. */ function _claimNFTs(address _token, uint256 _tokenId, address _to) internal { IERC165 checker = IERC165(_token); if(checker.supportsInterface(type(IERC721).interfaceId)) { IERC721 token = IERC721(_token); token.safeTransferFrom(address(this), _to, _tokenId, ""); } else if(checker.supportsInterface(type(IERC1155).interfaceId)) { IERC1155 token = IERC1155(_token); uint256 balance = token.balanceOf(address(this), _tokenId); token.safeTransferFrom(address(this), _to, _tokenId, balance, ""); } revert("Not a IERC721 or IERC1155 contract"); } }
contract Claimable is Context { using SafeERC20 for IERC20; /** * @dev Withdraws the erc20 tokens or native coins from this contract. * Caller should additionally check that the claimed token is not a part of bridge operations (i.e. that token != erc20token()). * @param _token address of the claimed token or address(0) for native coins. * @param _to address of the tokens/coins receiver. */ function _claimValues(address _token, address _to) internal { if (_token == address(0)) { _claimNativeCoins(_to); } else { _claimErc20Tokens(_token, _to); } } /** * @dev Internal function for withdrawing all native coins from the contract. * @param _to address of the coins receiver. */ function _claimNativeCoins(address _to) internal { uint256 amount = address(this).balance; // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = _to.call{ value: amount }(""); require(success, "ERC20: Address: unable to send value, recipient may have reverted"); } /** * @dev Internal function for withdrawing all tokens of some particular ERC20 contract from this contract. * @param _token address of the claimed ERC20 token. * @param _to address of the tokens receiver. */ function _claimErc20Tokens(address _token, address _to) internal { IERC20 token = IERC20(_token); uint256 balance = token.balanceOf(address(this)); token.safeTransfer(_to, balance); } /** * @dev Internal function for withdrawing all tokens of some particular ERC721 contract from this contract. * @param _token address of the claimed ERC721 token. * @param _to address of the tokens receiver. */ function _claimNFTs(address _token, uint256 _tokenId, address _to) internal { IERC165 checker = IERC165(_token); if(checker.supportsInterface(type(IERC721).interfaceId)) { IERC721 token = IERC721(_token); token.safeTransferFrom(address(this), _to, _tokenId, ""); } else if(checker.supportsInterface(type(IERC1155).interfaceId)) { IERC1155 token = IERC1155(_token); uint256 balance = token.balanceOf(address(this), _tokenId); token.safeTransferFrom(address(this), _to, _tokenId, balance, ""); } revert("Not a IERC721 or IERC1155 contract"); } }
10,169
17
// push values to flat-arrays
coordinates.push(coordinate); rgba.push(_rgba); prices.push(msg.value); owners.push(msg.sender);
coordinates.push(coordinate); rgba.push(_rgba); prices.push(msg.value); owners.push(msg.sender);
9,500
1
// wraps tokens _amount amount of unwrapped tokens to wrap /
function wrap(uint256 _amount) external;
function wrap(uint256 _amount) external;
5,674
1
// Events
event LogMigrationEnabled( address target );
event LogMigrationEnabled( address target );
20,087
167
// Returns difference over the given _from to _to block.
function getMultiplier(uint256 _from, uint256 _to) public pure returns (uint256)
function getMultiplier(uint256 _from, uint256 _to) public pure returns (uint256)
6,803
12
// returns all tokens that can mint this SY /
function getTokensIn() external view returns (address[] memory res);
function getTokensIn() external view returns (address[] memory res);
35,401