file_name
stringlengths
71
779k
comments
stringlengths
0
29.4k
code_string
stringlengths
20
7.69M
__index_level_0__
int64
2
17.2M
./full_match/42161/0x00B7F6b5d9C982e0A78BD18100856092C7d54c4e/sources/_looksrare/contracts-libs/contracts/OwnableTwoSteps.sol
This function is used to cancel the ownership transfer. This function can be used for both cancelling a transfer to a new owner and cancelling the renouncement of the ownership./
function cancelOwnershipTransfer() external onlyOwner { Status _ownershipStatus = ownershipStatus; if (_ownershipStatus == Status.NoOngoingTransfer) { revert NoOngoingTransferInProgress(); } if (_ownershipStatus == Status.TransferInProgress) { delete potentialOwner; } delete ownershipStatus; emit CancelOwnershipTransfer(); }
16,303,136
pragma solidity 0.5.0; import "./Sponsorships.sol"; import "./FinanceManager.sol"; /** * @title Sponsorships minter contract */ contract SponsorshipsMinter is FinanceManager { Sponsorships internal sp; uint256 public totalSold; ERC20 public purchaseToken; uint256 public price; string private constant INSUFFICIENT_PAYMENT = "Insufficient payment."; string private constant MINT_ERROR = "Mint error."; string private constant TRANSFER_FROM_ERROR = "Purchase token transferFrom failed."; string private constant FINANCE_MESSAGE = "Revenue of Sponsorships sale."; string private constant INVALID_PRICE = "Price must be greater than zero."; string private constant IS_NOT_CONTRACT = "Address doesn't belong to a smart contract."; event SponsorshipsPurchased(address account, uint256 amount, uint256 price); event PurchaseTokenSet(address purchaseTokenAddr); event PriceSet(uint256 price); constructor(Sponsorships _sp, ERC20 _purchaseToken) public { sp = _sp; purchaseToken = _purchaseToken; // The initial price is one. price = 10**18; } /** * @notice Set the ERC20 token used as payment for Sponsorships. * @dev Set the ERC20 token used as payment for Sponsorships. * @param _purchaseToken The token used for payments. */ function setPurchaseToken(ERC20 _purchaseToken) external onlyOwner { require(address(_purchaseToken).isContract(), IS_NOT_CONTRACT); purchaseToken = _purchaseToken; emit PurchaseTokenSet(address(_purchaseToken)); } /** * @notice Set the price per Sponsorship. * @dev Set the price per Sponsorship. * @param _price price per Sponsorship. */ function setPrice(uint256 _price) external onlyOwner { require(0 < _price, INVALID_PRICE); price = _price; emit PriceSet(price); } /** * @notice Purchase Sponsorships. * @dev Purchase Sponsorships. */ function purchase() external returns (bool success) { uint256 allowance = purchaseToken.allowance(msg.sender, address(this)); require(price <= allowance, INSUFFICIENT_PAYMENT); uint256 spAmount = allowance.div(price); uint256 purchaseTokenAmount = spAmount.mul(price); totalSold = totalSold.add(spAmount); require(purchaseToken.transferFrom(msg.sender, address(this), purchaseTokenAmount), TRANSFER_FROM_ERROR); deposit(purchaseToken, purchaseTokenAmount, FINANCE_MESSAGE); require(sp.mint(msg.sender, spAmount), MINT_ERROR); emit SponsorshipsPurchased(msg.sender, spAmount, price); return true; } /** * @notice Disable purchases. * @dev Renounce minter. */ function disablePurchases() external onlyOwner { sp.renounceMinter(); } }
Disable purchases. Renounce minter./
function disablePurchases() external onlyOwner { sp.renounceMinter(); }
5,409,045
pragma solidity 0.4.21; import "./HumanIdentityInterface.sol"; import "./zeppelin/ownership/Ownable.sol"; import "./zeppelin/math/SafeMath.sol"; /** * @title HumanIdentityToken * @author Adam Gall ([email protected]) * @notice HumanIdentityToken is a generic implementation of the HumanIdentityInterface. * This implementation provides a recommended approach for implementing * the `register` and `verify` functions, along with simple */ contract HumanIdentityBasic is HumanIdentityInterface, Ownable { using SafeMath for uint; /** * @notice Receive biometrically verified payload and signature * from offchain oracle, along with `to` recipient, and * number of tokens to transfer. * @param oracleNonce Unique identifier from offchain oracle identity provider * @param confidenceResult Confidence level returned by the identity provider * @param user Public address of the user verifyting their transaction * @param r Signature data * @param s Signature data * @param v Signature data * @dev Valid inputs * oracleNonce Any unique `string`, such as a `UUID`/`GUID` https://en.wikipedia.org/wiki/Universally_unique_identifier * confidenceResult Any valid `uint`; is not saved in `registrations` struct but is used to compute signature * user Any valid Ethereum `address`; is not saved in `registrations` struct but is used to compute signature * r Any bytes data are accepted * s Any bytes data are accepted * v Any uint8 is accepted */ function register( string oracleNonce, uint confidenceResult, address user, bytes32 r, bytes32 s, uint8 v ) public returns (bool success) { // concatenate and sha3 the message data. // require that the data was signed by the contract's `identityProvider` account <- secret sauce bytes32 dataHash = keccak256(oracleNonce, confidenceResult, user); require(identityProvider == ecrecover(dataHash, v, r, s)); // require that the `msg.sender` has not executed this function before Registration memory existingRegistration = registrations[msg.sender]; require(existingRegistration.registered == false); // generate and save a new `Registration` struct Registration memory registration = generateRegistration(oracleNonce); registrations[msg.sender] = registration; // save the new struct into contract storage, mapping `msg.sender` to the data success = registrations[msg.sender].timestamp != 0; emit RegisterUser(msg.sender, oracleNonce, success); } /** * @notice Receive biometrically verified payload and signature from offchain oracle, * along with `to` recipient, and number of tokens to transfer. * A user may call this method multiple times after `register`ing. * @dev This function reverts if the data being passed in does not have a valid signature * from the private key of the contract's `identityProvider`. * It also reverts if the sender has not yet `register`ed on the contract * It also reverts if the input data has been successfully used in a validation. * @param oracleNonce Unique identifier from offchain oracle identity provider * @param confidenceResult Confidence level returned by the identity provider * @param user Public address of the user verifyting their transaction * @param r Signature data * @param s Signature data * @param v Signature data * @dev Valid inputs * oracleNonce Any unique `string`, such as a `UUID`/`GUID` https://en.wikipedia.org/wiki/Universally_unique_identifier * confidenceResult Any valid `uint`; is not saved in `registrations` struct but is used to compute signature * user Any valid Ethereum `address`; is not saved in `registrations` struct but is used to compute signature * r Any bytes data are accepted * s Any bytes data are accepted * v Any uint8 is accepted * @return Whether or not the verification's `confidenceResult` was above the contract's threshold */ function verify( string oracleNonce, uint confidenceResult, address user, bytes32 r, bytes32 s, uint8 v ) public returns (bool success) { // concatenate and sha3 the message data. // require that the data was signed by the contract's `identityProvider` account <- secret sauce pt. 1. // require that the `msg.sender` has registered with the contract. // require that this specific set of data has not yet been verififed by this contract. // to prevent replay attacks. bytes32 dataHash = keccak256(oracleNonce, confidenceResult, user); require(identityProvider == ecrecover(dataHash, v, r, s)); require(registrations[msg.sender].registered == true); require(verificationAttempts[dataHash] == false); // generate `Verification` struct to save Verification memory verification = generateVerification(oracleNonce, confidenceResult, user); // compute the current verification "count" for this user. // each new successful `verify` call adds one. // use a hash of concatenated `msg.sender` and their `newCount` as the key for the new `verification` struct in `verifications` contract storage mapping. // save the `newCount`. uint newCount = verificationCounts[msg.sender].add(1); verifications[keccak256(msg.sender, newCount)] = verification; verificationCounts[msg.sender] = newCount; // save the data hash to prevent future replay attacks for this data verificationAttempts[dataHash] = true; // finally compare the signed `confidenceResult` with contracts `confidenceThreshold` // to verify that the `identityProvider` is sufficiently confident in user's identity. <- secret sauce pt. 2 success = confidenceResult >= confidenceThreshold; emit VerifyUser(msg.sender, oracleNonce, confidenceResult, success); } /** * @notice OnlyOwner method to update the contract's `identityProvider` * @param newIdentityProvider New offchain identity provider address * @dev Valid input: Any valid Ethereum account address */ function updateIdentityProvider ( address newIdentityProvider ) public onlyOwner { require(newIdentityProvider != address(0)); emit IdentityProviderUpdated(identityProvider, newIdentityProvider); identityProvider = newIdentityProvider; } /** * @notice OnlyOwner method to update the contract's `confidenceThreshold` * @param newThreshold Value which to compare `verify` confidence requests against * @dev Valid input: Any valid Ethereum based `uint` */ function updateConfidenceThreshold ( uint newThreshold ) public onlyOwner { require(newThreshold != 0); emit ConfidenceThresholdUpdated(confidenceThreshold, newThreshold); confidenceThreshold = newThreshold; } /** * @notice Generates and returns a new `Registration` struct, given * `oracleNonce`, the contract's `identityProvider`, and the block's timestamp * @param oracleNonce Unique identifier from offchain oracle identity provider */ function generateRegistration ( string oracleNonce ) private view returns (Registration registration) { registration.timestamp = block.timestamp; registration.identityProvider = identityProvider; registration.oracleNonce = oracleNonce; registration.registered = true; } /** * @notice Generates and returns a new `Verification` struct, given * `oracleNonce`, `confidenceResult`, `user` (all from the offchain oracle's * signed data), the contract's `identityProvider` and `confidenceThreshold, * and the block's timestamp. * @param oracleNonce Unique identifier from offchain oracle identity provider * @param confidenceResult Confidence level returned by the identity provider * @param user Public address of the user verifyting their transaction */ function generateVerification ( string oracleNonce, uint confidenceResult, address user ) private view returns (Verification verification) { verification.oracleNonce = oracleNonce; verification.confidenceResult = confidenceResult; verification.user = user; verification.threshold = confidenceThreshold; verification.timestamp = block.timestamp; verification.identityProvider = identityProvider; } }
Generates and returns a new `Registration` struct, given `oracleNonce`, the contract's `identityProvider`, and the block's timestamp oracleNonce Unique identifier from offchain oracle identity provider/
function generateRegistration ( string oracleNonce ) private view returns (Registration registration) { registration.timestamp = block.timestamp; registration.identityProvider = identityProvider; registration.oracleNonce = oracleNonce; registration.registered = true; }
12,795,434
// ____ ___ ____ ___ _ _ __ __ // | _ \ / _ \| _ \_ _| | | | \/ | // | |_) | | | | | | | || | | | |\/| | // | __/| |_| | |_| | || |_| | | | | // |_| \___/|____/___|\___/|_| |_| // // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; /* ---------------------------------------------------------------------------- * Podium Genesis NFT miniting * Used ERC721-R for refund mechanism with customizable cliff settings. * More infomration about refund on github and in ERC721R.sol * There is more work to be done in the space. This is a good start. BAG_TIME / -------------------------------------------------------------------------- */ import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "@openzeppelin/contracts/security/Pausable.sol"; import "./ERC721R.sol"; import "./MerkleProof.sol"; contract Podium is Ownable, ERC721R, ReentrancyGuard, Pausable { // Declerations // ------------------------------------------------------------------------ uint256 public maxMintPublic = 2; uint256 internal collectionSize_ = 777; uint256 internal reservedQuantity_ = 57; // For dev mint uint256 internal refundTimeIntervals_ = 14 days; // When refund cliffs uint256 internal refundIncrements_ = 20; // How much decrease % at cliff uint64 public mintListPrice = 0.12 ether; uint64 public publicPrice = 0.15 ether; uint32 public publicSaleStart; uint32 public mintListSaleStart; uint256 public refundPaidSum; // Not init bc 0 to save gas How much was actually paid out mapping(address => bool) public mintListClaimed; // Did they claim ML mapping(address => bool) public teamMember; mapping(bytes4 => bool) public functionLocked; string private _baseTokenURI; // metadata URI address private teamRefundTreasury = msg.sender; // Address where refunded tokens sent bytes32 public merkleRoot; // Merkle Root for WL verification constructor( uint32 publicSaleStart_, uint32 mintListSaleStart_, bytes32 merkleRoot_ ) ERC721R("Podium", "PODIUM", reservedQuantity_, collectionSize_, refundTimeIntervals_, refundIncrements_) { publicSaleStart = publicSaleStart_; mintListSaleStart = mintListSaleStart_; merkleRoot = merkleRoot_; teamMember[msg.sender] = true; } // Modifiers // ------------------------------------------------------------------------ /* * Make sure the caller is sender and not bot */ modifier callerNotBot() { require(tx.origin == msg.sender, "The caller is another contract"); _; } /** * @dev Throws if called by any account other than team members */ modifier onlyTeamMember() { require(teamMember[msg.sender], "Caller is not an owner"); _; } /** * @notice Modifier applied to functions that will be disabled when they're no longer needed */ modifier lockable() { require(!functionLocked[msg.sig], "Function has been locked"); _; } // Mint functions and helpers // ------------------------------------------------------------------------ /* * WL Mint default quanitiy is 1. Uses merkle tree proof */ function mintListMint(bytes32[] calldata _merkleProof) external payable nonReentrant callerNotBot whenNotPaused { // Overall checks require(totalSupply() + 1 <= collectionSize,"All tokens minted"); require(isMintListSaleOn(), "Mintlist not active"); // Merkle check for WL verification require(!mintListClaimed[msg.sender],"Already minted WL"); bytes32 leaf = keccak256(abi.encodePacked(msg.sender)); require(MerkleProof.verify(_merkleProof, merkleRoot, leaf), "Not on ML"); // Please pay us require(msg.value == mintListPrice, "Invalid Ether amount"); mintListClaimed[msg.sender] = true; _safeMint(msg.sender, 1, mintListPrice); // Mint list quantity 1 refundEligbleSum += mintListPrice; } /* * Public mint */ function publicSaleMint(uint256 quantity) external payable nonReentrant callerNotBot whenNotPaused { // Overall checks require( totalSupply() + quantity <= collectionSize, "All tokens minted" ); require( numberMinted(msg.sender) + quantity <= maxMintPublic, "Allowance allocated" ); require(isPublicSaleOn(), "Public sale not active"); // Please pay us require(msg.value == (publicPrice * quantity), "Invalid Ether amount"); _safeMint(msg.sender, quantity, publicPrice); refundEligbleSum += (publicPrice * quantity); } /* * Has public sale started */ function isPublicSaleOn() public view returns (bool) { return block.timestamp >= publicSaleStart; } /* * Has WL sale started */ function isMintListSaleOn() public view returns (bool) { return block.timestamp >= mintListSaleStart && block.timestamp < publicSaleStart; } /* * Is specific address on WL * Need merkle proof and root (mint page call) */ function isOnMintList(bytes32[] calldata _merkleProof, address _wallet) public view returns (bool) { bytes32 leaf = keccak256(abi.encodePacked(_wallet)); return MerkleProof.verify(_merkleProof, merkleRoot, leaf); } // Remaining Public functions // ------------------------------------------------------------------------ /* * How many were minted by owner */ function numberMinted(address owner) public view returns (uint256) { return _numberMinted(owner); } /* * Who owns this token and since when */ function getOwnershipData(uint256 tokenId) external view returns (TokenOwnership memory) { return ownershipOf(tokenId); } // Refund logic // ------------------------------------------------------------------------ /** * Refund owner token at refund rate mint price * If elgible (not been transfered) */ function refund(uint256 tokenId) external nonReentrant callerNotBot whenNotPaused { require(isRefundActive(), "Refund is over"); // Confirm origin and refund activity uint256 purchaseValueCurrent = _checkPurchasePriceCurrent(tokenId); require(purchaseValueCurrent > 0, "Token was minted by devs or transfered"); require(ownerOf(tokenId) == msg.sender, "You do not own token"); // Send token to refund Address _refund(msg.sender, teamRefundTreasury, tokenId); // Refund based on purchase price and time uint256 refundValue; refundValue = purchaseValueCurrent * refundRate()/100; payable(msg.sender).transfer(refundValue); refundPaidSum += refundValue; } /** * Allow only withdrawal of non refund locked-up funds */ function withdrawPossibleAmount() external onlyTeamMember whenNotPaused { if(isRefundActive()) { // How much can be withdrawn uint256 amount = address(this).balance - fundsNeededForRefund(); (bool success, ) = msg.sender.call{value: amount}(""); require(success, "Transfer failed."); } else { (bool success, ) = msg.sender.call{value: address(this).balance}(""); require(success, "Transfer failed."); } } /** * How much ETH is eligible for refund * */ function checkRefundEligbleSum() public view onlyTeamMember returns (uint256) { return refundEligbleSum; } /** * Amount needed for refunds at current rate */ function fundsNeededForRefund() public view returns(uint256) { return refundEligbleSum * refundRate() / 100; } /** * Will return refund rate in as int (i.e. 100, 80, etc) * To be devided by 100 for percentage */ function refundRate() public view returns (uint256) { return (100 - (_currentPeriod(publicSaleStart) * refundIncrements)); } /** * How much ETH was paid out for redunds */ function checkRefundedAmount() public view onlyTeamMember returns(uint256) { return refundPaidSum; } /** * Is refund live */ function isRefundActive() public view returns(bool) { return ( block.timestamp < (publicSaleStart + (5 * refundTimeIntervals)) ); } // Admin only functions (WL, update data, dev mint, etc.) // Note: Withdraw in refund // ------------------------------------------------------------------------ /* * Change where refund NFTs are sent */ function changeTeamRefundTreasury(address _teamRefundTreasury) external onlyTeamMember { require(_teamRefundTreasury != address(0)); teamRefundTreasury = _teamRefundTreasury; } /* * Update prices and dates */ function manageSale( uint64 _mintListPrice, uint64 _publicPrice, uint32 _publicSaleStart, uint32 _mintListSaleStart, uint256 _maxMintPublic, uint256 _collectionSize ) external onlyTeamMember lockable { mintListPrice = _mintListPrice; publicPrice = _publicPrice; publicSaleStart = _publicSaleStart; mintListSaleStart = _mintListSaleStart; maxMintPublic = _maxMintPublic; collectionSize = _collectionSize; } /** * Mintlist update by using new merkle root */ function updateMintListHash(bytes32 _newMerkleroot) external onlyTeamMember { merkleRoot = _newMerkleroot; } /* * Regular dev mint without override */ function teamInitMint( uint256 quantity ) public onlyTeamMember { teamInitMint(msg.sender, quantity, false, 0); } /* * Emergency override if needed to be called by external contract * To maintain token continuity */ function teamInitMint( address to, uint256 quantity, bool emergencyOverride, uint256 purchasePriceOverride ) public onlyTeamMember { if (!emergencyOverride) require( quantity <= maxBatchSize, "Dev cannot mint more than allocated" ); _safeMint(to, quantity, purchasePriceOverride); // Team mint list price = 0 } /* * Override internal ERC URI */ function _baseURI() internal view virtual override returns (string memory) { return _baseTokenURI; } /* * Update BaseURI (for reaveal) */ function setBaseURI(string calldata baseURI) external onlyTeamMember { _baseTokenURI = baseURI; } /* * Set owners of tokens explicitly with ERC721A */ function setOwnersExplicit(uint256 quantity) external onlyTeamMember nonReentrant { _setOwnersExplicit(quantity); } // ------------------------------------------------------------------------ // Security and ownership /** * Pause functions as needed (in case of exploits) */ function pause() public onlyTeamMember { _pause(); } /** * Unpause functions as needed */ function unpause() public onlyTeamMember { _unpause(); } /** * Add new team meber role with admin permissions */ function addTeamMemberAdmin(address newMember) external onlyTeamMember { teamMember[newMember] = true; } /** * Remove team meber role from admin permissions */ function removeTeamMemberAdmin(address newMember) external onlyTeamMember { teamMember[newMember] = false; } /** * Returns true if address is team member */ function isTeamMemberAdmin(address checkAddress) public view onlyTeamMember returns (bool) { return teamMember[checkAddress]; } /** * @notice Lock individual functions that are no longer needed * @dev Only affects functions with the lockable modifier * @param id First 4 bytes of the calldata (i.e. function identifier) */ function lockFunction(bytes4 id) public onlyTeamMember { functionLocked[id] = true; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/Pausable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // ERC721-R Created by Podium builds on the ERC721-A. // It allows for flexibility in refunds policies in the child contracts // In this scenario, refunds are void if the token is transfered (_transfer) // TODO: For multiple mint projects migrate Token RefundPolicy to system similar to ERC721A owner data // That can we determined by serial ordering or explicitly set. // TODO: Build in a more flexible manner on top of ERC721A or new format to accomodate other contract types // Test this and ensure intended behavior in any future implementations // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/utils/Context.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "@openzeppelin/contracts/utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at 0 (e.g. 0, 1, 2, 3..). * * Assumes the number of issuable tokens (collection size) is capped and fits in a uint128. * * Does not support burning tokens to address(0). */ contract ERC721R is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using Address for address; using Strings for uint256; struct TokenOwnership { address addr; uint64 startTimestamp; } struct AddressData { uint128 balance; uint128 numberMinted; } uint256 private currentIndex = 0; uint256 internal refundEligbleSum; // Value of eligible refunds at original rate uint256 internal collectionSize; uint256 internal maxBatchSize; uint256 internal immutable refundTimeIntervals; // / When refund cliffs uint256 internal immutable refundIncrements; // // How much decrease % at cliff // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to ownership details // An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details. mapping(uint256 => TokenOwnership) private _ownerships; // Mapping owner address to address data mapping(address => AddressData) private _addressData; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; // Mappring from token ID to purchase price 0 if transfered mapping(uint256 => uint256) private _tokenPurchasePriceCurrent; /** * @dev * `maxBatchSize` refers to how much a minter can mint at a time. * `collectionSize_` refers to how many tokens are in the collection. * `refundTimeIntervals_` refers to epoch between each interval * `refundIncrements_` refers to percentage decrease in refund */ constructor( string memory name_, string memory symbol_, uint256 maxBatchSize_, uint256 collectionSize_, uint256 refundTimeIntervals_, uint256 refundIncrements_ ) { require( collectionSize_ > 0, "ERC721R: collection must have a nonzero supply" ); require(maxBatchSize_ > 0, "ERC721R: max batch size must be nonzero"); _name = name_; _symbol = symbol_; maxBatchSize = maxBatchSize_; collectionSize = collectionSize_; refundTimeIntervals = refundTimeIntervals_; refundIncrements = refundIncrements_; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { return currentIndex; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view override returns (uint256) { require(index < totalSupply(), "ERC721R: global index out of bounds"); return index; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. * This read function is O(collectionSize). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { require(index < balanceOf(owner), "ERC721R: owner index out of bounds"); uint256 numMintedSoFar = totalSupply(); uint256 tokenIdsIdx = 0; address currOwnershipAddr = address(0); for (uint256 i = 0; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } revert("ERC721R: unable to get token of owner by index"); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view override returns (uint256) { require(owner != address(0), "ERC721R: balance query for the zero address"); return uint256(_addressData[owner].balance); } function _numberMinted(address owner) internal view returns (uint256) { require( owner != address(0), "ERC721R: number minted query for the zero address" ); return uint256(_addressData[owner].numberMinted); } function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { require(_exists(tokenId), "ERC721R: owner query for nonexistent token"); uint256 lowestTokenToCheck; if (tokenId >= maxBatchSize) { lowestTokenToCheck = tokenId - maxBatchSize + 1; } for (uint256 curr = tokenId; curr >= lowestTokenToCheck; curr--) { TokenOwnership memory ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } revert("ERC721R: unable to determine the owner of token"); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return ownershipOf(tokenId).addr; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @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 returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public override { address owner = ERC721R.ownerOf(tokenId); require(to != owner, "ERC721R: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721R: approve caller is not owner nor approved for all" ); _approve(to, tokenId, owner); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { require(_exists(tokenId), "ERC721R: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public override { require(operator != _msgSender(), "ERC721R: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public override { _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public override { _transfer(from, to, tokenId); require( _checkOnERC721Received(from, to, tokenId, _data), "ERC721R: transfer to non ERC721Receiver implementer" ); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), */ function _exists(uint256 tokenId) internal view returns (bool) { return tokenId < currentIndex; } function _safeMint(address to, uint256 quantity, uint256 purchasePrice) internal { _safeMint(to, quantity, purchasePrice, ""); } /** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - there must be `quantity` tokens remaining unminted in the total collection. * - `to` cannot be the zero address. * - `quantity` cannot be larger than the max batch size. * * Emits a {Transfer} event. */ function _safeMint( address to, uint256 quantity, uint256 purchasePrice, bytes memory _data ) internal { uint256 startTokenId = currentIndex; require(to != address(0), "ERC721R: mint to the zero address"); // We know if the first token in the batch doesn't exist, the other ones don't as well, because of serial ordering. require(!_exists(startTokenId), "ERC721R: token already minted"); require(quantity <= maxBatchSize, "ERC721R: quantity to mint too high"); // NOTE PODIUM WILL USE 77 FOR DEV MINT. ENSURE NO EXPLOIT POSSIBLE _beforeTokenTransfers(address(0), to, startTokenId, quantity); AddressData memory addressData = _addressData[to]; _addressData[to] = AddressData( addressData.balance + uint128(quantity), addressData.numberMinted + uint128(quantity) ); _ownerships[startTokenId] = TokenOwnership(to, uint64(block.timestamp)); uint256 updatedIndex = startTokenId; for (uint256 i = 0; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); require( _checkOnERC721Received(address(0), to, updatedIndex, _data), "ERC721R: transfer to non ERC721Receiver implementer" ); if(purchasePrice > 0) { // Team mint _tokenPurchasePriceCurrent[updatedIndex] = purchasePrice; // What was token purchased at } updatedIndex++; } currentIndex = updatedIndex; _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @dev Transfers `tokenId` from `from` to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) private { TokenOwnership memory prevOwnership = ownershipOf(tokenId); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || getApproved(tokenId) == _msgSender() || isApprovedForAll(prevOwnership.addr, _msgSender())); require( isApprovedOrOwner, "ERC721R: transfer caller is not owner nor approved" ); require( prevOwnership.addr == from, "ERC721R: transfer from incorrect owner" ); require(to != address(0), "ERC721R: transfer to the zero address"); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId] = TokenOwnership(to, uint64(block.timestamp)); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { if (_exists(nextTokenId)) { _ownerships[nextTokenId] = TokenOwnership( prevOwnership.addr, prevOwnership.startTimestamp ); } } // Refund logic to set purchase price of token // If eligible if(_checkPurchasePriceCurrent(tokenId) > 0){ refundEligbleSum -= _tokenPurchasePriceCurrent[tokenId]; _tokenPurchasePriceCurrent[tokenId] = 0; // Transfer voids refund } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } uint256 public nextOwnerToExplicitlySet = 0; /** * @dev Explicitly set `owners` to eliminate loops in future calls of ownerOf(). */ function _setOwnersExplicit(uint256 quantity) internal { uint256 oldNextOwnerToSet = nextOwnerToExplicitlySet; require(quantity > 0, "quantity must be nonzero"); uint256 endIndex = oldNextOwnerToSet + quantity - 1; if (endIndex > collectionSize - 1) { endIndex = collectionSize - 1; } // We know if the last one in the group exists, all in the group exist, due to serial ordering. require(_exists(endIndex), "not enough minted yet for this cleanup"); for (uint256 i = oldNextOwnerToSet; i <= endIndex; i++) { if (_ownerships[i].addr == address(0)) { TokenOwnership memory ownership = ownershipOf(i); _ownerships[i] = TokenOwnership( ownership.addr, ownership.startTimestamp ); } } nextOwnerToExplicitlySet = endIndex + 1; } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721R: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. */ function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} /** * @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes * minting. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - when `from` and `to` are both non-zero. * - `from` and `to` are never both zero. */ function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} /** * Will current period in timestamp */ function _currentPeriod(uint32 _refundStartTime) internal view returns (uint32){ if (block.timestamp < (_refundStartTime + (1 * refundTimeIntervals))){ return 0; } else if (block.timestamp < (_refundStartTime + (2 * refundTimeIntervals))){ return 1; } else if (block.timestamp < (_refundStartTime + (3 * refundTimeIntervals))){ return 2; } else if (block.timestamp < (_refundStartTime + (4 * refundTimeIntervals))){ return 3; } else if (block.timestamp < (_refundStartTime + (5 * refundTimeIntervals))){ return 4; } else{ return 5; } } /** * @dev Function that returns the mint price of the token. * Will be 0 if transfered * Calling conditions: * * - `tokenId` is the queried tokenId */ function checkPurchasePriceCurrent(uint256 tokenId) public view virtual returns (uint256) { return _checkPurchasePriceCurrent(tokenId); } function _checkPurchasePriceCurrent(uint256 tokenId) internal view virtual returns (uint256) { return _tokenPurchasePriceCurrent[tokenId]; } /** * @dev Send token to refund address * If eligible (price not 0 either dev mint or transfer) * Calling conditions: * * - `from` is address of the refunder * - `to` is the address where refunded token will go * - `tokenId` is the queried tokenId */ function _refund( address from, address to, uint256 tokenId ) internal { require(_checkPurchasePriceCurrent(tokenId) > 0, "Token has already been refunded or minted by devs"); safeTransferFrom(from, to, tokenId, ""); } /** * @dev Owner and date owned of token * Calling conditions: * * - `tokenId` is the queried tokenId */ function ownerOfData(uint256 tokenId) public view returns (TokenOwnership memory) { return ownershipOf(tokenId); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/cryptography/MerkleProof.sol) pragma solidity ^0.8.0; /** * @dev These functions deal with verification of Merkle Trees proofs. * * The proofs can be generated using the JavaScript library * https://github.com/miguelmota/merkletreejs[merkletreejs]. * Note: the hashing algorithm should be keccak256 and pair sorting should be enabled. * * See `test/utils/cryptography/MerkleProof.test.js` for some examples. * * WARNING: You should avoid using leaf values that are 64 bytes long prior to * hashing, or use a hash function other than keccak256 for hashing leaves. * This is because the concatenation of a sorted pair of internal nodes in * the merkle tree could be reinterpreted as a leaf value. */ library MerkleProof { /** * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree * defined by `root`. For this, a `proof` must be provided, containing * sibling hashes on the branch from the leaf to the root of the tree. Each * pair of leaves and each pair of pre-images are assumed to be sorted. */ function verify( bytes32[] memory proof, bytes32 root, bytes32 leaf ) internal pure returns (bool) { return processProof(proof, leaf) == root; } /** * @dev Returns the rebuilt hash obtained by traversing a Merkle tree up * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt * hash matches the root of the tree. When processing the proof, the pairs * of leafs & pre-images are assumed to be sorted. * * _Available since v4.4._ */ function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash <= proofElement) { // Hash(current computed hash + current element of the proof) computedHash = _efficientHash(computedHash, proofElement); } else { // Hash(current element of the proof + current computed hash) computedHash = _efficientHash(proofElement, computedHash); } } return computedHash; } function _efficientHash(bytes32 a, bytes32 b) private pure returns (bytes32 value) { assembly { mstore(0x00, a) mstore(0x20, b) value := keccak256(0x00, 0x40) } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev 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, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol) pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); }
See {IERC721Enumerable-tokenOfOwnerByIndex}. This read function is O(collectionSize). If calling from a separate contract, be sure to test gas first. It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case./
function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { require(index < balanceOf(owner), "ERC721R: owner index out of bounds"); uint256 numMintedSoFar = totalSupply(); uint256 tokenIdsIdx = 0; address currOwnershipAddr = address(0); for (uint256 i = 0; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } revert("ERC721R: unable to get token of owner by index"); }
410,411
./partial_match/3/0xa54B20de67B059944c0eeD388e71f4D1a9e14041/sources/RigelGift.sol
Set max referral spins per user address, per project that can be earned
function setMaxReferralSpins(uint8 count) external onlyOwner { _maxReferralSpins = count; }
5,272,839
pragma solidity ^0.4.24; //============================================================================== // _ _ _ _|_ _ . // (/_\/(/_| | | _\ . //============================================================================== contract F3Devents { // fired whenever a player registers a name event onNewName ( uint256 indexed playerID, address indexed playerAddress, bytes32 indexed playerName, bool isNewPlayer, uint256 affiliateID, address affiliateAddress, bytes32 affiliateName, uint256 amountPaid, uint256 timeStamp ); // fired at end of buy or reload event onEndTx ( uint256 compressedData, uint256 compressedIDs, bytes32 playerName, address playerAddress, uint256 ethIn, uint256 keysBought, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 P3DAmount, uint256 genAmount, uint256 potAmount, uint256 airDropPot ); // fired whenever theres a withdraw event onWithdraw ( uint256 indexed playerID, address playerAddress, bytes32 playerName, uint256 ethOut, uint256 timeStamp ); // fired whenever a withdraw forces end round to be ran event onWithdrawAndDistribute ( address playerAddress, bytes32 playerName, uint256 ethOut, uint256 compressedData, uint256 compressedIDs, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 P3DAmount, uint256 genAmount ); // (fomo3d long only) fired whenever a player tries a buy after round timer // hit zero, and causes end round to be ran. event onBuyAndDistribute ( address playerAddress, bytes32 playerName, uint256 ethIn, uint256 compressedData, uint256 compressedIDs, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 P3DAmount, uint256 genAmount ); // (fomo3d long only) fired whenever a player tries a reload after round timer // hit zero, and causes end round to be ran. event onReLoadAndDistribute ( address playerAddress, bytes32 playerName, uint256 compressedData, uint256 compressedIDs, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 P3DAmount, uint256 genAmount ); // fired whenever an affiliate is paid event onAffiliatePayout ( uint256 indexed affiliateID, address affiliateAddress, bytes32 affiliateName, uint256 indexed roundID, uint256 indexed buyerID, uint256 amount, uint256 timeStamp ); // received pot swap deposit event onPotSwapDeposit ( uint256 roundID, uint256 amountAddedToPot ); } //============================================================================== // _ _ _ _|_ _ _ __|_ _ _ _|_ _ . // (_(_)| | | | (_|(_ | _\(/_ | |_||_) . //====================================|========================================= contract modularLong is F3Devents {} contract FoMoGame is modularLong { using SafeMath for *; using NameFilter for string; using F3DKeysCalcLong for uint256; otherFoMo3D private otherF3D_; ForwarderInterface constant private Team_Forwarder = ForwarderInterface(0xBd4C9aB2F3e241F1291D55af51CB0D949077B591); PlayerBookInterface constant private PlayerBook = PlayerBookInterface(0xe97fad5ccb766cbd515067e4bdc3cb1a2a112195); address private swapDeposit = 0x24F73508ee8FBF5ac39e51C363ff87E736fe659b; //============================================================================== // _ _ _ |`. _ _ _ |_ | _ _ . // (_(_)| |~|~|(_||_|| (_||_)|(/__\ . (game settings) //=================_|=========================================================== string constant public name = "FoMoGame Official"; string constant public symbol = "FGame"; uint256 private rndExtra_ = 0; // length of the very first ICO uint256 private rndGap_ = 0; // length of ICO phase, set to 1 year for EOS. uint256 constant private rndInit_ = 1 hours; // round timer starts at this uint256 constant private rndInc_ = 30 seconds; // every full key purchased adds this much to the timer uint256 constant private rndMax_ = 24 hours; // max length a round timer can be //============================================================================== // _| _ _|_ _ _ _ _|_ _ . // (_|(_| | (_| _\(/_ | |_||_) . (data used to store game info that changes) //=============================|================================================ uint256 public airDropPot_; // person who gets the airdrop wins part of this pot uint256 public airDropTracker_ = 0; // incremented each time a "qualified" tx occurs. used to determine winning air drop uint256 public rID_; // round id number / total rounds that have happened //**************** // PLAYER DATA //**************** mapping (address => uint256) public pIDxAddr_; // (addr => pID) returns player id by address mapping (bytes32 => uint256) public pIDxName_; // (name => pID) returns player id by name mapping (uint256 => F3Ddatasets.Player) public plyr_; // (pID => data) player data mapping (uint256 => mapping (uint256 => F3Ddatasets.PlayerRounds)) public plyrRnds_; // (pID => rID => data) player round data by player id & round id mapping (uint256 => mapping (bytes32 => bool)) public plyrNames_; // (pID => name => bool) list of names a player owns. (used so you can change your display name amongst any name you own) //**************** // ROUND DATA //**************** mapping (uint256 => F3Ddatasets.Round) public round_; // (rID => data) round data mapping (uint256 => mapping(uint256 => uint256)) public rndTmEth_; // (rID => tID => data) eth in per team, by round id and team id //**************** // TEAM FEE DATA //**************** mapping (uint256 => F3Ddatasets.TeamFee) public fees_; // (team => fees) fee distribution by team mapping (uint256 => F3Ddatasets.PotSplit) public potSplit_; // (team => fees) pot split distribution by team //============================================================================== // _ _ _ __|_ _ __|_ _ _ . // (_(_)| |_\ | | |_|(_ | (_)| . (initial data setup upon contract deploy) //============================================================================== constructor() public { // Team allocation structures // 0 = whales // 1 = bears // 2 = sneks // 3 = bulls // Team allocation percentages // (F3D, P3D) + (Pot , Referrals, Community) // Referrals / Community rewards are mathematically designed to come from the winner's share of the pot. fees_[0] = F3Ddatasets.TeamFee(36,0); //50% to pot, 10% to aff, 2% to com, 1% to pot swap, 1% to air drop pot fees_[1] = F3Ddatasets.TeamFee(43,0); //43% to pot, 10% to aff, 2% to com, 1% to pot swap, 1% to air drop pot fees_[2] = F3Ddatasets.TeamFee(66,0); //20% to pot, 10% to aff, 2% to com, 1% to pot swap, 1% to air drop pot fees_[3] = F3Ddatasets.TeamFee(50,0); //36% to pot, 10% to aff, 2% to com, 1% to pot swap, 1% to air drop pot // how to split up the final pot based on which team was picked // (F3D, P3D) potSplit_[0] = F3Ddatasets.PotSplit(20,0); //48% to winner, 30% to next round, 2% to com potSplit_[1] = F3Ddatasets.PotSplit(25,0); //48% to winner, 25% to next round, 2% to com potSplit_[2] = F3Ddatasets.PotSplit(40,0); //48% to winner, 10% to next round, 2% to com potSplit_[3] = F3Ddatasets.PotSplit(45,0); //48% to winner, 5% to next round, 2% to com } //============================================================================== // _ _ _ _|. |`. _ _ _ . // | | |(_)(_||~|~|(/_| _\ . (these are safety checks) //============================================================================== /** * @dev used to make sure no one can interact with contract until it has * been activated. */ modifier isActivated() { require(activated_ == true, "its not ready yet. check ?eta in discord"); _; } /** * @dev prevents contracts from interacting with fomo3d */ modifier isHuman() { address _addr = msg.sender; uint256 _codeLength; assembly {_codeLength := extcodesize(_addr)} require(_codeLength == 0, "sorry humans only"); _; } /** * @dev sets boundaries for incoming tx */ modifier isWithinLimits(uint256 _eth) { require(_eth >= 1000000000, "pocket lint: not a valid currency"); require(_eth <= 100000000000000000000000, "no vitalik, no"); _; } //============================================================================== // _ |_ |. _ |` _ __|_. _ _ _ . // |_)|_||_)||(_ ~|~|_|| |(_ | |(_)| |_\ . (use these to interact with contract) //====|========================================================================= /** * @dev emergency buy uses last stored affiliate ID and team snek */ function() isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // buy core buyCore(_pID, plyr_[_pID].laff, 2, _eventData_); } /** * @dev converts all incoming ethereum to keys. * -functionhash- 0x8f38f309 (using ID for affiliate) * -functionhash- 0x98a0871d (using address for affiliate) * -functionhash- 0xa65b37a1 (using name for affiliate) * @param _affCode the ID/address/name of the player who gets the affiliate fee * @param _team what team is the player playing for? */ function buyXid(uint256 _affCode, uint256 _team) isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals // if no affiliate code was given or player tried to use their own, lolz if (_affCode == 0 || _affCode == _pID) { // use last stored affiliate code _affCode = plyr_[_pID].laff; // if affiliate code was given & its not the same as previously stored } else if (_affCode != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affCode; } // verify a valid team was selected _team = verifyTeam(_team); // buy core buyCore(_pID, _affCode, _team, _eventData_); } function buyXaddr(address _affCode, uint256 _team) isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == address(0) || _affCode == msg.sender) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxAddr_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // verify a valid team was selected _team = verifyTeam(_team); // buy core buyCore(_pID, _affID, _team, _eventData_); } function buyXname(bytes32 _affCode, uint256 _team) isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == '' || _affCode == plyr_[_pID].name) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxName_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // verify a valid team was selected _team = verifyTeam(_team); // buy core buyCore(_pID, _affID, _team, _eventData_); } /** * @dev essentially the same as buy, but instead of you sending ether * from your wallet, it uses your unwithdrawn earnings. * -functionhash- 0x349cdcac (using ID for affiliate) * -functionhash- 0x82bfc739 (using address for affiliate) * -functionhash- 0x079ce327 (using name for affiliate) * @param _affCode the ID/address/name of the player who gets the affiliate fee * @param _team what team is the player playing for? * @param _eth amount of earnings to use (remainder returned to gen vault) */ function reLoadXid(uint256 _affCode, uint256 _team, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { // set up our tx event data F3Ddatasets.EventReturns memory _eventData_; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals // if no affiliate code was given or player tried to use their own, lolz if (_affCode == 0 || _affCode == _pID) { // use last stored affiliate code _affCode = plyr_[_pID].laff; // if affiliate code was given & its not the same as previously stored } else if (_affCode != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affCode; } // verify a valid team was selected _team = verifyTeam(_team); // reload core reLoadCore(_pID, _affCode, _team, _eth, _eventData_); } function reLoadXaddr(address _affCode, uint256 _team, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { // set up our tx event data F3Ddatasets.EventReturns memory _eventData_; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == address(0) || _affCode == msg.sender) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxAddr_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // verify a valid team was selected _team = verifyTeam(_team); // reload core reLoadCore(_pID, _affID, _team, _eth, _eventData_); } function reLoadXname(bytes32 _affCode, uint256 _team, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { // set up our tx event data F3Ddatasets.EventReturns memory _eventData_; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == '' || _affCode == plyr_[_pID].name) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxName_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // verify a valid team was selected _team = verifyTeam(_team); // reload core reLoadCore(_pID, _affID, _team, _eth, _eventData_); } /** * @dev withdraws all of your earnings. * -functionhash- 0x3ccfd60b */ function withdraw() isActivated() isHuman() public { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // setup temp var for player eth uint256 _eth; // check to see if round has ended and no one has run round end yet if (_now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0) { // set up our tx event data F3Ddatasets.EventReturns memory _eventData_; // end the round (distributes pot) round_[_rID].ended = true; _eventData_ = endRound(_eventData_); // get their earnings _eth = withdrawEarnings(_pID); // gib moni if (_eth > 0) plyr_[_pID].addr.transfer(_eth); // build event data _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; // fire withdraw and distribute event emit F3Devents.onWithdrawAndDistribute ( msg.sender, plyr_[_pID].name, _eth, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.P3DAmount, _eventData_.genAmount ); // in any other situation } else { // get their earnings _eth = withdrawEarnings(_pID); // gib moni if (_eth > 0) plyr_[_pID].addr.transfer(_eth); // fire withdraw event emit F3Devents.onWithdraw(_pID, msg.sender, plyr_[_pID].name, _eth, _now); } } /** * @dev use these to register names. they are just wrappers that will send the * registration requests to the PlayerBook contract. So registering here is the * same as registering there. UI will always display the last name you registered. * but you will still own all previously registered names to use as affiliate * links. * - must pay a registration fee. * - name must be unique * - names will be converted to lowercase * - name cannot start or end with a space * - cannot have more than 1 space in a row * - cannot be only numbers * - cannot start with 0x * - name must be at least 1 char * - max length of 32 characters long * - allowed characters: a-z, 0-9, and space * -functionhash- 0x921dec21 (using ID for affiliate) * -functionhash- 0x3ddd4698 (using address for affiliate) * -functionhash- 0x685ffd83 (using name for affiliate) * @param _nameString players desired name * @param _affCode affiliate ID, address, or name of who referred you * @param _all set to true if you want this to push your info to all games * (this might cost a lot of gas) */ function registerNameXID(string _nameString, uint256 _affCode, bool _all) isHuman() public payable { bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXIDFromDapp.value(_paid)(_addr, _name, _affCode, _all); uint256 _pID = pIDxAddr_[_addr]; // fire event emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); } function registerNameXaddr(string _nameString, address _affCode, bool _all) isHuman() public payable { bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXaddrFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all); uint256 _pID = pIDxAddr_[_addr]; // fire event emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); } function registerNameXname(string _nameString, bytes32 _affCode, bool _all) isHuman() public payable { bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXnameFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all); uint256 _pID = pIDxAddr_[_addr]; // fire event emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); } //============================================================================== // _ _ _|__|_ _ _ _ . // (_|(/_ | | (/_| _\ . (for UI & viewing things on etherscan) //=====_|======================================================================= /** * @dev return the price buyer will pay for next 1 individual key. * -functionhash- 0x018a25e8 * @return price for next key bought (in wei format) */ function getBuyPrice() public view returns(uint256) { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // are we in a round? if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) return ( (round_[_rID].keys.add(1000000000000000000)).ethRec(1000000000000000000) ); else // rounds over. need price for new round return ( 75000000000001 ); // init } /** * @dev returns time left. dont spam this, you'll ddos yourself from your node * provider * -functionhash- 0xc7e284b8 * @return time left in seconds */ function getTimeLeft() public view returns(uint256) { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; if (_now < round_[_rID].end) if (_now > round_[_rID].strt + rndGap_) return( (round_[_rID].end).sub(_now) ); else return( (round_[_rID].strt + rndGap_).sub(_now) ); else return(0); } /** * @dev returns player earnings per vaults * -functionhash- 0x63066434 * @return winnings vault * @return general vault * @return affiliate vault */ function getPlayerVaults(uint256 _pID) public view returns(uint256 ,uint256, uint256) { // setup local rID uint256 _rID = rID_; // if round has ended. but round end has not been run (so contract has not distributed winnings) if (now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0) { // if player is winner if (round_[_rID].plyr == _pID) { return ( (plyr_[_pID].win).add( ((round_[_rID].pot).mul(48)) / 100 ), (plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ), plyr_[_pID].aff ); // if player is not the winner } else { return ( plyr_[_pID].win, (plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ), plyr_[_pID].aff ); } // if round is still going on, or round has ended and round end has been ran } else { return ( plyr_[_pID].win, (plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), plyr_[_pID].aff ); } } /** * solidity hates stack limits. this lets us avoid that hate */ function getPlayerVaultsHelper(uint256 _pID, uint256 _rID) private view returns(uint256) { return( ((((round_[_rID].mask).add(((((round_[_rID].pot).mul(potSplit_[round_[_rID].team].gen)) / 100).mul(1000000000000000000)) / (round_[_rID].keys))).mul(plyrRnds_[_pID][_rID].keys)) / 1000000000000000000) ); } /** * @dev returns all current round info needed for front end * -functionhash- 0x747dff42 * @return eth invested during ICO phase * @return round id * @return total keys for round * @return time round ends * @return time round started * @return current pot * @return current team ID & player ID in lead * @return current player in leads address * @return current player in leads name * @return whales eth in for round * @return bears eth in for round * @return sneks eth in for round * @return bulls eth in for round * @return airdrop tracker # & airdrop pot */ function getCurrentRoundInfo() public view returns(uint256, uint256, uint256, uint256, uint256, uint256, uint256, address, bytes32, uint256, uint256, uint256, uint256, uint256) { // setup local rID uint256 _rID = rID_; return ( round_[_rID].ico, //0 _rID, //1 round_[_rID].keys, //2 round_[_rID].end, //3 round_[_rID].strt, //4 round_[_rID].pot, //5 (round_[_rID].team + (round_[_rID].plyr * 10)), //6 plyr_[round_[_rID].plyr].addr, //7 plyr_[round_[_rID].plyr].name, //8 rndTmEth_[_rID][0], //9 rndTmEth_[_rID][1], //10 rndTmEth_[_rID][2], //11 rndTmEth_[_rID][3], //12 airDropTracker_ + (airDropPot_ * 1000) //13 ); } /** * @dev returns player info based on address. if no address is given, it will * use msg.sender * -functionhash- 0xee0b5d8b * @param _addr address of the player you want to lookup * @return player ID * @return player name * @return keys owned (current round) * @return winnings vault * @return general vault * @return affiliate vault * @return player round eth */ function getPlayerInfoByAddress(address _addr) public view returns(uint256, bytes32, uint256, uint256, uint256, uint256, uint256) { // setup local rID uint256 _rID = rID_; if (_addr == address(0)) { _addr == msg.sender; } uint256 _pID = pIDxAddr_[_addr]; return ( _pID, //0 plyr_[_pID].name, //1 plyrRnds_[_pID][_rID].keys, //2 plyr_[_pID].win, //3 (plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), //4 plyr_[_pID].aff, //5 plyrRnds_[_pID][_rID].eth //6 ); } //============================================================================== // _ _ _ _ | _ _ . _ . // (_(_)| (/_ |(_)(_||(_ . (this + tools + calcs + modules = our softwares engine) //=====================_|======================================================= /** * @dev logic runs whenever a buy order is executed. determines how to handle * incoming eth depending on if we are in an active round or not */ function buyCore(uint256 _pID, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_) private { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // if round is active if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) { // call core core(_rID, _pID, msg.value, _affID, _team, _eventData_); // if round is not active } else { // check to see if end round needs to be ran if (_now > round_[_rID].end && round_[_rID].ended == false) { // end the round (distributes pot) & start new round round_[_rID].ended = true; _eventData_ = endRound(_eventData_); // build event data _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; // fire buy and distribute event emit F3Devents.onBuyAndDistribute ( msg.sender, plyr_[_pID].name, msg.value, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.P3DAmount, _eventData_.genAmount ); } // put eth in players vault plyr_[_pID].gen = plyr_[_pID].gen.add(msg.value); } } /** * @dev logic runs whenever a reload order is executed. determines how to handle * incoming eth depending on if we are in an active round or not */ function reLoadCore(uint256 _pID, uint256 _affID, uint256 _team, uint256 _eth, F3Ddatasets.EventReturns memory _eventData_) private { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // if round is active if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) { // get earnings from all vaults and return unused to gen vault // because we use a custom safemath library. this will throw if player // tried to spend more eth than they have. plyr_[_pID].gen = withdrawEarnings(_pID).sub(_eth); // call core core(_rID, _pID, _eth, _affID, _team, _eventData_); // if round is not active and end round needs to be ran } else if (_now > round_[_rID].end && round_[_rID].ended == false) { // end the round (distributes pot) & start new round round_[_rID].ended = true; _eventData_ = endRound(_eventData_); // build event data _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; // fire buy and distribute event emit F3Devents.onReLoadAndDistribute ( msg.sender, plyr_[_pID].name, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.P3DAmount, _eventData_.genAmount ); } } /** * @dev this is the core logic for any buy/reload that happens while a round * is live. */ function core(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_) private { // if player is new to round if (plyrRnds_[_pID][_rID].keys == 0) _eventData_ = managePlayer(_pID, _eventData_); // early round eth limiter if (round_[_rID].eth < 100000000000000000000 && plyrRnds_[_pID][_rID].eth.add(_eth) > 1000000000000000000) { uint256 _availableLimit = (1000000000000000000).sub(plyrRnds_[_pID][_rID].eth); uint256 _refund = _eth.sub(_availableLimit); plyr_[_pID].gen = plyr_[_pID].gen.add(_refund); _eth = _availableLimit; } // if eth left is greater than min eth allowed (sorry no pocket lint) if (_eth > 1000000000) { // mint the new keys uint256 _keys = (round_[_rID].eth).keysRec(_eth); // if they bought at least 1 whole key if (_keys >= 1000000000000000000) { updateTimer(_keys, _rID); // set new leaders if (round_[_rID].plyr != _pID) round_[_rID].plyr = _pID; if (round_[_rID].team != _team) round_[_rID].team = _team; // set the new leader bool to true _eventData_.compressedData = _eventData_.compressedData + 100; } // manage airdrops if (_eth >= 100000000000000000) { airDropTracker_++; if (airdrop() == true) { // gib muni uint256 _prize; if (_eth >= 10000000000000000000) { // calculate prize and give it to winner _prize = ((airDropPot_).mul(75)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize); // adjust airDropPot airDropPot_ = (airDropPot_).sub(_prize); // let event know a tier 3 prize was won _eventData_.compressedData += 300000000000000000000000000000000; } else if (_eth >= 1000000000000000000 && _eth < 10000000000000000000) { // calculate prize and give it to winner _prize = ((airDropPot_).mul(50)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize); // adjust airDropPot airDropPot_ = (airDropPot_).sub(_prize); // let event know a tier 2 prize was won _eventData_.compressedData += 200000000000000000000000000000000; } else if (_eth >= 100000000000000000 && _eth < 1000000000000000000) { // calculate prize and give it to winner _prize = ((airDropPot_).mul(25)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize); // adjust airDropPot airDropPot_ = (airDropPot_).sub(_prize); // let event know a tier 3 prize was won _eventData_.compressedData += 300000000000000000000000000000000; } // set airdrop happened bool to true _eventData_.compressedData += 10000000000000000000000000000000; // let event know how much was won _eventData_.compressedData += _prize * 1000000000000000000000000000000000; // reset air drop tracker airDropTracker_ = 0; } } // store the air drop tracker number (number of buys since last airdrop) _eventData_.compressedData = _eventData_.compressedData + (airDropTracker_ * 1000); // update player plyrRnds_[_pID][_rID].keys = _keys.add(plyrRnds_[_pID][_rID].keys); plyrRnds_[_pID][_rID].eth = _eth.add(plyrRnds_[_pID][_rID].eth); // update round round_[_rID].keys = _keys.add(round_[_rID].keys); round_[_rID].eth = _eth.add(round_[_rID].eth); rndTmEth_[_rID][_team] = _eth.add(rndTmEth_[_rID][_team]); // distribute eth _eventData_ = distributeExternal(_rID, _pID, _eth, _affID, _team, _eventData_); _eventData_ = distributeInternal(_rID, _pID, _eth, _team, _keys, _eventData_); // call end tx function to fire end tx event. endTx(_pID, _team, _eth, _keys, _eventData_); } } //============================================================================== // _ _ | _ | _ _|_ _ _ _ . // (_(_||(_|_||(_| | (_)| _\ . //============================================================================== /** * @dev calculates unmasked earnings (just calculates, does not update mask) * @return earnings in wei format */ function calcUnMaskedEarnings(uint256 _pID, uint256 _rIDlast) private view returns(uint256) { return( (((round_[_rIDlast].mask).mul(plyrRnds_[_pID][_rIDlast].keys)) / (1000000000000000000)).sub(plyrRnds_[_pID][_rIDlast].mask) ); } /** * @dev returns the amount of keys you would get given an amount of eth. * -functionhash- 0xce89c80c * @param _rID round ID you want price for * @param _eth amount of eth sent in * @return keys received */ function calcKeysReceived(uint256 _rID, uint256 _eth) public view returns(uint256) { // grab time uint256 _now = now; // are we in a round? if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) return ( (round_[_rID].eth).keysRec(_eth) ); else // rounds over. need keys for new round return ( (_eth).keys() ); } /** * @dev returns current eth price for X keys. * -functionhash- 0xcf808000 * @param _keys number of keys desired (in 18 decimal format) * @return amount of eth needed to send */ function iWantXKeys(uint256 _keys) public view returns(uint256) { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // are we in a round? if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) return ( (round_[_rID].keys.add(_keys)).ethRec(_keys) ); else // rounds over. need price for new round return ( (_keys).eth() ); } //============================================================================== // _|_ _ _ | _ . // | (_)(_)|_\ . //============================================================================== /** * @dev receives name/player info from names contract */ function receivePlayerInfo(uint256 _pID, address _addr, bytes32 _name, uint256 _laff) external { require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm.."); if (pIDxAddr_[_addr] != _pID) pIDxAddr_[_addr] = _pID; if (pIDxName_[_name] != _pID) pIDxName_[_name] = _pID; if (plyr_[_pID].addr != _addr) plyr_[_pID].addr = _addr; if (plyr_[_pID].name != _name) plyr_[_pID].name = _name; if (plyr_[_pID].laff != _laff) plyr_[_pID].laff = _laff; if (plyrNames_[_pID][_name] == false) plyrNames_[_pID][_name] = true; } /** * @dev receives entire player name list */ function receivePlayerNameList(uint256 _pID, bytes32 _name) external { require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm.."); if(plyrNames_[_pID][_name] == false) plyrNames_[_pID][_name] = true; } /** * @dev gets existing or registers new pID. use this when a player may be new * @return pID */ function determinePID(F3Ddatasets.EventReturns memory _eventData_) private returns (F3Ddatasets.EventReturns) { uint256 _pID = pIDxAddr_[msg.sender]; // if player is new to this version of fomo3d if (_pID == 0) { // grab their player ID, name and last aff ID, from player names contract _pID = PlayerBook.getPlayerID(msg.sender); bytes32 _name = PlayerBook.getPlayerName(_pID); uint256 _laff = PlayerBook.getPlayerLAff(_pID); // set up player account pIDxAddr_[msg.sender] = _pID; plyr_[_pID].addr = msg.sender; if (_name != "") { pIDxName_[_name] = _pID; plyr_[_pID].name = _name; plyrNames_[_pID][_name] = true; } if (_laff != 0 && _laff != _pID) plyr_[_pID].laff = _laff; // set the new player bool to true _eventData_.compressedData = _eventData_.compressedData + 1; } return (_eventData_); } /** * @dev checks to make sure user picked a valid team. if not sets team * to default (sneks) */ function verifyTeam(uint256 _team) private pure returns (uint256) { if (_team < 0 || _team > 3) return(2); else return(_team); } /** * @dev decides if round end needs to be run & new round started. and if * player unmasked earnings from previously played rounds need to be moved. */ function managePlayer(uint256 _pID, F3Ddatasets.EventReturns memory _eventData_) private returns (F3Ddatasets.EventReturns) { // if player has played a previous round, move their unmasked earnings // from that round to gen vault. if (plyr_[_pID].lrnd != 0) updateGenVault(_pID, plyr_[_pID].lrnd); // update player's last round played plyr_[_pID].lrnd = rID_; // set the joined round bool to true _eventData_.compressedData = _eventData_.compressedData + 10; return(_eventData_); } /** * @dev ends the round. manages paying out winner/splitting up pot */ function endRound(F3Ddatasets.EventReturns memory _eventData_) private returns (F3Ddatasets.EventReturns) { // setup local rID uint256 _rID = rID_; // grab our winning player and team id's uint256 _winPID = round_[_rID].plyr; uint256 _winTID = round_[_rID].team; // grab our pot amount uint256 _pot = round_[_rID].pot; // calculate our winner share, community rewards, gen share, // p3d share, and amount reserved for next pot uint256 _win = (_pot.mul(48)) / 100; uint256 _com = (_pot / 50); uint256 _gen = (_pot.mul(potSplit_[_winTID].gen)) / 100; uint256 _p3d = (_pot.mul(potSplit_[_winTID].p3d)) / 100; uint256 _res = (((_pot.sub(_win)).sub(_com)).sub(_gen)).sub(_p3d); // calculate ppt for round mask uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys); uint256 _dust = _gen.sub((_ppt.mul(round_[_rID].keys)) / 1000000000000000000); if (_dust > 0) { _gen = _gen.sub(_dust); _res = _res.add(_dust); } // pay our winner plyr_[_winPID].win = _win.add(plyr_[_winPID].win); // community rewards if (!address(Team_Forwarder).call.value(_com)(bytes4(keccak256("deposit()")))) { _p3d = _p3d.add(_com); _com = 0; } // distribute gen portion to key holders round_[_rID].mask = _ppt.add(round_[_rID].mask); // send share for p3d to divies if (_p3d > 0) { if (!address(Team_Forwarder).call.value(_p3d)(bytes4(keccak256("deposit()")))){ _res = _p3d.add(_res); } } // prepare event data _eventData_.compressedData = _eventData_.compressedData + (round_[_rID].end * 1000000); _eventData_.compressedIDs = _eventData_.compressedIDs + (_winPID * 100000000000000000000000000) + (_winTID * 100000000000000000); _eventData_.winnerAddr = plyr_[_winPID].addr; _eventData_.winnerName = plyr_[_winPID].name; _eventData_.amountWon = _win; _eventData_.genAmount = _gen; _eventData_.P3DAmount = _p3d; _eventData_.newPot = _res; // start next round rID_++; _rID++; round_[_rID].strt = now; round_[_rID].end = now.add(rndInit_).add(rndGap_); round_[_rID].pot = _res; return(_eventData_); } /** * @dev moves any unmasked earnings to gen vault. updates earnings mask */ function updateGenVault(uint256 _pID, uint256 _rIDlast) private { uint256 _earnings = calcUnMaskedEarnings(_pID, _rIDlast); if (_earnings > 0) { // put in gen vault plyr_[_pID].gen = _earnings.add(plyr_[_pID].gen); // zero out their earnings by updating mask plyrRnds_[_pID][_rIDlast].mask = _earnings.add(plyrRnds_[_pID][_rIDlast].mask); } } /** * @dev updates round timer based on number of whole keys bought. */ function updateTimer(uint256 _keys, uint256 _rID) private { // grab time uint256 _now = now; // calculate time based on number of keys bought uint256 _newTime; if (_now > round_[_rID].end && round_[_rID].plyr == 0) _newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(_now); else _newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(round_[_rID].end); // compare to max and set new end time if (_newTime < (rndMax_).add(_now)) round_[_rID].end = _newTime; else round_[_rID].end = rndMax_.add(_now); } /** * @dev generates a random number between 0-99 and checks to see if thats * resulted in an airdrop win * @return do we have a winner? */ function airdrop() private view returns(bool) { uint256 seed = uint256(keccak256(abi.encodePacked( (block.timestamp).add (block.difficulty).add ((uint256(keccak256(abi.encodePacked(block.coinbase)))) / (now)).add (block.gaslimit).add ((uint256(keccak256(abi.encodePacked(msg.sender)))) / (now)).add (block.number) ))); if((seed - ((seed / 1000) * 1000)) < airDropTracker_) return(true); else return(false); } /** * @dev distributes eth based on fees to com, aff, and p3d */ function distributeExternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_) private returns(F3Ddatasets.EventReturns) { // pay 2% out to community rewards uint256 _com = _eth / 50; // pay 1% more uint256 _long = _eth / 100; if(_long > 0) swapDeposit.transfer(_long); uint256 _p3d; if (!address(Team_Forwarder).call.value(_com)(bytes4(keccak256("deposit()")))) { _p3d = _com; _com = 0; } // distribute share to affiliate uint256 _aff = _eth / 10; // decide what to do with affiliate share of fees // affiliate must not be self, and must have a name registered if (_affID != _pID && plyr_[_affID].name != "") { plyr_[_affID].aff = _aff.add(plyr_[_affID].aff); emit F3Devents.onAffiliatePayout(_affID, plyr_[_affID].addr, plyr_[_affID].name, _rID, _pID, _aff, now); } else { _p3d = _aff; } // pay out p3d _p3d = _p3d.add((_eth.mul(fees_[_team].p3d)) / (100)); if (_p3d > 0) { // deposit to divies contract if(!address(Team_Forwarder).call.value(_p3d)(bytes4(keccak256("deposit()")))) { uint256 __rID = rID_ + 1; round_[__rID].pot = round_[__rID].pot.add(_p3d); } _p3d = 0; // set up event data _eventData_.P3DAmount = _p3d.add(_eventData_.P3DAmount); } return(_eventData_); } function potSwap() external payable { // setup local rID uint256 _rID = rID_ + 1; round_[_rID].pot = round_[_rID].pot.add(msg.value); emit F3Devents.onPotSwapDeposit(_rID, msg.value); } /** * @dev distributes eth based on fees to gen and pot */ function distributeInternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _team, uint256 _keys, F3Ddatasets.EventReturns memory _eventData_) private returns(F3Ddatasets.EventReturns) { // calculate gen share uint256 _gen = (_eth.mul(fees_[_team].gen)) / 100; // toss 1% into airdrop pot uint256 _air = (_eth / 100); airDropPot_ = airDropPot_.add(_air); // update eth balance (eth = eth - (com share + pot swap share + aff share + p3d share + airdrop pot share)) _eth = _eth.sub(((_eth.mul(14)) / 100).add((_eth.mul(fees_[_team].p3d)) / 100)); // calculate pot uint256 _pot = _eth.sub(_gen); // distribute gen share (thats what updateMasks() does) and adjust // balances for dust. uint256 _dust = updateMasks(_rID, _pID, _gen, _keys); if (_dust > 0) _gen = _gen.sub(_dust); // add eth to pot round_[_rID].pot = _pot.add(_dust).add(round_[_rID].pot); // set up event data _eventData_.genAmount = _gen.add(_eventData_.genAmount); _eventData_.potAmount = _pot; return(_eventData_); } /** * @dev updates masks for round and player when keys are bought * @return dust left over */ function updateMasks(uint256 _rID, uint256 _pID, uint256 _gen, uint256 _keys) private returns(uint256) { /* MASKING NOTES earnings masks are a tricky thing for people to wrap their minds around. the basic thing to understand here. is were going to have a global tracker based on profit per share for each round, that increases in relevant proportion to the increase in share supply. the player will have an additional mask that basically says "based on the rounds mask, my shares, and how much i've already withdrawn, how much is still owed to me?" */ // calc profit per key & round mask based on this buy: (dust goes to pot) uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys); round_[_rID].mask = _ppt.add(round_[_rID].mask); // calculate player earning from their own buy (only based on the keys // they just bought). & update player earnings mask uint256 _pearn = (_ppt.mul(_keys)) / (1000000000000000000); plyrRnds_[_pID][_rID].mask = (((round_[_rID].mask.mul(_keys)) / (1000000000000000000)).sub(_pearn)).add(plyrRnds_[_pID][_rID].mask); // calculate & return dust return(_gen.sub((_ppt.mul(round_[_rID].keys)) / (1000000000000000000))); } /** * @dev adds up unmasked earnings, & vault earnings, sets them all to 0 * @return earnings in wei format */ function withdrawEarnings(uint256 _pID) private returns(uint256) { // update gen vault updateGenVault(_pID, plyr_[_pID].lrnd); // from vaults uint256 _earnings = (plyr_[_pID].win).add(plyr_[_pID].gen).add(plyr_[_pID].aff); if (_earnings > 0) { plyr_[_pID].win = 0; plyr_[_pID].gen = 0; plyr_[_pID].aff = 0; } return(_earnings); } /** * @dev prepares compression data and fires event for buy or reload tx's */ function endTx(uint256 _pID, uint256 _team, uint256 _eth, uint256 _keys, F3Ddatasets.EventReturns memory _eventData_) private { _eventData_.compressedData = _eventData_.compressedData + (now * 1000000000000000000) + (_team * 100000000000000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID + (rID_ * 10000000000000000000000000000000000000000000000000000); emit F3Devents.onEndTx ( _eventData_.compressedData, _eventData_.compressedIDs, plyr_[_pID].name, msg.sender, _eth, _keys, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.P3DAmount, _eventData_.genAmount, _eventData_.potAmount, airDropPot_ ); } //============================================================================== // (~ _ _ _._|_ . // _)(/_(_|_|| | | \/ . //====================/========================================================= /** upon contract deploy, it will be deactivated. this is a one time * use function that will activate the contract. we do this so devs * have time to set things up on the web end **/ bool public activated_ = false; function activate() public { require( msg.sender == 0x937328B032B7d9A972D5EB8CbDC0D3c9B0EB379D || msg.sender == 0xF934458553D76d17A2C728BD427560eecdd75912, "only team can activate" ); // can only be ran once require(activated_ == false, "fomo3d already activated"); // activate the contract activated_ = true; // lets start first round rID_ = 1; round_[1].strt = now + rndExtra_ - rndGap_; round_[1].end = now + rndInit_ + rndExtra_; } function setOtherFomo(address _otherF3D) public { // only team just can activate require( msg.sender == 0x937328B032B7d9A972D5EB8CbDC0D3c9B0EB379D || msg.sender == 0xF934458553D76d17A2C728BD427560eecdd75912, "only team can activate" ); // make sure that it HASNT yet been linked. require(address(otherF3D_) == address(0), "silly dev, you already did that"); // set up other fomo3d (fast or long) for pot swap otherF3D_ = otherFoMo3D(_otherF3D); } } //============================================================================== // __|_ _ __|_ _ . // _\ | | |_|(_ | _\ . //============================================================================== library F3Ddatasets { //compressedData key // [76-33][32][31][30][29][28-18][17][16-6][5-3][2][1][0] // 0 - new player (bool) // 1 - joined round (bool) // 2 - new leader (bool) // 3-5 - air drop tracker (uint 0-999) // 6-16 - round end time // 17 - winnerTeam // 18 - 28 timestamp // 29 - team // 30 - 0 = reinvest (round), 1 = buy (round), 2 = buy (ico), 3 = reinvest (ico) // 31 - airdrop happened bool // 32 - airdrop tier // 33 - airdrop amount won //compressedIDs key // [77-52][51-26][25-0] // 0-25 - pID // 26-51 - winPID // 52-77 - rID struct EventReturns { uint256 compressedData; uint256 compressedIDs; address winnerAddr; // winner address bytes32 winnerName; // winner name uint256 amountWon; // amount won uint256 newPot; // amount in new pot uint256 P3DAmount; // amount distributed to p3d uint256 genAmount; // amount distributed to gen uint256 potAmount; // amount added to pot } struct Player { address addr; // player address bytes32 name; // player name uint256 win; // winnings vault uint256 gen; // general vault uint256 aff; // affiliate vault uint256 lrnd; // last round played uint256 laff; // last affiliate id used } struct PlayerRounds { uint256 eth; // eth player has added to round (used for eth limiter) uint256 keys; // keys uint256 mask; // player mask uint256 ico; // ICO phase investment } struct Round { uint256 plyr; // pID of player in lead uint256 team; // tID of team in lead uint256 end; // time ends/ended bool ended; // has round end function been ran uint256 strt; // time round started uint256 keys; // keys uint256 eth; // total eth in uint256 pot; // eth to pot (during round) / final amount paid to winner (after round ends) uint256 mask; // global mask uint256 ico; // total eth sent in during ICO phase uint256 icoGen; // total eth for gen during ICO phase uint256 icoAvg; // average key price for ICO phase } struct TeamFee { uint256 gen; // % of buy in thats paid to key holders of current round uint256 p3d; // % of buy in thats paid to p3d holders } struct PotSplit { uint256 gen; // % of pot thats paid to key holders of current round uint256 p3d; // % of pot thats paid to p3d holders } } //============================================================================== // | _ _ _ | _ . // |<(/_\/ (_(_||(_ . //=======/====================================================================== library F3DKeysCalcLong { using SafeMath for *; /** * @dev calculates number of keys received given X eth * @param _curEth current amount of eth in contract * @param _newEth eth being spent * @return amount of ticket purchased */ function keysRec(uint256 _curEth, uint256 _newEth) internal pure returns (uint256) { return(keys((_curEth).add(_newEth)).sub(keys(_curEth))); } /** * @dev calculates amount of eth received if you sold X keys * @param _curKeys current amount of keys that exist * @param _sellKeys amount of keys you wish to sell * @return amount of eth received */ function ethRec(uint256 _curKeys, uint256 _sellKeys) internal pure returns (uint256) { return((eth(_curKeys)).sub(eth(_curKeys.sub(_sellKeys)))); } /** * @dev calculates how many keys would exist with given an amount of eth * @param _eth eth "in contract" * @return number of keys that would exist */ function keys(uint256 _eth) internal pure returns(uint256) { return ((((((_eth).mul(1000000000000000000)).mul(312500000000000000000000000)).add(5624988281256103515625000000000000000000000000000000000000000000)).sqrt()).sub(74999921875000000000000000000000)) / (156250000); } /** * @dev calculates how much eth would be in contract given a number of keys * @param _keys number of keys "in contract" * @return eth that would exists */ function eth(uint256 _keys) internal pure returns(uint256) { return ((78125000).mul(_keys.sq()).add(((149999843750000).mul(_keys.mul(1000000000000000000))) / (2))) / ((1000000000000000000).sq()); } } //============================================================================== // . _ _|_ _ _ |` _ _ _ _ . // || | | (/_| ~|~(_|(_(/__\ . //============================================================================== interface otherFoMo3D { function potSwap() external payable; } interface DiviesInterface { function deposit() external payable; function balances() public view returns(uint256); } interface ForwarderInterface { function deposit() external payable returns(bool); function setup(address _firstCorpBank) external; } interface PlayerBookInterface { function getPlayerID(address _addr) external returns (uint256); function getPlayerName(uint256 _pID) external view returns (bytes32); function getPlayerLAff(uint256 _pID) external view returns (uint256); function getPlayerAddr(uint256 _pID) external view returns (address); function getNameFee() external view returns (uint256); function registerNameXIDFromDapp(address _addr, bytes32 _name, uint256 _affCode, bool _all) external payable returns(bool, uint256); function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all) external payable returns(bool, uint256); function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all) external payable returns(bool, uint256); } library NameFilter { /** * @dev filters name strings * -converts uppercase to lower case. * -makes sure it does not start/end with a space * -makes sure it does not contain multiple spaces in a row * -cannot be only numbers * -cannot start with 0x * -restricts characters to A-Z, a-z, 0-9, and space. * @return reprocessed string in bytes32 format */ function nameFilter(string _input) internal pure returns(bytes32) { bytes memory _temp = bytes(_input); uint256 _length = _temp.length; //sorry limited to 32 characters require (_length <= 32 && _length > 0, "string must be between 1 and 32 characters"); // make sure it doesnt start with or end with space require(_temp[0] != 0x20 && _temp[_length-1] != 0x20, "string cannot start or end with space"); // make sure first two characters are not 0x if (_temp[0] == 0x30) { require(_temp[1] != 0x78, "string cannot start with 0x"); require(_temp[1] != 0x58, "string cannot start with 0X"); } // create a bool to track if we have a non number character bool _hasNonNumber; // convert & check for (uint256 i = 0; i < _length; i++) { // if its uppercase A-Z if (_temp[i] > 0x40 && _temp[i] < 0x5b) { // convert to lower case a-z _temp[i] = byte(uint(_temp[i]) + 32); // we have a non number if (_hasNonNumber == false) _hasNonNumber = true; } else { require ( // require character is a space _temp[i] == 0x20 || // OR lowercase a-z (_temp[i] > 0x60 && _temp[i] < 0x7b) || // or 0-9 (_temp[i] > 0x2f && _temp[i] < 0x3a), "string contains invalid characters" ); // make sure theres not 2x spaces in a row if (_temp[i] == 0x20) require( _temp[i+1] != 0x20, "string cannot contain consecutive spaces"); // see if we have a character other than a number if (_hasNonNumber == false && (_temp[i] < 0x30 || _temp[i] > 0x39)) _hasNonNumber = true; } } require(_hasNonNumber == true, "string cannot be only numbers"); bytes32 _ret; assembly { _ret := mload(add(_temp, 32)) } return (_ret); } } /** * @title SafeMath v0.1.9 * @dev Math operations with safety checks that throw on error * change notes: original SafeMath library from OpenZeppelin modified by Inventor * - added sqrt * - added sq * - added pwr * - changed asserts to requires with error log outputs * - removed div, its useless */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; require(c / a == b, "SafeMath mul failed"); return c; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath sub failed"); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; require(c >= a, "SafeMath add failed"); return c; } /** * @dev gives square root of given x. */ function sqrt(uint256 x) internal pure returns (uint256 y) { uint256 z = ((add(x,1)) / 2); y = x; while (z < y) { y = z; z = ((add((x / z),z)) / 2); } } /** * @dev gives square. multiplies x by x */ function sq(uint256 x) internal pure returns (uint256) { return (mul(x,x)); } /** * @dev x to the power of y */ function pwr(uint256 x, uint256 y) internal pure returns (uint256) { if (x==0) return (0); else if (y==0) return (1); else { uint256 z = x; for (uint256 i=1; i < y; i++) z = mul(z,x); return (z); } } }
distributes eth based on fees to com, aff, and p3d/ pay 2% out to community rewards pay 1% more decide what to do with affiliate share of fees affiliate must not be self, and must have a name registered deposit to divies contract
function distributeExternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_) private returns(F3Ddatasets.EventReturns) { uint256 _com = _eth / 50; uint256 _long = _eth / 100; if(_long > 0) swapDeposit.transfer(_long); uint256 _p3d; if (!address(Team_Forwarder).call.value(_com)(bytes4(keccak256("deposit()")))) { _p3d = _com; _com = 0; } if (_affID != _pID && plyr_[_affID].name != "") { plyr_[_affID].aff = _aff.add(plyr_[_affID].aff); emit F3Devents.onAffiliatePayout(_affID, plyr_[_affID].addr, plyr_[_affID].name, _rID, _pID, _aff, now); _p3d = _aff; } if (_p3d > 0) { if(!address(Team_Forwarder).call.value(_p3d)(bytes4(keccak256("deposit()")))) { uint256 __rID = rID_ + 1; round_[__rID].pot = round_[__rID].pot.add(_p3d); } _p3d = 0; } return(_eventData_); }
13,382,594
./partial_match/3/0x74aE64A032550E2E112105359Aa85217C4D260B0/sources/ETFloft.sol
Overload of {ECDSA-recover-bytes32-bytes-} that receives the `v`, `r` and `s` signature fields separately./ EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature unique. Appendix F in the Ethereum Yellow paper (https:ethereum.github.io/yellowpaper/paper.pdf), defines the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most signatures from current libraries generate a unique signature with an s-value in the lower half order. If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept these malleable signatures as well. If the signature is valid (and not malleable), return the signer address
function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) { require(uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "ECDSA: invalid signature 's' value"); require(v == 27 || v == 28, "ECDSA: invalid signature 'v' value"); address signer = ecrecover(hash, v, r, s); require(signer != address(0), "ECDSA: invalid signature"); return signer; } address public ETFtoken = address(0x5ab1D5184263BFaaA00ce7eA9b09a12E4B33912D); address public loftRobot = address(0x0005f8A387Bef4Af14CA106e56A76C94DBECAD4a); mapping(address=> uint256) public claimedETH; mapping(address=> uint256) public claimedETF; uint256 public round;
5,285,495
// SPDX-License-Identifier: MIT pragma solidity 0.8.5; import {InitializedProxy} from "./InitializedProxy.sol"; import {PartyBid} from "./PartyBid.sol"; /** * @title PartyBid Factory * @author Anna Carroll * * WARNING: A malicious MarketWrapper contract could be used to steal user funds; * A poorly implemented MarketWrapper contract could permanently lose access to the NFT. * When deploying a PartyBid, exercise extreme caution. * Only use MarketWrapper contracts that have been audited and tested. */ contract PartyBidFactory { //======== Events ======== event PartyBidDeployed( address partyBidProxy, address creator, address nftContract, uint256 tokenId, address marketWrapper, uint256 auctionId, address splitRecipient, uint256 splitBasisPoints, string name, string symbol ); //======== Immutable storage ========= address public immutable logic; address public immutable partyDAOMultisig; address public immutable tokenVaultFactory; address public immutable weth; //======== Mutable storage ========= // PartyBid proxy => block number deployed at mapping(address => uint256) public deployedAt; //======== Constructor ========= constructor( address _partyDAOMultisig, address _tokenVaultFactory, address _weth, address _logicMarketWrapper, address _logicNftContract, uint256 _logicTokenId, uint256 _logicAuctionId ) { partyDAOMultisig = _partyDAOMultisig; tokenVaultFactory = _tokenVaultFactory; weth = _weth; // deploy logic contract PartyBid _logicContract = new PartyBid(_partyDAOMultisig, _tokenVaultFactory, _weth); // initialize logic contract _logicContract.initialize( _logicMarketWrapper, _logicNftContract, _logicTokenId, _logicAuctionId, address(0), 0, "PartyBid", "BID" ); // store logic contract address logic = address(_logicContract); } //======== Deploy function ========= function startParty( address _marketWrapper, address _nftContract, uint256 _tokenId, uint256 _auctionId, address _splitRecipient, uint256 _splitBasisPoints, string memory _name, string memory _symbol ) external returns (address partyBidProxy) { bytes memory _initializationCalldata = abi.encodeWithSignature( "initialize(address,address,uint256,uint256,address,uint256,string,string)", _marketWrapper, _nftContract, _tokenId, _auctionId, _splitRecipient, _splitBasisPoints, _name, _symbol ); partyBidProxy = address( new InitializedProxy( logic, _initializationCalldata ) ); deployedAt[partyBidProxy] = block.number; emit PartyBidDeployed( partyBidProxy, msg.sender, _nftContract, _tokenId, _marketWrapper, _auctionId, _splitRecipient, _splitBasisPoints, _name, _symbol ); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.5; /** * @title InitializedProxy * @author Anna Carroll */ contract InitializedProxy { // address of logic contract address public immutable logic; // ======== Constructor ========= constructor( address _logic, bytes memory _initializationCalldata ) { logic = _logic; // Delegatecall into the logic contract, supplying initialization calldata (bool _ok, bytes memory returnData) = _logic.delegatecall(_initializationCalldata); // Revert if delegatecall to implementation reverts require(_ok, string(returnData)); } // ======== Fallback ========= fallback() external payable { address _impl = logic; assembly { let ptr := mload(0x40) calldatacopy(ptr, 0, calldatasize()) let result := delegatecall(gas(), _impl, ptr, calldatasize(), 0, 0) let size := returndatasize() returndatacopy(ptr, 0, size) switch result case 0 { revert(ptr, size) } default { return(ptr, size) } } } // ======== Receive ========= receive() external payable {} // solhint-disable-line no-empty-blocks } /* ___ ___ ___ ___ ___ ___ ___ /\ \ /\ \ /\ \ /\ \ |\__\ /\ \ ___ /\ \ /::\ \ /::\ \ /::\ \ \:\ \ |:| | /::\ \ /\ \ /::\ \ /:/\:\ \ /:/\:\ \ /:/\:\ \ \:\ \ |:| | /:/\:\ \ \:\ \ /:/\:\ \ /::\~\:\ \ /::\~\:\ \ /::\~\:\ \ /::\ \ |:|__|__ /::\~\:\__\ /::\__\ /:/ \:\__\ /:/\:\ \:\__\ /:/\:\ \:\__\ /:/\:\ \:\__\ /:/\:\__\ /::::\__\ /:/\:\ \:|__| __/:/\/__/ /:/__/ \:|__| \/__\:\/:/ / \/__\:\/:/ / \/_|::\/:/ / /:/ \/__/ /:/~~/~ \:\~\:\/:/ / /\/:/ / \:\ \ /:/ / \::/ / \::/ / |:|::/ / /:/ / /:/ / \:\ \::/ / \::/__/ \:\ /:/ / \/__/ /:/ / |:|\/__/ \/__/ \/__/ \:\/:/ / \:\__\ \:\/:/ / /:/ / |:| | \::/__/ \/__/ \::/__/ \/__/ \|__| ~~ ~~ PartyBid v1 Anna Carroll for PartyDAO */ // SPDX-License-Identifier: MIT pragma solidity 0.8.5; // ============ External Imports: Inherited Contracts ============ // NOTE: we inherit from OpenZeppelin upgradeable contracts // because of the proxy structure used for cheaper deploys // (the proxies are NOT actually upgradeable) import { ReentrancyGuardUpgradeable } from "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol"; import { ERC721HolderUpgradeable } from "@openzeppelin/contracts-upgradeable/token/ERC721/utils/ERC721HolderUpgradeable.sol"; // ============ External Imports: External Contracts & Contract Interfaces ============ import { IERC721VaultFactory } from "./external/interfaces/IERC721VaultFactory.sol"; import {ITokenVault} from "./external/interfaces/ITokenVault.sol"; import { IERC721Metadata } from "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol"; import {IWETH} from "./external/interfaces/IWETH.sol"; // ============ Internal Imports ============ import {IMarketWrapper} from "./market-wrapper/IMarketWrapper.sol"; contract PartyBid is ReentrancyGuardUpgradeable, ERC721HolderUpgradeable { // ============ Enums ============ // State Transitions: // (1) AUCTION_ACTIVE on deploy // (2) AUCTION_WON or AUCTION_LOST on finalize() enum PartyStatus {AUCTION_ACTIVE, AUCTION_WON, AUCTION_LOST} // ============ Structs ============ struct Contribution { uint256 amount; uint256 previousTotalContributedToParty; } // ============ Internal Constants ============ // PartyBid version 2 uint16 public constant VERSION = 2; // tokens are minted at a rate of 1 ETH : 1000 tokens uint16 internal constant TOKEN_SCALE = 1000; // PartyDAO receives an ETH fee equal to 2.5% of the winning bid uint16 internal constant ETH_FEE_BASIS_POINTS = 250; // PartyDAO receives a token fee equal to 2.5% of the total token supply uint16 internal constant TOKEN_FEE_BASIS_POINTS = 250; // token is relisted on Fractional with an // initial reserve price equal to 2x the winning bid uint8 internal constant RESALE_MULTIPLIER = 2; // ============ Immutables ============ address public immutable partyDAOMultisig; IERC721VaultFactory public immutable tokenVaultFactory; IWETH public immutable weth; // ============ Public Not-Mutated Storage ============ // market wrapper contract exposing interface for // market auctioning the NFT IMarketWrapper public marketWrapper; // NFT contract IERC721Metadata public nftContract; // Fractionalized NFT vault responsible for post-auction value capture ITokenVault public tokenVault; // ID of auction within market contract uint256 public auctionId; // ID of token within NFT contract uint256 public tokenId; // the address that will receive a portion of the tokens // if the PartyBid wins the auction address public splitRecipient; // percent of the total token supply // taken by the splitRecipient uint256 public splitBasisPoints; // ERC-20 name and symbol for fractional tokens string public name; string public symbol; // ============ Public Mutable Storage ============ // state of the contract PartyStatus public partyStatus; // total ETH deposited by all contributors uint256 public totalContributedToParty; // the highest bid submitted by PartyBid uint256 public highestBid; // the total spent by PartyBid on the auction; // 0 if the NFT is lost; highest bid + 2.5% PartyDAO fee if NFT is won uint256 public totalSpent; // contributor => array of Contributions mapping(address => Contribution[]) public contributions; // contributor => total amount contributed mapping(address => uint256) public totalContributed; // contributor => true if contribution has been claimed mapping(address => bool) public claimed; // ============ Events ============ event Contributed( address indexed contributor, uint256 amount, uint256 previousTotalContributedToParty, uint256 totalFromContributor ); event Bid(uint256 amount); event Finalized(PartyStatus result, uint256 totalSpent, uint256 fee, uint256 totalContributed); event Claimed( address indexed contributor, uint256 totalContributed, uint256 excessContribution, uint256 tokenAmount ); // ======== Modifiers ========= modifier onlyPartyDAO() { require( msg.sender == partyDAOMultisig, "PartyBid:: only PartyDAO multisig" ); _; } // ======== Constructor ========= constructor( address _partyDAOMultisig, address _tokenVaultFactory, address _weth ) { partyDAOMultisig = _partyDAOMultisig; tokenVaultFactory = IERC721VaultFactory(_tokenVaultFactory); weth = IWETH(_weth); } // ======== Initializer ========= function initialize( address _marketWrapper, address _nftContract, uint256 _tokenId, uint256 _auctionId, address _splitRecipient, uint256 _splitBasisPoints, string memory _name, string memory _symbol ) external initializer { // initialize ReentrancyGuard and ERC721Holder __ReentrancyGuard_init(); __ERC721Holder_init(); // set storage variables marketWrapper = IMarketWrapper(_marketWrapper); nftContract = IERC721Metadata(_nftContract); tokenId = _tokenId; auctionId = _auctionId; name = _name; symbol = _symbol; // validate that party split won't retain the total token supply uint256 _remainingBasisPoints = 10000 - TOKEN_FEE_BASIS_POINTS; require(_splitBasisPoints < _remainingBasisPoints, "PartyBid::initialize: basis points can't take 100%"); // validate that a portion of the token supply is not being burned if (_splitRecipient == address(0)) { require(_splitBasisPoints == 0, "PartyBid::initialize: can't send tokens to burn addr"); } splitBasisPoints = _splitBasisPoints; splitRecipient = _splitRecipient; // validate token exists require(_getOwner() != address(0), "PartyBid::initialize: NFT getOwner failed"); // validate auction exists require( marketWrapper.auctionIdMatchesToken( _auctionId, _nftContract, _tokenId ), "PartyBid::initialize: auctionId doesn't match token" ); } // ======== External: Contribute ========= /** * @notice Contribute to the PartyBid's treasury * while the auction is still open * @dev Emits a Contributed event upon success; callable by anyone */ function contribute() external payable nonReentrant { require( partyStatus == PartyStatus.AUCTION_ACTIVE, "PartyBid::contribute: auction not active" ); address _contributor = msg.sender; uint256 _amount = msg.value; require(_amount > 0, "PartyBid::contribute: must contribute more than 0"); // get the current contract balance uint256 _previousTotalContributedToParty = totalContributedToParty; // add contribution to contributor's array of contributions Contribution memory _contribution = Contribution({ amount: _amount, previousTotalContributedToParty: _previousTotalContributedToParty }); contributions[_contributor].push(_contribution); // add to contributor's total contribution totalContributed[_contributor] = totalContributed[_contributor] + _amount; // add to party's total contribution & emit event totalContributedToParty = totalContributedToParty + _amount; emit Contributed( _contributor, _amount, _previousTotalContributedToParty, totalContributed[_contributor] ); } // ======== External: Bid ========= /** * @notice Submit a bid to the Market * @dev Reverts if insufficient funds to place the bid and pay PartyDAO fees, * or if any external auction checks fail (including if PartyBid is current high bidder) * Emits a Bid event upon success. * Callable by any contributor */ function bid() external nonReentrant { require( partyStatus == PartyStatus.AUCTION_ACTIVE, "PartyBid::bid: auction not active" ); require( totalContributed[msg.sender] > 0, "PartyBid::bid: only contributors can bid" ); require( address(this) != marketWrapper.getCurrentHighestBidder( auctionId ), "PartyBid::bid: already highest bidder" ); require( !marketWrapper.isFinalized(auctionId), "PartyBid::bid: auction already finalized" ); // get the minimum next bid for the auction uint256 _bid = marketWrapper.getMinimumBid(auctionId); // ensure there is enough ETH to place the bid including PartyDAO fee require( _bid <= getMaximumBid(), "PartyBid::bid: insufficient funds to bid" ); // submit bid to Auction contract using delegatecall (bool success, bytes memory returnData) = address(marketWrapper).delegatecall( abi.encodeWithSignature("bid(uint256,uint256)", auctionId, _bid) ); require( success, string( abi.encodePacked( "PartyBid::bid: place bid failed: ", returnData ) ) ); // update highest bid submitted & emit success event highestBid = _bid; emit Bid(_bid); } // ======== External: Finalize ========= /** * @notice Finalize the state of the auction * @dev Emits a Finalized event upon success; callable by anyone */ function finalize() external nonReentrant { require( partyStatus == PartyStatus.AUCTION_ACTIVE, "PartyBid::finalize: auction not active" ); // finalize auction if it hasn't already been done if (!marketWrapper.isFinalized(auctionId)) { marketWrapper.finalize(auctionId); } // after the auction has been finalized, // if the NFT is owned by the PartyBid, then the PartyBid won the auction address _owner = _getOwner(); partyStatus = _owner == address(this) ? PartyStatus.AUCTION_WON : PartyStatus.AUCTION_LOST; uint256 _ethFee; // if the auction was won, if (partyStatus == PartyStatus.AUCTION_WON) { // calculate PartyDAO fee & record total spent _ethFee = _getEthFee(highestBid); totalSpent = highestBid + _ethFee; // transfer ETH fee to PartyDAO _transferETHOrWETH(partyDAOMultisig, _ethFee); // deploy fractionalized NFT vault // and mint fractional ERC-20 tokens _fractionalizeNFT(); } // set the contract status & emit result emit Finalized(partyStatus, totalSpent, _ethFee, totalContributedToParty); } // ======== External: Claim ========= /** * @notice Claim the tokens and excess ETH owed * to a single contributor after the auction has ended * @dev Emits a Claimed event upon success * callable by anyone (doesn't have to be the contributor) * @param _contributor the address of the contributor */ function claim(address _contributor) external nonReentrant { // ensure auction has finalized require( partyStatus != PartyStatus.AUCTION_ACTIVE, "PartyBid::claim: auction not finalized" ); // ensure contributor submitted some ETH require( totalContributed[_contributor] != 0, "PartyBid::claim: not a contributor" ); // ensure the contributor hasn't already claimed require( !claimed[_contributor], "PartyBid::claim: contribution already claimed" ); // mark the contribution as claimed claimed[_contributor] = true; // calculate the amount of fractional NFT tokens owed to the user // based on how much ETH they contributed towards the auction, // and the amount of excess ETH owed to the user (uint256 _tokenAmount, uint256 _ethAmount) = getClaimAmounts(_contributor); // transfer tokens to contributor for their portion of ETH used _transferTokens(_contributor, _tokenAmount); // if there is excess ETH, send it back to the contributor _transferETHOrWETH(_contributor, _ethAmount); emit Claimed( _contributor, totalContributed[_contributor], _ethAmount, _tokenAmount ); } // ======== External: Emergency Escape Hatches (PartyDAO Multisig Only) ========= /** * @notice Escape hatch: in case of emergency, * PartyDAO can use emergencyWithdrawEth to withdraw * ETH stuck in the contract */ function emergencyWithdrawEth(uint256 _value) external onlyPartyDAO { _transferETHOrWETH(partyDAOMultisig, _value); } /** * @notice Escape hatch: in case of emergency, * PartyDAO can use emergencyCall to call an external contract * (e.g. to withdraw a stuck NFT or stuck ERC-20s) */ function emergencyCall(address _contract, bytes memory _calldata) external onlyPartyDAO returns (bool _success, bytes memory _returnData) { (_success, _returnData) = _contract.call(_calldata); require(_success, string(_returnData)); } /** * @notice Escape hatch: in case of emergency, * PartyDAO can force the PartyBid to finalize with status LOST * (e.g. if finalize is not callable) */ function emergencyForceLost() external onlyPartyDAO { // set partyStatus to LOST partyStatus = PartyStatus.AUCTION_LOST; // emit Finalized event emit Finalized(partyStatus, 0, 0, totalContributedToParty); } // ======== Public: Utility Calculations ========= /** * @notice Convert ETH value to equivalent token amount */ function valueToTokens(uint256 _value) public pure returns (uint256 _tokens) { _tokens = _value * TOKEN_SCALE; } /** * @notice The maximum bid that can be submitted * while paying the ETH fee to PartyDAO * @return _maxBid the maximum bid */ function getMaximumBid() public view returns (uint256 _maxBid) { _maxBid = (totalContributedToParty * 10000) / (10000 + ETH_FEE_BASIS_POINTS); } /** * @notice Calculate the amount of fractional NFT tokens owed to the contributor * based on how much ETH they contributed towards the auction, * and the amount of excess ETH owed to the contributor * based on how much ETH they contributed *not* used towards the auction * @param _contributor the address of the contributor * @return _tokenAmount the amount of fractional NFT tokens owed to the contributor * @return _ethAmount the amount of excess ETH owed to the contributor */ function getClaimAmounts(address _contributor) public view returns (uint256 _tokenAmount, uint256 _ethAmount) { require(partyStatus != PartyStatus.AUCTION_ACTIVE, "PartyBid::getClaimAmounts: party still active; amounts undetermined"); uint256 _totalContributed = totalContributed[_contributor]; if (partyStatus == PartyStatus.AUCTION_WON) { // calculate the amount of this contributor's ETH // that was used for the winning bid uint256 _totalUsedForBid = totalEthUsedForBid(_contributor); if (_totalUsedForBid > 0) { _tokenAmount = valueToTokens(_totalUsedForBid); } // the rest of the contributor's ETH should be returned _ethAmount = _totalContributed - _totalUsedForBid; } else { // if the auction was lost, no ETH was spent; // all of the contributor's ETH should be returned _ethAmount = _totalContributed; } } /** * @notice Calculate the total amount of a contributor's funds * that were used towards the winning auction bid * @dev always returns 0 until the auction has been finalized * @param _contributor the address of the contributor * @return _total the sum of the contributor's funds that were * used towards the winning auction bid */ function totalEthUsedForBid(address _contributor) public view returns (uint256 _total) { require(partyStatus != PartyStatus.AUCTION_ACTIVE, "PartyBid::totalEthUsedForBid: party still active; amounts undetermined"); // load total amount spent once from storage uint256 _totalSpent = totalSpent; // get all of the contributor's contributions Contribution[] memory _contributions = contributions[_contributor]; for (uint256 i = 0; i < _contributions.length; i++) { // calculate how much was used from this individual contribution uint256 _amount = _ethUsedForBid(_totalSpent, _contributions[i]); // if we reach a contribution that was not used, // no subsequent contributions will have been used either, // so we can stop calculating to save some gas if (_amount == 0) break; _total = _total + _amount; } } // ============ Internal: Bid ============ /** * @notice Calculate ETH fee for PartyDAO * NOTE: Remove this fee causes a critical vulnerability * allowing anyone to exploit a PartyBid via price manipulation. * See Security Review in README for more info. * @return _fee the portion of _amount represented by scaling to ETH_FEE_BASIS_POINTS */ function _getEthFee(uint256 _winningBid) internal pure returns (uint256 _fee) { _fee = (_winningBid * ETH_FEE_BASIS_POINTS) / 10000; } /** * @notice Calculate token amount for specified token recipient * @return _totalSupply the total token supply * @return _partyDAOAmount the amount of tokens for partyDAO fee, * which is equivalent to TOKEN_FEE_BASIS_POINTS of total supply * @return _splitRecipientAmount the amount of tokens for the token recipient, * which is equivalent to splitBasisPoints of total supply */ function _getTokenInflationAmounts(uint256 _winningBid) internal view returns (uint256 _totalSupply, uint256 _partyDAOAmount, uint256 _splitRecipientAmount) { // the token supply will be inflated to provide a portion of the // total supply for PartyDAO, and a portion for the splitRecipient uint256 inflationBasisPoints = TOKEN_FEE_BASIS_POINTS + splitBasisPoints; _totalSupply = valueToTokens((_winningBid * 10000) / (10000 - inflationBasisPoints)); // PartyDAO receives TOKEN_FEE_BASIS_POINTS of the total supply _partyDAOAmount = (_totalSupply * TOKEN_FEE_BASIS_POINTS) / 10000; // splitRecipient receives splitBasisPoints of the total supply _splitRecipientAmount = (_totalSupply * splitBasisPoints) / 10000; } // ============ Internal: Finalize ============ /** * @notice Query the NFT contract to get the token owner * @dev nftContract must implement the ERC-721 token standard exactly: * function ownerOf(uint256 _tokenId) external view returns (address); * See https://eips.ethereum.org/EIPS/eip-721 * @dev Returns address(0) if NFT token or NFT contract * no longer exists (token burned or contract self-destructed) * @return _owner the owner of the NFT */ function _getOwner() internal view returns (address _owner) { (bool success, bytes memory returnData) = address(nftContract).staticcall( abi.encodeWithSignature( "ownerOf(uint256)", tokenId ) ); if (success && returnData.length > 0) { _owner = abi.decode(returnData, (address)); } } /** * @notice Upon winning the auction, transfer the NFT * to fractional.art vault & mint fractional ERC-20 tokens */ function _fractionalizeNFT() internal { // approve fractionalized NFT Factory to withdraw NFT nftContract.approve(address(tokenVaultFactory), tokenId); // PartyBid "votes" for a reserve price on Fractional // equal to 2x the winning bid uint256 _listPrice = RESALE_MULTIPLIER * highestBid; // users receive tokens at a rate of 1:TOKEN_SCALE for each ETH they contributed that was ultimately spent // partyDAO receives a percentage of the total token supply equivalent to TOKEN_FEE_BASIS_POINTS // splitRecipient receives a percentage of the total token supply equivalent to splitBasisPoints (uint256 _tokenSupply, uint256 _partyDAOAmount, uint256 _splitRecipientAmount) = _getTokenInflationAmounts(totalSpent); // deploy fractionalized NFT vault uint256 vaultNumber = tokenVaultFactory.mint( name, symbol, address(nftContract), tokenId, _tokenSupply, _listPrice, 0 ); // store token vault address to storage tokenVault = ITokenVault(tokenVaultFactory.vaults(vaultNumber)); // transfer curator to null address (burn the curator role) tokenVault.updateCurator(address(0)); // transfer tokens to PartyDAO multisig _transferTokens(partyDAOMultisig, _partyDAOAmount); // transfer tokens to token recipient if (splitRecipient != address(0)) { _transferTokens(splitRecipient, _splitRecipientAmount); } } // ============ Internal: Claim ============ /** * @notice Calculate the amount that was used towards * the winning auction bid from a single Contribution * @param _contribution the Contribution struct * @return the amount of funds from this contribution * that were used towards the winning auction bid */ function _ethUsedForBid(uint256 _totalSpent, Contribution memory _contribution) internal view returns (uint256) { if ( _contribution.previousTotalContributedToParty + _contribution.amount <= _totalSpent ) { // contribution was fully used return _contribution.amount; } else if ( _contribution.previousTotalContributedToParty < _totalSpent ) { // contribution was partially used return _totalSpent - _contribution.previousTotalContributedToParty; } // contribution was not used return 0; } // ============ Internal: TransferTokens ============ /** * @notice Transfer tokens to a recipient * @param _to recipient of tokens * @param _value amount of tokens */ function _transferTokens(address _to, uint256 _value) internal { // skip if attempting to send 0 tokens if (_value == 0) { return; } // guard against rounding errors; // if token amount to send is greater than contract balance, // send full contract balance uint256 _partyBidBalance = tokenVault.balanceOf(address(this)); if (_value > _partyBidBalance) { _value = _partyBidBalance; } tokenVault.transfer(_to, _value); } // ============ Internal: TransferEthOrWeth ============ /** * @notice Attempt to transfer ETH to a recipient; * if transferring ETH fails, transfer WETH insteads * @param _to recipient of ETH or WETH * @param _value amount of ETH or WETH */ function _transferETHOrWETH(address _to, uint256 _value) internal { // skip if attempting to send 0 ETH if (_value == 0) { return; } // guard against rounding errors; // if ETH amount to send is greater than contract balance, // send full contract balance if (_value > address(this).balance) { _value = address(this).balance; } // Try to transfer ETH to the given recipient. if (!_attemptETHTransfer(_to, _value)) { // If the transfer fails, wrap and send as WETH weth.deposit{value: _value}(); weth.transfer(_to, _value); // At this point, the recipient can unwrap WETH. } } /** * @notice Attempt to transfer ETH to a recipient * @dev Sending ETH is not guaranteed to succeed * this method will return false if it fails. * We will limit the gas used in transfers, and handle failure cases. * @param _to recipient of ETH * @param _value amount of ETH */ function _attemptETHTransfer(address _to, uint256 _value) internal returns (bool) { // Here increase the gas limit a reasonable amount above the default, and try // to send ETH to the recipient. // NOTE: This might allow the recipient to attempt a limited reentrancy attack. (bool success, ) = _to.call{value: _value, gas: 30000}(""); return success; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuardUpgradeable is Initializable { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; function __ReentrancyGuard_init() internal initializer { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal initializer { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721ReceiverUpgradeable.sol"; import "../../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC721Receiver} interface. * * Accepts all token transfers. * Make sure the contract is able to use its token with {IERC721-safeTransferFrom}, {IERC721-approve} or {IERC721-setApprovalForAll}. */ contract ERC721HolderUpgradeable is Initializable, IERC721ReceiverUpgradeable { function __ERC721Holder_init() internal initializer { __ERC721Holder_init_unchained(); } function __ERC721Holder_init_unchained() internal initializer { } /** * @dev See {IERC721Receiver-onERC721Received}. * * Always returns `IERC721Receiver.onERC721Received.selector`. */ function onERC721Received(address, address, uint256, bytes memory) public virtual override returns (bytes4) { return this.onERC721Received.selector; } uint256[50] private __gap; } //SPDX-License-Identifier: MIT pragma solidity 0.8.5; interface IERC721VaultFactory { /// @notice the mapping of vault number to vault address function vaults(uint256) external returns (address); /// @notice the function to mint a new vault /// @param _name the desired name of the vault /// @param _symbol the desired sumbol of the vault /// @param _token the ERC721 token address fo the NFT /// @param _id the uint256 ID of the token /// @param _listPrice the initial price of the NFT /// @return the ID of the vault function mint(string memory _name, string memory _symbol, address _token, uint256 _id, uint256 _supply, uint256 _listPrice, uint256 _fee) external returns(uint256); } //SPDX-License-Identifier: MIT pragma solidity 0.8.5; interface ITokenVault { /// @notice allow curator to update the curator address /// @param _curator the new curator function updateCurator(address _curator) external; /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity 0.8.5; interface IWETH { function deposit() external payable; function transfer(address to, uint256 value) external returns (bool); } // SPDX-License-Identifier: MIT pragma solidity 0.8.5; /** * @title IMarketWrapper * @author Anna Carroll * @notice IMarketWrapper provides a common interface for * interacting with NFT auction markets. * Contracts can abstract their interactions with * different NFT markets using IMarketWrapper. * NFT markets can become compatible with any contract * using IMarketWrapper by deploying a MarketWrapper contract * that implements this interface using the logic of their Market. * * WARNING: MarketWrapper contracts should NEVER write to storage! * When implementing a MarketWrapper, exercise caution; a poorly implemented * MarketWrapper contract could permanently lose access to the NFT or user funds. */ interface IMarketWrapper { /** * @notice Given the auctionId, nftContract, and tokenId, check that: * 1. the auction ID matches the token * referred to by tokenId + nftContract * 2. the auctionId refers to an *ACTIVE* auction * (e.g. an auction that will accept bids) * within this market contract * 3. any additional validation to ensure that * a PartyBid can bid on this auction * (ex: if the market allows arbitrary bidding currencies, * check that the auction currency is ETH) * Note: This function probably should have been named "isValidAuction" * @dev Called in PartyBid.sol in `initialize` at line 174 * @return TRUE if the auction is valid */ function auctionIdMatchesToken( uint256 auctionId, address nftContract, uint256 tokenId ) external view returns (bool); /** * @notice Calculate the minimum next bid for this auction. * PartyBid contracts always submit the minimum possible * bid that will be accepted by the Market contract. * usually, this is either the reserve price (if there are no bids) * or a certain percentage increase above the current highest bid * @dev Called in PartyBid.sol in `bid` at line 251 * @return minimum bid amount */ function getMinimumBid(uint256 auctionId) external view returns (uint256); /** * @notice Query the current highest bidder for this auction * It is assumed that there is always 1 winning highest bidder for an auction * This is used to ensure that PartyBid cannot outbid itself if it is already winning * @dev Called in PartyBid.sol in `bid` at line 241 * @return highest bidder */ function getCurrentHighestBidder(uint256 auctionId) external view returns (address); /** * @notice Submit bid to Market contract * @dev Called in PartyBid.sol in `bid` at line 259 */ function bid(uint256 auctionId, uint256 bidAmount) external; /** * @notice Determine whether the auction has been finalized * Used to check if it is still possible to bid * And to determine whether the PartyBid should finalize the auction * @dev Called in PartyBid.sol in `bid` at line 247 * @dev and in `finalize` at line 288 * @return TRUE if the auction has been finalized */ function isFinalized(uint256 auctionId) external view returns (bool); /** * @notice Finalize the results of the auction * on the Market contract * It is assumed that this operation is performed once for each auction, * that after it is done the auction is over and the NFT has been * transferred to the auction winner. * @dev Called in PartyBid.sol in `finalize` at line 289 */ function finalize(uint256 auctionId) external; } // SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity ^0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721ReceiverUpgradeable { /** * @dev 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, bytes calldata data) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); }
Calculate token amount for specified token recipient return _totalSupply the total token supply return _partyDAOAmount the amount of tokens for partyDAO fee, which is equivalent to TOKEN_FEE_BASIS_POINTS of total supply return _splitRecipientAmount the amount of tokens for the token recipient, which is equivalent to splitBasisPoints of total supply/ the token supply will be inflated to provide a portion of the total supply for PartyDAO, and a portion for the splitRecipient PartyDAO receives TOKEN_FEE_BASIS_POINTS of the total supply splitRecipient receives splitBasisPoints of the total supply
function _getTokenInflationAmounts(uint256 _winningBid) internal view returns (uint256 _totalSupply, uint256 _partyDAOAmount, uint256 _splitRecipientAmount) { uint256 inflationBasisPoints = TOKEN_FEE_BASIS_POINTS + splitBasisPoints; _totalSupply = valueToTokens((_winningBid * 10000) / (10000 - inflationBasisPoints)); _partyDAOAmount = (_totalSupply * TOKEN_FEE_BASIS_POINTS) / 10000; _splitRecipientAmount = (_totalSupply * splitBasisPoints) / 10000; }
102,735
pragma solidity ^0.4.21; contract LuckchemyCrowdsale { using SafeMath for uint256; // Token for selling LuckchemyToken public token; /* * Start and End date of investment process */ // 2018-04-30 00:00:00 GMT - start time for public sale uint256 public constant START_TIME_SALE = 1525046400; // 2018-07-20 23:59:59 GMT - end time for public sale uint256 public constant END_TIME_SALE = 1532131199; // 2018-04-02 00:00:00 GMT - start time for private sale uint256 public constant START_TIME_PRESALE = 1522627200; // 2018-04-24 23:59:59 GMT - end time for private sale uint256 public constant END_TIME_PRESALE = 1524614399; // amount of already sold tokens uint256 public tokensSold = 0; //supply for crowdSale uint256 public totalSupply = 0; // hard cap uint256 public constant hardCap = 45360 ether; // soft cap uint256 public constant softCap = 2000 ether; // wei representation of collected fiat uint256 public fiatBalance = 0; // ether collected in wei uint256 public ethBalance = 0; //address of serviceAgent (it can calls payFiat function) address public serviceAgent; // owner of the contract address public owner; //default token rate uint256 public constant RATE = 12500; // Token price in ETH - 0.00008 ETH 1 ETHER = 12500 tokens // 2018/04/30 - 2018/07/22 uint256 public constant DISCOUNT_PRIVATE_PRESALE = 80; // 80 % discount // 2018/04/30 - 2018/07/20 uint256 public constant DISCOUNT_STAGE_ONE = 40; // 40% discount // 2018/04/02 - 2018/04/24 uint256 public constant DISCOUNT_STAGE_TWO = 20; // 20% discount // 2018/04/30 - 2018/07/22 uint256 public constant DISCOUNT_STAGE_THREE = 0; //White list of addresses that are allowed to by a token mapping(address => bool) public whitelist; /** * List of addresses for ICO fund with shares in % * */ uint256 public constant LOTTERY_FUND_SHARE = 40; uint256 public constant OPERATIONS_SHARE = 50; uint256 public constant PARTNERS_SHARE = 10; address public constant LOTTERY_FUND_ADDRESS = 0x84137CB59076a61F3f94B2C39Da8fbCb63B6f096; address public constant OPERATIONS_ADDRESS = 0xEBBeAA0699837De527B29A03ECC914159D939Eea; address public constant PARTNERS_ADDRESS = 0x820502e8c80352f6e11Ce036DF03ceeEBE002642; /** * event for token ETH purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokenETHPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); /** * event for token FIAT purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param amount amount of tokens purchased */ event TokenFiatPurchase(address indexed purchaser, address indexed beneficiary, uint256 amount); /* * modifier which gives specific rights to owner */ modifier onlyOwner(){ require(msg.sender == owner); _; } /* * modifier which gives possibility to call payFiat function */ modifier onlyServiceAgent(){ require(msg.sender == serviceAgent); _; } /* * *modifier which gives possibility to purchase * */ modifier onlyWhiteList(address _address){ require(whitelist[_address] == true); _; } /* * Enum which defines stages of ICO */ enum Stage { Private, Discount40, Discount20, NoDiscount } //current stage Stage public currentStage; //pools of token for each stage mapping(uint256 => uint256) public tokenPools; //number of tokens per 1 ether for each stage mapping(uint256 => uint256) public stageRates; /* * deposit is amount in wei , which was sent to the contract * @ address - address of depositor * @ uint256 - amount */ mapping(address => uint256) public deposits; /* * constructor of contract * @ _service- address which has rights to call payFiat */ function LuckchemyCrowdsale(address _service) public { require(START_TIME_SALE >= now); require(START_TIME_SALE > END_TIME_PRESALE); require(END_TIME_SALE > START_TIME_SALE); require(_service != 0x0); owner = msg.sender; serviceAgent = _service; token = new LuckchemyToken(); totalSupply = token.CROWDSALE_SUPPLY(); currentStage = Stage.Private; uint256 decimals = uint256(token.decimals()); tokenPools[uint256(Stage.Private)] = 70000000 * (10 ** decimals); tokenPools[uint256(Stage.Discount40)] = 105000000 * (10 ** decimals); tokenPools[uint256(Stage.Discount20)] = 175000000 * (10 ** decimals); tokenPools[uint256(Stage.NoDiscount)] = 350000000 * (10 ** decimals); stageRates[uint256(Stage.Private)] = RATE.mul(10 ** decimals).mul(100).div(100 - DISCOUNT_PRIVATE_PRESALE); stageRates[uint256(Stage.Discount40)] = RATE.mul(10 ** decimals).mul(100).div(100 - DISCOUNT_STAGE_ONE); stageRates[uint256(Stage.Discount20)] = RATE.mul(10 ** decimals).mul(100).div(100 - DISCOUNT_STAGE_TWO); stageRates[uint256(Stage.NoDiscount)] = RATE.mul(10 ** decimals).mul(100).div(100 - DISCOUNT_STAGE_THREE); } /* * function to get amount ,which invested by depositor * @depositor - address ,which bought tokens */ function depositOf(address depositor) public constant returns (uint256) { return deposits[depositor]; } /* * fallback function can be used to buy tokens */ function() public payable { payETH(msg.sender); } /* * function for tracking ethereum purchases * @beneficiary - address ,which received tokens */ function payETH(address beneficiary) public onlyWhiteList(beneficiary) payable { require(msg.value >= 0.1 ether); require(beneficiary != 0x0); require(validPurchase()); if (isPrivateSale()) { processPrivatePurchase(msg.value, beneficiary); } else { processPublicPurchase(msg.value, beneficiary); } } /* * function for processing purchase in private sale * @weiAmount - amount of wei , which send to the contract * @beneficiary - address for receiving tokens */ function processPrivatePurchase(uint256 weiAmount, address beneficiary) private { uint256 stage = uint256(Stage.Private); require(currentStage == Stage.Private); require(tokenPools[stage] > 0); //calculate number tokens uint256 tokensToBuy = (weiAmount.mul(stageRates[stage])).div(1 ether); if (tokensToBuy <= tokenPools[stage]) { //pool has enough tokens payoutTokens(beneficiary, tokensToBuy, weiAmount); } else { //pool doesn&#39;t have enough tokens tokensToBuy = tokenPools[stage]; //left wei uint256 usedWei = (tokensToBuy.mul(1 ether)).div(stageRates[stage]); uint256 leftWei = weiAmount.sub(usedWei); payoutTokens(beneficiary, tokensToBuy, usedWei); //change stage to Public Sale currentStage = Stage.Discount40; //return left wei to beneficiary and change stage beneficiary.transfer(leftWei); } } /* * function for processing purchase in public sale * @weiAmount - amount of wei , which send to the contract * @beneficiary - address for receiving tokens */ function processPublicPurchase(uint256 weiAmount, address beneficiary) private { if (currentStage == Stage.Private) { currentStage = Stage.Discount40; tokenPools[uint256(Stage.Discount40)] = tokenPools[uint256(Stage.Discount40)].add(tokenPools[uint256(Stage.Private)]); tokenPools[uint256(Stage.Private)] = 0; } for (uint256 stage = uint256(currentStage); stage <= 3; stage++) { //calculate number tokens uint256 tokensToBuy = (weiAmount.mul(stageRates[stage])).div(1 ether); if (tokensToBuy <= tokenPools[stage]) { //pool has enough tokens payoutTokens(beneficiary, tokensToBuy, weiAmount); break; } else { //pool doesn&#39;t have enough tokens tokensToBuy = tokenPools[stage]; //left wei uint256 usedWei = (tokensToBuy.mul(1 ether)).div(stageRates[stage]); uint256 leftWei = weiAmount.sub(usedWei); payoutTokens(beneficiary, tokensToBuy, usedWei); if (stage == 3) { //return unused wei when all tokens sold beneficiary.transfer(leftWei); break; } else { weiAmount = leftWei; //change current stage currentStage = Stage(stage + 1); } } } } /* * function for actual payout in public sale * @beneficiary - address for receiving tokens * @tokenAmount - amount of tokens to payout * @weiAmount - amount of wei used */ function payoutTokens(address beneficiary, uint256 tokenAmount, uint256 weiAmount) private { uint256 stage = uint256(currentStage); tokensSold = tokensSold.add(tokenAmount); tokenPools[stage] = tokenPools[stage].sub(tokenAmount); deposits[beneficiary] = deposits[beneficiary].add(weiAmount); ethBalance = ethBalance.add(weiAmount); token.transfer(beneficiary, tokenAmount); TokenETHPurchase(msg.sender, beneficiary, weiAmount, tokenAmount); } /* * function for change btc agent * can be called only by owner of the contract * @_newServiceAgent - new serviceAgent address */ function setServiceAgent(address _newServiceAgent) public onlyOwner { serviceAgent = _newServiceAgent; } /* * function for tracking bitcoin purchases received by bitcoin wallet * each transaction and amount of tokens according to rate can be validated on public bitcoin wallet * public key - # * @beneficiary - address, which received tokens * @amount - amount tokens * @stage - number of the stage (80% 40% 20% 0% discount) * can be called only by serviceAgent address */ function payFiat(address beneficiary, uint256 amount, uint256 stage) public onlyServiceAgent onlyWhiteList(beneficiary) { require(beneficiary != 0x0); require(tokenPools[stage] >= amount); require(stage == uint256(currentStage)); //calculate fiat amount in wei uint256 fiatWei = amount.mul(1 ether).div(stageRates[stage]); fiatBalance = fiatBalance.add(fiatWei); require(validPurchase()); tokenPools[stage] = tokenPools[stage].sub(amount); tokensSold = tokensSold.add(amount); token.transfer(beneficiary, amount); TokenFiatPurchase(msg.sender, beneficiary, amount); } /* * function for checking if crowdsale is finished */ function hasEnded() public constant returns (bool) { return now > END_TIME_SALE || tokensSold >= totalSupply; } /* * function for checking if hardCapReached */ function hardCapReached() public constant returns (bool) { return tokensSold >= totalSupply || fiatBalance.add(ethBalance) >= hardCap; } /* * function for checking if crowdsale goal is reached */ function softCapReached() public constant returns (bool) { return fiatBalance.add(ethBalance) >= softCap; } function isPrivateSale() public constant returns (bool) { return now >= START_TIME_PRESALE && now <= END_TIME_PRESALE; } /* * function that call after crowdsale is ended * releaseTokenTransfer - enable token transfer between users. * burn tokens which are left on crowsale contract balance * transfer balance of contract to wallets according to shares. */ function forwardFunds() public onlyOwner { require(hasEnded()); require(softCapReached()); token.releaseTokenTransfer(); token.burn(token.balanceOf(this)); //transfer token ownership to this owner of crowdsale token.transferOwnership(msg.sender); //transfer funds here uint256 totalBalance = this.balance; LOTTERY_FUND_ADDRESS.transfer((totalBalance.mul(LOTTERY_FUND_SHARE)).div(100)); OPERATIONS_ADDRESS.transfer((totalBalance.mul(OPERATIONS_SHARE)).div(100)); PARTNERS_ADDRESS.transfer(this.balance); // send the rest to partners (PARTNERS_SHARE) } /* * function that call after crowdsale is ended * conditions : ico ended and goal isn&#39;t reached. amount of depositor > 0. * * refund eth deposit (fiat refunds will be done manually) */ function refund() public { require(hasEnded()); require(!softCapReached() || ((now > END_TIME_SALE + 30 days) && !token.released())); uint256 amount = deposits[msg.sender]; require(amount > 0); deposits[msg.sender] = 0; msg.sender.transfer(amount); } /* internal functions */ /* * function for checking period of investment and investment amount restriction for ETH purchases */ function validPurchase() internal constant returns (bool) { bool withinPeriod = (now >= START_TIME_PRESALE && now <= END_TIME_PRESALE) || (now >= START_TIME_SALE && now <= END_TIME_SALE); return withinPeriod && !hardCapReached(); } /* * function for adding address to whitelist * @_whitelistAddress - address to add */ function addToWhiteList(address _whitelistAddress) public onlyServiceAgent { whitelist[_whitelistAddress] = true; } /* * function for removing address from whitelist * @_whitelistAddress - address to remove */ function removeWhiteList(address _whitelistAddress) public onlyServiceAgent { delete whitelist[_whitelistAddress]; } } contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } } contract BurnableToken is BasicToken { event Burn(address indexed burner, uint256 value); /** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) public { require(_value <= balances[msg.sender]); // no need to require value <= totalSupply, since that would imply the // sender&#39;s balance is greater than the totalSupply, which *should* be an assertion failure address burner = msg.sender; balances[burner] = balances[burner].sub(_value); totalSupply_ = totalSupply_.sub(_value); Burn(burner, _value); Transfer(burner, address(0), _value); } } contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender&#39;s allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract Claimable is Ownable { address public pendingOwner; /** * @dev Modifier throws if called by any account other than the pendingOwner. */ modifier onlyPendingOwner() { require(msg.sender == pendingOwner); _; } /** * @dev Allows the current owner to set the pendingOwner address. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner public { pendingOwner = newOwner; } /** * @dev Allows the pendingOwner address to finalize the transfer. */ function claimOwnership() onlyPendingOwner public { OwnershipTransferred(owner, pendingOwner); owner = pendingOwner; pendingOwner = address(0); } } contract LuckchemyToken is BurnableToken, StandardToken, Claimable { bool public released = false; string public constant name = "Luckchemy"; string public constant symbol = "LUK"; uint8 public constant decimals = 8; uint256 public CROWDSALE_SUPPLY; uint256 public OWNERS_AND_PARTNERS_SUPPLY; address public constant OWNERS_AND_PARTNERS_ADDRESS = 0x603a535a1D7C5050021F9f5a4ACB773C35a67602; // Index of unique addresses uint256 public addressCount = 0; // Map of unique addresses mapping(uint256 => address) public addressMap; mapping(address => bool) public addressAvailabilityMap; //blacklist of addresses (product/developers addresses) that are not included in the final Holder lottery mapping(address => bool) public blacklist; // service agent for managing blacklist address public serviceAgent; event Release(); event BlacklistAdd(address indexed addr); event BlacklistRemove(address indexed addr); /** * Do not transfer tokens until the crowdsale is over. * */ modifier canTransfer() { require(released || msg.sender == owner); _; } /* * modifier which gives specific rights to serviceAgent */ modifier onlyServiceAgent(){ require(msg.sender == serviceAgent); _; } function LuckchemyToken() public { totalSupply_ = 1000000000 * (10 ** uint256(decimals)); CROWDSALE_SUPPLY = 700000000 * (10 ** uint256(decimals)); OWNERS_AND_PARTNERS_SUPPLY = 300000000 * (10 ** uint256(decimals)); addAddressToUniqueMap(msg.sender); addAddressToUniqueMap(OWNERS_AND_PARTNERS_ADDRESS); balances[msg.sender] = CROWDSALE_SUPPLY; balances[OWNERS_AND_PARTNERS_ADDRESS] = OWNERS_AND_PARTNERS_SUPPLY; owner = msg.sender; Transfer(0x0, msg.sender, CROWDSALE_SUPPLY); Transfer(0x0, OWNERS_AND_PARTNERS_ADDRESS, OWNERS_AND_PARTNERS_SUPPLY); } function transfer(address _to, uint256 _value) public canTransfer returns (bool success) { //Add address to map of unique token owners addAddressToUniqueMap(_to); // Call StandardToken.transfer() return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint256 _value) public canTransfer returns (bool success) { //Add address to map of unique token owners addAddressToUniqueMap(_to); // Call StandardToken.transferForm() return super.transferFrom(_from, _to, _value); } /** * * Release the tokens to the public. * Can be called only by owner which should be the Crowdsale contract * Should be called if the crowdale is successfully finished * */ function releaseTokenTransfer() public onlyOwner { released = true; Release(); } /** * Add address to the black list. * Only service agent can do this */ function addBlacklistItem(address _blackAddr) public onlyServiceAgent { blacklist[_blackAddr] = true; BlacklistAdd(_blackAddr); } /** * Remove address from the black list. * Only service agent can do this */ function removeBlacklistItem(address _blackAddr) public onlyServiceAgent { delete blacklist[_blackAddr]; } /** * Add address to unique map if it is not added */ function addAddressToUniqueMap(address _addr) private returns (bool) { if (addressAvailabilityMap[_addr] == true) { return true; } addressAvailabilityMap[_addr] = true; addressMap[addressCount++] = _addr; return true; } /** * Get address by index from map of unique addresses */ function getUniqueAddressByIndex(uint256 _addressIndex) public view returns (address) { return addressMap[_addressIndex]; } /** * Change service agent */ function changeServiceAgent(address _addr) public onlyOwner { serviceAgent = _addr; } } library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;t hold return c; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } }
Change service agent/
function changeServiceAgent(address _addr) public onlyOwner { serviceAgent = _addr; }
8,049,970
./partial_match/1/0x705AeE4D26e30738ca32630540D85D8EB11332af/sources/YVAULT.sol
Sets {_burnEnabled} to enable burning./
function _setBurnEnable(bool burnEnabled_) internal virtual { _burnEnabled = burnEnabled_; }
4,418,530
//Address: 0xa6714a2e5f0b1bdb97b895b0913b4fcd3a775e4d //Contract name: PromotionCoin //Balance: 0 Ether //Verification Date: 2/5/2018 //Transacion Count: 30887 // CODE STARTS HERE pragma solidity ^0.4.18; /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } contract DateTime { /* * Date and Time utilities for ethereum contracts * */ struct _DateTime { uint16 year; uint8 month; uint8 day; uint8 hour; uint8 minute; uint8 second; uint8 weekday; } uint constant DAY_IN_SECONDS = 86400; uint constant YEAR_IN_SECONDS = 31536000; uint constant LEAP_YEAR_IN_SECONDS = 31622400; uint constant HOUR_IN_SECONDS = 3600; uint constant MINUTE_IN_SECONDS = 60; uint16 constant ORIGIN_YEAR = 1970; function isLeapYear(uint16 year) public pure returns (bool) { if (year % 4 != 0) { return false; } if (year % 100 != 0) { return true; } if (year % 400 != 0) { return false; } return true; } function leapYearsBefore(uint year) public pure returns (uint) { year -= 1; return year / 4 - year / 100 + year / 400; } function getDaysInMonth(uint8 month, uint16 year) public pure returns (uint8) { if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) { return 31; } else if (month == 4 || month == 6 || month == 9 || month == 11) { return 30; } else if (isLeapYear(year)) { return 29; } else { return 28; } } function parseTimestamp(uint timestamp) internal pure returns (_DateTime dt) { uint secondsAccountedFor = 0; uint buf; uint8 i; // Year dt.year = getYear(timestamp); buf = leapYearsBefore(dt.year) - leapYearsBefore(ORIGIN_YEAR); secondsAccountedFor += LEAP_YEAR_IN_SECONDS * buf; secondsAccountedFor += YEAR_IN_SECONDS * (dt.year - ORIGIN_YEAR - buf); // Month uint secondsInMonth; for (i = 1; i <= 12; i++) { secondsInMonth = DAY_IN_SECONDS * getDaysInMonth(i, dt.year); if (secondsInMonth + secondsAccountedFor > timestamp) { dt.month = i; break; } secondsAccountedFor += secondsInMonth; } // Day for (i = 1; i <= getDaysInMonth(dt.month, dt.year); i++) { if (DAY_IN_SECONDS + secondsAccountedFor > timestamp) { dt.day = i; break; } secondsAccountedFor += DAY_IN_SECONDS; } // Hour dt.hour = getHour(timestamp); // Minute dt.minute = getMinute(timestamp); // Second dt.second = getSecond(timestamp); // Day of week. dt.weekday = getWeekday(timestamp); } function getYear(uint timestamp) public pure returns (uint16) { uint secondsAccountedFor = 0; uint16 year; uint numLeapYears; // Year year = uint16(ORIGIN_YEAR + timestamp / YEAR_IN_SECONDS); numLeapYears = leapYearsBefore(year) - leapYearsBefore(ORIGIN_YEAR); secondsAccountedFor += LEAP_YEAR_IN_SECONDS * numLeapYears; secondsAccountedFor += YEAR_IN_SECONDS * (year - ORIGIN_YEAR - numLeapYears); while (secondsAccountedFor > timestamp) { if (isLeapYear(uint16(year - 1))) { secondsAccountedFor -= LEAP_YEAR_IN_SECONDS; } else { secondsAccountedFor -= YEAR_IN_SECONDS; } year -= 1; } return year; } function getMonth(uint timestamp) public pure returns (uint8) { return parseTimestamp(timestamp).month; } function getDay(uint timestamp) public pure returns (uint8) { return parseTimestamp(timestamp).day; } function getHour(uint timestamp) public pure returns (uint8) { return uint8((timestamp / 60 / 60) % 24); } function getMinute(uint timestamp) public pure returns (uint8) { return uint8((timestamp / 60) % 60); } function getSecond(uint timestamp) public pure returns (uint8) { return uint8(timestamp % 60); } function getWeekday(uint timestamp) public pure returns (uint8) { return uint8((timestamp / DAY_IN_SECONDS + 4) % 7); } function toTimestamp(uint16 year, uint8 month, uint8 day) public pure returns (uint timestamp) { return toTimestamp(year, month, day, 0, 0, 0); } function toTimestamp(uint16 year, uint8 month, uint8 day, uint8 hour) public pure returns (uint timestamp) { return toTimestamp(year, month, day, hour, 0, 0); } function toTimestamp(uint16 year, uint8 month, uint8 day, uint8 hour, uint8 minute) public pure returns (uint timestamp) { return toTimestamp(year, month, day, hour, minute, 0); } function toTimestamp(uint16 year, uint8 month, uint8 day, uint8 hour, uint8 minute, uint8 second) public pure returns (uint timestamp) { uint16 i; // Year for (i = ORIGIN_YEAR; i < year; i++) { if (isLeapYear(i)) { timestamp += LEAP_YEAR_IN_SECONDS; } else { timestamp += YEAR_IN_SECONDS; } } // Month uint8[12] memory monthDayCounts; monthDayCounts[0] = 31; if (isLeapYear(year)) { monthDayCounts[1] = 29; } else { monthDayCounts[1] = 28; } monthDayCounts[2] = 31; monthDayCounts[3] = 30; monthDayCounts[4] = 31; monthDayCounts[5] = 30; monthDayCounts[6] = 31; monthDayCounts[7] = 31; monthDayCounts[8] = 30; monthDayCounts[9] = 31; monthDayCounts[10] = 30; monthDayCounts[11] = 31; for (i = 1; i < month; i++) { timestamp += DAY_IN_SECONDS * monthDayCounts[i - 1]; } // Day timestamp += DAY_IN_SECONDS * (day - 1); // Hour timestamp += HOUR_IN_SECONDS * (hour); // Minute timestamp += MINUTE_IN_SECONDS * (minute); // Second timestamp += second; return timestamp; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title Authorizable * @dev Allows to authorize access to certain function calls * * ABI * [{"constant":true,"inputs":[{"name":"authorizerIndex","type":"uint256"}],"name":"getAuthorizer","outputs":[{"name":"","type":"address"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_addr","type":"address"}],"name":"addAuthorized","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[{"name":"_addr","type":"address"}],"name":"isAuthorized","outputs":[{"name":"","type":"bool"}],"payable":false,"type":"function"},{"inputs":[],"payable":false,"type":"constructor"}] */ contract Authorizable { address[] authorizers; mapping(address => uint) authorizerIndex; /** * @dev Throws if called by any account tat is not authorized. */ modifier onlyAuthorized { require(isAuthorized(msg.sender)); _; } /** * @dev Contructor that authorizes the msg.sender. */ function Authorizable() public { authorizers.length = 2; authorizers[1] = msg.sender; authorizerIndex[msg.sender] = 1; } /** * @dev Function to get a specific authorizer * @param _authorizerIndex index of the authorizer to be retrieved. * @return The address of the authorizer. */ function getAuthorizer(uint _authorizerIndex) external view returns(address) { return address(authorizers[_authorizerIndex + 1]); } /** * @dev Function to check if an address is authorized * @param _addr the address to check if it is authorized. * @return boolean flag if address is authorized. */ function isAuthorized(address _addr) public view returns(bool) { return authorizerIndex[_addr] > 0; } /** * @dev Function to add a new authorizer * @param _addr the address to add as a new authorizer. */ function addAuthorized(address _addr) external onlyAuthorized { authorizerIndex[_addr] = authorizers.length; authorizers.length++; authorizers[authorizers.length - 1] = _addr; } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) public onlyOwner canMint returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() public onlyOwner canMint returns (bool) { mintingFinished = true; MintFinished(); return true; } } /** * @title PromotionCoin * @dev The main PC token contract */ contract PromotionCoin is MintableToken { string public name = "PromotionCoin"; string public symbol = "PC"; uint public decimals = 5; /** * @dev Allows anyone to transfer * @param _to the recipient address of the tokens. * @param _value number of tokens to be transfered. */ function transfer(address _to, uint256 _value) public returns (bool) { super.transfer(_to, _value); } /** * @dev Allows anyone to transfer * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint the amout of tokens to be transfered */ function transferFrom(address _from, address _to, uint _value) public returns (bool) { super.transferFrom(_from, _to, _value); } } /** * @title PromotionCoinDistribution * @dev The main PC token sale contract * * ABI */ contract PromotionCoinDistribution is Ownable, Authorizable { using SafeMath for uint; event AuthorizedCreateToPrivate(address recipient, uint pay_amount); event Mined(address recipient, uint pay_amount); event CreateTokenToTeam(address recipient, uint pay_amount); event CreateTokenToMarket(address recipient, uint pay_amount); event CreateTokenToOperation(address recipient, uint pay_amount); event CreateTokenToTax(address recipient, uint pay_amount); event PromotionCoinMintFinished(); PromotionCoin public token = new PromotionCoin(); DateTime internal dateTime = new DateTime(); uint public DICIMALS = 5; uint totalToken = 21000000000 * (10 ** DICIMALS); //210亿 uint public privateTokenCap = 5000000000 * (10 ** DICIMALS); //私募发行50亿 uint public marketToken2018 = 0.50 * 1500000000 * (10 ** DICIMALS); //全球推广15亿,第一年 50% uint public marketToken2019 = 0.25 * 1500000000 * (10 ** DICIMALS); //全球推广15亿, 第二年 25% uint public marketToken2020 = 0.15 * 1500000000 * (10 ** DICIMALS); //全球推广15亿, 第三年 15% uint public marketToken2021 = 0.10 * 1500000000 * (10 ** DICIMALS); //全球推广15亿, 第四年 10% uint public operationToken = 2000000000 * (10 ** DICIMALS); //社区运营20亿 uint public minedTokenCap = 11000000000 * (10 ** DICIMALS); //挖矿110亿 uint public teamToken2018 = 500000000 * (10 ** DICIMALS); //团队预留10亿(10%),2018年发放5亿 uint public teamToken2019 = 500000000 * (10 ** DICIMALS); //团队预留10亿(10%),2019年发放5亿 uint public taxToken = 500000000 * (10 ** DICIMALS); //税务及法务年发放5亿 uint public privateToken = 0; //私募已发行数量 address public teamAddress; address public operationAddress; address public marketAddress; address public taxAddress; bool public team2018TokenCreated = false; bool public team2019TokenCreated = false; bool public operationTokenCreated = false; bool public market2018TokenCreated = false; bool public market2019TokenCreated = false; bool public market2020TokenCreated = false; bool public market2021TokenCreated = false; bool public taxTokenCreated = false; //year => token mapping(uint16 => uint) public minedToken; //游戏挖矿已发行数量 uint public firstYearMinedTokenCap = 5500000000 * (10 ** DICIMALS); //2018年55亿(110亿*0.5),以后逐年减半 uint public minedTokenStartTime = 1514736000; //new Date("Jan 01 2018 00:00:00 GMT+8").getTime() / 1000; function isContract(address _addr) internal view returns(bool) { uint size; if (_addr == 0) return false; assembly { size := extcodesize(_addr) } return size > 0; } //2018年55亿(110亿*0.5),以后逐年减半,到2028年发放剩余的全部 function getCurrentYearMinedTokenCap(uint _currentYear) public view returns(uint) { require(_currentYear <= 2028); if (_currentYear < 2028) { uint divTimes = 2 ** (_currentYear - 2018); uint currentYearMinedTokenCap = firstYearMinedTokenCap.div(divTimes).div(10 ** DICIMALS).mul(10 ** DICIMALS); return currentYearMinedTokenCap; } else if (_currentYear == 2028) { return 10742188 * (10 ** DICIMALS); } else { revert(); } } function getCurrentYearRemainToken(uint16 _currentYear) public view returns(uint) { uint currentYearMinedTokenCap = getCurrentYearMinedTokenCap(_currentYear); if (minedToken[_currentYear] == 0) { return currentYearMinedTokenCap; } else { return currentYearMinedTokenCap.sub(minedToken[_currentYear]); } } function setTeamAddress(address _address) public onlyAuthorized { teamAddress = _address; } function setMarketAddress(address _address) public onlyAuthorized { marketAddress = _address; } function setOperationAddress(address _address) public onlyAuthorized { operationAddress = _address; } function setTaxAddress(address _address) public onlyAuthorized { taxAddress = _address; } function createTokenToMarket2018() public onlyAuthorized { require(marketAddress != address(0)); require(market2018TokenCreated == false); market2018TokenCreated = true; token.mint(marketAddress, marketToken2018); CreateTokenToMarket(marketAddress, marketToken2018); } function createTokenToMarket2019() public onlyAuthorized { require(marketAddress != address(0)); require(market2018TokenCreated == false); market2019TokenCreated = true; token.mint(marketAddress, marketToken2019); CreateTokenToMarket(marketAddress, marketToken2019); } function createTokenToMarket2020() public onlyAuthorized { require(marketAddress != address(0)); require(market2020TokenCreated == false); market2020TokenCreated = true; token.mint(marketAddress, marketToken2020); CreateTokenToMarket(marketAddress, marketToken2020); } function createTokenToMarket2021() public onlyAuthorized { require(marketAddress != address(0)); require(market2021TokenCreated == false); market2021TokenCreated = true; token.mint(marketAddress, marketToken2021); CreateTokenToMarket(marketAddress, marketToken2021); } function createTokenToOperation() public onlyAuthorized { require(operationAddress != address(0)); require(operationTokenCreated == false); operationTokenCreated = true; token.mint(operationAddress, operationToken); CreateTokenToOperation(operationAddress, operationToken); } function createTokenToTax() public onlyAuthorized { require(taxAddress != address(0)); require(taxTokenCreated == false); taxTokenCreated = true; token.mint(taxAddress, taxToken); CreateTokenToOperation(taxAddress, taxToken); } function _createTokenToTeam(uint16 _currentYear) internal { if (_currentYear == 2018) { require(team2018TokenCreated == false); team2018TokenCreated = true; token.mint(teamAddress, teamToken2018); CreateTokenToTeam(teamAddress, teamToken2018); } else if (_currentYear == 2019) { require(team2019TokenCreated == false); team2019TokenCreated = true; token.mint(teamAddress, teamToken2019); CreateTokenToTeam(teamAddress, teamToken2019); } else { revert(); } } function createTokenToTeam() public onlyAuthorized { require(teamAddress != address(0)); uint16 currentYear = dateTime.getYear(now); require(currentYear == 2018 || currentYear == 2019); _createTokenToTeam(currentYear); } function mined(address recipient, uint _tokens) public onlyAuthorized { require(now > minedTokenStartTime); uint16 currentYear = dateTime.getYear(now); uint currentYearRemainTokens = getCurrentYearRemainToken(currentYear); require(_tokens <= currentYearRemainTokens); minedToken[currentYear] += _tokens; token.mint(recipient, _tokens); Mined(recipient, _tokens); } function authorizedCreateTokensToPrivate(address recipient, uint _tokens) public onlyAuthorized { require(privateToken + _tokens <= privateTokenCap); privateToken += _tokens; token.mint(recipient, _tokens); AuthorizedCreateToPrivate(recipient, _tokens); } function finishMinting() public onlyOwner { token.finishMinting(); token.transferOwnership(owner); PromotionCoinMintFinished(); } //不允许直接转账以太币购买 function () external { revert(); } }
Function to stop minting new tokens. return True if the operation was successful./
function finishMinting() public onlyOwner canMint returns (bool) { mintingFinished = true; MintFinished(); return true; }
13,125,843
./partial_match/1/0xf1F246e629198E7D13cc821A1ef767E3591C7c87/sources/TradeHandler.sol
Settlement can't be a mech.
function setSettlement(address _settlement) external onlyGovernance { require(!mechs[_settlement]); settlement = _settlement; emit UpdatedSettlement(_settlement); }
2,849,165
./partial_match/3/0x6E3F4a8829eC34C0109462fF8A90387461F14ca3/sources/SimpleAuction.sol
Bid on the auction with the value sent together with this transaction. The value will only be refunded if the auction is not won. No arguments are necessary, all information is already part of the transaction. The keyword payable is required for the function to be able to receive Ether. Revert the call if the bidding period is over. If the bid is not higher, send the money back. Sending back the money by simply using highestBidder.send(highestBid) is a security risk because it could execute an untrusted contract. It is always safer to let the recipients withdraw their money themselves.
function bid() public payable { require( now <= auctionEndTime, "Auction already ended." ); require( msg.value > highestBid, "There already is a higher bid." ); if (highestBid != 0) { pendingReturns[highestBidder] += highestBid; } highestBidder = msg.sender; highestBid = msg.value; emit HighestBidIncreased(msg.sender, msg.value); }
5,336,142
./full_match/137/0xb453Ee1e040A71e48217Bd7fB680F860f5cD68E2/sources/contracts/UniswapHelper.sol
only owner functions
function ownerTransfer(address _newOwner) external onlyOwner { owner = _newOwner; }
3,737,226
./full_match/43114/0x7695CCAC61a42f5EB57456Af5B428a2a371226f8/sources/Airdrop/lottery.sol
solhint-disable-next-line max-line-length
function safeApprove(IERC20 token, address spender, uint256 value) internal { require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); }
4,530,571
./partial_match/1/0x3C9C88A7B9A625a6bcE57DE8c05d9dC9a5f9591c/sources/ERC721Batch.sol
Returns whether `spender` is allowed to manage `tokenId`. Requirements: - `tokenId` must exist./
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) { require( _exists(tokenId), "ERC721: operator query for nonexistent token" ); address owner = ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); }
2,838,725
pragma solidity ^0.5.0; pragma experimental ABIEncoderV2; import "./SafeMath.sol"; import "./Events.sol"; import "./Ownable.sol"; import "./Upgradeable.sol"; import "./UpgradeableMaster.sol"; /// @title Upgrade Gatekeeper Contract /// @author Matter Labs /// @author ZKSwap L2 Labs contract UpgradeGatekeeper is UpgradeEvents, Ownable { using SafeMath for uint256; /// @notice Array of addresses of upgradeable contracts managed by the gatekeeper Upgradeable[] public managedContracts; /// @notice Upgrade mode statuses enum UpgradeStatus { Idle, NoticePeriod, Preparation } UpgradeStatus public upgradeStatus; /// @notice Notice period finish timestamp (as seconds since unix epoch) /// @dev Will be equal to zero in case of not active upgrade mode uint public noticePeriodFinishTimestamp; /// @notice Addresses of the next versions of the contracts to be upgraded (if element of this array is equal to zero address it means that appropriate upgradeable contract wouldn't be upgraded this time) /// @dev Will be empty in case of not active upgrade mode address[] public nextTargets; /// @notice Version id of contracts uint public versionId; /// @notice Contract which defines notice period duration and allows finish upgrade during preparation of it UpgradeableMaster public mainContract; /// @notice Contract constructor /// @param _mainContract Contract which defines notice period duration and allows finish upgrade during preparation of it /// @dev Calls Ownable contract constructor constructor(UpgradeableMaster _mainContract) Ownable(msg.sender) public { mainContract = _mainContract; versionId = 0; } /// @notice Adds a new upgradeable contract to the list of contracts managed by the gatekeeper /// @param addr Address of upgradeable contract to add function addUpgradeable(address addr) external { requireMaster(msg.sender); require(upgradeStatus == UpgradeStatus.Idle, "apc11"); /// apc11 - upgradeable contract can't be added during upgrade managedContracts.push(Upgradeable(addr)); emit NewUpgradable(versionId, addr); } /// @notice Starts upgrade (activates notice period) /// @param newTargets New managed contracts targets (if element of this array is equal to zero address it means that appropriate upgradeable contract wouldn't be upgraded this time) function startUpgrade(address[] calldata newTargets) external { requireMaster(msg.sender); require(upgradeStatus == UpgradeStatus.Idle, "spu11"); // spu11 - unable to activate active upgrade mode require(newTargets.length == managedContracts.length, "spu12"); // spu12 - number of new targets must be equal to the number of managed contracts uint noticePeriod = mainContract.getNoticePeriod(); mainContract.upgradeNoticePeriodStarted(); upgradeStatus = UpgradeStatus.NoticePeriod; noticePeriodFinishTimestamp = now.add(noticePeriod); nextTargets = newTargets; emit NoticePeriodStart(versionId, newTargets, noticePeriod); } /// @notice Cancels upgrade function cancelUpgrade() external { requireMaster(msg.sender); require(upgradeStatus != UpgradeStatus.Idle, "cpu11"); // cpu11 - unable to cancel not active upgrade mode mainContract.upgradeCanceled(); upgradeStatus = UpgradeStatus.Idle; noticePeriodFinishTimestamp = 0; delete nextTargets; emit UpgradeCancel(versionId); } /// @notice Activates preparation status /// @return Bool flag indicating that preparation status has been successfully activated function startPreparation() external returns (bool) { requireMaster(msg.sender); require(upgradeStatus == UpgradeStatus.NoticePeriod, "ugp11"); // ugp11 - unable to activate preparation status in case of not active notice period status if (now >= noticePeriodFinishTimestamp) { upgradeStatus = UpgradeStatus.Preparation; mainContract.upgradePreparationStarted(); emit PreparationStart(versionId); return true; } else { return false; } } /// @notice Finishes upgrade /// @param targetsUpgradeParameters New targets upgrade parameters per each upgradeable contract function finishUpgrade(bytes[] calldata targetsUpgradeParameters) external { requireMaster(msg.sender); require(upgradeStatus == UpgradeStatus.Preparation, "fpu11"); // fpu11 - unable to finish upgrade without preparation status active require(targetsUpgradeParameters.length == managedContracts.length, "fpu12"); // fpu12 - number of new targets upgrade parameters must be equal to the number of managed contracts require(mainContract.isReadyForUpgrade(), "fpu13"); // fpu13 - main contract is not ready for upgrade mainContract.upgradeFinishes(); for (uint64 i = 0; i < managedContracts.length; i++) { address newTarget = nextTargets[i]; if (newTarget != address(0)) { managedContracts[i].upgradeTarget(newTarget, targetsUpgradeParameters[i]); } } versionId++; emit UpgradeComplete(versionId, nextTargets); upgradeStatus = UpgradeStatus.Idle; noticePeriodFinishTimestamp = 0; delete nextTargets; } } pragma solidity ^0.5.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @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. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // 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; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } pragma solidity ^0.5.0; import "./Upgradeable.sol"; import "./Operations.sol"; /// @title ZKSwap events /// @author Matter Labs /// @author ZKSwap L2 Labs interface Events { /// @notice Event emitted when a block is committed event BlockCommit(uint32 indexed blockNumber); /// @notice Event emitted when a block is verified event BlockVerification(uint32 indexed blockNumber); /// @notice Event emitted when a sequence of blocks is verified event MultiblockVerification(uint32 indexed blockNumberFrom, uint32 indexed blockNumberTo); /// @notice Event emitted when user send a transaction to withdraw her funds from onchain balance event OnchainWithdrawal( address indexed owner, uint16 indexed tokenId, uint128 amount ); /// @notice Event emitted when user send a transaction to deposit her funds event OnchainDeposit( address indexed sender, uint16 indexed tokenId, uint128 amount, address indexed owner ); /// @notice Event emitted when user send a transaction to deposit her NFT event OnchainDepositNFT( address indexed sender, address indexed token, uint256 tokenId, address indexed owner ); /// @notice Event emitted when user send a transaction to full exit her NFT event OnchainFullExitNFT( uint32 indexed accountId, address indexed owner, uint64 indexed globalId ); event OnchainCreatePair( uint16 indexed tokenAId, uint16 indexed tokenBId, uint16 indexed pairId, address pair ); /// @notice Event emitted when user sends a authentication fact (e.g. pub-key hash) event FactAuth( address indexed sender, uint32 nonce, bytes fact ); /// @notice Event emitted when blocks are reverted event BlocksRevert( uint32 indexed totalBlocksVerified, uint32 indexed totalBlocksCommitted ); /// @notice Exodus mode entered event event ExodusMode(); /// @notice New priority request event. Emitted when a request is placed into mapping event NewPriorityRequest( address sender, uint64 serialId, Operations.OpType opType, bytes pubData, bytes userData, uint256 expirationBlock ); /// @notice Deposit committed event. event DepositCommit( uint32 indexed zkSyncBlockId, uint32 indexed accountId, address owner, uint16 indexed tokenId, uint128 amount ); /// @notice Deposit committed event. event DepositNFTCommit( uint32 indexed zkSyncBlockId, uint32 indexed accountId, address owner, uint64 indexed globalId ); /// @notice Full exit committed event. event FullExitCommit( uint32 indexed zkSyncBlockId, uint32 indexed accountId, address owner, uint16 indexed tokenId, uint128 amount ); /// @notice Full exit committed event. event FullExitNFTCommit( uint32 indexed zkSyncBlockId, uint32 indexed accountId, address owner, uint64 indexed globalId ); /// @notice Pending withdrawals index range that were added in the verifyBlock operation. /// NOTE: processed indexes in the queue map are [queueStartIndex, queueEndIndex) event PendingWithdrawalsAdd( uint32 queueStartIndex, uint32 queueEndIndex ); /// @notice Pending withdrawals index range that were executed in the completeWithdrawals operation. /// NOTE: processed indexes in the queue map are [queueStartIndex, queueEndIndex) event PendingWithdrawalsComplete( uint32 queueStartIndex, uint32 queueEndIndex ); event CreatePairCommit( uint32 indexed zkSyncBlockId, uint32 indexed accountId, uint16 tokenAId, uint16 tokenBId, uint16 indexed tokenPairId, address pair ); } /// @title Upgrade events /// @author Matter Labs interface UpgradeEvents { /// @notice Event emitted when new upgradeable contract is added to upgrade gatekeeper's list of managed contracts event NewUpgradable( uint indexed versionId, address indexed upgradeable ); /// @notice Upgrade mode enter event event NoticePeriodStart( uint indexed versionId, address[] newTargets, uint noticePeriod // notice period (in seconds) ); /// @notice Upgrade mode cancel event event UpgradeCancel( uint indexed versionId ); /// @notice Upgrade mode preparation status event event PreparationStart( uint indexed versionId ); /// @notice Upgrade mode complete event event UpgradeComplete( uint indexed versionId, address[] newTargets ); } pragma solidity ^0.5.0; /// @title Ownable Contract /// @author Matter Labs /// @author ZKSwap L2 Labs contract Ownable { /// @notice Storage position of the masters address (keccak256('eip1967.proxy.admin') - 1) bytes32 private constant masterPosition = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; /// @notice Contract constructor /// @dev Sets msg sender address as masters address /// @param masterAddress Master address constructor(address masterAddress) public { setMaster(masterAddress); } /// @notice Check if specified address is master /// @param _address Address to check function requireMaster(address _address) internal view { require(_address == getMaster(), "oro11"); // oro11 - only by master } /// @notice Returns contract masters address /// @return Masters address function getMaster() public view returns (address master) { bytes32 position = masterPosition; assembly { master := sload(position) } } /// @notice Sets new masters address /// @param _newMaster New masters address function setMaster(address _newMaster) internal { bytes32 position = masterPosition; assembly { sstore(position, _newMaster) } } /// @notice Transfer mastership of the contract to new master /// @param _newMaster New masters address function transferMastership(address _newMaster) external { requireMaster(msg.sender); require(_newMaster != address(0), "otp11"); // otp11 - new masters address can't be zero address setMaster(_newMaster); } } pragma solidity ^0.5.0; /// @title Interface of the upgradeable contract /// @author Matter Labs /// @author ZKSwap L2 Labs interface Upgradeable { /// @notice Upgrades target of upgradeable contract /// @param newTarget New target /// @param newTargetInitializationParameters New target initialization parameters function upgradeTarget(address newTarget, bytes calldata newTargetInitializationParameters) external; } pragma solidity ^0.5.0; /// @title Interface of the upgradeable master contract (defines notice period duration and allows finish upgrade during preparation of it) /// @author Matter Labs /// @author ZKSwap L2 Labs interface UpgradeableMaster { /// @notice Notice period before activation preparation status of upgrade mode function getNoticePeriod() external returns (uint); /// @notice Notifies contract that notice period started function upgradeNoticePeriodStarted() external; /// @notice Notifies contract that upgrade preparation status is activated function upgradePreparationStarted() external; /// @notice Notifies contract that upgrade canceled function upgradeCanceled() external; /// @notice Notifies contract that upgrade finishes function upgradeFinishes() external; /// @notice Checks that contract is ready for upgrade /// @return bool flag indicating that contract is ready for upgrade function isReadyForUpgrade() external returns (bool); } pragma solidity ^0.5.0; pragma experimental ABIEncoderV2; import "./Bytes.sol"; /// @title ZKSwap operations tools library Operations { // Circuit ops and their pubdata (chunks * bytes) /// @notice ZKSwap circuit operation type enum OpType { Noop, Deposit, TransferToNew, PartialExit, _CloseAccount, // used for correct op id offset Transfer, FullExit, ChangePubKey, CreatePair, AddLiquidity, RemoveLiquidity, Swap, DepositNFT, MintNFT, TransferNFT, TransferToNewNFT, PartialExitNFT, FullExitNFT, ApproveNFT, ExchangeNFT } // Byte lengths uint8 constant TOKEN_BYTES = 2; uint8 constant PUBKEY_BYTES = 32; uint8 constant NONCE_BYTES = 4; uint8 constant PUBKEY_HASH_BYTES = 20; uint8 constant ADDRESS_BYTES = 20; /// @notice Packed fee bytes lengths uint8 constant FEE_BYTES = 2; /// @notice ZKSwap account id bytes lengths uint8 constant ACCOUNT_ID_BYTES = 4; uint8 constant AMOUNT_BYTES = 16; /// @notice Signature (for example full exit signature) bytes length uint8 constant SIGNATURE_BYTES = 64; /// @notice nft uri bytes lengths uint8 constant NFT_URI_BYTES = 32; /// @notice nft seq id bytes lengths uint8 constant NFT_SEQUENCE_ID_BYTES = 4; /// @notice nft creator bytes lengths uint8 constant NFT_CREATOR_ID_BYTES = 4; /// @notice nft priority op id bytes lengths uint8 constant NFT_PRIORITY_OP_ID_BYTES = 8; /// @notice nft global id bytes lengths uint8 constant NFT_GLOBAL_ID_BYTES = 8; /// @notic withdraw nft use fee token id bytes lengths uint8 constant NFT_FEE_TOKEN_ID = 1; /// @notic fullexit nft success bytes lengths uint8 constant NFT_SUCCESS = 1; // Deposit pubdata struct Deposit { uint32 accountId; uint16 tokenId; uint128 amount; address owner; } uint public constant PACKED_DEPOSIT_PUBDATA_BYTES = ACCOUNT_ID_BYTES + TOKEN_BYTES + AMOUNT_BYTES + ADDRESS_BYTES; /// Deserialize deposit pubdata function readDepositPubdata(bytes memory _data) internal pure returns (Deposit memory parsed) { // NOTE: there is no check that variable sizes are same as constants (i.e. TOKEN_BYTES), fix if possible. uint offset = 0; (offset, parsed.accountId) = Bytes.readUInt32(_data, offset); // accountId (offset, parsed.tokenId) = Bytes.readUInt16(_data, offset); // tokenId (offset, parsed.amount) = Bytes.readUInt128(_data, offset); // amount (offset, parsed.owner) = Bytes.readAddress(_data, offset); // owner require(offset == PACKED_DEPOSIT_PUBDATA_BYTES, "rdp10"); // reading invalid deposit pubdata size } /// Serialize deposit pubdata function writeDepositPubdata(Deposit memory op) internal pure returns (bytes memory buf) { buf = abi.encodePacked( bytes4(0), // accountId (ignored) (update when ACCOUNT_ID_BYTES is changed) op.tokenId, // tokenId op.amount, // amount op.owner // owner ); } /// @notice Check that deposit pubdata from request and block matches function depositPubdataMatch(bytes memory _lhs, bytes memory _rhs) internal pure returns (bool) { // We must ignore `accountId` because it is present in block pubdata but not in priority queue bytes memory lhs_trimmed = Bytes.slice(_lhs, ACCOUNT_ID_BYTES, PACKED_DEPOSIT_PUBDATA_BYTES - ACCOUNT_ID_BYTES); bytes memory rhs_trimmed = Bytes.slice(_rhs, ACCOUNT_ID_BYTES, PACKED_DEPOSIT_PUBDATA_BYTES - ACCOUNT_ID_BYTES); return keccak256(lhs_trimmed) == keccak256(rhs_trimmed); } // FullExit pubdata struct FullExit { uint32 accountId; address owner; uint16 tokenId; uint128 amount; } uint public constant PACKED_FULL_EXIT_PUBDATA_BYTES = ACCOUNT_ID_BYTES + ADDRESS_BYTES + TOKEN_BYTES + AMOUNT_BYTES; function readFullExitPubdata(bytes memory _data) internal pure returns (FullExit memory parsed) { // NOTE: there is no check that variable sizes are same as constants (i.e. TOKEN_BYTES), fix if possible. uint offset = 0; (offset, parsed.accountId) = Bytes.readUInt32(_data, offset); // accountId (offset, parsed.owner) = Bytes.readAddress(_data, offset); // owner (offset, parsed.tokenId) = Bytes.readUInt16(_data, offset); // tokenId (offset, parsed.amount) = Bytes.readUInt128(_data, offset); // amount require(offset == PACKED_FULL_EXIT_PUBDATA_BYTES, "rfp10"); // reading invalid full exit pubdata size } function writeFullExitPubdata(FullExit memory op) internal pure returns (bytes memory buf) { buf = abi.encodePacked( op.accountId, // accountId op.owner, // owner op.tokenId, // tokenId op.amount // amount ); } /// @notice Check that full exit pubdata from request and block matches function fullExitPubdataMatch(bytes memory _lhs, bytes memory _rhs) internal pure returns (bool) { // `amount` is ignored because it is present in block pubdata but not in priority queue uint lhs = Bytes.trim(_lhs, PACKED_FULL_EXIT_PUBDATA_BYTES - AMOUNT_BYTES); uint rhs = Bytes.trim(_rhs, PACKED_FULL_EXIT_PUBDATA_BYTES - AMOUNT_BYTES); return lhs == rhs; } // PartialExit pubdata struct PartialExit { //uint32 accountId; -- present in pubdata, ignored at serialization uint16 tokenId; uint128 amount; //uint16 fee; -- present in pubdata, ignored at serialization address owner; } function readPartialExitPubdata(bytes memory _data, uint _offset) internal pure returns (PartialExit memory parsed) { // NOTE: there is no check that variable sizes are same as constants (i.e. TOKEN_BYTES), fix if possible. uint offset = _offset + ACCOUNT_ID_BYTES; // accountId (ignored) (offset, parsed.owner) = Bytes.readAddress(_data, offset); // owner (offset, parsed.tokenId) = Bytes.readUInt16(_data, offset); // tokenId (offset, parsed.amount) = Bytes.readUInt128(_data, offset); // amount } function writePartialExitPubdata(PartialExit memory op) internal pure returns (bytes memory buf) { buf = abi.encodePacked( bytes4(0), // accountId (ignored) (update when ACCOUNT_ID_BYTES is changed) op.tokenId, // tokenId op.amount, // amount bytes2(0), // fee (ignored) (update when FEE_BYTES is changed) op.owner // owner ); } // ChangePubKey struct ChangePubKey { uint32 accountId; bytes20 pubKeyHash; address owner; uint32 nonce; } function readChangePubKeyPubdata(bytes memory _data, uint _offset) internal pure returns (ChangePubKey memory parsed) { uint offset = _offset; (offset, parsed.accountId) = Bytes.readUInt32(_data, offset); // accountId (offset, parsed.pubKeyHash) = Bytes.readBytes20(_data, offset); // pubKeyHash (offset, parsed.owner) = Bytes.readAddress(_data, offset); // owner (offset, parsed.nonce) = Bytes.readUInt32(_data, offset); // nonce } // Withdrawal nft data process struct WithdrawNFTData { bool valid; //confirm the necessity of this field bool pendingWithdraw; uint64 globalId; uint32 creatorId; uint32 seqId; address target; bytes32 uri; } function readWithdrawalData(bytes memory _data, uint _offset) internal pure returns (bool isNFTWithdraw, uint128 amount, uint16 _tokenId, WithdrawNFTData memory parsed) { uint offset = _offset; (offset, isNFTWithdraw) = Bytes.readBool(_data, offset); (offset, parsed.pendingWithdraw) = Bytes.readBool(_data, offset); (offset, parsed.target) = Bytes.readAddress(_data, offset); // target if (isNFTWithdraw) { (offset, parsed.globalId) = Bytes.readUInt64(_data, offset); (offset, parsed.creatorId) = Bytes.readUInt32(_data, offset); // creatorId (offset, parsed.seqId) = Bytes.readUInt32(_data, offset); // seqId (offset, parsed.uri) = Bytes.readBytes32(_data, offset); // uri (offset, parsed.valid) = Bytes.readBool(_data, offset); // is withdraw valid } else { (offset, _tokenId) = Bytes.readUInt16(_data, offset); (offset, amount) = Bytes.readUInt128(_data, offset); // withdraw erc20 or eth token amount } } // CreatePair pubdata struct CreatePair { uint32 accountId; uint16 tokenA; uint16 tokenB; uint16 tokenPair; address pair; } uint public constant PACKED_CREATE_PAIR_PUBDATA_BYTES = ACCOUNT_ID_BYTES + TOKEN_BYTES + TOKEN_BYTES + TOKEN_BYTES + ADDRESS_BYTES; function readCreatePairPubdata(bytes memory _data) internal pure returns (CreatePair memory parsed) { uint offset = 0; (offset, parsed.accountId) = Bytes.readUInt32(_data, offset); // accountId (offset, parsed.tokenA) = Bytes.readUInt16(_data, offset); // tokenAId (offset, parsed.tokenB) = Bytes.readUInt16(_data, offset); // tokenBId (offset, parsed.tokenPair) = Bytes.readUInt16(_data, offset); // pairId (offset, parsed.pair) = Bytes.readAddress(_data, offset); // pairId require(offset == PACKED_CREATE_PAIR_PUBDATA_BYTES, "rcp10"); // reading invalid create pair pubdata size } function writeCreatePairPubdata(CreatePair memory op) internal pure returns (bytes memory buf) { buf = abi.encodePacked( bytes4(0), // accountId (ignored) (update when ACCOUNT_ID_BYTES is changed) op.tokenA, // tokenAId op.tokenB, // tokenBId op.tokenPair, // pairId op.pair // pair account ); } /// @notice Check that create pair pubdata from request and block matches function createPairPubdataMatch(bytes memory _lhs, bytes memory _rhs) internal pure returns (bool) { // We must ignore `accountId` because it is present in block pubdata but not in priority queue bytes memory lhs_trimmed = Bytes.slice(_lhs, ACCOUNT_ID_BYTES, PACKED_CREATE_PAIR_PUBDATA_BYTES - ACCOUNT_ID_BYTES); bytes memory rhs_trimmed = Bytes.slice(_rhs, ACCOUNT_ID_BYTES, PACKED_CREATE_PAIR_PUBDATA_BYTES - ACCOUNT_ID_BYTES); return keccak256(lhs_trimmed) == keccak256(rhs_trimmed); } // DepositNFT pubdata struct DepositNFT { uint64 globalId; uint32 creatorId; uint32 seqId; bytes32 uri; address owner; uint32 accountId; } uint public constant PACKED_DEPOSIT_NFT_PUBDATA_BYTES = ACCOUNT_ID_BYTES + NFT_GLOBAL_ID_BYTES + NFT_CREATOR_ID_BYTES + NFT_SEQUENCE_ID_BYTES + NFT_URI_BYTES + ADDRESS_BYTES ; /// Deserialize deposit nft pubdata function readDepositNFTPubdata(bytes memory _data) internal pure returns (DepositNFT memory parsed) { uint offset = 0; (offset, parsed.globalId) = Bytes.readUInt64(_data, offset); // globalId (offset, parsed.creatorId) = Bytes.readUInt32(_data, offset); // creatorId (offset, parsed.seqId) = Bytes.readUInt32(_data, offset); // seqId (offset, parsed.uri) = Bytes.readBytes32(_data, offset); // uri (offset, parsed.owner) = Bytes.readAddress(_data, offset); // owner (offset, parsed.accountId) = Bytes.readUInt32(_data, offset); // accountId require(offset == PACKED_DEPOSIT_NFT_PUBDATA_BYTES, "rdnp10"); // reading invalid deposit pubdata size } /// Serialize deposit pubdata function writeDepositNFTPubdata(DepositNFT memory op) internal pure returns (bytes memory buf) { buf = abi.encodePacked( op.globalId, op.creatorId, op.seqId, op.uri, op.owner, // owner bytes4(0) ); } /// @notice Check that deposit nft pubdata from request and block matches function depositNFTPubdataMatch(bytes memory _lhs, bytes memory _rhs) internal pure returns (bool) { // We must ignore `accountId` because it is present in block pubdata but not in priority queue uint offset = 0; uint64 globalId; (offset, globalId) = Bytes.readUInt64(_lhs, offset); // globalId if (globalId == 0){ bytes memory lhs_trimmed = Bytes.slice(_lhs, NFT_GLOBAL_ID_BYTES, PACKED_DEPOSIT_NFT_PUBDATA_BYTES - ACCOUNT_ID_BYTES - NFT_GLOBAL_ID_BYTES); bytes memory rhs_trimmed = Bytes.slice(_rhs, NFT_GLOBAL_ID_BYTES, PACKED_DEPOSIT_NFT_PUBDATA_BYTES - ACCOUNT_ID_BYTES - NFT_GLOBAL_ID_BYTES); return keccak256(lhs_trimmed) == keccak256(rhs_trimmed); }else{ bytes memory lhs_trimmed = Bytes.slice(_lhs, 0, PACKED_DEPOSIT_NFT_PUBDATA_BYTES - ACCOUNT_ID_BYTES); bytes memory rhs_trimmed = Bytes.slice(_rhs, 0, PACKED_DEPOSIT_NFT_PUBDATA_BYTES - ACCOUNT_ID_BYTES); return keccak256(lhs_trimmed) == keccak256(rhs_trimmed); } } // FullExitNFT pubdata struct FullExitNFT { uint32 accountId; uint64 globalId; uint32 creatorId; uint32 seqId; bytes32 uri; address owner; uint8 success; } uint public constant PACKED_FULL_EXIT_NFT_PUBDATA_BYTES = ACCOUNT_ID_BYTES + NFT_GLOBAL_ID_BYTES + NFT_CREATOR_ID_BYTES + NFT_SEQUENCE_ID_BYTES + NFT_URI_BYTES + ADDRESS_BYTES + NFT_SUCCESS; function readFullExitNFTPubdata(bytes memory _data) internal pure returns (FullExitNFT memory parsed) { uint offset = 0; (offset, parsed.accountId) = Bytes.readUInt32(_data, offset); // accountId (offset, parsed.globalId) = Bytes.readUInt64(_data, offset); // globalId (offset, parsed.creatorId) = Bytes.readUInt32(_data, offset); // creator (offset, parsed.seqId) = Bytes.readUInt32(_data, offset); // seqId (offset, parsed.uri) = Bytes.readBytes32(_data, offset); // uri (offset, parsed.owner) = Bytes.readAddress(_data, offset); // owner (offset, parsed.success) = Bytes.readUint8(_data, offset); // success require(offset == PACKED_FULL_EXIT_NFT_PUBDATA_BYTES, "rfnp10"); // reading invalid deposit pubdata size } function writeFullExitNFTPubdata(FullExitNFT memory op) internal pure returns (bytes memory buf) { buf = abi.encodePacked( op.accountId, op.globalId, // nft id in layer2 op.creatorId, op.seqId, op.uri, op.owner, op.success ); } /// @notice Check that full exit pubdata from request and block matches /// TODO check it function fullExitNFTPubdataMatch(bytes memory _lhs, bytes memory _rhs) internal pure returns (bool) { bytes memory lhs_trimmed_1 = Bytes.slice(_lhs, 0, ACCOUNT_ID_BYTES + NFT_GLOBAL_ID_BYTES); bytes memory rhs_trimmed_1 = Bytes.slice(_rhs, 0, ACCOUNT_ID_BYTES + NFT_GLOBAL_ID_BYTES); bytes memory lhs_trimmed_2 = Bytes.slice(_lhs, PACKED_FULL_EXIT_NFT_PUBDATA_BYTES - ADDRESS_BYTES - NFT_SUCCESS, ADDRESS_BYTES); bytes memory rhs_trimmed_2 = Bytes.slice(_rhs, PACKED_FULL_EXIT_NFT_PUBDATA_BYTES - ADDRESS_BYTES - NFT_SUCCESS, ADDRESS_BYTES); return keccak256(lhs_trimmed_1) == keccak256(rhs_trimmed_1) && keccak256(lhs_trimmed_2) == keccak256(rhs_trimmed_2); } // PartialExitNFT pubdata struct PartialExitNFT { // uint32 accountId; uint64 globalId; uint32 creatorId; uint32 seqId; bytes32 uri; address owner; } function readPartialExitNFTPubdata(bytes memory _data, uint _offset) internal pure returns (PartialExitNFT memory parsed) { uint offset = _offset + ACCOUNT_ID_BYTES; // accountId (ignored) (offset, parsed.globalId) = Bytes.readUInt64(_data, offset); // globalId (offset, parsed.creatorId) = Bytes.readUInt32(_data, offset); // creatorId (offset, parsed.seqId) = Bytes.readUInt32(_data, offset); // seqId (offset, parsed.uri) = Bytes.readBytes32(_data, offset); // uri (offset, parsed.owner) = Bytes.readAddress(_data, offset); // owner } function writePartialExitNFTPubdata(PartialExitNFT memory op) internal pure returns (bytes memory buf) { buf = abi.encodePacked( bytes4(0), // accountId (ignored) (update when ACCOUNT_ID_BYTES is changed) op.globalId, // tokenId in layer2 bytes4(0), bytes4(0), bytes32(0), op.owner ); } } pragma solidity ^0.5.0; // Functions named bytesToX, except bytesToBytes20, where X is some type of size N < 32 (size of one word) // implements the following algorithm: // f(bytes memory input, uint offset) -> X out // where byte representation of out is N bytes from input at the given offset // 1) We compute memory location of the word W such that last N bytes of W is input[offset..offset+N] // W_address = input + 32 (skip stored length of bytes) + offset - (32 - N) == input + offset + N // 2) We load W from memory into out, last N bytes of W are placed into out library Bytes { function toBytesFromUInt16(uint16 self) internal pure returns (bytes memory _bts) { return toBytesFromUIntTruncated(uint(self), 2); } function toBytesFromUInt24(uint24 self) internal pure returns (bytes memory _bts) { return toBytesFromUIntTruncated(uint(self), 3); } function toBytesFromUInt32(uint32 self) internal pure returns (bytes memory _bts) { return toBytesFromUIntTruncated(uint(self), 4); } function toBytesFromUInt128(uint128 self) internal pure returns (bytes memory _bts) { return toBytesFromUIntTruncated(uint(self), 16); } // Copies 'len' lower bytes from 'self' into a new 'bytes memory'. // Returns the newly created 'bytes memory'. The returned bytes will be of length 'len'. function toBytesFromUIntTruncated(uint self, uint8 byteLength) private pure returns (bytes memory bts) { require(byteLength <= 32, "bt211"); bts = new bytes(byteLength); // Even though the bytes will allocate a full word, we don't want // any potential garbage bytes in there. uint data = self << ((32 - byteLength) * 8); assembly { mstore(add(bts, /*BYTES_HEADER_SIZE*/32), data) } } // Copies 'self' into a new 'bytes memory'. // Returns the newly created 'bytes memory'. The returned bytes will be of length '20'. function toBytesFromAddress(address self) internal pure returns (bytes memory bts) { bts = toBytesFromUIntTruncated(uint(self), 20); } // See comment at the top of this file for explanation of how this function works. // NOTE: theoretically possible overflow of (_start + 20) function bytesToAddress(bytes memory self, uint256 _start) internal pure returns (address addr) { uint256 offset = _start + 20; require(self.length >= offset, "bta11"); assembly { addr := mload(add(self, offset)) } } // Reasoning about why this function works is similar to that of other similar functions, except NOTE below. // NOTE: that bytes1..32 is stored in the beginning of the word unlike other primitive types // NOTE: theoretically possible overflow of (_start + 20) function bytesToBytes20(bytes memory self, uint256 _start) internal pure returns (bytes20 r) { require(self.length >= (_start + 20), "btb20"); assembly { r := mload(add(add(self, 0x20), _start)) } } // See comment at the top of this file for explanation of how this function works. // NOTE: theoretically possible overflow of (_start + 0x2) function bytesToUInt16(bytes memory _bytes, uint256 _start) internal pure returns (uint16 r) { uint256 offset = _start + 0x2; require(_bytes.length >= offset, "btu02"); assembly { r := mload(add(_bytes, offset)) } } // See comment at the top of this file for explanation of how this function works. // NOTE: theoretically possible overflow of (_start + 0x3) function bytesToUInt24(bytes memory _bytes, uint256 _start) internal pure returns (uint24 r) { uint256 offset = _start + 0x3; require(_bytes.length >= offset, "btu03"); assembly { r := mload(add(_bytes, offset)) } } // NOTE: theoretically possible overflow of (_start + 0x4) function bytesToUInt32(bytes memory _bytes, uint256 _start) internal pure returns (uint32 r) { uint256 offset = _start + 0x4; require(_bytes.length >= offset, "btu04"); assembly { r := mload(add(_bytes, offset)) } } // NOTE: theoretically possible overflow of (_start + 0x8) function bytesToUInt64(bytes memory _bytes, uint256 _start) internal pure returns (uint64 r) { uint256 offset = _start + 0x8; require(_bytes.length >= offset, "btu08"); assembly { r := mload(add(_bytes, offset)) } } // NOTE: theoretically possible overflow of (_start + 0x10) function bytesToUInt128(bytes memory _bytes, uint256 _start) internal pure returns (uint128 r) { uint256 offset = _start + 0x10; require(_bytes.length >= offset, "btu16"); assembly { r := mload(add(_bytes, offset)) } } // See comment at the top of this file for explanation of how this function works. // NOTE: theoretically possible overflow of (_start + 0x14) function bytesToUInt160(bytes memory _bytes, uint256 _start) internal pure returns (uint160 r) { uint256 offset = _start + 0x14; require(_bytes.length >= offset, "btu20"); assembly { r := mload(add(_bytes, offset)) } } // NOTE: theoretically possible overflow of (_start + 0x20) function bytesToBytes32(bytes memory _bytes, uint256 _start) internal pure returns (bytes32 r) { uint256 offset = _start + 0x20; require(_bytes.length >= offset, "btb32"); assembly { r := mload(add(_bytes, offset)) } } // Original source code: https://github.com/GNSPS/solidity-bytes-utils/blob/master/contracts/BytesLib.sol#L228 // Get slice from bytes arrays // Returns the newly created 'bytes memory' // NOTE: theoretically possible overflow of (_start + _length) function slice( bytes memory _bytes, uint _start, uint _length ) internal pure returns (bytes memory) { require(_bytes.length >= (_start + _length), "bse11"); // bytes length is less then start byte + length bytes bytes memory tempBytes = new bytes(_length); if (_length != 0) { // TODO: Review this thoroughly. assembly { let slice_curr := add(tempBytes, 0x20) let slice_end := add(slice_curr, _length) for { let array_current := add(_bytes, add(_start, 0x20)) } lt(slice_curr, slice_end) { slice_curr := add(slice_curr, 0x20) array_current := add(array_current, 0x20) } { mstore(slice_curr, mload(array_current)) } } } return tempBytes; } /// Reads byte stream /// @return new_offset - offset + amount of bytes read /// @return data - actually read data // NOTE: theoretically possible overflow of (_offset + _length) function read(bytes memory _data, uint _offset, uint _length) internal pure returns (uint new_offset, bytes memory data) { data = slice(_data, _offset, _length); new_offset = _offset + _length; } // NOTE: theoretically possible overflow of (_offset + 1) function readBool(bytes memory _data, uint _offset) internal pure returns (uint new_offset, bool r) { new_offset = _offset + 1; r = uint8(_data[_offset]) != 0; } // NOTE: theoretically possible overflow of (_offset + 1) function readUint8(bytes memory _data, uint _offset) internal pure returns (uint new_offset, uint8 r) { new_offset = _offset + 1; r = uint8(_data[_offset]); } // NOTE: theoretically possible overflow of (_offset + 2) function readUInt16(bytes memory _data, uint _offset) internal pure returns (uint new_offset, uint16 r) { new_offset = _offset + 2; r = bytesToUInt16(_data, _offset); } // NOTE: theoretically possible overflow of (_offset + 3) function readUInt24(bytes memory _data, uint _offset) internal pure returns (uint new_offset, uint24 r) { new_offset = _offset + 3; r = bytesToUInt24(_data, _offset); } // NOTE: theoretically possible overflow of (_offset + 4) function readUInt32(bytes memory _data, uint _offset) internal pure returns (uint new_offset, uint32 r) { new_offset = _offset + 4; r = bytesToUInt32(_data, _offset); } // NOTE: theoretically possible overflow of (_offset + 8) function readUInt64(bytes memory _data, uint _offset) internal pure returns (uint new_offset, uint64 r) { new_offset = _offset + 8; r = bytesToUInt64(_data, _offset); } // NOTE: theoretically possible overflow of (_offset + 16) function readUInt128(bytes memory _data, uint _offset) internal pure returns (uint new_offset, uint128 r) { new_offset = _offset + 16; r = bytesToUInt128(_data, _offset); } // NOTE: theoretically possible overflow of (_offset + 20) function readUInt160(bytes memory _data, uint _offset) internal pure returns (uint new_offset, uint160 r) { new_offset = _offset + 20; r = bytesToUInt160(_data, _offset); } // NOTE: theoretically possible overflow of (_offset + 20) function readAddress(bytes memory _data, uint _offset) internal pure returns (uint new_offset, address r) { new_offset = _offset + 20; r = bytesToAddress(_data, _offset); } // NOTE: theoretically possible overflow of (_offset + 20) function readBytes20(bytes memory _data, uint _offset) internal pure returns (uint new_offset, bytes20 r) { new_offset = _offset + 20; r = bytesToBytes20(_data, _offset); } // NOTE: theoretically possible overflow of (_offset + 32) function readBytes32(bytes memory _data, uint _offset) internal pure returns (uint new_offset, bytes32 r) { new_offset = _offset + 32; r = bytesToBytes32(_data, _offset); } // Helper function for hex conversion. function halfByteToHex(byte _byte) internal pure returns (byte _hexByte) { require(uint8(_byte) < 0x10, "hbh11"); // half byte's value is out of 0..15 range. // "FEDCBA9876543210" ASCII-encoded, shifted and automatically truncated. return byte (uint8 (0x66656463626139383736353433323130 >> (uint8 (_byte) * 8))); } // Convert bytes to ASCII hex representation function bytesToHexASCIIBytes(bytes memory _input) internal pure returns (bytes memory _output) { bytes memory outStringBytes = new bytes(_input.length * 2); // code in `assembly` construction is equivalent of the next code: // for (uint i = 0; i < _input.length; ++i) { // outStringBytes[i*2] = halfByteToHex(_input[i] >> 4); // outStringBytes[i*2+1] = halfByteToHex(_input[i] & 0x0f); // } assembly { let input_curr := add(_input, 0x20) let input_end := add(input_curr, mload(_input)) for { let out_curr := add(outStringBytes, 0x20) } lt(input_curr, input_end) { input_curr := add(input_curr, 0x01) out_curr := add(out_curr, 0x02) } { let curr_input_byte := shr(0xf8, mload(input_curr)) // here outStringByte from each half of input byte calculates by the next: // // "FEDCBA9876543210" ASCII-encoded, shifted and automatically truncated. // outStringByte = byte (uint8 (0x66656463626139383736353433323130 >> (uint8 (_byteHalf) * 8))) mstore(out_curr, shl(0xf8, shr(mul(shr(0x04, curr_input_byte), 0x08), 0x66656463626139383736353433323130))) mstore(add(out_curr, 0x01), shl(0xf8, shr(mul(and(0x0f, curr_input_byte), 0x08), 0x66656463626139383736353433323130))) } } return outStringBytes; } /// Trim bytes into single word function trim(bytes memory _data, uint _new_length) internal pure returns (uint r) { require(_new_length <= 0x20, "trm10"); // new_length is longer than word require(_data.length >= _new_length, "trm11"); // data is to short uint a; assembly { a := mload(add(_data, 0x20)) // load bytes into uint256 } return a >> ((0x20 - _new_length) * 8); } }
Reasoning about why this function works is similar to that of other similar functions, except NOTE below. NOTE: that bytes1..32 is stored in the beginning of the word unlike other primitive types NOTE: theoretically possible overflow of (_start + 20)
function bytesToBytes20(bytes memory self, uint256 _start) internal pure returns (bytes20 r) { require(self.length >= (_start + 20), "btb20"); assembly { r := mload(add(add(self, 0x20), _start)) } }
287,852
./full_match/641230/0x9650d2Abb5EF35Cbd1Cf0CE246e29eFB60295754/sources/SMBV3Factory1.sol
Sets the initial price for the pool Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value sqrtPriceX96 the initial sqrt price of the pool as a Q64.96 Adds liquidity for the given recipient/tickLower/tickUpper position The caller of this method receives a callback in the form of ISMBV3MintCallbacksmbV3MintCallback in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends on tickLower, tickUpper, the amount of liquidity, and the current price. recipient The address for which the liquidity will be created tickLower The lower tick of the position in which to add liquidity tickUpper The upper tick of the position in which to add liquidity amount The amount of liquidity to mint data Any data that should be passed through to the callback return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback Collects tokens owed to a position Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity. Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity. recipient The address which should receive the fees collected tickLower The lower tick of the position for which to collect fees tickUpper The upper tick of the position for which to collect fees amount0Requested How much token0 should be withdrawn from the fees owed amount1Requested How much token1 should be withdrawn from the fees owed return amount0 The amount of fees collected in token0 return amount1 The amount of fees collected in token1 Burn liquidity from the sender and account tokens owed for the liquidity to the position Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0 Fees must be collected separately via a call to collect tickLower The lower tick of the position for which to burn liquidity tickUpper The upper tick of the position for which to burn liquidity amount How much liquidity to burn return amount0 The amount of token0 sent to the recipient return amount1 The amount of token1 sent to the recipient Swap token0 for token1, or token1 for token0 The caller of this method receives a callback in the form of ISMBV3SwapCallbacksmbV3SwapCallback recipient The address to receive the output of the swap zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0 amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative) sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this value after the swap. If one for zero, the price cannot be greater than this value after the swap data Any data to be passed through to the callback return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive Receive token0 and/or token1 and pay it back, plus a fee, in the callback The caller of this method receives a callback in the form of ISMBV3FlashCallbacksmbV3FlashCallback Can be used to donate underlying tokens pro-rata to currently in-range liquidity providers by calling with 0 amount{0,1} and sending the donation amount(s) from the callback recipient The address which will receive the token0 and token1 amounts amount0 The amount of token0 to send amount1 The amount of token1 to send data Any data to be passed through to the callback Increase the maximum number of price and liquidity observations that this pool will store This method is no-op if the pool already has an observationCardinalityNext greater than or equal to the input observationCardinalityNext. observationCardinalityNext The desired minimum number of observations for the pool to store Permissioned pool actions Contains pool methods that may only be called by the factory owner
interface ISMBV3PoolOwnerActions { function setFeeProtocol(uint32 feeProtocol0, uint32 feeProtocol1) external; function collectProtocol( address recipient, uint128 amount0Requested, uint128 amount1Requested ) external returns (uint128 amount0, uint128 amount1); function setLmPool(address lmPool) external; }
14,292,080
./partial_match/56/0x0d8Ad2624EaA3A0789dc0611d091b085344EFC94/sources/EToken2.sol
Trust an address to perform recovery procedure for the caller. _to trustee. return success./ Should trust to another address. Should trust to yet untrusted.
function trust(address _to) returns(bool) { uint fromId = _createHolderId(msg.sender); if (fromId == getHolderId(_to)) { _error('Cannot trust to oneself'); return false; } if (isTrusted(msg.sender, _to)) { _error('Already trusted'); return false; } holders[fromId].trust[_to] = true; return true; }
11,327,736
// SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "./Context.sol"; import "./IERC20.sol"; import "./SafeMath.sol"; import "./Address.sol"; import "./AccessControl.sol"; import "./PriceFeed.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * */ contract Brrr is Context, IERC20, AccessControl, PriceFeed { bool public Online = true; modifier isOffline { _; require(!Online, "Contract is running still"); } modifier isOnline { _; require(Online, "Contract has been turned off"); } using SafeMath for uint256; using Address for address; IERC20 Tether; bytes32 public constant FOUNDING_FATHER = keccak256("FOUNDING_FATHER"); mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; //list of accepted coins for transferring mapping(address => bool) public _acceptedStableCoins; //address of the oracle price feed for accept coins mapping(address => address) private _contract_address_to_oracle; //deposits for each user in eth mapping(address => uint256) public _deposits_eth; //total withdrawals per user mapping(address => uint256) public _total_withdrawals; //deposits for each user in their coins mapping(address => mapping(address => uint256)) public _coin_deposits; //claimed stimulus per user per stimulus mapping(address => mapping(uint128 => bool)) public _claimed_stimulus; //all stimulus ids mapping(uint128 => bool) public _all_Claim_ids; //stimulus id to stimulus info mapping(uint128 => Claims) public _all_Claims; //tether total supply checks/history supplyCheck[] public _all_supply_checks; //total coins related to tether in reserves uint256 public TreasuryReserve; uint256 private _totalSupply; //max limit uint256 public TOTALCAP = 8000000000000000 * 10**18; //total coins in circulation uint256 public _circulatingSupply; string private _name; string private _symbol; uint8 private _decimals; //usdt address address public tether = 0xdAC17F958D2ee523a2206206994597C13D831ec7; //brrr3x address address public brrr3x; //brrr10x address address public brrr10x; struct Claims { uint256 _amount; uint256 _ending; uint256 _amount_to_give; } struct supplyCheck { uint256 _last_check; uint256 _totalSupply; } event Withdraw(address indexed _reciever, uint256 indexed _amount); /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * Sets the total supply from tether * * Gives founding father liquidity share for uniswap * * Sets first supply check * */ constructor(string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setupRole(FOUNDING_FATHER, msg.sender); Tether = IERC20(tether); uint256 d = Tether.totalSupply(); TreasuryReserve = d * 10**13; _balances[msg.sender] = 210000000 * 10**18; _circulatingSupply = 210000000 * 10**18; _totalSupply = TreasuryReserve.sub(_circulatingSupply); TreasuryReserve = TreasuryReserve.sub(_circulatingSupply); supplyCheck memory sa = supplyCheck(block.timestamp, d); _all_supply_checks.push(sa); } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public override view returns (uint256) { return _circulatingSupply.add(TreasuryReserve); } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public override view returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public virtual override view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * If address is approved brrr3x or brrr10x address don't check allowance and allow 1 transaction transfer (no approval needed) */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); if (msg.sender != brrr3x && msg.sender != brrr10x) { _approve( sender, _msgSender(), _allowances[sender][_msgSender()].sub( amount, "ERC20: transfer amount exceeds allowance" ) ); } return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue) ); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender].sub( subtractedValue, "ERC20: decreased allowance below zero" ) ); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub( amount, "ERC20: transfer amount exceeds balance" ); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens from tether burning tokens * * Cannot go past cap. * * Emits a {Transfer} event with `from` set to the zero address. */ function _printerGoesBrrr(uint256 amount) internal returns (bool) { require(amount > 0, "Can't mint 0 tokens"); require(TreasuryReserve.add(amount) < cap(), "Cannot exceed cap"); TreasuryReserve = TreasuryReserve.add(amount); _totalSupply = TreasuryReserve; emit Transfer(address(0), address(this), amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual isOnline { require(account != address(0), "ERC20: mint to the zero address"); require(amount <= TreasuryReserve, "More than the reserve holds"); _circulatingSupply = _circulatingSupply.add(amount); TreasuryReserve = TreasuryReserve.sub(amount); _totalSupply = TreasuryReserve; _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `TreasuryReserve`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `Treasury Reserve` must have at least `amount` tokens. */ function _burn(uint256 amount) internal virtual { if (amount <= TreasuryReserve) { TreasuryReserve = TreasuryReserve.sub( amount, "ERC20: burn amount exceeds Treasury Reserve" ); _totalSupply = TreasuryReserve; emit Transfer(address(this), address(0), amount); } else { TreasuryReserve = 0; _totalSupply = TreasuryReserve; emit Transfer(address(this), address(0), amount); } } /** * @dev Returns the users deposit in ETH and changes the circulating supply and treasury reserves based off the brrr sent back * * * Emits withdraw event. * * */ function _payBackBrrrETH( uint256 _brrrAmount, address payable _owner, uint256 _returnAmount ) internal returns (bool) { require( _deposits_eth[_owner] >= _returnAmount, "More than deposit amount" ); _balances[_owner] = _balances[_owner].sub(_brrrAmount); TreasuryReserve = TreasuryReserve.add(_brrrAmount); _totalSupply = TreasuryReserve; _circulatingSupply = _circulatingSupply.sub(_brrrAmount); emit Transfer(address(_owner), address(this), _brrrAmount); _deposits_eth[_owner] = _deposits_eth[_owner].sub(_returnAmount); _transferEth(_owner, _returnAmount); emit Withdraw(address(_owner), _returnAmount); return true; } /** * @dev Returns the users deposit in alt coins and changes the circulating supply and treasury reserves based off the brrr sent back * * * Emits withdraw event. * * */ function _payBackBrrrCoins( uint256 _brrrAmount, address payable _owner, address _contract, uint256 _returnAmount ) internal returns (bool) { require( _coin_deposits[_owner][_contract] >= _returnAmount, "More than deposit amount" ); _balances[_owner] = _balances[_owner].sub(_brrrAmount); TreasuryReserve = TreasuryReserve.add(_brrrAmount); _totalSupply = TreasuryReserve; _circulatingSupply = _circulatingSupply.sub(_brrrAmount); emit Transfer(address(_owner), address(this), _brrrAmount); _coin_deposits[_owner][_contract] = _coin_deposits[_owner][_contract] .sub(_returnAmount); _transferCoin(_owner, _contract, _returnAmount); emit Withdraw(address(_owner), _returnAmount); return true; } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Gives user reward for updating the total supply. */ function _giveReward(uint256 reward) internal returns (bool) { _circulatingSupply = _circulatingSupply.add(reward); _balances[_msgSender()] = _balances[_msgSender()].add(reward); emit Transfer(address(this), address(_msgSender()), reward); return true; } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Returns the cap on the token's total supply. */ function cap() public view returns (uint256) { return TOTALCAP; } /** * @dev Returns the price of the bonding curve divided by number of withdrawals the user has already made. * * Prevents spamming deposit -> withdrawal -> deposit... to drain all brrr. */ function calculateWithdrawalPrice() internal view returns (uint256) { uint256 p = calculateCurve(); uint256 w = _total_withdrawals[_msgSender()]; if (w < 1) { w = 1; } p = p.div(w); return p; } /** * @dev Internal transfer eth function * */ function _transferEth(address payable _recipient, uint256 _amount) internal returns (bool) { _recipient.transfer(_amount); return true; } /** * @dev Internal transfer altcoin function * */ function _transferCoin( address _owner, address _contract, uint256 _returnAmount ) internal returns (bool) { IERC20 erc; erc = IERC20(_contract); require( erc.balanceOf(address(this)) >= _returnAmount, "Not enough funds to transfer" ); require(erc.transfer(_owner, _returnAmount)); return true; } /**@dev Adds another token to the accepted coins for printing * * * Calling conditions: * * - Address of the contract to be added * - Only can be added by founding fathers * */ function addAcceptedStableCoin(address _contract, address _oracleAddress) public isOnline returns (bool) { require( hasRole(FOUNDING_FATHER, msg.sender), "Caller is not a Founding Father" ); _acceptedStableCoins[_contract] = true; _contract_address_to_oracle[_contract] = _oracleAddress; return _acceptedStableCoins[_contract]; } /**@dev Adds stimulus package to be claimed by users * * * Calling conditions: * - Only can be added by founding fathers * */ function addStimulus( uint128 _id, uint256 _total_amount, uint256 _ending_in_days, uint256 _amount_to_get ) public isOnline returns (bool) { require( hasRole(FOUNDING_FATHER, msg.sender), "Caller is not a Founding Father" ); require(_all_Claim_ids[_id] == false, "ID already used"); require(_total_amount <= TreasuryReserve); _all_Claim_ids[_id] = true; _all_Claims[_id]._amount = _total_amount * 10**18; _all_Claims[_id]._amount_to_give = _amount_to_get; _all_Claims[_id]._ending = block.timestamp + (_ending_in_days * 1 days); return true; } /**@dev Claim a stimulus package. * * requires _id of stimulus package. * Calling conditions: * - can only claim once * - must not be ended * - must not be out of funds. * */ function claimStimulus(uint128 _id) public isOnline returns (bool) { require(_all_Claim_ids[_id], "Claim not valid"); require( _claimed_stimulus[_msgSender()][_id] == false, "Already claimed!" ); require( block.timestamp <= _all_Claims[_id]._ending, "Stimulus package has ended" ); require( _all_Claims[_id]._amount >= _all_Claims[_id]._amount_to_give, "Out of money :(" ); _claimed_stimulus[_msgSender()][_id] = true; _all_Claims[_id]._amount = _all_Claims[_id]._amount.sub( _all_Claims[_id]._amount_to_give * 10**18 ); _mint(_msgSender(), _all_Claims[_id]._amount_to_give * 10**18); return true; } /** Bonding curve * circulating * reserve ratio / total supply * circulating * .10 / totalSupply * * */ function calculateCurve() public override view returns (uint256) { uint256 p = ( (_circulatingSupply.mul(10).div(100) * 10**18).div(TreasuryReserve) ); if (p <= 0) { p = 1; } return p; } /**@dev Deposit eth and get the value of brrr based off bonding curve * * * */ function printWithETH() public payable isOnline returns (bool) { require( msg.value > 0, "Please send money to make the printer go brrrrrrrr" ); uint256 p = calculateCurve(); uint256 amount = (msg.value.mul(10**18).div(p)); require(amount > 0, "Not enough sent for 1 brrr"); _deposits_eth[_msgSender()] = _deposits_eth[_msgSender()].add( msg.value ); _mint(_msgSender(), amount); return true; } /**@dev Deposit alt coins and get the value of brrr based off bonding curve * * * */ function printWithStablecoin(address _contract, uint256 _amount) public isOnline returns (bool) { require( _acceptedStableCoins[_contract], "Not accepted as a form of payment" ); IERC20 erc; erc = IERC20(_contract); uint256 al = erc.allowance(_msgSender(), address(this)); require(al >= _amount, "Token allowance not enough"); uint256 p = calculateCurve(); uint256 tp = getLatestPrice(_contract_address_to_oracle[_contract]); uint256 a = _amount.mul(tp).div(p); require(a > 0, "Not enough sent for 1 brrr"); require( erc.transferFrom(_msgSender(), address(this), _amount), "Transfer failed" ); _coin_deposits[_msgSender()][_contract] = _coin_deposits[_msgSender()][_contract] .add(_amount); _mint(_msgSender(), a); return true; } /**@dev Internal transfer from brrr3x or brrr10x in order to transfer and update balances * * * */ function _transferBrr(address _contract) internal returns (bool) { IERC20 brr; brr = IERC20(_contract); uint256 brrbalance = brr.balanceOf(_msgSender()); if (brrbalance > 0) { require( brr.transferFrom(_msgSender(), address(this), brrbalance), "Transfer failed" ); _mint(_msgSender(), brrbalance); } return true; } /**@dev Transfers entire brrrX balance into brrr at 1 to 1 * Deposits on brrrX will not be cleared. * * */ function convertBrrrXintoBrrr() public isOnline returns (bool) { _transferBrr(address(brrr3x)); _transferBrr(address(brrr10x)); return true; } /**@dev Deposit brrr and get the value of eth for that amount of brrr based off bonding curve * * * */ function returnBrrrForETH() public isOnline returns (bool) { require(_deposits_eth[_msgSender()] > 0, "You have no deposits"); require(_balances[_msgSender()] > 0, "No brrr balance"); uint256 p = calculateWithdrawalPrice(); uint256 r = _deposits_eth[_msgSender()].div(p).mul(10**18); if (_balances[_msgSender()] >= r) { _payBackBrrrETH(r, _msgSender(), _deposits_eth[_msgSender()]); } else { uint256 t = _balances[_msgSender()].mul(p).div(10**18); require( t <= _balances[_msgSender()], "More than in your balance, error with math" ); _payBackBrrrETH(_balances[_msgSender()], _msgSender(), t); } _total_withdrawals[_msgSender()] = _total_withdrawals[_msgSender()].add( 1 ); } /**@dev Deposit brrr and get the value of alt coins for that amount of brrr based off bonding curve * * * */ function returnBrrrForCoins(address _contract) public isOnline returns (bool) { require( _acceptedStableCoins[_contract], "Not accepted as a form of payment" ); require( _coin_deposits[_msgSender()][_contract] != 0, "You have no deposits" ); require(_balances[_msgSender()] > 0, "No brrr balance"); uint256 o = calculateWithdrawalPrice(); uint256 rg = getLatestPrice(_contract_address_to_oracle[_contract]); uint256 y = _coin_deposits[_msgSender()][_contract].mul(rg).div(o); if (_balances[_msgSender()] >= y) { _payBackBrrrCoins( y, _msgSender(), _contract, _coin_deposits[_msgSender()][_contract] ); } else { uint256 t = _balances[_msgSender()].mul(o).div(rg).div(10**18); require( t <= _balances[_msgSender()], "More than in your balance, error with math" ); _payBackBrrrCoins( _balances[_msgSender()], _msgSender(), _contract, t ); } _total_withdrawals[_msgSender()] = _total_withdrawals[_msgSender()].add( 1 ); } /**@dev Update the total supply from tether - if tether has changed total supply. * * Makes the money printer go brrrrrrrr * Reward is given to whoever updates * */ function brrrEvent() public isOnline returns (uint256) { require( block.timestamp > _all_supply_checks[_all_supply_checks.length.sub(1)] ._last_check, "Already checked!" ); uint256 l = _all_supply_checks[_all_supply_checks.length.sub(1)] ._last_check; uint256 s = _all_supply_checks[_all_supply_checks.length.sub(1)] ._totalSupply; uint256 d = Tether.totalSupply(); require(d != s, "The supply hasn't changed"); if (d < s) { supplyCheck memory sa = supplyCheck(block.timestamp, d); _all_supply_checks.push(sa); d = (s.sub(d)) * 10**12; uint256 reward = d.div(1000); d = d.sub(reward); _printerGoesBrrr(d); _giveReward(reward); return reward; } if (d > s) { supplyCheck memory sa = supplyCheck(block.timestamp, d); _all_supply_checks.push(sa); d = (d.sub(s)) * 10**12; uint256 reward = d.div(1000); d = d.sub(reward); _burn(d); _giveReward(reward); return reward; } } /**@dev In case of emgergency - withdrawal all eth. * * Contract must be offline * * */ function EmergencyWithdrawalETH() public isOffline returns (bool) { require(!Online, "Contract is not turned off"); require(_deposits_eth[_msgSender()] > 0, "You have no deposits"); _payBackBrrrETH( _balances[_msgSender()], _msgSender(), _deposits_eth[_msgSender()] ); return true; } /**@dev In case of emgergency - withdrawal all coins. * * Contract must be offline * * */ function EmergencyWithdrawalCoins(address _contract) public isOffline returns (bool) { require(!Online, "Contract is not turned off"); require( _acceptedStableCoins[_contract], "Not accepted as a form of payment" ); require( _coin_deposits[_msgSender()][_contract] != 0, "You have no deposits" ); _payBackBrrrCoins( _balances[_msgSender()], _msgSender(), _contract, _coin_deposits[_msgSender()][_contract] ); return true; } /**@dev In case of emgergency - turn offline. * * Must be admin * * */ function toggleOffline() public returns (bool) { require( hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "Caller is not an admin" ); Online = !Online; return true; } /**@dev Set brrrX addresses. One time, cannot be changed. * * Must be admin * * */ function setBrrrXAddress(address _brrr3xcontract, address _brrr10xcontract) public returns (bool) { require( hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "Caller is not an admin" ); require( brrr3x == address(0x0) && brrr10x == address(0x0), "Already set the addresses" ); if (_brrr3xcontract != address(0x0)) { brrr3x = _brrr3xcontract; } if (_brrr10xcontract != address(0x0)) { brrr10x = _brrr10xcontract; } } fallback() external payable { printWithETH(); } }
Returns the price of the bonding curve divided by number of withdrawals the user has already made. Prevents spamming deposit -> withdrawal -> deposit... to drain all brrr./
function calculateWithdrawalPrice() internal view returns (uint256) { uint256 p = calculateCurve(); uint256 w = _total_withdrawals[_msgSender()]; if (w < 1) { w = 1; } p = p.div(w); return p; }
9,910,612
// Author: Alex Roan pragma solidity ^0.5.5; import "./TennisPlayerBase.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/SafeCast.sol"; contract CompetingTennisPlayer is TennisPlayerBase { using SafeMath for uint; using SafeCast for uint; // conditionCostToPlay uint8 public conditionCostToPlay = 20; // xpGainWin uint8 public xpGainWin = 10; // xpGainLose uint8 public xpGainLose = 5; // enlistedPlayers mapping(uint => bool) public enlistedPlayers; // enlistEvent event Enlist(uint indexed playerId); // delistEvent event Delist(uint indexed playerId); // matchPlayed event MatchPlayed(uint indexed playerId, uint indexed opponentId, uint indexed winner); // Enlist player to compete with others function enlist(uint _id) public { // Only the owner of the player can train require(ownerOf(_id) == msg.sender, "Must be owner of player to enlist"); // Must not be enlisted already require(enlistedPlayers[_id] == false, "Must not already be enlisted"); // Match fit check require(players[_id].condition >= conditionCostToPlay, "Must be match fit to enlist"); // Enlist enlistedPlayers[_id] = true; // Emit event emit Enlist(_id); } // Delist player from competing with others function delist(uint _id) public { // Only the owner of the player can train require(ownerOf(_id) == msg.sender, "Must be owner of player to enlist"); // Must be enlisted require(enlistedPlayers[_id] == true, "Must be enlisted"); // Run delist _delist(_id); } // Play match against opponent function playMatch(uint _id, uint _opponentId) public { // Only the owner of the player can train require(ownerOf(_id) == msg.sender, "Must be owner of player to enlist"); // Must be enlisted require(enlistedPlayers[_id] == true, "Must be enlisted"); // Opponent must be enlisted require(enlistedPlayers[_opponentId] == true, "Opponent must be enlisted"); // Ensure player's condition is high enough _requireMatchCondition(_id, "Player not match condition"); // Ensure opponents's condition is high enough _requireMatchCondition(_opponentId, "Opponent not match condition"); // TODO move this to train? // TODO Better match mechanics uint playerScore = uint(players[_id].agility) .add(uint(players[_id].power)) .add(uint(players[_id].stamina)) .add(uint(players[_id].technique)); uint opponentScore = uint(players[_opponentId].agility) .add(uint(players[_opponentId].power)) .add(uint(players[_opponentId].stamina)) .add(uint(players[_opponentId].technique)); // condition changes players[_id].condition = uint(players[_id].condition).sub(uint(conditionCostToPlay)).toUint8(); players[_opponentId].condition = uint(players[_opponentId].condition).sub(uint(conditionCostToPlay)).toUint8(); // determine winner (uint winner, uint loser) = (playerScore >= opponentScore) ? (_id, _opponentId) : (_opponentId, _id); // xp changes players[winner].xp = uint(players[winner].xp).add(uint(xpGainWin)); players[loser].xp = uint(players[loser].xp).add(uint(xpGainLose)); // emit matchplayed emit MatchPlayed(_id, _opponentId, winner); // check condition again _isMatchCondition(_id); _isMatchCondition(_opponentId); } // Perform the delisting function _delist(uint _id) private { // Delist enlistedPlayers[_id] = false; // Emit event emit Delist(_id); } // Revert if not match condition function _requireMatchCondition(uint _id, string memory _message) private { if (!_isMatchCondition(_id)) { revert(_message); } } // Check player is in match condition, if not, delist function _isMatchCondition(uint _id) private returns (bool) { // Ensure player's condition is high enough // Delist if not if (players[_id].condition <= conditionCostToPlay) { _delist(_id); return false; } return true; } }
Check player is in match condition, if not, delist Ensure player's condition is high enough Delist if not
function _isMatchCondition(uint _id) private returns (bool) { if (players[_id].condition <= conditionCostToPlay) { _delist(_id); return false; } return true; }
954,866
./partial_match/1/0x2AF772E90398B6Eca5bfb4c36d20bEAb71979938/sources/src/SteamerBuffer.sol
Initialize the contract _admin The governing address of the buffer. _debtToken The debt token minted by the ZeroLiquid and accepted by the Steamer.
function initialize(address _admin, address _debtToken) external initializer { _setupRole(ADMIN, _admin); _setRoleAdmin(ADMIN, ADMIN); _setRoleAdmin(KEEPER, ADMIN); debtToken = _debtToken; }
2,685,880
./partial_match/1/0xD3111A14E8df0Df749CF881AE414037D732D8d28/sources/ComboOracle_KyberSwapElasticV2.sol
require(token_address != address(0), "Cannot add zero address"); See if there are any missing decimals between a cToken and the underlying
function _setTokenInfo( address token_address, address agg_addr_for_underlying, address underlying_tkn_address, address pps_override_address, bytes4 pps_call_selector, uint256 pps_decimals ) internal { int256 ctkn_undrly_missing_decs = 0; if (underlying_tkn_address != address(0)){ uint256 cToken_decs = ERC20(token_address).decimals(); uint256 underlying_decs = ERC20(underlying_tkn_address).decimals(); ctkn_undrly_missing_decs = int256(cToken_decs) - int256(underlying_decs); } for (uint i = 0; i < all_token_addresses.length; i++){ if (all_token_addresses[i] == token_address) { token_exists = true; break; } } if (!token_exists) all_token_addresses.push(token_address); uint256 agg_decs = uint256(AggregatorV3Interface(agg_addr_for_underlying).decimals()); string memory name_to_use; if (token_address == address(0)) { name_to_use = native_token_symbol; } else { name_to_use = ERC20(token_address).name(); } token_address, ERC20(token_address).name(), agg_addr_for_underlying, agg_other_side, agg_decs, underlying_tkn_address, pps_override_address, pps_call_selector, pps_decimals, ctkn_undrly_missing_decs ); has_info[token_address] = true; }
2,731,440
// SPDX-License-Identifier: MIT pragma solidity ^0.6.6; contract Polling { address payable public author; uint8 maxPollOptionCount; struct PollOption { string content; uint256 voteCount; } struct Poll { address creator; string title; uint256 startTimeStamp; uint256 endTimeStamp; uint256 totalVotesCasted; uint8 pollOptionCount; mapping(uint8 => PollOption) pollOptions; mapping(address => uint8) votes; } struct User { string name; bool created; uint256 pollCount; mapping(uint256 => bytes32) ids; } mapping(address => User) users; address[] userAddresses; mapping(bytes32 => Poll) polls; mapping(bytes32 => address) pollIdToUser; bytes32[] pollIds; event UserCreated(string name, address identifier); event PollIsLive(string name, address identifier, bytes32 pollId); event PollResult( address identifier, bytes32 pollId, uint8 winningOptionIndex, uint256 winningOptionVoteCount, uint256 totalVotesCasted ); constructor() public { author = msg.sender; maxPollOptionCount = 4; } modifier onlyAuthor() { require(author == msg.sender, "You're not author !"); _; } modifier isValidMaxPollOptionCount(uint8 count) { require( count >= 2 && count <= 16, "Max poll option count out of range !" ); _; } function setMaxPollOptionCount(uint8 count) external onlyAuthor isValidMaxPollOptionCount(count) { maxPollOptionCount = count; } // returns maximum poll option count, allowed to be set as of now function getMaxPollOptionCount() public view returns (uint8) { return maxPollOptionCount; } modifier canCreateAccount() { require(!users[msg.sender].created, "User already exists !"); _; } function createUser(string memory _name) public canCreateAccount { User memory user; user.name = _name; user.created = true; users[msg.sender] = user; userAddresses.push(msg.sender); emit UserCreated(_name, msg.sender); } modifier canCreatePoll() { require(users[msg.sender].created, "User account doesn't exist !"); _; } function createPoll(string memory _title) public canCreatePoll returns (bytes32) { bytes32 pollId = keccak256( abi.encodePacked(_title, msg.sender, users[msg.sender].pollCount) ); Poll memory poll; poll.creator = msg.sender; poll.title = _title; users[msg.sender].ids[users[msg.sender].pollCount] = pollId; users[msg.sender].pollCount++; polls[pollId] = poll; pollIdToUser[pollId] = msg.sender; pollIds.push(pollId); return pollId; } modifier didYouCreatePoll(bytes32 _pollId) { require(pollIdToUser[_pollId] == msg.sender, "You're not allowed !"); _; } modifier canAddPollOption(bytes32 _pollId) { require( polls[_pollId].pollOptionCount < maxPollOptionCount, "Reached max poll option count !" ); _; } function addPollOption(bytes32 _pollId, string memory _pollOption) public didYouCreatePoll(_pollId) isPollAlreadyLive(_pollId) canAddPollOption(_pollId) { PollOption memory pollOption; pollOption.content = _pollOption; Poll storage poll = polls[_pollId]; poll.pollOptions[poll.pollOptionCount] = pollOption; poll.pollOptionCount++; } modifier isPollAlreadyLive(bytes32 _pollId) { require( polls[_pollId].startTimeStamp != 0 && polls[_pollId].endTimeStamp != 0, "Poll already live !" ); _; } modifier areEnoughPollOptionsSet(bytes32 _pollId) { require( polls[_pollId].pollOptionCount >= 2, "Atleast 2 options required !" ); _; } modifier isPollEndTimeValid(bytes32 _pollId, uint8 _hours) { require( _hours > 0 && _hours <= 72, "Poll can be live for >= 1 hour && <= 72 hours" ); _; } function makePollLive(bytes32 _pollId, uint8 _activeForHours) public didYouCreatePoll(_pollId) isPollAlreadyLive(_pollId) areEnoughPollOptionsSet(_pollId) isPollEndTimeValid(_pollId, _activeForHours) { polls[_pollId].startTimeStamp = now; polls[_pollId].endTimeStamp = now + (_activeForHours * 1 hours); emit PollIsLive(users[msg.sender].name, msg.sender, _pollId); } modifier checkPollExistance(bytes32 _pollId) { require(pollIdToUser[_pollId] != address(0), "Poll doesn't exist !"); _; } modifier isPollLive(bytes32 _pollId) { require( polls[_pollId].startTimeStamp <= now && polls[_pollId].endTimeStamp > now, "Poll not live !" ); _; } modifier checkDuplicateVote(bytes32 _pollId) { require( polls[_pollId].votes[msg.sender] == 0, "Attempt to cast duplicate vote !" ); _; } modifier isValidOptionToCastVote(bytes32 _pollId, uint8 _option) { require( _option >= 0 && _option < polls[_pollId].pollOptionCount, "Invalid option, can't cast vote !" ); _; } function castVote(bytes32 _pollId, uint8 _option) public checkPollExistance(_pollId) isPollLive(_pollId) checkDuplicateVote(_pollId) isValidOptionToCastVote(_pollId, _option) { Poll storage poll = polls[_pollId]; poll.totalVotesCasted++; poll.pollOptions[_option].voteCount++; poll.votes[msg.sender] = _option + 1; } // Added check for poll activation function isPollActive(bytes32 _pollId) public view returns (bool) { return polls[_pollId].startTimeStamp <= now && polls[_pollId].endTimeStamp > now; } // Given number of recent active polls required, returns a list of them function getRecentXActivePolls(uint8 x) public view returns (bytes32[] memory) { require(x > 0, "Can't return 0 recent polls !"); bytes32[] memory recentPolls = new bytes32[](x); uint8 idx = 0; for (uint256 i = pollIds.length - 1; i >= 0 && idx < x; i--) { if (isPollActive(pollIds[i])) { recentPolls[idx] = pollIds[i]; idx++; } } return recentPolls; } // Checks whether given address has account or not ( in this platform ) // if yes, they are allowed to proceed further modifier accountCreated(address _addr) { require(users[_addr].created, "Account not found !"); _; } // Returns person name at account in given address function getAccountNameByAddress(address _addr) public view accountCreated(_addr) returns (string memory) { return users[_addr].name; } // Get person name of invoker account function getMyAccountName() public view returns (string memory) { return getAccountNameByAddress(msg.sender); } // Returns number of polls created by given address function getAccountPollCountByAddress(address _addr) public view accountCreated(_addr) returns (uint256) { return users[_addr].pollCount; } // Returns number of poll created by this account function getMyPollCount() public view returns (uint256) { return getAccountPollCountByAddress(msg.sender); } // Returns unique pollId, given creator address & index of // poll ( >= 0 && < #-of all polls created by creator ) function getPollIdByAddressAndIndex(address _addr, uint256 index) public view accountCreated(_addr) returns (bytes32) { require( index < users[_addr].pollCount, "Invalid index for looking up PollId !" ); return users[_addr].ids[index]; } // Given poll index ( < number of polls created by msg.sender ), // it'll lookup pollId from my account function getMyPollIdByIndex(uint256 index) public view returns (bytes32) { return getPollIdByAddressAndIndex(msg.sender, index); } // Given pollId, returns account which created this poll function getCreatorAddressByPollId(bytes32 _pollId) public view checkPollExistance(_pollId) returns (address) { return pollIdToUser[_pollId]; } // Returns title of poll, by given pollId function getTitleByPollId(bytes32 _pollId) public view checkPollExistance(_pollId) returns (string memory) { return polls[_pollId].title; } // Get timestamp when poll was set active function getStartTimeByPollId(bytes32 _pollId) public view checkPollExistance(_pollId) returns (uint256) { return polls[_pollId].startTimeStamp; } // Get timestamp when poll will go deactive function getEndTimeByPollId(bytes32 _pollId) public view checkPollExistance(_pollId) returns (uint256) { return polls[_pollId].endTimeStamp; } // Given pollId, looks up total #-of votes casted function getTotalVotesCastedByPollId(bytes32 _pollId) public view checkPollExistance(_pollId) returns (uint256) { return polls[_pollId].totalVotesCasted; } // Given pollId, returns number of options present function getPollOptionCountByPollId(bytes32 _pollId) public view checkPollExistance(_pollId) returns (uint8) { return polls[_pollId].pollOptionCount; } // checks whether address has voted in specified poll ( by pollId ) or not modifier votedYet(bytes32 _pollId, address _addr) { require(polls[_pollId].votes[_addr] != 0, "Not voted yet !"); _; } // Given target pollId & voter's unique address, it'll lookup // pollOptionIndex ( >=0 && < #-of-options ) choice made by voter // // If voter hasn't yet participated in this poll, it'll fail function getVoteByPollIdAndAddress(bytes32 _pollId, address _addr) public view checkPollExistance(_pollId) isPollAlreadyLive(_pollId) votedYet(_pollId, msg.sender) returns (uint8) { return polls[_pollId].votes[_addr] - 1; } // Looks up vote choice made by function invoker in specified poll, // given that user has already voted or fails function getMyVoteByPollId(bytes32 _pollId) public view returns (uint8) { return getVoteByPollIdAndAddress(_pollId, msg.sender); } // Given pollId & option index, returns content of that option function getPollOptionContentByPollIdAndIndex(bytes32 _pollId, uint8 index) public view checkPollExistance(_pollId) returns (string memory) { require( index < polls[_pollId].pollOptionCount, "Invalid index for looking up PollOption !" ); return polls[_pollId].pollOptions[index].content; } // Given pollId & option index, returns votes casted on that option function getPollOptionVoteCountByPollIdAndIndex( bytes32 _pollId, uint8 index ) public view checkPollExistance(_pollId) returns (uint256) { require( index < polls[_pollId].pollOptionCount, "Invalid index for looking up PollOption !" ); return polls[_pollId].pollOptions[index].voteCount; } // Given pollId, checks what's current status of poll i.e. // which is winning option upto this point, returns index & vote count of winning option // // poll must be started before invoking this function, otherwise fails function getWinningOptionIndexAndVotesByPollId(bytes32 _pollId) public view checkPollExistance(_pollId) isPollAlreadyLive(_pollId) votedYet(_pollId, msg.sender) returns (uint8, uint256) { uint8 count = getPollOptionCountByPollId(_pollId); uint8 maxVoteIndex = 0; uint256 maxVoteCount = getPollOptionVoteCountByPollIdAndIndex( _pollId, maxVoteIndex ); for (uint8 i = 1; i < count; i++) { uint256 _tmp = getPollOptionVoteCountByPollIdAndIndex(_pollId, i); if (_tmp > maxVoteCount) { maxVoteIndex = i; maxVoteCount = _tmp; } } return (maxVoteIndex, maxVoteCount); } // Given pollId, and poll creator is invoking this function, // it'll announce that poll has ended with result, where result is event emitted // // Make sure poll has ended, before invoking this function, otherwise it'll fail function announcePollResult(bytes32 _pollId) public didYouCreatePoll(_pollId) { require(polls[_pollId].endTimeStamp <= now, "Poll not ended yet !"); ( uint8 winningIndex, uint256 winningVotes ) = getWinningOptionIndexAndVotesByPollId(_pollId); emit PollResult( msg.sender, _pollId, winningIndex, winningVotes, getTotalVotesCastedByPollId(_pollId) ); } // Given pollid, checks whether poll has ended or not function hasPollEnded(bytes32 _pollId) public view checkPollExistance(_pollId) returns (bool) { return polls[_pollId].endTimeStamp <= now; } // given address of user account, checks existence, // only author of smart contract can do so function userAccountExists(address _addr) public view onlyAuthor returns (bool) { return users[_addr].created; } // checks for existence of account of this function invoker ( msg.sender ) function amIRegistered() public view returns (bool) { return users[msg.sender].created; } }
Given target pollId & voter's unique address, it'll lookup pollOptionIndex ( >=0 && < -of-options ) choice made by voter If voter hasn't yet participated in this poll, it'll fail
function getVoteByPollIdAndAddress(bytes32 _pollId, address _addr) public view checkPollExistance(_pollId) isPollAlreadyLive(_pollId) votedYet(_pollId, msg.sender) returns (uint8) { return polls[_pollId].votes[_addr] - 1; }
15,814,564
./partial_match/1/0x715F06DA4bB270bD6924014dee44172834Cb219D/sources/contracts/rewards/FarmingRange.sol
@inheritdoc IFarmingRange
function removeLastRewardInfo(uint256 _campaignID) external virtual onlyOwner { RewardInfo[] storage rewardInfo = campaignRewardInfo[_campaignID]; CampaignInfo storage campaign = campaignInfo[_campaignID]; uint256 _rewardInfoLength = rewardInfo.length; require(_rewardInfoLength != 0, "FarmingRange::updateCampaignsRewards::no rewardInfoLen"); RewardInfo storage lastRewardInfo = rewardInfo[_rewardInfoLength - 1]; uint256 _lastRewardInfoEndBlock = lastRewardInfo.endBlock; require(_lastRewardInfoEndBlock > block.number, "FarmingRange::removeLastRewardInfo::reward period ended"); _updateCampaign(_campaignID); if (lastRewardInfo.rewardPerBlock != 0) { (bool _refund, uint256 _diff) = _updateRewardsDiff( _rewardInfoLength - 1, _lastRewardInfoEndBlock, 0, rewardInfo, campaign, lastRewardInfo ); if (_refund) { campaign.totalRewards = campaign.totalRewards - _diff; } } rewardInfo.pop(); emit RemoveRewardInfo(_campaignID, _rewardInfoLength - 1); }
9,390,807
pragma solidity ^0.5.0; import "@openzeppelin/contracts/ownership/Ownable.sol"; contract IRewardDistributionRecipient is Ownable { address public rewardDistribution; function notifyRewardAmount(uint256 reward) external; modifier onlyRewardDistribution() { require(_msgSender() == rewardDistribution, "Caller is not reward distribution"); _; } function setRewardDistribution(address _rewardDistribution) external onlyOwner { rewardDistribution = _rewardDistribution; } } pragma solidity ^0.5.0; import "@openzeppelin/contracts/math/Math.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/ownership/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./IRewardDistributionRecipient.sol"; contract LPTokenWrapper { using SafeMath for uint256; using SafeERC20 for IERC20; IERC20 public token; uint256 private _totalSupply; mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; event Approval(address indexed owner, address indexed spender, uint256 value); constructor(address _token) public { token = IERC20(_token); } function totalSupply() public view returns (uint256) { return _totalSupply; } function balanceOf(address account) public view returns (uint256) { return _balances[account]; } function stakeFor(address _user, uint256 _amount) public { _stake(_user, _amount); } function stake(uint256 _amount) public { _stake(msg.sender, _amount); } function approve(address _user, uint256 _amount) public { _approve(msg.sender, _user, _amount); } function withdraw(uint256 _amount) public { _withdraw(msg.sender, _amount); } function withdrawFrom(address _user, uint256 _amount) public { _withdraw(_user, _amount); _approve( _user, msg.sender, _allowances[_user][msg.sender].sub(_amount, "LPTokenWrapper: withdraw amount exceeds allowance") ); } function allowance(address _owner, address _spender) public view returns (uint256) { return _allowances[_owner][_spender]; } function _stake(address _user, uint256 _amount) internal { _totalSupply = _totalSupply.add(_amount); _balances[_user] = _balances[_user].add(_amount); token.safeTransferFrom(msg.sender, address(this), _amount); } function _withdraw(address _owner, uint256 _amount) internal { _totalSupply = _totalSupply.sub(_amount); _balances[_owner] = _balances[_owner].sub(_amount); IERC20(token).safeTransfer(msg.sender, _amount); } function _approve( address _owner, address _user, uint256 _amount ) internal returns (bool) { require(_user != address(0), "LPTokenWrapper: approve to the zero address"); _allowances[_owner][_user] = _amount; emit Approval(_owner, _user, _amount); return true; } } contract ModifiedUnipoolV2 is LPTokenWrapper, IRewardDistributionRecipient { using SafeERC20 for IERC20; address public rewardToken; uint256 public constant DURATION = 7 days; uint256 public periodFinish = 0; uint256 public rewardRate = 0; uint256 public lastUpdateTime; uint256 public rewardPerTokenStored; mapping(address => uint256) public userRewardPerTokenPaid; mapping(address => uint256) public rewards; event RewardAdded(uint256 reward); event Staked(address indexed user, uint256 amount); event Withdrawn(address indexed user, uint256 amount); event RewardPaid(address indexed user, uint256 reward); modifier updateReward(address account) { rewardPerTokenStored = rewardPerToken(); lastUpdateTime = lastTimeRewardApplicable(); if (account != address(0)) { rewards[account] = earned(account); userRewardPerTokenPaid[account] = rewardPerTokenStored; } _; } constructor(address _rewardToken, address _token) public LPTokenWrapper(_token) { rewardToken = _rewardToken; } function notifyRewardAmount(uint256 _reward) external onlyRewardDistribution updateReward(address(0)) { IERC20(rewardToken).safeTransferFrom(msg.sender, address(this), _reward); if (block.timestamp >= periodFinish) { rewardRate = _reward.div(DURATION); } else { uint256 remaining = periodFinish.sub(block.timestamp); uint256 leftover = remaining.mul(rewardRate); rewardRate = _reward.add(leftover).div(DURATION); } lastUpdateTime = block.timestamp; periodFinish = block.timestamp.add(DURATION); emit RewardAdded(_reward); } function exit() external { withdraw(balanceOf(msg.sender)); getReward(msg.sender); } function lastTimeRewardApplicable() public view returns (uint256) { return Math.min(block.timestamp, periodFinish); } function rewardPerToken() public view returns (uint256) { if (totalSupply() == 0) { return rewardPerTokenStored; } return rewardPerTokenStored.add( lastTimeRewardApplicable().sub(lastUpdateTime).mul(rewardRate).mul(1e18).div(totalSupply()) ); } function earned(address account) public view returns (uint256) { return balanceOf(account).mul(rewardPerToken().sub(userRewardPerTokenPaid[account])).div(1e18).add( rewards[account] ); } function stake(uint256 amount) public updateReward(msg.sender) { require(amount > 0, "Cannot stake 0"); super.stake(amount); emit Staked(msg.sender, amount); } function stakeFor(address _user, uint256 _amount) public updateReward(_user) { require(_amount > 0, "Cannot stake 0"); super.stakeFor(_user, _amount); emit Staked(_user, _amount); } function withdraw(uint256 amount) public updateReward(msg.sender) { require(amount > 0, "Cannot withdraw 0"); super.withdraw(amount); emit Withdrawn(msg.sender, amount); } function withdrawFrom(address _user, uint256 amount) public updateReward(_user) { require(amount > 0, "Cannot withdraw 0"); super.withdrawFrom(_user, amount); emit Withdrawn(_user, amount); } function getReward() public { _getReward(msg.sender); } function getReward(address _user) public { _getReward(_user); } function _getReward(address _user) internal updateReward(_user) { uint256 _reward = earned(_user); if (_reward > 0) { rewards[_user] = 0; IERC20(rewardToken).safeTransfer(_user, _reward); emit RewardPaid(_user, _reward); } } } pragma solidity 0.5.16; interface ICurveDepositPBTC { function add_liquidity(uint256[4] calldata call_data_amounts, uint256 min_mint_amount) external returns (uint256); function remove_liquidity_one_coin( uint256 _token_amount, int128 i, uint256 _min_amount ) external returns (uint256); function token() external returns (address); } pragma solidity 0.5.16; interface ICurveGaugeV2 { function deposit(uint256 _value, address _addr) external; function withdraw(uint256 _value) external; function balanceOf(address _addr) external returns (uint256); function approve(address _addr, uint256 _amount) external returns (bool); function crv_token() external returns (address); function claim_rewards(address _addr) external; } pragma solidity ^0.5.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/ownership/Ownable.sol"; import "@openzeppelin/contracts/introspection/IERC1820Registry.sol"; import "@openzeppelin/contracts/token/ERC777/IERC777Recipient.sol"; import "../interfaces/ICurveDepositPBTC.sol"; import "../interfaces/ICurveGaugeV2.sol"; import "../ModifiedUnipoolV2.sol"; contract RewardedPbtcSbtcCurveMetapool is IERC777Recipient, Ownable { using SafeERC20 for IERC20; // prettier-ignore IERC1820Registry private _erc1820 = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24); bytes32 private constant TOKENS_RECIPIENT_INTERFACE_HASH = keccak256("ERC777TokensRecipient"); uint256 private constant SLIPPAGE_BASE_UNIT = 10**18; IERC20 public pbtc; IERC20 public metaToken; IERC20 public crv; ICurveDepositPBTC public depositPbtc; ICurveGaugeV2 public gauge; ModifiedUnipoolV2 public modifiedUnipool; uint256 public allowedSlippage; event Staked(address indexed user, uint256 amount, uint256 metaTokenAmount); event Unstaked(address indexed user, uint256 amount, uint256 metaTokenAmount); event AllowedSlippageChanged(uint256 slippage); /** * @param _depositPbtc MetaPool address * @param _gauge Curve Gauge address * @param _modifiedUnipool ModifiedUnipoolV2 address * @param _pbtc pbtc address */ constructor( address _depositPbtc, address _gauge, address _modifiedUnipool, address _pbtc ) public { depositPbtc = ICurveDepositPBTC(_depositPbtc); gauge = ICurveGaugeV2(_gauge); crv = IERC20(gauge.crv_token()); pbtc = IERC20(_pbtc); metaToken = IERC20(depositPbtc.token()); modifiedUnipool = ModifiedUnipoolV2(_modifiedUnipool); _erc1820.setInterfaceImplementer(address(this), TOKENS_RECIPIENT_INTERFACE_HASH, address(this)); } /** * @param _allowedSlippage new max allowed in percentage (1% = 10 ** 18) */ function setAllowedSlippage(uint256 _allowedSlippage) external onlyOwner { allowedSlippage = _allowedSlippage; emit AllowedSlippageChanged(_allowedSlippage); } /** * @notice ERC777 hook invoked when this contract receives a token. */ function tokensReceived( address _operator, address _from, address _to, uint256 _amount, bytes calldata _userData, bytes calldata _operatorData ) external { if (_from == address(depositPbtc)) return; require(msg.sender == address(pbtc), "RewardedPbtcSbtcCurveMetapool: Invalid token"); require(_amount > 0, "RewardedPbtcSbtcCurveMetapool: amount must be greater than 0"); _stakeFor(_from, _amount); } /** * @notice Remove Gauge tokens from Modified Unipool (earning PNT), * withdraw pBTC/sbtcCRV (earning CRV) from the Gauge and then * remove liquidty from pBTC/sBTC Curve Metapool and then * transfer all back to the msg.sender. * User must approve this contract to to withdraw the corresponing * amount of his metaToken balance in behalf of him. */ function unstake() public returns (bool) { uint256 gaugeTokenSenderBalance = modifiedUnipool.balanceOf(msg.sender); require( modifiedUnipool.allowance(msg.sender, address(this)) >= gaugeTokenSenderBalance, "RewardedPbtcSbtcCurveMetapool: amount not approved" ); modifiedUnipool.withdrawFrom(msg.sender, gaugeTokenSenderBalance); // NOTE: collect Modified Unipool rewards modifiedUnipool.getReward(msg.sender); // NOTE: collect CRV uint256 gaugeTokenAmount = gauge.balanceOf(address(this)); gauge.withdraw(gaugeTokenAmount); uint256 crvAmount = crv.balanceOf(address(this)); crv.transfer(msg.sender, crvAmount); uint256 metaTokenAmount = metaToken.balanceOf(address(this)); metaToken.safeApprove(address(depositPbtc), metaTokenAmount); // prettier-ignore uint256 maxAllowedMinAmount = metaTokenAmount - ((metaTokenAmount * allowedSlippage) / (SLIPPAGE_BASE_UNIT * 100)); uint256 pbtcAmount = depositPbtc.remove_liquidity_one_coin(metaTokenAmount, 0, maxAllowedMinAmount); pbtc.transfer(msg.sender, pbtcAmount); emit Unstaked(msg.sender, pbtcAmount, metaTokenAmount); return true; } /** * @notice Collect all available rewards * * @param _addr address to claim for */ function claimRewards(address _addr) public returns (bool) { modifiedUnipool.getReward(_addr); gauge.claim_rewards(_addr); return true; } /** * @notice Add liquidity into Curve pBTC/SBTC Metapool, * put the minted pBTC/sbtcCRV tokens into the Gauge in * order to earn CRV and then put the Liquidi Gauge tokens * into Unipool in order to get the PNT reward. * * @param _user user address * @param _amount pBTC amount to put into the meta pool */ function _stakeFor(address _user, uint256 _amount) internal returns (bool) { uint256 maxAllowedMinAmount = _amount - ((_amount * allowedSlippage) / (SLIPPAGE_BASE_UNIT * 100)); pbtc.safeApprove(address(depositPbtc), _amount); uint256 metaTokenAmount = depositPbtc.add_liquidity([_amount, 0, 0, 0], maxAllowedMinAmount); metaToken.safeApprove(address(gauge), metaTokenAmount); gauge.deposit(metaTokenAmount, address(this)); uint256 gaugeTokenAmount = gauge.balanceOf(address(this)); gauge.approve(address(modifiedUnipool), gaugeTokenAmount); modifiedUnipool.stakeFor(_user, gaugeTokenAmount); emit Staked(_user, _amount, metaTokenAmount); return true; } } pragma solidity ^0.5.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } pragma solidity ^0.5.0; /** * @dev Interface of the global ERC1820 Registry, as defined in the * https://eips.ethereum.org/EIPS/eip-1820[EIP]. Accounts may register * implementers for interfaces in this registry, as well as query support. * * Implementers may be shared by multiple accounts, and can also implement more * than a single interface for each account. Contracts can implement interfaces * for themselves, but externally-owned accounts (EOA) must delegate this to a * contract. * * {IERC165} interfaces can also be queried via the registry. * * For an in-depth explanation and source code analysis, see the EIP text. */ interface IERC1820Registry { /** * @dev Sets `newManager` as the manager for `account`. A manager of an * account is able to set interface implementers for it. * * By default, each account is its own manager. Passing a value of `0x0` in * `newManager` will reset the manager to this initial state. * * Emits a {ManagerChanged} event. * * Requirements: * * - the caller must be the current manager for `account`. */ function setManager(address account, address newManager) external; /** * @dev Returns the manager for `account`. * * See {setManager}. */ function getManager(address account) external view returns (address); /** * @dev Sets the `implementer` contract as `account`'s implementer for * `interfaceHash`. * * `account` being the zero address is an alias for the caller's address. * The zero address can also be used in `implementer` to remove an old one. * * See {interfaceHash} to learn how these are created. * * Emits an {InterfaceImplementerSet} event. * * Requirements: * * - the caller must be the current manager for `account`. * - `interfaceHash` must not be an {IERC165} interface id (i.e. it must not * end in 28 zeroes). * - `implementer` must implement {IERC1820Implementer} and return true when * queried for support, unless `implementer` is the caller. See * {IERC1820Implementer-canImplementInterfaceForAddress}. */ function setInterfaceImplementer(address account, bytes32 interfaceHash, address implementer) external; /** * @dev Returns the implementer of `interfaceHash` for `account`. If no such * implementer is registered, returns the zero address. * * If `interfaceHash` is an {IERC165} interface id (i.e. it ends with 28 * zeroes), `account` will be queried for support of it. * * `account` being the zero address is an alias for the caller's address. */ function getInterfaceImplementer(address account, bytes32 interfaceHash) external view returns (address); /** * @dev Returns the interface hash for an `interfaceName`, as defined in the * corresponding * https://eips.ethereum.org/EIPS/eip-1820#interface-name[section of the EIP]. */ function interfaceHash(string calldata interfaceName) external pure returns (bytes32); /** * @notice Updates the cache with whether the contract implements an ERC165 interface or not. * @param account Address of the contract for which to update the cache. * @param interfaceId ERC165 interface for which to update the cache. */ function updateERC165Cache(address account, bytes4 interfaceId) external; /** * @notice Checks whether a contract implements an ERC165 interface or not. * If the result is not cached a direct lookup on the contract address is performed. * If the result is not cached or the cached value is out-of-date, the cache MUST be updated manually by calling * {updateERC165Cache} with the contract address. * @param account Address of the contract to check. * @param interfaceId ERC165 interface to check. * @return True if `account` implements `interfaceId`, false otherwise. */ function implementsERC165Interface(address account, bytes4 interfaceId) external view returns (bool); /** * @notice Checks whether a contract implements an ERC165 interface or not without using nor updating the cache. * @param account Address of the contract to check. * @param interfaceId ERC165 interface to check. * @return True if `account` implements `interfaceId`, false otherwise. */ function implementsERC165InterfaceNoCache(address account, bytes4 interfaceId) external view returns (bool); event InterfaceImplementerSet(address indexed account, bytes32 indexed interfaceHash, address indexed implementer); event ManagerChanged(address indexed account, address indexed newManager); } pragma solidity ^0.5.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } pragma solidity ^0.5.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @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. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // 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; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } pragma solidity ^0.5.0; import "../GSN/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { _owner = _msgSender(); emit OwnershipTransferred(address(0), _owner); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return _msgSender() == _owner; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } pragma solidity ^0.5.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } pragma solidity ^0.5.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { // 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' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } pragma solidity ^0.5.0; /** * @dev Interface of the ERC777TokensRecipient standard as defined in the EIP. * * Accounts can be notified of {IERC777} tokens being sent to them by having a * contract implement this interface (contract holders can be their own * implementer) and registering it on the * https://eips.ethereum.org/EIPS/eip-1820[ERC1820 global registry]. * * See {IERC1820Registry} and {ERC1820Implementer}. */ interface IERC777Recipient { /** * @dev Called by an {IERC777} token contract whenever tokens are being * moved or created into a registered account (`to`). The type of operation * is conveyed by `from` being the zero address or not. * * This call occurs _after_ the token contract's state is updated, so * {IERC777-balanceOf}, etc., can be used to query the post-operation state. * * This function may revert to prevent the operation from being executed. */ function tokensReceived( address operator, address from, address to, uint256 amount, bytes calldata userData, bytes calldata operatorData ) external; } pragma solidity ^0.5.5; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * This test is non-exhaustive, and there may be false-negatives: during the * execution of a contract's constructor, its address will be reported as * not containing a contract. * * IMPORTANT: It is unsafe to assume that an address for which this * function returns false is an externally-owned account (EOA) and not a * contract. */ function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } /** * @dev Converts an `address` into `address payable`. Note that this is * simply a type cast: the actual underlying value is not changed. * * _Available since v2.4.0._ */ function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. * * _Available since v2.4.0._ */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } }
ERC777 hook invoked when this contract receives a token./
function tokensReceived( address _operator, address _from, address _to, uint256 _amount, bytes calldata _userData, bytes calldata _operatorData ) external { if (_from == address(depositPbtc)) return; require(msg.sender == address(pbtc), "RewardedPbtcSbtcCurveMetapool: Invalid token"); require(_amount > 0, "RewardedPbtcSbtcCurveMetapool: amount must be greater than 0"); _stakeFor(_from, _amount); }
239,271
./partial_match/1/0xae308E57FD7F179e25D62988ec4c7a3676E603B7/sources/contracts/TheLittleKingsV2.sol
Start token IDs at 1 instead of 0
function _startTokenId() internal view virtual override returns (uint256) { return 1; }
4,221,563
pragma solidity ^0.5.0; pragma experimental ABIEncoderV2; /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ interface IERC20 { function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @return the address of the owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner()); _; } /** * @return true if `msg.sender` is the owner of the contract. */ function isOwner() public view returns (bool) { return msg.sender == _owner; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0)); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } /** * @title SafeMath * @dev Unsigned math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two unsigned integers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // 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-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } /** * @title SignedSafeMath * @dev Signed math operations with safety checks that revert on error */ library SignedSafeMath { int256 constant private INT256_MIN = -2**255; /** * @dev Multiplies two signed integers, reverts on overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { // 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-solidity/pull/522 if (a == 0) { return 0; } require(!(a == -1 && b == INT256_MIN)); // This is the only case of overflow not detected by the check below int256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two signed integers truncating the quotient, reverts on division by zero. */ function div(int256 a, int256 b) internal pure returns (int256) { require(b != 0); // Solidity only automatically asserts when dividing by 0 require(!(b == -1 && a == INT256_MIN)); // This is the only case of overflow int256 c = a / b; return c; } /** * @dev Subtracts two signed integers, reverts on overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a)); return c; } /** * @dev Adds two signed integers, reverts on overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a)); return c; } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md * Originally based on code by FirstBlood: * https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol * * This implementation emits additional Approval events, allowing applications to reconstruct the allowance status for * all accounts just by listening to said events. Note that this isn't required by the specification, and other * compliant implementations may not do it. */ contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; uint256 private _totalSupply; /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev Gets the balance of the specified address. * @param owner The address to query the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address owner) public view returns (uint256) { return _balances[owner]; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param owner address The address which owns the funds. * @param spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowed[owner][spender]; } /** * @dev Transfer token for a specified address * @param to The address to transfer to. * @param value The amount to be transferred. */ function transfer(address to, uint256 value) public returns (bool) { _transfer(msg.sender, to, value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param spender The address which will spend the funds. * @param value The amount of tokens to be spent. */ function approve(address spender, uint256 value) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /** * @dev Transfer tokens from one address to another. * Note that while this function emits an Approval event, this is not required as per the specification, * and other compliant implementations may not emit the event. * @param from address The address which you want to send tokens from * @param to address The address which you want to transfer to * @param value uint256 the amount of tokens to be transferred */ function transferFrom(address from, address to, uint256 value) public returns (bool) { _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value); _transfer(from, to, value); emit Approval(from, msg.sender, _allowed[from][msg.sender]); return true; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when allowed_[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * Emits an Approval event. * @param spender The address which will spend the funds. * @param addedValue The amount of tokens to increase the allowance by. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = _allowed[msg.sender][spender].add(addedValue); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when allowed_[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * Emits an Approval event. * @param spender The address which will spend the funds. * @param subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = _allowed[msg.sender][spender].sub(subtractedValue); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } /** * @dev Transfer token for a specified addresses * @param from The address to transfer from. * @param to The address to transfer to. * @param value The amount to be transferred. */ function _transfer(address from, address to, uint256 value) internal { require(to != address(0)); _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(from, to, value); } /** * @dev Internal function that mints an amount of the token and assigns it to * an account. This encapsulates the modification of balances such that the * proper events are emitted. * @param account The account that will receive the created tokens. * @param value The amount that will be created. */ function _mint(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.add(value); _balances[account] = _balances[account].add(value); emit Transfer(address(0), account, value); } /** * @dev Internal function that burns an amount of the token of a given * account. * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burn(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); } /** * @dev Internal function that burns an amount of the token of a given * account, deducting from the sender's allowance for said account. Uses the * internal burn function. * Emits an Approval event (reflecting the reduced allowance). * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burnFrom(address account, uint256 value) internal { _allowed[account][msg.sender] = _allowed[account][msg.sender].sub(value); _burn(account, value); emit Approval(account, msg.sender, _allowed[account][msg.sender]); } } // The functionality that all derivative contracts expose to the admin. interface AdminInterface { // Initiates the shutdown process, in case of an emergency. function emergencyShutdown() external; // A core contract method called immediately before or after any financial transaction. It pays fees and moves money // between margin accounts to make sure they reflect the NAV of the contract. function remargin() external; } contract ExpandedIERC20 is IERC20 { // Burns a specific amount of tokens. Burns the sender's tokens, so it is safe to leave this method permissionless. function burn(uint value) external; // Mints tokens and adds them to the balance of the `to` address. // Note: this method should be permissioned to only allow designated parties to mint tokens. function mint(address to, uint value) external; } // This interface allows derivative contracts to pay Oracle fees for their use of the system. interface StoreInterface { // Pays Oracle fees in ETH to the store. To be used by contracts whose margin currency is ETH. function payOracleFees() external payable; // Pays Oracle fees in the margin currency, erc20Address, to the store. To be used if the margin currency is an // ERC20 token rather than ETH. All approved tokens are transfered. function payOracleFeesErc20(address erc20Address) external; // Computes the Oracle fees that a contract should pay for a period. `pfc` is the "profit from corruption", or the // maximum amount of margin currency that a token sponsor could extract from the contract through corrupting the // price feed in their favor. function computeOracleFees(uint startTime, uint endTime, uint pfc) external view returns (uint feeAmount); } interface ReturnCalculatorInterface { // Computes the return between oldPrice and newPrice. function computeReturn(int oldPrice, int newPrice) external view returns (int assetReturn); // Gets the effective leverage for the return calculator. // Note: if this parameter doesn't exist for this calculator, this method should return 1. function leverage() external view returns (int _leverage); } // This interface allows contracts to query unverified prices. interface PriceFeedInterface { // Whether this PriceFeeds provides prices for the given identifier. function isIdentifierSupported(bytes32 identifier) external view returns (bool isSupported); // Gets the latest time-price pair at which a price was published. The transaction will revert if no prices have // been published for this identifier. function latestPrice(bytes32 identifier) external view returns (uint publishTime, int price); // An event fired when a price is published. event PriceUpdated(bytes32 indexed identifier, uint indexed time, int price); } contract AddressWhitelist is Ownable { enum Status { None, In, Out } mapping(address => Status) private whitelist; address[] private whitelistIndices; // Adds an address to the whitelist function addToWhitelist(address newElement) external onlyOwner { // Ignore if address is already included if (whitelist[newElement] == Status.In) { return; } // Only append new addresses to the array, never a duplicate if (whitelist[newElement] == Status.None) { whitelistIndices.push(newElement); } whitelist[newElement] = Status.In; emit AddToWhitelist(newElement); } // Removes an address from the whitelist. function removeFromWhitelist(address elementToRemove) external onlyOwner { if (whitelist[elementToRemove] != Status.Out) { whitelist[elementToRemove] = Status.Out; emit RemoveFromWhitelist(elementToRemove); } } // Checks whether an address is on the whitelist. function isOnWhitelist(address elementToCheck) external view returns (bool) { return whitelist[elementToCheck] == Status.In; } // Gets all addresses that are currently included in the whitelist // Note: This method skips over, but still iterates through addresses. // It is possible for this call to run out of gas if a large number of // addresses have been removed. To prevent this unlikely scenario, we can // modify the implementation so that when addresses are removed, the last addresses // in the array is moved to the empty index. function getWhitelist() external view returns (address[] memory activeWhitelist) { // Determine size of whitelist first uint activeCount = 0; for (uint i = 0; i < whitelistIndices.length; i++) { if (whitelist[whitelistIndices[i]] == Status.In) { activeCount++; } } // Populate whitelist activeWhitelist = new address[](activeCount); activeCount = 0; for (uint i = 0; i < whitelistIndices.length; i++) { address addr = whitelistIndices[i]; if (whitelist[addr] == Status.In) { activeWhitelist[activeCount] = addr; activeCount++; } } } event AddToWhitelist(address indexed addedAddress); event RemoveFromWhitelist(address indexed removedAddress); } contract Withdrawable is Ownable { // Withdraws ETH from the contract. function withdraw(uint amount) external onlyOwner { msg.sender.transfer(amount); } // Withdraws ERC20 tokens from the contract. function withdrawErc20(address erc20Address, uint amount) external onlyOwner { IERC20 erc20 = IERC20(erc20Address); require(erc20.transfer(msg.sender, amount)); } } // This interface allows contracts to query a verified, trusted price. interface OracleInterface { // Requests the Oracle price for an identifier at a time. Returns the time at which a price will be available. // Returns 0 is the price is available now, and returns 2^256-1 if the price will never be available. Reverts if // the Oracle doesn't support this identifier. Only contracts registered in the Registry are authorized to call this // method. function requestPrice(bytes32 identifier, uint time) external returns (uint expectedTime); // Checks whether a price has been resolved. function hasPrice(bytes32 identifier, uint time) external view returns (bool hasPriceAvailable); // Returns the Oracle price for identifier at a time. Reverts if the Oracle doesn't support this identifier or if // the Oracle doesn't have a price for this time. Only contracts registered in the Registry are authorized to call // this method. function getPrice(bytes32 identifier, uint time) external view returns (int price); // Returns whether the Oracle provides verified prices for the given identifier. function isIdentifierSupported(bytes32 identifier) external view returns (bool isSupported); // An event fired when a request for a (identifier, time) pair is made. event VerifiedPriceRequested(bytes32 indexed identifier, uint indexed time); // An event fired when a verified price is available for a (identifier, time) pair. event VerifiedPriceAvailable(bytes32 indexed identifier, uint indexed time, int price); } interface RegistryInterface { struct RegisteredDerivative { address derivativeAddress; address derivativeCreator; } // Registers a new derivative. Only authorized derivative creators can call this method. function registerDerivative(address[] calldata counterparties, address derivativeAddress) external; // Adds a new derivative creator to this list of authorized creators. Only the owner of this contract can call // this method. function addDerivativeCreator(address derivativeCreator) external; // Removes a derivative creator to this list of authorized creators. Only the owner of this contract can call this // method. function removeDerivativeCreator(address derivativeCreator) external; // Returns whether the derivative has been registered with the registry (and is therefore an authorized participant // in the UMA system). function isDerivativeRegistered(address derivative) external view returns (bool isRegistered); // Returns a list of all derivatives that are associated with a particular party. function getRegisteredDerivatives(address party) external view returns (RegisteredDerivative[] memory derivatives); // Returns all registered derivatives. function getAllRegisteredDerivatives() external view returns (RegisteredDerivative[] memory derivatives); // Returns whether an address is authorized to register new derivatives. function isDerivativeCreatorAuthorized(address derivativeCreator) external view returns (bool isAuthorized); } contract Registry is RegistryInterface, Withdrawable { using SafeMath for uint; // Array of all registeredDerivatives that are approved to use the UMA Oracle. RegisteredDerivative[] private registeredDerivatives; // This enum is required because a WasValid state is required to ensure that derivatives cannot be re-registered. enum PointerValidity { Invalid, Valid, WasValid } struct Pointer { PointerValidity valid; uint128 index; } // Maps from derivative address to a pointer that refers to that RegisteredDerivative in registeredDerivatives. mapping(address => Pointer) private derivativePointers; // Note: this must be stored outside of the RegisteredDerivative because mappings cannot be deleted and copied // like normal data. This could be stored in the Pointer struct, but storing it there would muddy the purpose // of the Pointer struct and break separation of concern between referential data and data. struct PartiesMap { mapping(address => bool) parties; } // Maps from derivative address to the set of parties that are involved in that derivative. mapping(address => PartiesMap) private derivativesToParties; // Maps from derivative creator address to whether that derivative creator has been approved to register contracts. mapping(address => bool) private derivativeCreators; modifier onlyApprovedDerivativeCreator { require(derivativeCreators[msg.sender]); _; } function registerDerivative(address[] calldata parties, address derivativeAddress) external onlyApprovedDerivativeCreator { // Create derivative pointer. Pointer storage pointer = derivativePointers[derivativeAddress]; // Ensure that the pointer was not valid in the past (derivatives cannot be re-registered or double // registered). require(pointer.valid == PointerValidity.Invalid); pointer.valid = PointerValidity.Valid; registeredDerivatives.push(RegisteredDerivative(derivativeAddress, msg.sender)); // No length check necessary because we should never hit (2^127 - 1) derivatives. pointer.index = uint128(registeredDerivatives.length.sub(1)); // Set up PartiesMap for this derivative. PartiesMap storage partiesMap = derivativesToParties[derivativeAddress]; for (uint i = 0; i < parties.length; i = i.add(1)) { partiesMap.parties[parties[i]] = true; } address[] memory partiesForEvent = parties; emit RegisterDerivative(derivativeAddress, partiesForEvent); } function addDerivativeCreator(address derivativeCreator) external onlyOwner { if (!derivativeCreators[derivativeCreator]) { derivativeCreators[derivativeCreator] = true; emit AddDerivativeCreator(derivativeCreator); } } function removeDerivativeCreator(address derivativeCreator) external onlyOwner { if (derivativeCreators[derivativeCreator]) { derivativeCreators[derivativeCreator] = false; emit RemoveDerivativeCreator(derivativeCreator); } } function isDerivativeRegistered(address derivative) external view returns (bool isRegistered) { return derivativePointers[derivative].valid == PointerValidity.Valid; } function getRegisteredDerivatives(address party) external view returns (RegisteredDerivative[] memory derivatives) { // This is not ideal - we must statically allocate memory arrays. To be safe, we make a temporary array as long // as registeredDerivatives. We populate it with any derivatives that involve the provided party. Then, we copy // the array over to the return array, which is allocated using the correct size. Note: this is done by double // copying each value rather than storing some referential info (like indices) in memory to reduce the number // of storage reads. This is because storage reads are far more expensive than extra memory space (~100:1). RegisteredDerivative[] memory tmpDerivativeArray = new RegisteredDerivative[](registeredDerivatives.length); uint outputIndex = 0; for (uint i = 0; i < registeredDerivatives.length; i = i.add(1)) { RegisteredDerivative storage derivative = registeredDerivatives[i]; if (derivativesToParties[derivative.derivativeAddress].parties[party]) { // Copy selected derivative to the temporary array. tmpDerivativeArray[outputIndex] = derivative; outputIndex = outputIndex.add(1); } } // Copy the temp array to the return array that is set to the correct size. derivatives = new RegisteredDerivative[](outputIndex); for (uint j = 0; j < outputIndex; j = j.add(1)) { derivatives[j] = tmpDerivativeArray[j]; } } function getAllRegisteredDerivatives() external view returns (RegisteredDerivative[] memory derivatives) { return registeredDerivatives; } function isDerivativeCreatorAuthorized(address derivativeCreator) external view returns (bool isAuthorized) { return derivativeCreators[derivativeCreator]; } event RegisterDerivative(address indexed derivativeAddress, address[] parties); event AddDerivativeCreator(address indexed addedDerivativeCreator); event RemoveDerivativeCreator(address indexed removedDerivativeCreator); } contract Testable is Ownable { // Is the contract being run on the test network. Note: this variable should be set on construction and never // modified. bool public isTest; uint private currentTime; constructor(bool _isTest) internal { isTest = _isTest; if (_isTest) { currentTime = now; // solhint-disable-line not-rely-on-time } } modifier onlyIfTest { require(isTest); _; } function setCurrentTime(uint _time) external onlyOwner onlyIfTest { currentTime = _time; } function getCurrentTime() public view returns (uint) { if (isTest) { return currentTime; } else { return now; // solhint-disable-line not-rely-on-time } } } contract ContractCreator is Withdrawable { Registry internal registry; address internal oracleAddress; address internal storeAddress; address internal priceFeedAddress; constructor(address registryAddress, address _oracleAddress, address _storeAddress, address _priceFeedAddress) public { registry = Registry(registryAddress); oracleAddress = _oracleAddress; storeAddress = _storeAddress; priceFeedAddress = _priceFeedAddress; } function _registerContract(address[] memory parties, address contractToRegister) internal { registry.registerDerivative(parties, contractToRegister); } } library TokenizedDerivativeParams { enum ReturnType { Linear, Compound } struct ConstructorParams { address sponsor; address admin; address oracle; address store; address priceFeed; uint defaultPenalty; // Percentage of margin requirement * 10^18 uint supportedMove; // Expected percentage move in the underlying price that the long is protected against. bytes32 product; uint fixedYearlyFee; // Percentage of nav * 10^18 uint disputeDeposit; // Percentage of margin requirement * 10^18 address returnCalculator; uint startingTokenPrice; uint expiry; address marginCurrency; uint withdrawLimit; // Percentage of derivativeStorage.shortBalance * 10^18 ReturnType returnType; uint startingUnderlyingPrice; uint creationTime; } } // TokenizedDerivativeStorage: this library name is shortened due to it being used so often. library TDS { enum State { // The contract is active, and tokens can be created and redeemed. Margin can be added and withdrawn (as long as // it exceeds required levels). Remargining is allowed. Created contracts immediately begin in this state. // Possible state transitions: Disputed, Expired, Defaulted. Live, // Disputed, Expired, Defaulted, and Emergency are Frozen states. In a Frozen state, the contract is frozen in // time awaiting a resolution by the Oracle. No tokens can be created or redeemed. Margin cannot be withdrawn. // The resolution of these states moves the contract to the Settled state. Remargining is not allowed. // The derivativeStorage.externalAddresses.sponsor has disputed the price feed output. If the dispute is valid (i.e., the NAV calculated from the // Oracle price differs from the NAV calculated from the price feed), the dispute fee is added to the short // account. Otherwise, the dispute fee is added to the long margin account. // Possible state transitions: Settled. Disputed, // Contract expiration has been reached. // Possible state transitions: Settled. Expired, // The short margin account is below its margin requirement. The derivativeStorage.externalAddresses.sponsor can choose to confirm the default and // move to Settle without waiting for the Oracle. Default penalties will be assessed when the contract moves to // Settled. // Possible state transitions: Settled. Defaulted, // UMA has manually triggered a shutdown of the account. // Possible state transitions: Settled. Emergency, // Token price is fixed. Tokens can be redeemed by anyone. All short margin can be withdrawn. Tokens can't be // created, and contract can't remargin. // Possible state transitions: None. Settled } // The state of the token at a particular time. The state gets updated on remargin. struct TokenState { int underlyingPrice; int tokenPrice; uint time; } // The information in the following struct is only valid if in the midst of a Dispute. struct Dispute { int disputedNav; uint deposit; } struct WithdrawThrottle { uint startTime; uint remainingWithdrawal; } struct FixedParameters { // Fixed contract parameters. uint defaultPenalty; // Percentage of margin requirement * 10^18 uint supportedMove; // Expected percentage move that the long is protected against. uint disputeDeposit; // Percentage of margin requirement * 10^18 uint fixedFeePerSecond; // Percentage of nav*10^18 uint withdrawLimit; // Percentage of derivativeStorage.shortBalance*10^18 bytes32 product; TokenizedDerivativeParams.ReturnType returnType; uint initialTokenUnderlyingRatio; uint creationTime; string symbol; } struct ExternalAddresses { // Other addresses/contracts address sponsor; address admin; address apDelegate; OracleInterface oracle; StoreInterface store; PriceFeedInterface priceFeed; ReturnCalculatorInterface returnCalculator; IERC20 marginCurrency; } struct Storage { FixedParameters fixedParameters; ExternalAddresses externalAddresses; // Balances int shortBalance; int longBalance; State state; uint endTime; // The NAV of the contract always reflects the transition from (`prev`, `current`). // In the case of a remargin, a `latest` price is retrieved from the price feed, and we shift `current` -> `prev` // and `latest` -> `current` (and then recompute). // In the case of a dispute, `current` might change (which is why we have to hold on to `prev`). TokenState referenceTokenState; TokenState currentTokenState; int nav; // Net asset value is measured in Wei Dispute disputeInfo; // Only populated once the contract enters a frozen state. int defaultPenaltyAmount; WithdrawThrottle withdrawThrottle; } } library TokenizedDerivativeUtils { using TokenizedDerivativeUtils for TDS.Storage; using SafeMath for uint; using SignedSafeMath for int; uint private constant SECONDS_PER_DAY = 86400; uint private constant SECONDS_PER_YEAR = 31536000; uint private constant INT_MAX = 2**255 - 1; uint private constant UINT_FP_SCALING_FACTOR = 10**18; int private constant INT_FP_SCALING_FACTOR = 10**18; modifier onlySponsor(TDS.Storage storage s) { require(msg.sender == s.externalAddresses.sponsor); _; } modifier onlyAdmin(TDS.Storage storage s) { require(msg.sender == s.externalAddresses.admin); _; } modifier onlySponsorOrAdmin(TDS.Storage storage s) { require(msg.sender == s.externalAddresses.sponsor || msg.sender == s.externalAddresses.admin); _; } modifier onlySponsorOrApDelegate(TDS.Storage storage s) { require(msg.sender == s.externalAddresses.sponsor || msg.sender == s.externalAddresses.apDelegate); _; } // Contract initializer. Should only be called at construction. // Note: Must be a public function because structs cannot be passed as calldata (required data type for external // functions). function _initialize( TDS.Storage storage s, TokenizedDerivativeParams.ConstructorParams memory params, string memory symbol) public { s._setFixedParameters(params, symbol); s._setExternalAddresses(params); // Keep the starting token price relatively close to FP_SCALING_FACTOR to prevent users from unintentionally // creating rounding or overflow errors. require(params.startingTokenPrice >= UINT_FP_SCALING_FACTOR.div(10**9)); require(params.startingTokenPrice <= UINT_FP_SCALING_FACTOR.mul(10**9)); // TODO(mrice32): we should have an ideal start time rather than blindly polling. (uint latestTime, int latestUnderlyingPrice) = s.externalAddresses.priceFeed.latestPrice(s.fixedParameters.product); // If nonzero, take the user input as the starting price. if (params.startingUnderlyingPrice != 0) { latestUnderlyingPrice = _safeIntCast(params.startingUnderlyingPrice); } require(latestUnderlyingPrice > 0); require(latestTime != 0); // Keep the ratio in case it's needed for margin computation. s.fixedParameters.initialTokenUnderlyingRatio = params.startingTokenPrice.mul(UINT_FP_SCALING_FACTOR).div(_safeUintCast(latestUnderlyingPrice)); require(s.fixedParameters.initialTokenUnderlyingRatio != 0); // Set end time to max value of uint to implement no expiry. if (params.expiry == 0) { s.endTime = ~uint(0); } else { require(params.expiry >= latestTime); s.endTime = params.expiry; } s.nav = s._computeInitialNav(latestUnderlyingPrice, latestTime, params.startingTokenPrice); s.state = TDS.State.Live; } function _depositAndCreateTokens(TDS.Storage storage s, uint marginForPurchase, uint tokensToPurchase) external onlySponsorOrApDelegate(s) { s._remarginInternal(); int newTokenNav = _computeNavForTokens(s.currentTokenState.tokenPrice, tokensToPurchase); if (newTokenNav < 0) { newTokenNav = 0; } uint positiveTokenNav = _safeUintCast(newTokenNav); // Get any refund due to sending more margin than the argument indicated (should only be able to happen in the // ETH case). uint refund = s._pullSentMargin(marginForPurchase); // Subtract newTokenNav from amount sent. uint depositAmount = marginForPurchase.sub(positiveTokenNav); // Deposit additional margin into the short account. s._depositInternal(depositAmount); // The _createTokensInternal call returns any refund due to the amount sent being larger than the amount // required to purchase the tokens, so we add that to the running refund. This should be 0 in this case, // but we leave this here in case of some refund being generated due to rounding errors or any bugs to ensure // the sender never loses money. refund = refund.add(s._createTokensInternal(tokensToPurchase, positiveTokenNav)); // Send the accumulated refund. s._sendMargin(refund); } function _redeemTokens(TDS.Storage storage s, uint tokensToRedeem) external { require(s.state == TDS.State.Live || s.state == TDS.State.Settled); require(tokensToRedeem > 0); if (s.state == TDS.State.Live) { require(msg.sender == s.externalAddresses.sponsor || msg.sender == s.externalAddresses.apDelegate); s._remarginInternal(); require(s.state == TDS.State.Live); } ExpandedIERC20 thisErc20Token = ExpandedIERC20(address(this)); uint initialSupply = _totalSupply(); require(initialSupply > 0); _pullAuthorizedTokens(thisErc20Token, tokensToRedeem); thisErc20Token.burn(tokensToRedeem); emit TokensRedeemed(s.fixedParameters.symbol, tokensToRedeem); // Value of the tokens is just the percentage of all the tokens multiplied by the balance of the investor // margin account. uint tokenPercentage = tokensToRedeem.mul(UINT_FP_SCALING_FACTOR).div(initialSupply); uint tokenMargin = _takePercentage(_safeUintCast(s.longBalance), tokenPercentage); s.longBalance = s.longBalance.sub(_safeIntCast(tokenMargin)); assert(s.longBalance >= 0); s.nav = _computeNavForTokens(s.currentTokenState.tokenPrice, _totalSupply()); s._sendMargin(tokenMargin); } function _dispute(TDS.Storage storage s, uint depositMargin) external onlySponsor(s) { require( s.state == TDS.State.Live, "Contract must be Live to dispute" ); uint requiredDeposit = _safeUintCast(_takePercentage(s._getRequiredMargin(s.currentTokenState), s.fixedParameters.disputeDeposit)); uint sendInconsistencyRefund = s._pullSentMargin(depositMargin); require(depositMargin >= requiredDeposit); uint overpaymentRefund = depositMargin.sub(requiredDeposit); s.state = TDS.State.Disputed; s.endTime = s.currentTokenState.time; s.disputeInfo.disputedNav = s.nav; s.disputeInfo.deposit = requiredDeposit; // Store the default penalty in case the dispute pushes the sponsor into default. s.defaultPenaltyAmount = s._computeDefaultPenalty(); emit Disputed(s.fixedParameters.symbol, s.endTime, s.nav); s._requestOraclePrice(s.endTime); // Add the two types of refunds: // 1. The refund for ETH sent if it was > depositMargin. // 2. The refund for depositMargin > requiredDeposit. s._sendMargin(sendInconsistencyRefund.add(overpaymentRefund)); } function _withdraw(TDS.Storage storage s, uint amount) external onlySponsor(s) { // Remargin before allowing a withdrawal, but only if in the live state. if (s.state == TDS.State.Live) { s._remarginInternal(); } // Make sure either in Live or Settled after any necessary remargin. require(s.state == TDS.State.Live || s.state == TDS.State.Settled); // If the contract has been settled or is in prefunded state then can // withdraw up to full balance. If the contract is in live state then // must leave at least the required margin. Not allowed to withdraw in // other states. int withdrawableAmount; if (s.state == TDS.State.Settled) { withdrawableAmount = s.shortBalance; } else { // Update throttling snapshot and verify that this withdrawal doesn't go past the throttle limit. uint currentTime = s.currentTokenState.time; if (s.withdrawThrottle.startTime <= currentTime.sub(SECONDS_PER_DAY)) { // We've passed the previous s.withdrawThrottle window. Start new one. s.withdrawThrottle.startTime = currentTime; s.withdrawThrottle.remainingWithdrawal = _takePercentage(_safeUintCast(s.shortBalance), s.fixedParameters.withdrawLimit); } int marginMaxWithdraw = s.shortBalance.sub(s._getRequiredMargin(s.currentTokenState)); int throttleMaxWithdraw = _safeIntCast(s.withdrawThrottle.remainingWithdrawal); // Take the smallest of the two withdrawal limits. withdrawableAmount = throttleMaxWithdraw < marginMaxWithdraw ? throttleMaxWithdraw : marginMaxWithdraw; // Note: this line alone implicitly ensures the withdrawal throttle is not violated, but the above // ternary is more explicit. s.withdrawThrottle.remainingWithdrawal = s.withdrawThrottle.remainingWithdrawal.sub(amount); } // Can only withdraw the allowed amount. require( withdrawableAmount >= _safeIntCast(amount), "Attempting to withdraw more than allowed" ); // Transfer amount - Note: important to `-=` before the send so that the // function can not be called multiple times while waiting for transfer // to return. s.shortBalance = s.shortBalance.sub(_safeIntCast(amount)); emit Withdrawal(s.fixedParameters.symbol, amount); s._sendMargin(amount); } function _acceptPriceAndSettle(TDS.Storage storage s) external onlySponsor(s) { // Right now, only confirming prices in the defaulted state. require(s.state == TDS.State.Defaulted); // Remargin on agreed upon price. s._settleAgreedPrice(); } function _setApDelegate(TDS.Storage storage s, address _apDelegate) external onlySponsor(s) { s.externalAddresses.apDelegate = _apDelegate; } // Moves the contract into the Emergency state, where it waits on an Oracle price for the most recent remargin time. function _emergencyShutdown(TDS.Storage storage s) external onlyAdmin(s) { require(s.state == TDS.State.Live); s.state = TDS.State.Emergency; s.endTime = s.currentTokenState.time; s.defaultPenaltyAmount = s._computeDefaultPenalty(); emit EmergencyShutdownTransition(s.fixedParameters.symbol, s.endTime); s._requestOraclePrice(s.endTime); } function _settle(TDS.Storage storage s) external { s._settleInternal(); } function _createTokens(TDS.Storage storage s, uint marginForPurchase, uint tokensToPurchase) external onlySponsorOrApDelegate(s) { // Returns any refund due to sending more margin than the argument indicated (should only be able to happen in // the ETH case). uint refund = s._pullSentMargin(marginForPurchase); // The _createTokensInternal call returns any refund due to the amount sent being larger than the amount // required to purchase the tokens, so we add that to the running refund. refund = refund.add(s._createTokensInternal(tokensToPurchase, marginForPurchase)); // Send the accumulated refund. s._sendMargin(refund); } function _deposit(TDS.Storage storage s, uint marginToDeposit) external onlySponsor(s) { // Only allow the s.externalAddresses.sponsor to deposit margin. uint refund = s._pullSentMargin(marginToDeposit); s._depositInternal(marginToDeposit); // Send any refund due to sending more margin than the argument indicated (should only be able to happen in the // ETH case). s._sendMargin(refund); } // Returns the expected net asset value (NAV) of the contract using the latest available Price Feed price. function _calcNAV(TDS.Storage storage s) external view returns (int navNew) { (TDS.TokenState memory newTokenState, ) = s._calcNewTokenStateAndBalance(); navNew = _computeNavForTokens(newTokenState.tokenPrice, _totalSupply()); } // Returns the expected value of each the outstanding tokens of the contract using the latest available Price Feed // price. function _calcTokenValue(TDS.Storage storage s) external view returns (int newTokenValue) { (TDS.TokenState memory newTokenState,) = s._calcNewTokenStateAndBalance(); newTokenValue = newTokenState.tokenPrice; } // Returns the expected balance of the short margin account using the latest available Price Feed price. function _calcShortMarginBalance(TDS.Storage storage s) external view returns (int newShortMarginBalance) { (, newShortMarginBalance) = s._calcNewTokenStateAndBalance(); } function _calcExcessMargin(TDS.Storage storage s) external view returns (int newExcessMargin) { (TDS.TokenState memory newTokenState, int newShortMarginBalance) = s._calcNewTokenStateAndBalance(); // If the contract is in/will be moved to a settled state, the margin requirement will be 0. int requiredMargin = newTokenState.time >= s.endTime ? 0 : s._getRequiredMargin(newTokenState); return newShortMarginBalance.sub(requiredMargin); } function _getCurrentRequiredMargin(TDS.Storage storage s) external view returns (int requiredMargin) { if (s.state == TDS.State.Settled) { // No margin needs to be maintained when the contract is settled. return 0; } return s._getRequiredMargin(s.currentTokenState); } function _canBeSettled(TDS.Storage storage s) external view returns (bool canBeSettled) { TDS.State currentState = s.state; if (currentState == TDS.State.Settled) { return false; } // Technically we should also check if price will default the contract, but that isn't a normal flow of // operations that we want to simulate: we want to discourage the sponsor remargining into a default. (uint priceFeedTime, ) = s._getLatestPrice(); if (currentState == TDS.State.Live && (priceFeedTime < s.endTime)) { return false; } return s.externalAddresses.oracle.hasPrice(s.fixedParameters.product, s.endTime); } function _getUpdatedUnderlyingPrice(TDS.Storage storage s) external view returns (int underlyingPrice, uint time) { (TDS.TokenState memory newTokenState, ) = s._calcNewTokenStateAndBalance(); return (newTokenState.underlyingPrice, newTokenState.time); } function _calcNewTokenStateAndBalance(TDS.Storage storage s) internal view returns (TDS.TokenState memory newTokenState, int newShortMarginBalance) { // TODO: there's a lot of repeated logic in this method from elsewhere in the contract. It should be extracted // so the logic can be written once and used twice. However, much of this was written post-audit, so it was // deemed preferable not to modify any state changing code that could potentially introduce new security // bugs. This should be done before the next contract audit. if (s.state == TDS.State.Settled) { // If the contract is Settled, just return the current contract state. return (s.currentTokenState, s.shortBalance); } // Grab the price feed pricetime. (uint priceFeedTime, int priceFeedPrice) = s._getLatestPrice(); bool isContractLive = s.state == TDS.State.Live; bool isContractPostExpiry = priceFeedTime >= s.endTime; // If the time hasn't advanced since the last remargin, short circuit and return the most recently computed values. if (isContractLive && priceFeedTime <= s.currentTokenState.time) { return (s.currentTokenState, s.shortBalance); } // Determine which previous price state to use when computing the new NAV. // If the contract is live, we use the reference for the linear return type or if the contract will immediately // move to expiry. bool shouldUseReferenceTokenState = isContractLive && (s.fixedParameters.returnType == TokenizedDerivativeParams.ReturnType.Linear || isContractPostExpiry); TDS.TokenState memory lastTokenState = shouldUseReferenceTokenState ? s.referenceTokenState : s.currentTokenState; // Use the oracle settlement price/time if the contract is frozen or will move to expiry on the next remargin. (uint recomputeTime, int recomputePrice) = !isContractLive || isContractPostExpiry ? (s.endTime, s.externalAddresses.oracle.getPrice(s.fixedParameters.product, s.endTime)) : (priceFeedTime, priceFeedPrice); // Init the returned short balance to the current short balance. newShortMarginBalance = s.shortBalance; // Subtract the oracle fees from the short balance. newShortMarginBalance = isContractLive ? newShortMarginBalance.sub( _safeIntCast(s._computeExpectedOracleFees(s.currentTokenState.time, recomputeTime))) : newShortMarginBalance; // Compute the new NAV newTokenState = s._computeNewTokenState(lastTokenState, recomputePrice, recomputeTime); int navNew = _computeNavForTokens(newTokenState.tokenPrice, _totalSupply()); newShortMarginBalance = newShortMarginBalance.sub(_getLongDiff(navNew, s.longBalance, newShortMarginBalance)); // If the contract is frozen or will move into expiry, we need to settle it, which means adding the default // penalty and dispute deposit if necessary. if (!isContractLive || isContractPostExpiry) { // Subtract default penalty (if necessary) from the short balance. bool inDefault = !s._satisfiesMarginRequirement(newShortMarginBalance, newTokenState); if (inDefault) { int expectedDefaultPenalty = isContractLive ? s._computeDefaultPenalty() : s._getDefaultPenalty(); int defaultPenalty = (newShortMarginBalance < expectedDefaultPenalty) ? newShortMarginBalance : expectedDefaultPenalty; newShortMarginBalance = newShortMarginBalance.sub(defaultPenalty); } // Add the dispute deposit to the short balance if necessary. if (s.state == TDS.State.Disputed && navNew != s.disputeInfo.disputedNav) { int depositValue = _safeIntCast(s.disputeInfo.deposit); newShortMarginBalance = newShortMarginBalance.add(depositValue); } } } function _computeInitialNav(TDS.Storage storage s, int latestUnderlyingPrice, uint latestTime, uint startingTokenPrice) internal returns (int navNew) { int unitNav = _safeIntCast(startingTokenPrice); s.referenceTokenState = TDS.TokenState(latestUnderlyingPrice, unitNav, latestTime); s.currentTokenState = TDS.TokenState(latestUnderlyingPrice, unitNav, latestTime); // Starting NAV is always 0 in the TokenizedDerivative case. navNew = 0; } function _remargin(TDS.Storage storage s) external onlySponsorOrAdmin(s) { s._remarginInternal(); } function _withdrawUnexpectedErc20(TDS.Storage storage s, address erc20Address, uint amount) external onlySponsor(s) { if(address(s.externalAddresses.marginCurrency) == erc20Address) { uint currentBalance = s.externalAddresses.marginCurrency.balanceOf(address(this)); int totalBalances = s.shortBalance.add(s.longBalance); assert(totalBalances >= 0); uint withdrawableAmount = currentBalance.sub(_safeUintCast(totalBalances)).sub(s.disputeInfo.deposit); require(withdrawableAmount >= amount); } IERC20 erc20 = IERC20(erc20Address); require(erc20.transfer(msg.sender, amount)); } function _setExternalAddresses(TDS.Storage storage s, TokenizedDerivativeParams.ConstructorParams memory params) internal { // Note: not all "ERC20" tokens conform exactly to this interface (BNB, OMG, etc). The most common way that // tokens fail to conform is that they do not return a bool from certain state-changing operations. This // contract was not designed to work with those tokens because of the additional complexity they would // introduce. s.externalAddresses.marginCurrency = IERC20(params.marginCurrency); s.externalAddresses.oracle = OracleInterface(params.oracle); s.externalAddresses.store = StoreInterface(params.store); s.externalAddresses.priceFeed = PriceFeedInterface(params.priceFeed); s.externalAddresses.returnCalculator = ReturnCalculatorInterface(params.returnCalculator); // Verify that the price feed and s.externalAddresses.oracle support the given s.fixedParameters.product. require(s.externalAddresses.oracle.isIdentifierSupported(params.product)); require(s.externalAddresses.priceFeed.isIdentifierSupported(params.product)); s.externalAddresses.sponsor = params.sponsor; s.externalAddresses.admin = params.admin; } function _setFixedParameters(TDS.Storage storage s, TokenizedDerivativeParams.ConstructorParams memory params, string memory symbol) internal { // Ensure only valid enum values are provided. require(params.returnType == TokenizedDerivativeParams.ReturnType.Compound || params.returnType == TokenizedDerivativeParams.ReturnType.Linear); // Fee must be 0 if the returnType is linear. require(params.returnType == TokenizedDerivativeParams.ReturnType.Compound || params.fixedYearlyFee == 0); // The default penalty must be less than the required margin. require(params.defaultPenalty <= UINT_FP_SCALING_FACTOR); s.fixedParameters.returnType = params.returnType; s.fixedParameters.defaultPenalty = params.defaultPenalty; s.fixedParameters.product = params.product; s.fixedParameters.fixedFeePerSecond = params.fixedYearlyFee.div(SECONDS_PER_YEAR); s.fixedParameters.disputeDeposit = params.disputeDeposit; s.fixedParameters.supportedMove = params.supportedMove; s.fixedParameters.withdrawLimit = params.withdrawLimit; s.fixedParameters.creationTime = params.creationTime; s.fixedParameters.symbol = symbol; } // _remarginInternal() allows other functions to call remargin internally without satisfying permission checks for // _remargin(). function _remarginInternal(TDS.Storage storage s) internal { // If the state is not live, remargining does not make sense. require(s.state == TDS.State.Live); (uint latestTime, int latestPrice) = s._getLatestPrice(); // Checks whether contract has ended. if (latestTime <= s.currentTokenState.time) { // If the price feed hasn't advanced, remargining should be a no-op. return; } // Save the penalty using the current state in case it needs to be used. int potentialPenaltyAmount = s._computeDefaultPenalty(); if (latestTime >= s.endTime) { s.state = TDS.State.Expired; emit Expired(s.fixedParameters.symbol, s.endTime); // Applies the same update a second time to effectively move the current state to the reference state. int recomputedNav = s._computeNav(s.currentTokenState.underlyingPrice, s.currentTokenState.time); assert(recomputedNav == s.nav); uint feeAmount = s._deductOracleFees(s.currentTokenState.time, s.endTime); // Save the precomputed default penalty in case the expiry price pushes the sponsor into default. s.defaultPenaltyAmount = potentialPenaltyAmount; // We have no idea what the price was, exactly at s.endTime, so we can't set // s.currentTokenState, or update the nav, or do anything. s._requestOraclePrice(s.endTime); s._payOracleFees(feeAmount); return; } uint feeAmount = s._deductOracleFees(s.currentTokenState.time, latestTime); // Update nav of contract. int navNew = s._computeNav(latestPrice, latestTime); // Update the balances of the contract. s._updateBalances(navNew); // Make sure contract has not moved into default. bool inDefault = !s._satisfiesMarginRequirement(s.shortBalance, s.currentTokenState); if (inDefault) { s.state = TDS.State.Defaulted; s.defaultPenaltyAmount = potentialPenaltyAmount; s.endTime = latestTime; // Change end time to moment when default occurred. emit Default(s.fixedParameters.symbol, latestTime, s.nav); s._requestOraclePrice(latestTime); } s._payOracleFees(feeAmount); } function _createTokensInternal(TDS.Storage storage s, uint tokensToPurchase, uint navSent) internal returns (uint refund) { s._remarginInternal(); // Verify that remargining didn't push the contract into expiry or default. require(s.state == TDS.State.Live); int purchasedNav = _computeNavForTokens(s.currentTokenState.tokenPrice, tokensToPurchase); if (purchasedNav < 0) { purchasedNav = 0; } // Ensures that requiredNav >= navSent. refund = navSent.sub(_safeUintCast(purchasedNav)); s.longBalance = s.longBalance.add(purchasedNav); ExpandedIERC20 thisErc20Token = ExpandedIERC20(address(this)); thisErc20Token.mint(msg.sender, tokensToPurchase); emit TokensCreated(s.fixedParameters.symbol, tokensToPurchase); s.nav = _computeNavForTokens(s.currentTokenState.tokenPrice, _totalSupply()); // Make sure this still satisfies the margin requirement. require(s._satisfiesMarginRequirement(s.shortBalance, s.currentTokenState)); } function _depositInternal(TDS.Storage storage s, uint value) internal { // Make sure that we are in a "depositable" state. require(s.state == TDS.State.Live); s.shortBalance = s.shortBalance.add(_safeIntCast(value)); emit Deposited(s.fixedParameters.symbol, value); } function _settleInternal(TDS.Storage storage s) internal { TDS.State startingState = s.state; require(startingState == TDS.State.Disputed || startingState == TDS.State.Expired || startingState == TDS.State.Defaulted || startingState == TDS.State.Emergency); s._settleVerifiedPrice(); if (startingState == TDS.State.Disputed) { int depositValue = _safeIntCast(s.disputeInfo.deposit); if (s.nav != s.disputeInfo.disputedNav) { s.shortBalance = s.shortBalance.add(depositValue); } else { s.longBalance = s.longBalance.add(depositValue); } } } // Deducts the fees from the margin account. function _deductOracleFees(TDS.Storage storage s, uint lastTimeOracleFeesPaid, uint currentTime) internal returns (uint feeAmount) { feeAmount = s._computeExpectedOracleFees(lastTimeOracleFeesPaid, currentTime); s.shortBalance = s.shortBalance.sub(_safeIntCast(feeAmount)); // If paying the Oracle fee reduces the held margin below requirements, the rest of remargin() will default the // contract. } // Pays out the fees to the Oracle. function _payOracleFees(TDS.Storage storage s, uint feeAmount) internal { if (feeAmount == 0) { return; } if (address(s.externalAddresses.marginCurrency) == address(0x0)) { s.externalAddresses.store.payOracleFees.value(feeAmount)(); } else { require(s.externalAddresses.marginCurrency.approve(address(s.externalAddresses.store), feeAmount)); s.externalAddresses.store.payOracleFeesErc20(address(s.externalAddresses.marginCurrency)); } } function _computeExpectedOracleFees(TDS.Storage storage s, uint lastTimeOracleFeesPaid, uint currentTime) internal view returns (uint feeAmount) { // The profit from corruption is set as the max(longBalance, shortBalance). int pfc = s.shortBalance < s.longBalance ? s.longBalance : s.shortBalance; uint expectedFeeAmount = s.externalAddresses.store.computeOracleFees(lastTimeOracleFeesPaid, currentTime, _safeUintCast(pfc)); // Ensure the fee returned can actually be paid by the short margin account. uint shortBalance = _safeUintCast(s.shortBalance); return (shortBalance < expectedFeeAmount) ? shortBalance : expectedFeeAmount; } function _computeNewTokenState(TDS.Storage storage s, TDS.TokenState memory beginningTokenState, int latestUnderlyingPrice, uint recomputeTime) internal view returns (TDS.TokenState memory newTokenState) { int underlyingReturn = s.externalAddresses.returnCalculator.computeReturn( beginningTokenState.underlyingPrice, latestUnderlyingPrice); int tokenReturn = underlyingReturn.sub( _safeIntCast(s.fixedParameters.fixedFeePerSecond.mul(recomputeTime.sub(beginningTokenState.time)))); int tokenMultiplier = tokenReturn.add(INT_FP_SCALING_FACTOR); // In the compound case, don't allow the token price to go below 0. if (s.fixedParameters.returnType == TokenizedDerivativeParams.ReturnType.Compound && tokenMultiplier < 0) { tokenMultiplier = 0; } int newTokenPrice = _takePercentage(beginningTokenState.tokenPrice, tokenMultiplier); newTokenState = TDS.TokenState(latestUnderlyingPrice, newTokenPrice, recomputeTime); } function _satisfiesMarginRequirement(TDS.Storage storage s, int balance, TDS.TokenState memory tokenState) internal view returns (bool doesSatisfyRequirement) { return s._getRequiredMargin(tokenState) <= balance; } function _requestOraclePrice(TDS.Storage storage s, uint requestedTime) internal { uint expectedTime = s.externalAddresses.oracle.requestPrice(s.fixedParameters.product, requestedTime); if (expectedTime == 0) { // The Oracle price is already available, settle the contract right away. s._settleInternal(); } } function _getLatestPrice(TDS.Storage storage s) internal view returns (uint latestTime, int latestUnderlyingPrice) { (latestTime, latestUnderlyingPrice) = s.externalAddresses.priceFeed.latestPrice(s.fixedParameters.product); require(latestTime != 0); } function _computeNav(TDS.Storage storage s, int latestUnderlyingPrice, uint latestTime) internal returns (int navNew) { if (s.fixedParameters.returnType == TokenizedDerivativeParams.ReturnType.Compound) { navNew = s._computeCompoundNav(latestUnderlyingPrice, latestTime); } else { assert(s.fixedParameters.returnType == TokenizedDerivativeParams.ReturnType.Linear); navNew = s._computeLinearNav(latestUnderlyingPrice, latestTime); } } function _computeCompoundNav(TDS.Storage storage s, int latestUnderlyingPrice, uint latestTime) internal returns (int navNew) { s.referenceTokenState = s.currentTokenState; s.currentTokenState = s._computeNewTokenState(s.currentTokenState, latestUnderlyingPrice, latestTime); navNew = _computeNavForTokens(s.currentTokenState.tokenPrice, _totalSupply()); emit NavUpdated(s.fixedParameters.symbol, navNew, s.currentTokenState.tokenPrice); } function _computeLinearNav(TDS.Storage storage s, int latestUnderlyingPrice, uint latestTime) internal returns (int navNew) { // Only update the time - don't update the prices becuase all price changes are relative to the initial price. s.referenceTokenState.time = s.currentTokenState.time; s.currentTokenState = s._computeNewTokenState(s.referenceTokenState, latestUnderlyingPrice, latestTime); navNew = _computeNavForTokens(s.currentTokenState.tokenPrice, _totalSupply()); emit NavUpdated(s.fixedParameters.symbol, navNew, s.currentTokenState.tokenPrice); } function _recomputeNav(TDS.Storage storage s, int oraclePrice, uint recomputeTime) internal returns (int navNew) { // We're updating `last` based on what the Oracle has told us. assert(s.endTime == recomputeTime); s.currentTokenState = s._computeNewTokenState(s.referenceTokenState, oraclePrice, recomputeTime); navNew = _computeNavForTokens(s.currentTokenState.tokenPrice, _totalSupply()); emit NavUpdated(s.fixedParameters.symbol, navNew, s.currentTokenState.tokenPrice); } // Function is internally only called by `_settleAgreedPrice` or `_settleVerifiedPrice`. This function handles all // of the settlement logic including assessing penalties and then moves the state to `Settled`. function _settleWithPrice(TDS.Storage storage s, int price) internal { // Remargin at whatever price we're using (verified or unverified). s._updateBalances(s._recomputeNav(price, s.endTime)); bool inDefault = !s._satisfiesMarginRequirement(s.shortBalance, s.currentTokenState); if (inDefault) { int expectedDefaultPenalty = s._getDefaultPenalty(); int penalty = (s.shortBalance < expectedDefaultPenalty) ? s.shortBalance : expectedDefaultPenalty; s.shortBalance = s.shortBalance.sub(penalty); s.longBalance = s.longBalance.add(penalty); } s.state = TDS.State.Settled; emit Settled(s.fixedParameters.symbol, s.endTime, s.nav); } function _updateBalances(TDS.Storage storage s, int navNew) internal { // Compute difference -- Add the difference to owner and subtract // from counterparty. Then update nav state variable. int longDiff = _getLongDiff(navNew, s.longBalance, s.shortBalance); s.nav = navNew; s.longBalance = s.longBalance.add(longDiff); s.shortBalance = s.shortBalance.sub(longDiff); } function _getDefaultPenalty(TDS.Storage storage s) internal view returns (int penalty) { return s.defaultPenaltyAmount; } function _computeDefaultPenalty(TDS.Storage storage s) internal view returns (int penalty) { return _takePercentage(s._getRequiredMargin(s.currentTokenState), s.fixedParameters.defaultPenalty); } function _getRequiredMargin(TDS.Storage storage s, TDS.TokenState memory tokenState) internal view returns (int requiredMargin) { int leverageMagnitude = _absoluteValue(s.externalAddresses.returnCalculator.leverage()); int effectiveNotional; if (s.fixedParameters.returnType == TokenizedDerivativeParams.ReturnType.Linear) { int effectiveUnitsOfUnderlying = _safeIntCast(_totalSupply().mul(s.fixedParameters.initialTokenUnderlyingRatio).div(UINT_FP_SCALING_FACTOR)).mul(leverageMagnitude); effectiveNotional = effectiveUnitsOfUnderlying.mul(tokenState.underlyingPrice).div(INT_FP_SCALING_FACTOR); } else { int currentNav = _computeNavForTokens(tokenState.tokenPrice, _totalSupply()); effectiveNotional = currentNav.mul(leverageMagnitude); } // Take the absolute value of the notional since a negative notional has similar risk properties to a positive // notional of the same size, and, therefore, requires the same margin. requiredMargin = _takePercentage(_absoluteValue(effectiveNotional), s.fixedParameters.supportedMove); } function _pullSentMargin(TDS.Storage storage s, uint expectedMargin) internal returns (uint refund) { if (address(s.externalAddresses.marginCurrency) == address(0x0)) { // Refund is any amount of ETH that was sent that was above the amount that was expected. // Note: SafeMath will force a revert if msg.value < expectedMargin. return msg.value.sub(expectedMargin); } else { // If we expect an ERC20 token, no ETH should be sent. require(msg.value == 0); _pullAuthorizedTokens(s.externalAddresses.marginCurrency, expectedMargin); // There is never a refund in the ERC20 case since we use the argument to determine how much to "pull". return 0; } } function _sendMargin(TDS.Storage storage s, uint amount) internal { // There's no point in attempting a send if there's nothing to send. if (amount == 0) { return; } if (address(s.externalAddresses.marginCurrency) == address(0x0)) { msg.sender.transfer(amount); } else { require(s.externalAddresses.marginCurrency.transfer(msg.sender, amount)); } } function _settleAgreedPrice(TDS.Storage storage s) internal { int agreedPrice = s.currentTokenState.underlyingPrice; s._settleWithPrice(agreedPrice); } function _settleVerifiedPrice(TDS.Storage storage s) internal { int oraclePrice = s.externalAddresses.oracle.getPrice(s.fixedParameters.product, s.endTime); s._settleWithPrice(oraclePrice); } function _pullAuthorizedTokens(IERC20 erc20, uint amountToPull) private { // If nothing is being pulled, there's no point in calling a transfer. if (amountToPull > 0) { require(erc20.transferFrom(msg.sender, address(this), amountToPull)); } } // Gets the change in balance for the long side. // Note: there's a function for this because signage is tricky here, and it must be done the same everywhere. function _getLongDiff(int navNew, int longBalance, int shortBalance) private pure returns (int longDiff) { int newLongBalance = navNew; // Long balance cannot go below zero. if (newLongBalance < 0) { newLongBalance = 0; } longDiff = newLongBalance.sub(longBalance); // Cannot pull more margin from the short than is available. if (longDiff > shortBalance) { longDiff = shortBalance; } } function _computeNavForTokens(int tokenPrice, uint numTokens) private pure returns (int navNew) { int navPreDivision = _safeIntCast(numTokens).mul(tokenPrice); navNew = navPreDivision.div(INT_FP_SCALING_FACTOR); // The navNew division above truncates by default. Instead, we prefer to ceil this value to ensure tokens // cannot be purchased or backed with less than their true value. if ((navPreDivision % INT_FP_SCALING_FACTOR) != 0) { navNew = navNew.add(1); } } function _totalSupply() private view returns (uint totalSupply) { ExpandedIERC20 thisErc20Token = ExpandedIERC20(address(this)); return thisErc20Token.totalSupply(); } function _takePercentage(uint value, uint percentage) private pure returns (uint result) { return value.mul(percentage).div(UINT_FP_SCALING_FACTOR); } function _takePercentage(int value, uint percentage) private pure returns (int result) { return value.mul(_safeIntCast(percentage)).div(INT_FP_SCALING_FACTOR); } function _takePercentage(int value, int percentage) private pure returns (int result) { return value.mul(percentage).div(INT_FP_SCALING_FACTOR); } function _absoluteValue(int value) private pure returns (int result) { return value < 0 ? value.mul(-1) : value; } function _safeIntCast(uint value) private pure returns (int result) { require(value <= INT_MAX); return int(value); } function _safeUintCast(int value) private pure returns (uint result) { require(value >= 0); return uint(value); } // Note that we can't have the symbol parameter be `indexed` due to: // TypeError: Indexed reference types cannot yet be used with ABIEncoderV2. // An event emitted when the NAV of the contract changes. event NavUpdated(string symbol, int newNav, int newTokenPrice); // An event emitted when the contract enters the Default state on a remargin. event Default(string symbol, uint defaultTime, int defaultNav); // An event emitted when the contract settles. event Settled(string symbol, uint settleTime, int finalNav); // An event emitted when the contract expires. event Expired(string symbol, uint expiryTime); // An event emitted when the contract's NAV is disputed by the sponsor. event Disputed(string symbol, uint timeDisputed, int navDisputed); // An event emitted when the contract enters emergency shutdown. event EmergencyShutdownTransition(string symbol, uint shutdownTime); // An event emitted when tokens are created. event TokensCreated(string symbol, uint numTokensCreated); // An event emitted when tokens are redeemed. event TokensRedeemed(string symbol, uint numTokensRedeemed); // An event emitted when margin currency is deposited. event Deposited(string symbol, uint amount); // An event emitted when margin currency is withdrawn. event Withdrawal(string symbol, uint amount); } // TODO(mrice32): make this and TotalReturnSwap derived classes of a single base to encap common functionality. contract TokenizedDerivative is ERC20, AdminInterface, ExpandedIERC20 { using TokenizedDerivativeUtils for TDS.Storage; // Note: these variables are to give ERC20 consumers information about the token. string public name; string public symbol; uint8 public constant decimals = 18; // solhint-disable-line const-name-snakecase TDS.Storage public derivativeStorage; constructor( TokenizedDerivativeParams.ConstructorParams memory params, string memory _name, string memory _symbol ) public { // Set token properties. name = _name; symbol = _symbol; // Initialize the contract. derivativeStorage._initialize(params, _symbol); } // Creates tokens with sent margin and returns additional margin. function createTokens(uint marginForPurchase, uint tokensToPurchase) external payable { derivativeStorage._createTokens(marginForPurchase, tokensToPurchase); } // Creates tokens with sent margin and deposits additional margin in short account. function depositAndCreateTokens(uint marginForPurchase, uint tokensToPurchase) external payable { derivativeStorage._depositAndCreateTokens(marginForPurchase, tokensToPurchase); } // Redeems tokens for margin currency. function redeemTokens(uint tokensToRedeem) external { derivativeStorage._redeemTokens(tokensToRedeem); } // Triggers a price dispute for the most recent remargin time. function dispute(uint depositMargin) external payable { derivativeStorage._dispute(depositMargin); } // Withdraws `amount` from short margin account. function withdraw(uint amount) external { derivativeStorage._withdraw(amount); } // Pays (Oracle and service) fees for the previous period, updates the contract NAV, moves margin between long and // short accounts to reflect the new NAV, and checks if both accounts meet minimum requirements. function remargin() external { derivativeStorage._remargin(); } // Forgo the Oracle verified price and settle the contract with last remargin price. This method is only callable on // contracts in the `Defaulted` state, and the default penalty is always transferred from the short to the long // account. function acceptPriceAndSettle() external { derivativeStorage._acceptPriceAndSettle(); } // Assigns an address to be the contract's Delegate AP. Replaces previous value. Set to 0x0 to indicate there is no // Delegate AP. function setApDelegate(address apDelegate) external { derivativeStorage._setApDelegate(apDelegate); } // Moves the contract into the Emergency state, where it waits on an Oracle price for the most recent remargin time. function emergencyShutdown() external { derivativeStorage._emergencyShutdown(); } // Returns the expected net asset value (NAV) of the contract using the latest available Price Feed price. function calcNAV() external view returns (int navNew) { return derivativeStorage._calcNAV(); } // Returns the expected value of each the outstanding tokens of the contract using the latest available Price Feed // price. function calcTokenValue() external view returns (int newTokenValue) { return derivativeStorage._calcTokenValue(); } // Returns the expected balance of the short margin account using the latest available Price Feed price. function calcShortMarginBalance() external view returns (int newShortMarginBalance) { return derivativeStorage._calcShortMarginBalance(); } // Returns the expected short margin in excess of the margin requirement using the latest available Price Feed // price. Value will be negative if the short margin is expected to be below the margin requirement. function calcExcessMargin() external view returns (int excessMargin) { return derivativeStorage._calcExcessMargin(); } // Returns the required margin, as of the last remargin. Note that `calcExcessMargin` uses updated values using the // latest available Price Feed price. function getCurrentRequiredMargin() external view returns (int requiredMargin) { return derivativeStorage._getCurrentRequiredMargin(); } // Returns whether the contract can be settled, i.e., is it valid to call settle() now. function canBeSettled() external view returns (bool canContractBeSettled) { return derivativeStorage._canBeSettled(); } // Returns the updated underlying price that was used in the calc* methods above. It will be a price feed price if // the contract is Live and will remain Live, or an Oracle price if the contract is settled/about to be settled. // Reverts if no Oracle price is available but an Oracle price is required. function getUpdatedUnderlyingPrice() external view returns (int underlyingPrice, uint time) { return derivativeStorage._getUpdatedUnderlyingPrice(); } // When an Oracle price becomes available, performs a final remargin, assesses any penalties, and moves the contract // into the `Settled` state. function settle() external { derivativeStorage._settle(); } // Adds the margin sent along with the call (or in the case of an ERC20 margin currency, authorized before the call) // to the short account. function deposit(uint amountToDeposit) external payable { derivativeStorage._deposit(amountToDeposit); } // Allows the sponsor to withdraw any ERC20 balance that is not the margin token. function withdrawUnexpectedErc20(address erc20Address, uint amount) external { derivativeStorage._withdrawUnexpectedErc20(erc20Address, amount); } // ExpandedIERC20 methods. modifier onlyThis { require(msg.sender == address(this)); _; } // Only allow calls from this contract or its libraries to burn tokens. function burn(uint value) external onlyThis { // Only allow calls from this contract or its libraries to burn tokens. _burn(msg.sender, value); } // Only allow calls from this contract or its libraries to mint tokens. function mint(address to, uint256 value) external onlyThis { _mint(to, value); } // These events are actually emitted by TokenizedDerivativeUtils, but we unfortunately have to define the events // here as well. event NavUpdated(string symbol, int newNav, int newTokenPrice); event Default(string symbol, uint defaultTime, int defaultNav); event Settled(string symbol, uint settleTime, int finalNav); event Expired(string symbol, uint expiryTime); event Disputed(string symbol, uint timeDisputed, int navDisputed); event EmergencyShutdownTransition(string symbol, uint shutdownTime); event TokensCreated(string symbol, uint numTokensCreated); event TokensRedeemed(string symbol, uint numTokensRedeemed); event Deposited(string symbol, uint amount); event Withdrawal(string symbol, uint amount); } contract TokenizedDerivativeCreator is ContractCreator, Testable { struct Params { uint defaultPenalty; // Percentage of mergin requirement * 10^18 uint supportedMove; // Expected percentage move in the underlying that the long is protected against. bytes32 product; uint fixedYearlyFee; // Percentage of nav * 10^18 uint disputeDeposit; // Percentage of mergin requirement * 10^18 address returnCalculator; uint startingTokenPrice; uint expiry; address marginCurrency; uint withdrawLimit; // Percentage of shortBalance * 10^18 TokenizedDerivativeParams.ReturnType returnType; uint startingUnderlyingPrice; string name; string symbol; } AddressWhitelist public sponsorWhitelist; AddressWhitelist public returnCalculatorWhitelist; AddressWhitelist public marginCurrencyWhitelist; constructor( address registryAddress, address _oracleAddress, address _storeAddress, address _priceFeedAddress, address _sponsorWhitelist, address _returnCalculatorWhitelist, address _marginCurrencyWhitelist, bool _isTest ) public ContractCreator(registryAddress, _oracleAddress, _storeAddress, _priceFeedAddress) Testable(_isTest) { sponsorWhitelist = AddressWhitelist(_sponsorWhitelist); returnCalculatorWhitelist = AddressWhitelist(_returnCalculatorWhitelist); marginCurrencyWhitelist = AddressWhitelist(_marginCurrencyWhitelist); } function createTokenizedDerivative(Params memory params) public returns (address derivativeAddress) { TokenizedDerivative derivative = new TokenizedDerivative(_convertParams(params), params.name, params.symbol); address[] memory parties = new address[](1); parties[0] = msg.sender; _registerContract(parties, address(derivative)); return address(derivative); } // Converts createTokenizedDerivative params to TokenizedDerivative constructor params. function _convertParams(Params memory params) private view returns (TokenizedDerivativeParams.ConstructorParams memory constructorParams) { // Copy and verify externally provided variables. require(sponsorWhitelist.isOnWhitelist(msg.sender)); constructorParams.sponsor = msg.sender; require(returnCalculatorWhitelist.isOnWhitelist(params.returnCalculator)); constructorParams.returnCalculator = params.returnCalculator; require(marginCurrencyWhitelist.isOnWhitelist(params.marginCurrency)); constructorParams.marginCurrency = params.marginCurrency; constructorParams.defaultPenalty = params.defaultPenalty; constructorParams.supportedMove = params.supportedMove; constructorParams.product = params.product; constructorParams.fixedYearlyFee = params.fixedYearlyFee; constructorParams.disputeDeposit = params.disputeDeposit; constructorParams.startingTokenPrice = params.startingTokenPrice; constructorParams.expiry = params.expiry; constructorParams.withdrawLimit = params.withdrawLimit; constructorParams.returnType = params.returnType; constructorParams.startingUnderlyingPrice = params.startingUnderlyingPrice; // Copy internal variables. constructorParams.priceFeed = priceFeedAddress; constructorParams.oracle = oracleAddress; constructorParams.store = storeAddress; constructorParams.admin = oracleAddress; constructorParams.creationTime = getCurrentTime(); } }
Checks whether an address is on the whitelist.
function isOnWhitelist(address elementToCheck) external view returns (bool) { return whitelist[elementToCheck] == Status.In; }
972,243
// SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /* Library Imports */ import { Lib_ErrorUtils } from "../utils/Lib_ErrorUtils.sol"; import { Lib_PredeployAddresses } from "../constants/Lib_PredeployAddresses.sol"; /** * @title Lib_ExecutionManagerWrapper * @dev This library acts as a utility for easily calling the OVM_ExecutionManagerWrapper, the * predeployed contract which exposes the `kall` builtin. Effectively, this contract allows the * user to trigger OVM opcodes by directly calling the OVM_ExecutionManger. * * Compiler used: solc * Runtime target: OVM */ library Lib_ExecutionManagerWrapper { /********************** * Internal Functions * **********************/ /** * Performs a safe ovmCREATE call. * @param _bytecode Code for the new contract. * @return Address of the created contract. */ function ovmCREATE( bytes memory _bytecode ) internal returns ( address, bytes memory ) { bytes memory returndata = _callWrapperContract( abi.encodeWithSignature( "ovmCREATE(bytes)", _bytecode ) ); return abi.decode(returndata, (address, bytes)); } /** * Performs a safe ovmGETNONCE call. * @return Result of calling ovmGETNONCE. */ function ovmGETNONCE() internal returns ( uint256 ) { bytes memory returndata = _callWrapperContract( abi.encodeWithSignature( "ovmGETNONCE()" ) ); return abi.decode(returndata, (uint256)); } /** * Performs a safe ovmINCREMENTNONCE call. */ function ovmINCREMENTNONCE() internal { _callWrapperContract( abi.encodeWithSignature( "ovmINCREMENTNONCE()" ) ); } /** * Performs a safe ovmCREATEEOA call. * @param _messageHash Message hash which was signed by EOA * @param _v v value of signature (0 or 1) * @param _r r value of signature * @param _s s value of signature */ function ovmCREATEEOA( bytes32 _messageHash, uint8 _v, bytes32 _r, bytes32 _s ) internal { _callWrapperContract( abi.encodeWithSignature( "ovmCREATEEOA(bytes32,uint8,bytes32,bytes32)", _messageHash, _v, _r, _s ) ); } /** * Calls the ovmL1TXORIGIN opcode. * @return Address that sent this message from L1. */ function ovmL1TXORIGIN() internal returns ( address ) { bytes memory returndata = _callWrapperContract( abi.encodeWithSignature( "ovmL1TXORIGIN()" ) ); return abi.decode(returndata, (address)); } /** * Calls the ovmCHAINID opcode. * @return Chain ID of the current network. */ function ovmCHAINID() internal returns ( uint256 ) { bytes memory returndata = _callWrapperContract( abi.encodeWithSignature( "ovmCHAINID()" ) ); return abi.decode(returndata, (uint256)); } /** * Performs a safe ovmADDRESS call. * @return Result of calling ovmADDRESS. */ function ovmADDRESS() internal returns ( address ) { bytes memory returndata = _callWrapperContract( abi.encodeWithSignature( "ovmADDRESS()" ) ); return abi.decode(returndata, (address)); } /** * Calls the value-enabled ovmCALL opcode. * @param _gasLimit Amount of gas to be passed into this call. * @param _address Address of the contract to call. * @param _value ETH value to pass with the call. * @param _calldata Data to send along with the call. * @return _success Whether or not the call returned (rather than reverted). * @return _returndata Data returned by the call. */ function ovmCALL( uint256 _gasLimit, address _address, uint256 _value, bytes memory _calldata ) internal returns ( bool, bytes memory ) { bytes memory returndata = _callWrapperContract( abi.encodeWithSignature( "ovmCALL(uint256,address,uint256,bytes)", _gasLimit, _address, _value, _calldata ) ); return abi.decode(returndata, (bool, bytes)); } /** * Calls the ovmBALANCE opcode. * @param _address OVM account to query the balance of. * @return Balance of the account. */ function ovmBALANCE( address _address ) internal returns ( uint256 ) { bytes memory returndata = _callWrapperContract( abi.encodeWithSignature( "ovmBALANCE(address)", _address ) ); return abi.decode(returndata, (uint256)); } /** * Calls the ovmCALLVALUE opcode. * @return Value of the current call frame. */ function ovmCALLVALUE() internal returns ( uint256 ) { bytes memory returndata = _callWrapperContract( abi.encodeWithSignature( "ovmCALLVALUE()" ) ); return abi.decode(returndata, (uint256)); } /********************* * Private Functions * *********************/ /** * Performs an ovm interaction and the necessary safety checks. * @param _calldata Data to send to the OVM_ExecutionManager (encoded with sighash). * @return Data sent back by the OVM_ExecutionManager. */ function _callWrapperContract( bytes memory _calldata ) private returns ( bytes memory ) { (bool success, bytes memory returndata) = Lib_PredeployAddresses.EXECUTION_MANAGER_WRAPPER.delegatecall(_calldata); if (success == true) { return returndata; } else { assembly { revert(add(returndata, 0x20), mload(returndata)) } } } }
Performs a safe ovmCREATEEOA call. _messageHash Message hash which was signed by EOA _v v value of signature (0 or 1) _r r value of signature _s s value of signature/
function ovmCREATEEOA( bytes32 _messageHash, uint8 _v, bytes32 _r, bytes32 _s ) internal { _callWrapperContract( abi.encodeWithSignature( "ovmCREATEEOA(bytes32,uint8,bytes32,bytes32)", _messageHash, _v, _r, _s ) ); }
5,370,250
// SPDX-License-Identifier: MIT pragma solidity ^0.8.4; import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; import '@openzeppelin/contracts/access/Ownable.sol'; import '@openzeppelin/contracts/utils/math/SafeMath.sol'; import '@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol'; import './Aureus.sol'; import './ElysianFields.sol'; contract AerariumSanctius is Ownable { using SafeMath for uint256; using SafeERC20 for Aureus; using SafeERC20 for IERC20; // The reward token that will be used to redeem rewards at the end of the farming program Aureus public immutable rwdToken; // The endBlock after which rewards can be redeemable uint256 public immutable endBlock; // A timeout for withdraw after which the owner can withdraw any excess tokens left in the contract uint256 public immutable withdrawTimeout; // An array of structs holding information on each token that is deposited in the contract and will be distributed as reward at the end of the program IERC20[] public tokensHeld; // A mapping to track token amounts stored in the contract for each token in tokensHeld array mapping(IERC20 => uint256) public tokenAmounts; // A withdraw event emited on withdraw of rewards after the end of the program event Withdraw(address user, address token, uint256 amount); /** @dev - Constructor * @param _elysianFields - This is the address of the master contract used to farm the ERC20 token that will be used to unlock rewards from this contract * @param _owner - The address to which ownership of this contract will be passed in the constructor * @param _withdrawBlockTimeout - The timeout added after the end of the program after which the owner can withdraw any excess tokens left in this contract */ constructor( ElysianFields _elysianFields, address _owner, uint256 _withdrawBlockTimeout ) { require(_withdrawBlockTimeout > 0, 'Withdraw timeout can not be set to 0'); rwdToken = _elysianFields.rwdToken(); endBlock = _elysianFields.endBlock(); withdrawTimeout = _elysianFields.claimTimeout().add(_withdrawBlockTimeout); transferOwnership(_owner); } /** @dev - This function allows the owner to add tokens to this contract that can be distributed at the end of the farming program * @param _token - The address of the ERC20 token that will be deposited in the contract * @param _amount - The amount of ERC20 tokens that will be transferred from the owner to this contract */ function addTokens(IERC20 _token, uint256 _amount) external onlyOwner { require( block.number <= endBlock, 'The end time of the program is reached!' ); _token.safeTransferFrom(msg.sender, address(this), _amount); if (tokenAmounts[_token] == 0) { tokensHeld.push(_token); tokenAmounts[_token] = _amount; } else { tokenAmounts[_token] = tokenAmounts[_token].add(_amount); } } /** @dev - Claim function which is called by the user to claim their share of reward tokens after the end of the farming program * @param _rwdAmount - The amount of reward tokens that the user accumulated and will be burned to unlock the tokens held in this contract */ function claim(uint256 _rwdAmount) external { require( block.number > endBlock, 'The end time of the program is not reached!' ); rwdToken.safeTransferFrom(msg.sender, address(this), _rwdAmount); uint256 percentage = (_rwdAmount.mul(1e18)).div(rwdToken.cap()); rwdToken.burn(_rwdAmount); _withdraw(percentage); } /** @dev - A function to withdraw any excess tokens left in this contract after the program has ended and the timeout has expired * @param _receiver - The address to which the remaining excess tokens will be sent */ function withdrawExcess(address _receiver) external onlyOwner { require( block.number > withdrawTimeout, 'The current withdraw period has not finished' ); for (uint256 i = 0; i < tokensHeld.length; i++) { tokensHeld[i].safeTransfer( _receiver, tokensHeld[i].balanceOf(address(this)) ); } } /** @dev - A function to check the length of the array of structs */ function tokensHeldLength() external view returns (uint256) { return tokensHeld.length; } /** @dev - An internal withdraw function which transfers a percentage of each ERC20 held in this contract to the user. It is called within the claim funcion * @param _percentage - The percentage is calculated based on the reward token amount the user sent to be burned. It is calculated and passed within the claim function * emits a Withdraw event for each transfer of ERC20 tokens from this contract to the user */ function _withdraw(uint256 _percentage) internal { for (uint256 i = 0; i < tokensHeld.length; i++) { uint256 currentAmount = tokenAmounts[tokensHeld[i]]; uint256 _amount = currentAmount.mul(_percentage).div(1e18); tokensHeld[i].safeTransfer(msg.sender, _amount); emit Withdraw(msg.sender, address(tokensHeld[i]), _amount); } } }
- This function allows the owner to add tokens to this contract that can be distributed at the end of the farming program _token - The address of the ERC20 token that will be deposited in the contract _amount - The amount of ERC20 tokens that will be transferred from the owner to this contract/
function addTokens(IERC20 _token, uint256 _amount) external onlyOwner { require( block.number <= endBlock, 'The end time of the program is reached!' ); _token.safeTransferFrom(msg.sender, address(this), _amount); if (tokenAmounts[_token] == 0) { tokensHeld.push(_token); tokenAmounts[_token] = _amount; tokenAmounts[_token] = tokenAmounts[_token].add(_amount); } }
12,786,636
./full_match/3/0x7F59f06c03ed13740abBD931823CEc81974Ef7a8/sources/browser/KASSIAKOMMERCIALGovernance.sol
Delegates votes from signatory to `delegatee` delegatee The address to delegate votes to nonce The contract state required to match the signature expiry The time at which to expire the signature v The recovery byte of the signature r Half of the ECDSA signature pair s Half of the ECDSA signature pair/
function delegateBySig( address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s ) external { bytes32 domainSeparator = keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this) ) ); bytes32 structHash = keccak256( abi.encode( DELEGATION_TYPEHASH, delegatee, nonce, expiry ) ); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", domainSeparator, structHash ) ); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "KASSIAKOMMERCIAL::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "KASSIAKOMMERCIAL::delegateBySig: invalid nonce"); require(now <= expiry, "KASSIAKOMMERCIAL::delegateBySig: signature expired"); return _delegate(signatory, delegatee); }
8,104,850
// File: @openzeppelin/contracts/utils/Context.sol // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/introspection/IERC165.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol pragma solidity >=0.6.2 <0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // File: @openzeppelin/contracts/token/ERC721/IERC721Metadata.sol pragma solidity >=0.6.2 <0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: @openzeppelin/contracts/token/ERC721/IERC721Enumerable.sol pragma solidity >=0.6.2 <0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol pragma solidity >=0.6.0 <0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev 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, bytes calldata data) external returns (bytes4); } // File: @openzeppelin/contracts/introspection/ERC165.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ abstract contract ERC165 is IERC165 { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; constructor () { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal virtual { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } // File: @openzeppelin/contracts/math/SafeMath.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // 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 (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @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) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * 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); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/utils/EnumerableSet.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // File: @openzeppelin/contracts/utils/EnumerableMap.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing an enumerable variant of Solidity's * https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`] * type. * * Maps have the following properties: * * - Entries are added, removed, and checked for existence in constant time * (O(1)). * - Entries are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableMap for EnumerableMap.UintToAddressMap; * * // Declare a set state variable * EnumerableMap.UintToAddressMap private myMap; * } * ``` * * As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are * supported. */ library EnumerableMap { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Map type with // bytes32 keys and values. // The Map implementation uses private functions, and user-facing // implementations (such as Uint256ToAddressMap) are just wrappers around // the underlying Map. // This means that we can only create new EnumerableMaps for types that fit // in bytes32. struct MapEntry { bytes32 _key; bytes32 _value; } struct Map { // Storage of map keys and values MapEntry[] _entries; // Position of the entry defined by a key in the `entries` array, plus 1 // because index 0 means a key is not in the map. mapping (bytes32 => uint256) _indexes; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) { // Equivalent to !contains(map, key) map._entries.push(MapEntry({ _key: key, _value: value })); // The entry is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value map._indexes[key] = map._entries.length; return true; } else { map._entries[keyIndex - 1]._value = value; return false; } } /** * @dev Removes a key-value pair from a map. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function _remove(Map storage map, bytes32 key) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex != 0) { // Equivalent to contains(map, key) // To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one // in the array, and then remove the last entry (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = keyIndex - 1; uint256 lastIndex = map._entries.length - 1; // When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. MapEntry storage lastEntry = map._entries[lastIndex]; // Move the last entry to the index where the entry to delete is map._entries[toDeleteIndex] = lastEntry; // Update the index for the moved entry map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved entry was stored map._entries.pop(); // Delete the index for the deleted slot delete map._indexes[key]; return true; } else { return false; } } /** * @dev Returns true if the key is in the map. O(1). */ function _contains(Map storage map, bytes32 key) private view returns (bool) { return map._indexes[key] != 0; } /** * @dev Returns the number of key-value pairs in the map. O(1). */ function _length(Map storage map) private view returns (uint256) { return map._entries.length; } /** * @dev Returns the key-value pair stored at position `index` in the map. O(1). * * Note that there are no guarantees on the ordering of entries inside the * array, and it may change when more entries are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) { require(map._entries.length > index, "EnumerableMap: index out of bounds"); MapEntry storage entry = map._entries[index]; return (entry._key, entry._value); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. */ function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) { uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) return (false, 0); // Equivalent to contains(map, key) return (true, map._entries[keyIndex - 1]._value); // All indexes are 1-based } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function _get(Map storage map, bytes32 key) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, "EnumerableMap: nonexistent key"); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } /** * @dev Same as {_get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {_tryGet}. */ function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } // UintToAddressMap struct UintToAddressMap { Map _inner; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) { return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) { return _remove(map._inner, bytes32(key)); } /** * @dev Returns true if the key is in the map. O(1). */ function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) { return _contains(map._inner, bytes32(key)); } /** * @dev Returns the number of elements in the map. O(1). */ function length(UintToAddressMap storage map) internal view returns (uint256) { return _length(map._inner); } /** * @dev Returns the element stored at position `index` in the set. O(1). * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) { (bytes32 key, bytes32 value) = _at(map._inner, index); return (uint256(key), address(uint160(uint256(value)))); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. * * _Available since v3.4._ */ function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) { (bool success, bytes32 value) = _tryGet(map._inner, bytes32(key)); return (success, address(uint160(uint256(value)))); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function get(UintToAddressMap storage map, uint256 key) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key))))); } /** * @dev Same as {get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryGet}. */ function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage)))); } } // File: @openzeppelin/contracts/utils/Strings.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev String operations. */ library Strings { /** * @dev Converts a `uint256` to its ASCII `string` representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); uint256 index = digits - 1; temp = value; while (temp != 0) { buffer[index--] = bytes1(uint8(48 + temp % 10)); temp /= 10; } return string(buffer); } } // File: @openzeppelin/contracts/token/ERC721/ERC721.sol pragma solidity >=0.6.0 <0.8.0; /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using SafeMath for uint256; using Address for address; using EnumerableSet for EnumerableSet.UintSet; using EnumerableMap for EnumerableMap.UintToAddressMap; using Strings for uint256; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from holder address to their (enumerable) set of owned tokens mapping (address => EnumerableSet.UintSet) private _holderTokens; // Enumerable mapping from token ids to their owners EnumerableMap.UintToAddressMap private _tokenOwners; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; // Token name string private _name; // Token symbol string private _symbol; // Optional mapping for token URIs mapping (uint256 => string) private _tokenURIs; // Base URI string private _baseURI; /* * bytes4(keccak256('balanceOf(address)')) == 0x70a08231 * bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e * bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3 * bytes4(keccak256('getApproved(uint256)')) == 0x081812fc * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde * * => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^ * 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd */ bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; /* * bytes4(keccak256('name()')) == 0x06fdde03 * bytes4(keccak256('symbol()')) == 0x95d89b41 * bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd * * => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f */ bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; /* * bytes4(keccak256('totalSupply()')) == 0x18160ddd * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59 * bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7 * * => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63 */ bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor (string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); _registerInterface(_INTERFACE_ID_ERC721_METADATA); _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _holderTokens[owner].length(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token"); } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; string memory base = baseURI(); // If there is no base URI, return the token URI. if (bytes(base).length == 0) { return _tokenURI; } // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(base, _tokenURI)); } // If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI. return string(abi.encodePacked(base, tokenId.toString())); } /** * @dev Returns the base URI set via {_setBaseURI}. This will be * automatically added as a prefix in {tokenURI} to each token's URI, or * to the token ID if no specific URI is set for that token ID. */ function baseURI() public view virtual returns (string memory) { return _baseURI; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { return _holderTokens[owner].at(index); } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { // _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds return _tokenOwners.length(); } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { (uint256 tokenId, ) = _tokenOwners.at(index); return tokenId; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(_msgSender() == owner || ERC721.isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom(address from, address to, uint256 tokenId) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _tokenOwners.contains(tokenId); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || ERC721.isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: d* * - `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, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual { _mint(to, tokenId); require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); // internal owner _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); // Clear metadata (if any) if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } _holderTokens[owner].remove(tokenId); _tokenOwners.remove(tokenId); emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer(address from, address to, uint256 tokenId) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); // internal owner require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _holderTokens[from].remove(tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(from, to, tokenId); } /** * @dev Sets `_tokenURI` as the tokenURI of `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @dev Internal function to set the base URI for all token IDs. It is * automatically added as a prefix to the value returned in {tokenURI}, * or to the token ID if {tokenURI} is empty. */ function _setBaseURI(string memory baseURI_) internal virtual { _baseURI = baseURI_; } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) private returns (bool) { if (!to.isContract()) { return true; } bytes memory returndata = to.functionCall(abi.encodeWithSelector( IERC721Receiver(to).onERC721Received.selector, _msgSender(), from, tokenId, _data ), "ERC721: transfer to non ERC721Receiver implementer"); bytes4 retval = abi.decode(returndata, (bytes4)); return (retval == _ERC721_RECEIVED); } /** * @dev Approve `to` to operate on `tokenId` * * Emits an {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); // internal owner } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { } } // File: @openzeppelin/contracts/access/Ownable.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // PeripateticToken.sol pragma solidity ^0.7.0; contract PeripateticToken is ERC721, Ownable { string public PERIPATETIC_PROVENANCE = ""; uint public constant MAX_MEMBERSHIPS = 111; bool public mappingCreated = false; constructor() ERC721("PeripateticToken", "PERIPATETIC") {} address[29] public whitelisted = [ 0xa658eFf00A22F4344803BB26A374c0a7a2ac9EF9, 0xFa1C903EaA1f9E0fb256e6D21d4dB63C85c85855, 0xe126b3E5d052f1F575828f61fEBA4f4f2603652a, 0xb22fffa5B646CD9014CBa5e2fDE157817efA4536, 0x0CbE1fba05102c34365a742af159EfC5a93D1a68, 0xDd343C671AbB706D8E4f5dA9CD9662753E44A01E, 0xC17f20335080cD0b7283e042C89F16605f3A085f, 0xD9df7441f87C197887cf438eeBe3368637e76a78, 0x8d09d2543B29206DdDf0AA83FCd2d8b77A4ce09d, 0x71b3f6253d9e28Be4B08817BF83FE207DbDf5285, 0x3641f865ffEeeC785b759f0d1afAa4f40dBAa988, 0xa7a9593478dc4c4f191Cc97a88da0C1299aF0355, 0xEF76cf033F7feE8a75c7B0458f138122B38C0b68, 0x851Fe70498E1792739e429b466E3a12Cf6e50DE6, 0x478bB98378Fa40c1cbC8abfDFe6029929fF3F854, 0xcCBF5d0A96ca77da1D21438eB9c06e485e6723C2, 0x4a7DC0A1f68EcFfD1588Df798d95C95C8aA7efd9, 0x428D203bfaC03D491aE9DE732480c5d25A4b5f88, 0xcca467C01AEF7eF350a7Fb2A3B6a3c78fB9fcf6e, 0x1Bc2C46d6A3c1A1DEE9B623FCA10d72987DC639f, 0x7f5bE0C65e05D5567C0eC8E8F84D2310e784fb5e, 0x0701d19c4D9364b69Ca001061aE3eD169a40691B, 0x910B48C25aFC5b2a998458B62d467D482ECA74AF, 0x89b7F3c7B61Ca77CDf515095Ff194dF82636F2F5, 0xAfb9F3A1CF4A91AE113029b5E74151dC1c4f03B5, 0x0D3Ada2A0E63631e1515C208998bF63AD4882cEE, 0x8C367e29756573285075746185b384D148Ee0f68, 0xEd7d5608b85546300e12526BA688cb4F6A5641E4, 0x4c5f3D38b38117449C59aaF60BEDC35c753728FF ]; mapping (address => bool) private addressHasRedeemed; mapping (address => bool) private addressIsWhitelisted; function createMapping() public onlyOwner { require(mappingCreated == false, "Mapping already created"); for (uint i = 0; i < whitelisted.length; i++) { address airdropAddress = whitelisted[i]; addressHasRedeemed[airdropAddress] = false; addressIsWhitelisted[airdropAddress] = true; } mappingCreated = true; } function hasAddressRedeemed( address redeemer ) public view returns(bool addressRedeemed) { addressRedeemed = addressHasRedeemed[redeemer]; } function isAddressWhitelisted( address redeemer ) public view returns(bool addressWhitelisted) { addressWhitelisted = addressIsWhitelisted[redeemer]; } function redeemMemberships() public { require(totalSupply() < MAX_MEMBERSHIPS, "Mint was already completed"); require(mappingCreated == true, "Mapping has not been created"); require(isAddressWhitelisted(msg.sender) == true, "Address is not whitelisted"); require(hasAddressRedeemed(msg.sender) == false, "Address has already redeemed allocated memberships"); if (msg.sender == address(0x4c5f3D38b38117449C59aaF60BEDC35c753728FF)) { // if treasury address mint 27 mint(27); } else { // if whitelisted address, mint 3 mint(3); } addressHasRedeemed[msg.sender] = true; } function mint(uint count) private { for (uint i = 0; i < count; i++) { _safeMint(msg.sender, totalSupply()); } } /* * Set baseURI */ function setBaseURI(string memory baseURI) public onlyOwner { _setBaseURI(baseURI); } /* * Set provenance once it's calculated */ function setProvenanceHash(string memory provenanceHash) public onlyOwner { PERIPATETIC_PROVENANCE = provenanceHash; } }
if treasury address mint 27 if whitelisted address, mint 3
function redeemMemberships() public { require(totalSupply() < MAX_MEMBERSHIPS, "Mint was already completed"); require(mappingCreated == true, "Mapping has not been created"); require(isAddressWhitelisted(msg.sender) == true, "Address is not whitelisted"); require(hasAddressRedeemed(msg.sender) == false, "Address has already redeemed allocated memberships"); if (msg.sender == address(0x4c5f3D38b38117449C59aaF60BEDC35c753728FF)) { mint(27); mint(3); } addressHasRedeemed[msg.sender] = true; }
13,896,703
./full_match/137/0xa90dAF1975BA13c26F63976e0Fd73A21F966EE0D/sources/contracts/ToucanCarbonOffsets.sol
Internal helper to check if `projectVintageTokenId`s are matching
function checkMatchingAttributes(uint256 NFTprojectVintageTokenId) internal view virtual returns (bool) { if (NFTprojectVintageTokenId == projectVintageTokenId) { return true; return false; } }
3,776,881
// SPDX-License-Identifier: MIT // File: @openzeppelin/contracts/utils/Strings.sol // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: @openzeppelin/contracts/security/ReentrancyGuard.sol // OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // File: @openzeppelin/contracts/utils/Address.sol // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev 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, bytes calldata data ) external returns (bytes4); } // File: @openzeppelin/contracts/utils/introspection/IERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: @openzeppelin/contracts/utils/introspection/ERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: @openzeppelin/contracts/utils/Context.sol // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: @openzeppelin/contracts/access/Ownable.sol // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } pragma solidity ^0.8.0; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at 0 (e.g. 0, 1, 2, 3..). * * Assumes the number of issuable tokens (collection size) is capped and fits in a uint128. * * Does not support burning tokens to address(0). */ contract ERC721A is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using Address for address; using Strings for uint256; struct TokenOwnership { address addr; uint64 startTimestamp; } struct AddressData { uint128 balance; uint128 numberMinted; } uint256 private currentIndex = 0; uint256 internal immutable collectionSize; uint256 internal immutable maxBatchSize; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to ownership details // An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details. mapping(uint256 => TokenOwnership) private _ownerships; // Mapping owner address to address data mapping(address => AddressData) private _addressData; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev * `maxBatchSize` refers to how much a minter can mint at a time. * `collectionSize_` refers to how many tokens are in the collection. */ constructor( string memory name_, string memory symbol_, uint256 maxBatchSize_, uint256 collectionSize_ ) { require( collectionSize_ > 0, "ERC721A: collection must have a nonzero supply" ); require(maxBatchSize_ > 0, "ERC721A: max batch size must be nonzero"); _name = name_; _symbol = symbol_; maxBatchSize = maxBatchSize_; collectionSize = collectionSize_; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { return currentIndex; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view override returns (uint256) { require(index < totalSupply(), "ERC721A: global index out of bounds"); return index; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. * This read function is O(collectionSize). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { require(index < balanceOf(owner), "ERC721A: owner index out of bounds"); uint256 numMintedSoFar = totalSupply(); uint256 tokenIdsIdx = 0; address currOwnershipAddr = address(0); for (uint256 i = 0; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } revert("ERC721A: unable to get token of owner by index"); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view override returns (uint256) { require(owner != address(0), "ERC721A: balance query for the zero address"); return uint256(_addressData[owner].balance); } function _numberMinted(address owner) internal view returns (uint256) { require( owner != address(0), "ERC721A: number minted query for the zero address" ); return uint256(_addressData[owner].numberMinted); } function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { require(_exists(tokenId), "ERC721A: owner query for nonexistent token"); uint256 lowestTokenToCheck; if (tokenId >= maxBatchSize) { lowestTokenToCheck = tokenId - maxBatchSize + 1; } for (uint256 curr = tokenId; curr >= lowestTokenToCheck; curr--) { TokenOwnership memory ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } revert("ERC721A: unable to determine the owner of token"); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return ownershipOf(tokenId).addr; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @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 returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public override { address owner = ERC721A.ownerOf(tokenId); require(to != owner, "ERC721A: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721A: approve caller is not owner nor approved for all" ); _approve(to, tokenId, owner); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { require(_exists(tokenId), "ERC721A: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public override { require(operator != _msgSender(), "ERC721A: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public override { _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public override { _transfer(from, to, tokenId); require( _checkOnERC721Received(from, to, tokenId, _data), "ERC721A: transfer to non ERC721Receiver implementer" ); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), */ function _exists(uint256 tokenId) internal view returns (bool) { return tokenId < currentIndex; } function _safeMint(address to, uint256 quantity) internal { _safeMint(to, quantity, ""); } /** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - there must be `quantity` tokens remaining unminted in the total collection. * - `to` cannot be the zero address. * - `quantity` cannot be larger than the max batch size. * * Emits a {Transfer} event. */ function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { uint256 startTokenId = currentIndex; require(to != address(0), "ERC721A: mint to the zero address"); // We know if the first token in the batch doesn't exist, the other ones don't as well, because of serial ordering. require(!_exists(startTokenId), "ERC721A: token already minted"); require(quantity <= maxBatchSize, "ERC721A: quantity to mint too high"); _beforeTokenTransfers(address(0), to, startTokenId, quantity); AddressData memory addressData = _addressData[to]; _addressData[to] = AddressData( addressData.balance + uint128(quantity), addressData.numberMinted + uint128(quantity) ); _ownerships[startTokenId] = TokenOwnership(to, uint64(block.timestamp)); uint256 updatedIndex = startTokenId; for (uint256 i = 0; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); require( _checkOnERC721Received(address(0), to, updatedIndex, _data), "ERC721A: transfer to non ERC721Receiver implementer" ); updatedIndex++; } currentIndex = updatedIndex; _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @dev Transfers `tokenId` from `from` to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) private { TokenOwnership memory prevOwnership = ownershipOf(tokenId); require( prevOwnership.addr == from, "ERC721A: transfer from incorrect owner" ); require(to != address(0), "ERC721A: transfer to the zero address"); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId] = TokenOwnership(to, uint64(block.timestamp)); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { if (_exists(nextTokenId)) { _ownerships[nextTokenId] = TokenOwnership( prevOwnership.addr, prevOwnership.startTimestamp ); } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } uint256 public nextOwnerToExplicitlySet = 0; /** * @dev Explicitly set `owners` to eliminate loops in future calls of ownerOf(). */ function _setOwnersExplicit(uint256 quantity) internal { uint256 oldNextOwnerToSet = nextOwnerToExplicitlySet; require(quantity > 0, "quantity must be nonzero"); uint256 endIndex = oldNextOwnerToSet + quantity - 1; if (endIndex > collectionSize - 1) { endIndex = collectionSize - 1; } // We know if the last one in the group exists, all in the group exist, due to serial ordering. require(_exists(endIndex), "not enough minted yet for this cleanup"); for (uint256 i = oldNextOwnerToSet; i <= endIndex; i++) { if (_ownerships[i].addr == address(0)) { TokenOwnership memory ownership = ownershipOf(i); _ownerships[i] = TokenOwnership( ownership.addr, ownership.startTimestamp ); } } nextOwnerToExplicitlySet = endIndex + 1; } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721A: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. */ function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} /** * @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes * minting. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - when `from` and `to` are both non-zero. * - `from` and `to` are never both zero. */ function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} } pragma solidity ^0.8.7; contract notMoonBird is ERC721A, Ownable, ReentrancyGuard { bool public paused = false; uint256 private mintedPublic = 0; uint256 public price = 0.01 ether; uint256 public bundlePrice = 0.1 ether; uint256 public bundle = 10; uint256 public maxSupply = 2333; string private _baseTokenURI; mapping(uint256 => uint256) private mintedTime; constructor(uint256 maxSizeBatch, uint256 maxSupply_, string memory baseUri) ERC721A("NotMoonBird", "NMB", maxSizeBatch, maxSupply_) { _baseTokenURI = baseUri; } function _baseURI() internal view virtual override returns (string memory) { return _baseTokenURI; } function tokenURI(uint256 tokenId) public view override returns (string memory) { return string(abi.encodePacked(_baseTokenURI, Strings.toString(tokenId), ".json")); } modifier callerIsUser() { require(tx.origin == msg.sender, "The caller is another contract!"); _; } function togglePause() external onlyOwner { paused = !paused; } function setNewUri(string memory newUri) external onlyOwner { _baseTokenURI = newUri; } function mint() external payable callerIsUser { require(paused == false, "Contract paused."); require(mintedPublic + 1 <= maxSupply, "Count exceeds the maximum allowed supply for public mint."); require(totalSupply() + 1 <= collectionSize, "Count exceeds the maximum allowed supply."); require(msg.value >= price, "Incorrect payable amount."); mintedTime[totalSupply()] = block.timestamp; mintedPublic += 1; _safeMint(msg.sender, 1); } // mintBundle function mintBundle() external payable callerIsUser { require(paused == false, "Contract paused."); require(mintedPublic + bundle <= maxSupply, "Count exceeds the maximum allowed supply for public mint."); require(totalSupply() + bundle <= collectionSize, "Count exceeds the maximum allowed supply."); require(msg.value >= bundlePrice, "Incorrect payable amount."); mintedPublic += bundle; _safeMint(msg.sender, bundle); } function devMint(uint256 count) external onlyOwner { require(totalSupply() + count <= collectionSize, "Amount nfts for devs goes beyond the scope!"); require(count % maxBatchSize == 0, "Can only mint a multiple of the maxBatchSize!"); uint256 numChunks = count / maxBatchSize; for (uint256 i = 0; i < numChunks; i++) { _safeMint(address(this), maxBatchSize); } } function transferFromSingle(address to, uint256 tokenId) external callerIsUser onlyOwner { require(paused == false, "Contract paused."); require(ownerOf(tokenId) == address(this), "Contract is not the owner!"); transferFrom(address(this), to, tokenId); } function transferFromBatch(address[] calldata to, uint256[] calldata tokenIds) external callerIsUser onlyOwner { require(paused == false, "Contract paused."); for (uint256 i = 0; i < tokenIds.length; i++) { require(ownerOf(tokenIds[i]) == address(this), "Contract is not the owner!"); transferFrom(address(this), to[i], tokenIds[i]); } } function withdraw() external payable onlyOwner nonReentrant { uint balance = address(this).balance; require(balance > 0, " No balance"); payable(owner()).transfer(balance); } }
Returns whether `tokenId` exists. Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. Tokens start existing when they are minted (`_mint`),/
function _exists(uint256 tokenId) internal view returns (bool) { return tokenId < currentIndex; }
1,683,785
// File: contracts\lib\TransferHelper.sol // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.6; // helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false library TransferHelper { function safeApprove(address token, address to, uint value) internal { // bytes4(keccak256(bytes('approve(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED'); } function safeTransfer(address token, address to, uint value) internal { // bytes4(keccak256(bytes('transfer(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED'); } function safeTransferFrom(address token, address from, address to, uint value) internal { // bytes4(keccak256(bytes('transferFrom(address,address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED'); } function safeTransferETH(address to, uint value) internal { (bool success,) = to.call{value:value}(new bytes(0)); require(success, 'TransferHelper: ETH_TRANSFER_FAILED'); } } // File: contracts\interface\INestMining.sol /// @dev This interface defines the mining methods for nest interface INestMining { /// @dev Post event /// @param tokenAddress The address of TOKEN contract /// @param miner Address of miner /// @param index Index of the price sheet /// @param ethNum The numbers of ethers to post sheets event Post(address tokenAddress, address miner, uint index, uint ethNum, uint price); /* ========== Structures ========== */ /// @dev Nest mining configuration structure struct Config { // Eth number of each post. 30 // We can stop post and taking orders by set postEthUnit to 0 (closing and withdraw are not affected) uint32 postEthUnit; // Post fee(0.0001eth,DIMI_ETHER). 1000 uint16 postFeeUnit; // Proportion of miners digging(10000 based). 8000 uint16 minerNestReward; // The proportion of token dug by miners is only valid for the token created in version 3.0 // (10000 based). 9500 uint16 minerNTokenReward; // When the circulation of ntoken exceeds this threshold, post() is prohibited(Unit: 10000 ether). 500 uint32 doublePostThreshold; // The limit of ntoken mined blocks. 100 uint16 ntokenMinedBlockLimit; // -- Public configuration // The number of times the sheet assets have doubled. 4 uint8 maxBiteNestedLevel; // Price effective block interval. 20 uint16 priceEffectSpan; // The amount of nest to pledge for each post(Unit: 1000). 100 uint16 pledgeNest; } /// @dev PriceSheetView structure struct PriceSheetView { // Index of the price sheeet uint32 index; // Address of miner address miner; // The block number of this price sheet packaged uint32 height; // The remain number of this price sheet uint32 remainNum; // The eth number which miner will got uint32 ethNumBal; // The eth number which equivalent to token's value which miner will got uint32 tokenNumBal; // The pledged number of nest in this sheet. (Unit: 1000nest) uint24 nestNum1k; // The level of this sheet. 0 expresses initial price sheet, a value greater than 0 expresses bite price sheet uint8 level; // Post fee shares, if there are many sheets in one block, this value is used to divide up mining value uint8 shares; // The token price. (1eth equivalent to (price) token) uint152 price; } /* ========== Configuration ========== */ /// @dev Modify configuration /// @param config Configuration object function setConfig(Config calldata config) external; /// @dev Get configuration /// @return Configuration object function getConfig() external view returns (Config memory); /// @dev Set the ntokenAddress from tokenAddress, if ntokenAddress is equals to tokenAddress, means the token is disabled /// @param tokenAddress Destination token address /// @param ntokenAddress The ntoken address function setNTokenAddress(address tokenAddress, address ntokenAddress) external; /// @dev Get the ntokenAddress from tokenAddress, if ntokenAddress is equals to tokenAddress, means the token is disabled /// @param tokenAddress Destination token address /// @return The ntoken address function getNTokenAddress(address tokenAddress) external view returns (address); /* ========== Mining ========== */ /// @notice Post a price sheet for TOKEN /// @dev It is for TOKEN (except USDT and NTOKENs) whose NTOKEN has a total supply below a threshold (e.g. 5,000,000 * 1e18) /// @param tokenAddress The address of TOKEN contract /// @param ethNum The numbers of ethers to post sheets /// @param tokenAmountPerEth The price of TOKEN function post(address tokenAddress, uint ethNum, uint tokenAmountPerEth) external payable; /// @notice Post two price sheets for a token and its ntoken simultaneously /// @dev Support dual-posts for TOKEN/NTOKEN, (ETH, TOKEN) + (ETH, NTOKEN) /// @param tokenAddress The address of TOKEN contract /// @param ethNum The numbers of ethers to post sheets /// @param tokenAmountPerEth The price of TOKEN /// @param ntokenAmountPerEth The price of NTOKEN function post2(address tokenAddress, uint ethNum, uint tokenAmountPerEth, uint ntokenAmountPerEth) external payable; /// @notice Call the function to buy TOKEN/NTOKEN from a posted price sheet /// @dev bite TOKEN(NTOKEN) by ETH, (+ethNumBal, -tokenNumBal) /// @param tokenAddress The address of token(ntoken) /// @param index The position of the sheet in priceSheetList[token] /// @param takeNum The amount of biting (in the unit of ETH), realAmount = takeNum * newTokenAmountPerEth /// @param newTokenAmountPerEth The new price of token (1 ETH : some TOKEN), here some means newTokenAmountPerEth function takeToken(address tokenAddress, uint index, uint takeNum, uint newTokenAmountPerEth) external payable; /// @notice Call the function to buy ETH from a posted price sheet /// @dev bite ETH by TOKEN(NTOKEN), (-ethNumBal, +tokenNumBal) /// @param tokenAddress The address of token(ntoken) /// @param index The position of the sheet in priceSheetList[token] /// @param takeNum The amount of biting (in the unit of ETH), realAmount = takeNum /// @param newTokenAmountPerEth The new price of token (1 ETH : some TOKEN), here some means newTokenAmountPerEth function takeEth(address tokenAddress, uint index, uint takeNum, uint newTokenAmountPerEth) external payable; /// @notice Close a price sheet of (ETH, USDx) | (ETH, NEST) | (ETH, TOKEN) | (ETH, NTOKEN) /// @dev Here we allow an empty price sheet (still in VERIFICATION-PERIOD) to be closed /// @param tokenAddress The address of TOKEN contract /// @param index The index of the price sheet w.r.t. `token` function close(address tokenAddress, uint index) external; /// @notice Close a batch of price sheets passed VERIFICATION-PHASE /// @dev Empty sheets but in VERIFICATION-PHASE aren't allowed /// @param tokenAddress The address of TOKEN contract /// @param indices A list of indices of sheets w.r.t. `token` function closeList(address tokenAddress, uint[] memory indices) external; /// @notice Close two batch of price sheets passed VERIFICATION-PHASE /// @dev Empty sheets but in VERIFICATION-PHASE aren't allowed /// @param tokenAddress The address of TOKEN1 contract /// @param tokenIndices A list of indices of sheets w.r.t. `token` /// @param ntokenIndices A list of indices of sheets w.r.t. `ntoken` function closeList2(address tokenAddress, uint[] memory tokenIndices, uint[] memory ntokenIndices) external; /// @dev The function updates the statistics of price sheets /// It calculates from priceInfo to the newest that is effective. function stat(address tokenAddress) external; /// @dev Settlement Commission /// @param tokenAddress The token address function settle(address tokenAddress) external; /// @dev List sheets by page /// @param tokenAddress Destination token address /// @param offset Skip previous (offset) records /// @param count Return (count) records /// @param order Order. 0 reverse order, non-0 positive order /// @return List of price sheets function list(address tokenAddress, uint offset, uint count, uint order) external view returns (PriceSheetView[] memory); /// @dev Estimated mining amount /// @param tokenAddress Destination token address /// @return Estimated mining amount function estimate(address tokenAddress) external view returns (uint); /// @dev Query the quantity of the target quotation /// @param tokenAddress Token address. The token can't mine. Please make sure you don't use the token address when calling /// @param index The index of the sheet /// @return minedBlocks Mined block period from previous block /// @return totalShares Total shares of sheets in the block function getMinedBlocks(address tokenAddress, uint index) external view returns (uint minedBlocks, uint totalShares); /* ========== Accounts ========== */ /// @dev Withdraw assets /// @param tokenAddress Destination token address /// @param value The value to withdraw function withdraw(address tokenAddress, uint value) external; /// @dev View the number of assets specified by the user /// @param tokenAddress Destination token address /// @param addr Destination address /// @return Number of assets function balanceOf(address tokenAddress, address addr) external view returns (uint); /// @dev Gets the address corresponding to the given index number /// @param index The index number of the specified address /// @return The address corresponding to the given index number function indexAddress(uint index) external view returns (address); /// @dev Gets the registration index number of the specified address /// @param addr Destination address /// @return 0 means nonexistent, non-0 means index number function getAccountIndex(address addr) external view returns (uint); /// @dev Get the length of registered account array /// @return The length of registered account array function getAccountCount() external view returns (uint); } // File: contracts\interface\INestQuery.sol /// @dev This interface defines the methods for price query interface INestQuery { /// @dev Get the latest trigger price /// @param tokenAddress Destination token address /// @return blockNumber The block number of price /// @return price The token price. (1eth equivalent to (price) token) function triggeredPrice(address tokenAddress) external view returns (uint blockNumber, uint price); /// @dev Get the full information of latest trigger price /// @param tokenAddress Destination token address /// @return blockNumber The block number of price /// @return price The token price. (1eth equivalent to (price) token) /// @return avgPrice Average price /// @return sigmaSQ The square of the volatility (18 decimal places). The current implementation assumes that /// the volatility cannot exceed 1. Correspondingly, when the return value is equal to 999999999999996447, /// it means that the volatility has exceeded the range that can be expressed function triggeredPriceInfo(address tokenAddress) external view returns ( uint blockNumber, uint price, uint avgPrice, uint sigmaSQ ); /// @dev Find the price at block number /// @param tokenAddress Destination token address /// @param height Destination block number /// @return blockNumber The block number of price /// @return price The token price. (1eth equivalent to (price) token) function findPrice( address tokenAddress, uint height ) external view returns (uint blockNumber, uint price); /// @dev Get the latest effective price /// @param tokenAddress Destination token address /// @return blockNumber The block number of price /// @return price The token price. (1eth equivalent to (price) token) function latestPrice(address tokenAddress) external view returns (uint blockNumber, uint price); /// @dev Get the last (num) effective price /// @param tokenAddress Destination token address /// @param count The number of prices that want to return /// @return An array which length is num * 2, each two element expresses one price like blockNumber|price function lastPriceList(address tokenAddress, uint count) external view returns (uint[] memory); /// @dev Returns the results of latestPrice() and triggeredPriceInfo() /// @param tokenAddress Destination token address /// @return latestPriceBlockNumber The block number of latest price /// @return latestPriceValue The token latest price. (1eth equivalent to (price) token) /// @return triggeredPriceBlockNumber The block number of triggered price /// @return triggeredPriceValue The token triggered price. (1eth equivalent to (price) token) /// @return triggeredAvgPrice Average price /// @return triggeredSigmaSQ The square of the volatility (18 decimal places). The current implementation assumes that /// the volatility cannot exceed 1. Correspondingly, when the return value is equal to 999999999999996447, /// it means that the volatility has exceeded the range that can be expressed function latestPriceAndTriggeredPriceInfo(address tokenAddress) external view returns ( uint latestPriceBlockNumber, uint latestPriceValue, uint triggeredPriceBlockNumber, uint triggeredPriceValue, uint triggeredAvgPrice, uint triggeredSigmaSQ ); /// @dev Returns lastPriceList and triggered price info /// @param tokenAddress Destination token address /// @param count The number of prices that want to return /// @return prices An array which length is num * 2, each two element expresses one price like blockNumber|price /// @return triggeredPriceBlockNumber The block number of triggered price /// @return triggeredPriceValue The token triggered price. (1eth equivalent to (price) token) /// @return triggeredAvgPrice Average price /// @return triggeredSigmaSQ The square of the volatility (18 decimal places). The current implementation assumes that /// the volatility cannot exceed 1. Correspondingly, when the return value is equal to 999999999999996447, /// it means that the volatility has exceeded the range that can be expressed function lastPriceListAndTriggeredPriceInfo(address tokenAddress, uint count) external view returns ( uint[] memory prices, uint triggeredPriceBlockNumber, uint triggeredPriceValue, uint triggeredAvgPrice, uint triggeredSigmaSQ ); /// @dev Get the latest trigger price. (token and ntoken) /// @param tokenAddress Destination token address /// @return blockNumber The block number of price /// @return price The token price. (1eth equivalent to (price) token) /// @return ntokenBlockNumber The block number of ntoken price /// @return ntokenPrice The ntoken price. (1eth equivalent to (price) ntoken) function triggeredPrice2(address tokenAddress) external view returns ( uint blockNumber, uint price, uint ntokenBlockNumber, uint ntokenPrice ); /// @dev Get the full information of latest trigger price. (token and ntoken) /// @param tokenAddress Destination token address /// @return blockNumber The block number of price /// @return price The token price. (1eth equivalent to (price) token) /// @return avgPrice Average price /// @return sigmaSQ The square of the volatility (18 decimal places). The current implementation assumes that /// the volatility cannot exceed 1. Correspondingly, when the return value is equal to 999999999999996447, /// it means that the volatility has exceeded the range that can be expressed /// @return ntokenBlockNumber The block number of ntoken price /// @return ntokenPrice The ntoken price. (1eth equivalent to (price) ntoken) /// @return ntokenAvgPrice Average price of ntoken /// @return ntokenSigmaSQ The square of the volatility (18 decimal places). The current implementation assumes that /// the volatility cannot exceed 1. Correspondingly, when the return value is equal to 999999999999996447, /// it means that the volatility has exceeded the range that can be expressed function triggeredPriceInfo2(address tokenAddress) external view returns ( uint blockNumber, uint price, uint avgPrice, uint sigmaSQ, uint ntokenBlockNumber, uint ntokenPrice, uint ntokenAvgPrice, uint ntokenSigmaSQ ); /// @dev Get the latest effective price. (token and ntoken) /// @param tokenAddress Destination token address /// @return blockNumber The block number of price /// @return price The token price. (1eth equivalent to (price) token) /// @return ntokenBlockNumber The block number of ntoken price /// @return ntokenPrice The ntoken price. (1eth equivalent to (price) ntoken) function latestPrice2(address tokenAddress) external view returns ( uint blockNumber, uint price, uint ntokenBlockNumber, uint ntokenPrice ); } // File: contracts\interface\INTokenController.sol ///@dev This interface defines the methods for ntoken management interface INTokenController { /// @notice when the auction of a token gets started /// @param tokenAddress The address of the (ERC20) token /// @param ntokenAddress The address of the ntoken w.r.t. token for incentives /// @param owner The address of miner who opened the oracle event NTokenOpened(address tokenAddress, address ntokenAddress, address owner); /// @notice ntoken disable event /// @param tokenAddress token address event NTokenDisabled(address tokenAddress); /// @notice ntoken enable event /// @param tokenAddress token address event NTokenEnabled(address tokenAddress); /// @dev ntoken configuration structure struct Config { // The number of nest needed to pay for opening ntoken. 10000 ether uint96 openFeeNestAmount; // ntoken management is enabled. 0: not enabled, 1: enabled uint8 state; } /// @dev A struct for an ntoken struct NTokenTag { // ntoken address address ntokenAddress; // How much nest has paid for open this ntoken uint96 nestFee; // token address address tokenAddress; // Index for this ntoken uint40 index; // Create time uint48 startTime; // State of this ntoken. 0: disabled; 1 normal uint8 state; } /* ========== Governance ========== */ /// @dev Modify configuration /// @param config Configuration object function setConfig(Config calldata config) external; /// @dev Get configuration /// @return Configuration object function getConfig() external view returns (Config memory); /// @dev Set the token mapping /// @param tokenAddress Destination token address /// @param ntokenAddress Destination ntoken address /// @param state status for this map function setNTokenMapping(address tokenAddress, address ntokenAddress, uint state) external; /// @dev Get token address from ntoken address /// @param ntokenAddress Destination ntoken address /// @return token address function getTokenAddress(address ntokenAddress) external view returns (address); /// @dev Get ntoken address from token address /// @param tokenAddress Destination token address /// @return ntoken address function getNTokenAddress(address tokenAddress) external view returns (address); /* ========== ntoken management ========== */ /// @dev Bad tokens should be banned function disable(address tokenAddress) external; /// @dev enable ntoken function enable(address tokenAddress) external; /// @notice Open a NToken for a token by anyone (contracts aren't allowed) /// @dev Create and map the (Token, NToken) pair in NestPool /// @param tokenAddress The address of token contract function open(address tokenAddress) external; /* ========== VIEWS ========== */ /// @dev Get ntoken information /// @param tokenAddress Destination token address /// @return ntoken information function getNTokenTag(address tokenAddress) external view returns (NTokenTag memory); /// @dev Get opened ntoken count /// @return ntoken count function getNTokenCount() external view returns (uint); /// @dev List ntoken information by page /// @param offset Skip previous (offset) records /// @param count Return (count) records /// @param order Order. 0 reverse order, non-0 positive order /// @return ntoken information by page function list(uint offset, uint count, uint order) external view returns (NTokenTag[] memory); } // File: contracts\interface\INestLedger.sol /// @dev This interface defines the nest ledger methods interface INestLedger { /// @dev Application Flag Changed event /// @param addr DAO application contract address /// @param flag Authorization flag, 1 means authorization, 0 means cancel authorization event ApplicationChanged(address addr, uint flag); /// @dev Configuration structure of nest ledger contract struct Config { // nest reward scale(10000 based). 2000 uint16 nestRewardScale; // // ntoken reward scale(10000 based). 8000 // uint16 ntokenRewardScale; } /// @dev Modify configuration /// @param config Configuration object function setConfig(Config calldata config) external; /// @dev Get configuration /// @return Configuration object function getConfig() external view returns (Config memory); /// @dev Set DAO application /// @param addr DAO application contract address /// @param flag Authorization flag, 1 means authorization, 0 means cancel authorization function setApplication(address addr, uint flag) external; /// @dev Check DAO application flag /// @param addr DAO application contract address /// @return Authorization flag, 1 means authorization, 0 means cancel authorization function checkApplication(address addr) external view returns (uint); /// @dev Carve reward /// @param ntokenAddress Destination ntoken address function carveETHReward(address ntokenAddress) external payable; /// @dev Add reward /// @param ntokenAddress Destination ntoken address function addETHReward(address ntokenAddress) external payable; /// @dev The function returns eth rewards of specified ntoken /// @param ntokenAddress The ntoken address function totalETHRewards(address ntokenAddress) external view returns (uint); /// @dev Pay /// @param ntokenAddress Destination ntoken address. Indicates which ntoken to pay with /// @param tokenAddress Token address of receiving funds (0 means ETH) /// @param to Address to receive /// @param value Amount to receive function pay(address ntokenAddress, address tokenAddress, address to, uint value) external; /// @dev Settlement /// @param ntokenAddress Destination ntoken address. Indicates which ntoken to settle with /// @param tokenAddress Token address of receiving funds (0 means ETH) /// @param to Address to receive /// @param value Amount to receive function settle(address ntokenAddress, address tokenAddress, address to, uint value) external payable; } // File: contracts\interface\INToken.sol /// @dev ntoken interface interface INToken { event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); /// @dev Mint /// @param value The amount of NToken to add function increaseTotal(uint256 value) external; /// @notice The view of variables about minting /// @dev The naming follows Nestv3.0 /// @return createBlock The block number where the contract was created /// @return recentlyUsedBlock The block number where the last minting went function checkBlockInfo() external view returns(uint256 createBlock, uint256 recentlyUsedBlock); /// @dev The ABI keeps unchanged with old NTokens, so as to support token-and-ntoken-mining /// @return The address of bidder function checkBidder() external view returns(address); /// @notice The view of totalSupply /// @return The total supply of ntoken function totalSupply() external view returns (uint256); /// @dev The view of balances /// @param owner The address of an account /// @return The balance of the account function balanceOf(address owner) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); } // File: contracts\interface\INestMapping.sol /// @dev The interface defines methods for nest builtin contract address mapping interface INestMapping { /// @dev Set the built-in contract address of the system /// @param nestTokenAddress Address of nest token contract /// @param nestNodeAddress Address of nest node contract /// @param nestLedgerAddress INestLedger implementation contract address /// @param nestMiningAddress INestMining implementation contract address for nest /// @param ntokenMiningAddress INestMining implementation contract address for ntoken /// @param nestPriceFacadeAddress INestPriceFacade implementation contract address /// @param nestVoteAddress INestVote implementation contract address /// @param nestQueryAddress INestQuery implementation contract address /// @param nnIncomeAddress NNIncome contract address /// @param nTokenControllerAddress INTokenController implementation contract address function setBuiltinAddress( address nestTokenAddress, address nestNodeAddress, address nestLedgerAddress, address nestMiningAddress, address ntokenMiningAddress, address nestPriceFacadeAddress, address nestVoteAddress, address nestQueryAddress, address nnIncomeAddress, address nTokenControllerAddress ) external; /// @dev Get the built-in contract address of the system /// @return nestTokenAddress Address of nest token contract /// @return nestNodeAddress Address of nest node contract /// @return nestLedgerAddress INestLedger implementation contract address /// @return nestMiningAddress INestMining implementation contract address for nest /// @return ntokenMiningAddress INestMining implementation contract address for ntoken /// @return nestPriceFacadeAddress INestPriceFacade implementation contract address /// @return nestVoteAddress INestVote implementation contract address /// @return nestQueryAddress INestQuery implementation contract address /// @return nnIncomeAddress NNIncome contract address /// @return nTokenControllerAddress INTokenController implementation contract address function getBuiltinAddress() external view returns ( address nestTokenAddress, address nestNodeAddress, address nestLedgerAddress, address nestMiningAddress, address ntokenMiningAddress, address nestPriceFacadeAddress, address nestVoteAddress, address nestQueryAddress, address nnIncomeAddress, address nTokenControllerAddress ); /// @dev Get address of nest token contract /// @return Address of nest token contract function getNestTokenAddress() external view returns (address); /// @dev Get address of nest node contract /// @return Address of nest node contract function getNestNodeAddress() external view returns (address); /// @dev Get INestLedger implementation contract address /// @return INestLedger implementation contract address function getNestLedgerAddress() external view returns (address); /// @dev Get INestMining implementation contract address for nest /// @return INestMining implementation contract address for nest function getNestMiningAddress() external view returns (address); /// @dev Get INestMining implementation contract address for ntoken /// @return INestMining implementation contract address for ntoken function getNTokenMiningAddress() external view returns (address); /// @dev Get INestPriceFacade implementation contract address /// @return INestPriceFacade implementation contract address function getNestPriceFacadeAddress() external view returns (address); /// @dev Get INestVote implementation contract address /// @return INestVote implementation contract address function getNestVoteAddress() external view returns (address); /// @dev Get INestQuery implementation contract address /// @return INestQuery implementation contract address function getNestQueryAddress() external view returns (address); /// @dev Get NNIncome contract address /// @return NNIncome contract address function getNnIncomeAddress() external view returns (address); /// @dev Get INTokenController implementation contract address /// @return INTokenController implementation contract address function getNTokenControllerAddress() external view returns (address); /// @dev Registered address. The address registered here is the address accepted by nest system /// @param key The key /// @param addr Destination address. 0 means to delete the registration information function registerAddress(string memory key, address addr) external; /// @dev Get registered address /// @param key The key /// @return Destination address. 0 means empty function checkAddress(string memory key) external view returns (address); } // File: contracts\interface\INestGovernance.sol /// @dev This interface defines the governance methods interface INestGovernance is INestMapping { /// @dev Set governance authority /// @param addr Destination address /// @param flag Weight. 0 means to delete the governance permission of the target address. Weight is not /// implemented in the current system, only the difference between authorized and unauthorized. /// Here, a uint96 is used to represent the weight, which is only reserved for expansion function setGovernance(address addr, uint flag) external; /// @dev Get governance rights /// @param addr Destination address /// @return Weight. 0 means to delete the governance permission of the target address. Weight is not /// implemented in the current system, only the difference between authorized and unauthorized. /// Here, a uint96 is used to represent the weight, which is only reserved for expansion function getGovernance(address addr) external view returns (uint); /// @dev Check whether the target address has governance rights for the given target /// @param addr Destination address /// @param flag Permission weight. The permission of the target address must be greater than this weight to pass the check /// @return True indicates permission function checkGovernance(address addr, uint flag) external view returns (bool); } // File: contracts\NestBase.sol /// @dev Base contract of nest contract NestBase { // Address of nest token contract address constant NEST_TOKEN_ADDRESS = 0x04abEdA201850aC0124161F037Efd70c74ddC74C; // Genesis block number of nest // NEST token contract is created at block height 6913517. However, because the mining algorithm of nest1.0 // is different from that at present, a new mining algorithm is adopted from nest2.0. The new algorithm // includes the attenuation logic according to the block. Therefore, it is necessary to trace the block // where the nest begins to decay. According to the circulation when nest2.0 is online, the new mining // algorithm is used to deduce and convert the nest, and the new algorithm is used to mine the nest2.0 // on-line flow, the actual block is 5120000 uint constant NEST_GENESIS_BLOCK = 5120000; /// @dev To support open-zeppelin/upgrades /// @param nestGovernanceAddress INestGovernance implementation contract address function initialize(address nestGovernanceAddress) virtual public { require(_governance == address(0), 'NEST:!initialize'); _governance = nestGovernanceAddress; } /// @dev INestGovernance implementation contract address address public _governance; /// @dev Rewritten in the implementation contract, for load other contract addresses. Call /// super.update(nestGovernanceAddress) when overriding, and override method without onlyGovernance /// @param nestGovernanceAddress INestGovernance implementation contract address function update(address nestGovernanceAddress) virtual public { address governance = _governance; require(governance == msg.sender || INestGovernance(governance).checkGovernance(msg.sender, 0), "NEST:!gov"); _governance = nestGovernanceAddress; } /// @dev Migrate funds from current contract to NestLedger /// @param tokenAddress Destination token address.(0 means eth) /// @param value Migrate amount function migrate(address tokenAddress, uint value) external onlyGovernance { address to = INestGovernance(_governance).getNestLedgerAddress(); if (tokenAddress == address(0)) { INestLedger(to).addETHReward { value: value } (address(0)); } else { TransferHelper.safeTransfer(tokenAddress, to, value); } } //---------modifier------------ modifier onlyGovernance() { require(INestGovernance(_governance).checkGovernance(msg.sender, 0), "NEST:!gov"); _; } modifier noContract() { require(msg.sender == tx.origin, "NEST:!contract"); _; } } // File: contracts\NestMining.sol /// @dev This contract implemented the mining logic of nest contract NestMining is NestBase, INestMining, INestQuery { // /// @param nestTokenAddress Address of nest token contract // /// @param nestGenesisBlock Genesis block number of nest // constructor(address nestTokenAddress, uint nestGenesisBlock) { // NEST_TOKEN_ADDRESS = nestTokenAddress; // NEST_GENESIS_BLOCK = nestGenesisBlock; // // Placeholder in _accounts, the index of a real account must greater than 0 // _accounts.push(); // } /// @dev To support open-zeppelin/upgrades /// @param nestGovernanceAddress INestGovernance implementation contract address function initialize(address nestGovernanceAddress) override public { super.initialize(nestGovernanceAddress); // Placeholder in _accounts, the index of a real account must greater than 0 _accounts.push(); } ///@dev Definitions for the price sheet, include the full information. (use 256-bits, a storage unit in ethereum evm) struct PriceSheet { // Index of miner account in _accounts. for this way, mapping an address(which need 160-bits) to a 32-bits // integer, support 4 billion accounts uint32 miner; // The block number of this price sheet packaged uint32 height; // The remain number of this price sheet uint32 remainNum; // The eth number which miner will got uint32 ethNumBal; // The eth number which equivalent to token's value which miner will got uint32 tokenNumBal; // The pledged number of nest in this sheet. (Unit: 1000nest) uint24 nestNum1k; // The level of this sheet. 0 expresses initial price sheet, a value greater than 0 expresses bite price sheet uint8 level; // Post fee shares, if there are many sheets in one block, this value is used to divide up mining value uint8 shares; // Represent price as this way, may lose precision, the error less than 1/10^14 // price = priceFraction * 16 ^ priceExponent uint56 priceFloat; } /// @dev Definitions for the price information struct PriceInfo { // Record the index of price sheet, for update price information from price sheet next time. uint32 index; // The block number of this price uint32 height; // The remain number of this price sheet uint32 remainNum; // Price, represent as float // Represent price as this way, may lose precision, the error less than 1/10^14 uint56 priceFloat; // Avg Price, represent as float // Represent price as this way, may lose precision, the error less than 1/10^14 uint56 avgFloat; // Square of price volatility, need divide by 2^48 uint48 sigmaSQ; } /// @dev Price channel struct PriceChannel { // Array of price sheets PriceSheet[] sheets; // Price information PriceInfo price; // Commission is charged for every post(post2), the commission should be deposited to NestLedger, // for saving gas, according to sheets.length, every increase of 256 will deposit once, The calculation formula is: // // totalFee = fee * increment // // In consideration of takeToken, takeEth, change postFeeUnit or miner pay more fee, the formula will be invalid, // at this point, it is need to settle immediately, the details of triggering settlement logic are as follows // // 1. When there is a bite transaction(currentFee is 0), the counter of no fee sheets will be increase 1 // 2. If the Commission of this time is inconsistent with that of last time, deposit immediately // 3. When the increment of sheets.length is 256, deposit immediately // 4. Everyone can trigger immediate settlement by manually calling the settle() method // // In order to realize the logic above, the following values are defined // // 1. PriceChannel.feeInfo // Low 128-bits represent last fee per post // High 128-bits represent the current counter of no fee sheets (including settled) // // 2. COLLECT_REWARD_MASK // The mask of batch deposit trigger, while COLLECT_REWARD_MASK & sheets.length == COLLECT_REWARD_MASK, it will trigger deposit, // COLLECT_REWARD_MASK is set to 0xF for testing (means every 16 sheets will deposit once), // and it will be set to 0xFF for mainnet (means every 256 sheets will deposit once) // The information of mining fee // Low 128-bits represent fee per post // High 128-bits represent the current counter of no fee sheets (including settled) uint feeInfo; } /// @dev Structure is used to represent a storage location. Storage variable can be used to avoid indexing from mapping many times struct UINT { uint value; } /// @dev Account information struct Account { // Address of account address addr; // Balances of mining account // tokenAddress=>balance mapping(address=>UINT) balances; } // Configuration Config _config; // Registered account information Account[] _accounts; // Mapping from address to index of account. address=>accountIndex mapping(address=>uint) _accountMapping; // Mapping from token address to price channel. tokenAddress=>PriceChannel mapping(address=>PriceChannel) _channels; // Mapping from token address to ntoken address. tokenAddress=>ntokenAddress mapping(address=>address) _addressCache; // Cache for genesis block number of ntoken. ntokenAddress=>genesisBlockNumber mapping(address=>uint) _genesisBlockNumberCache; // INestPriceFacade implementation contract address address _nestPriceFacadeAddress; // INTokenController implementation contract address address _nTokenControllerAddress; // INestLegder implementation contract address address _nestLedgerAddress; // Unit of post fee. 0.0001 ether uint constant DIMI_ETHER = 0.0001 ether; // The mask of batch deposit trigger, while COLLECT_REWARD_MASK & sheets.length == COLLECT_REWARD_MASK, it will trigger deposit, // COLLECT_REWARD_MASK is set to 0xF for testing (means every 16 sheets will deposit once), // and it will be set to 0xFF for mainnet (means every 256 sheets will deposit once) uint constant COLLECT_REWARD_MASK = 0xFF; // Ethereum average block time interval, 14 seconds uint constant ETHEREUM_BLOCK_TIMESPAN = 14; /* ========== Governance ========== */ /// @dev Rewritten in the implementation contract, for load other contract addresses. Call /// super.update(nestGovernanceAddress) when overriding, and override method without onlyGovernance /// @param nestGovernanceAddress INestGovernance implementation contract address function update(address nestGovernanceAddress) override public { super.update(nestGovernanceAddress); ( //address nestTokenAddress , //address nestNodeAddress , //address nestLedgerAddress _nestLedgerAddress, //address nestMiningAddress , //address ntokenMiningAddress , //address nestPriceFacadeAddress _nestPriceFacadeAddress, //address nestVoteAddress , //address nestQueryAddress , //address nnIncomeAddress , //address nTokenControllerAddress _nTokenControllerAddress ) = INestGovernance(nestGovernanceAddress).getBuiltinAddress(); } /// @dev Modify configuration /// @param config Configuration object function setConfig(Config calldata config) override external onlyGovernance { _config = config; } /// @dev Get configuration /// @return Configuration object function getConfig() override external view returns (Config memory) { return _config; } /// @dev Clear chache of token. while ntoken recreated, this method is need to call /// @param tokenAddress Token address function resetNTokenCache(address tokenAddress) external onlyGovernance { // Clear cache address ntokenAddress = _getNTokenAddress(tokenAddress); _genesisBlockNumberCache[ntokenAddress] = 0; _addressCache[tokenAddress] = _addressCache[ntokenAddress] = address(0); } /// @dev Set the ntokenAddress from tokenAddress, if ntokenAddress is equals to tokenAddress, means the token is disabled /// @param tokenAddress Destination token address /// @param ntokenAddress The ntoken address function setNTokenAddress(address tokenAddress, address ntokenAddress) override external onlyGovernance { _addressCache[tokenAddress] = ntokenAddress; } /// @dev Get the ntokenAddress from tokenAddress, if ntokenAddress is equals to tokenAddress, means the token is disabled /// @param tokenAddress Destination token address /// @return The ntoken address function getNTokenAddress(address tokenAddress) override external view returns (address) { return _addressCache[tokenAddress]; } /* ========== Mining ========== */ // Get ntoken address of from token address function _getNTokenAddress(address tokenAddress) private returns (address) { address ntokenAddress = _addressCache[tokenAddress]; if (ntokenAddress == address(0)) { ntokenAddress = INTokenController(_nTokenControllerAddress).getNTokenAddress(tokenAddress); if (ntokenAddress != address(0)) { _addressCache[tokenAddress] = ntokenAddress; } } return ntokenAddress; } // Get genesis block number of ntoken function _getNTokenGenesisBlock(address ntokenAddress) private returns (uint) { uint genesisBlockNumber = _genesisBlockNumberCache[ntokenAddress]; if (genesisBlockNumber == 0) { (genesisBlockNumber,) = INToken(ntokenAddress).checkBlockInfo(); _genesisBlockNumberCache[ntokenAddress] = genesisBlockNumber; } return genesisBlockNumber; } /// @notice Post a price sheet for TOKEN /// @dev It is for TOKEN (except USDT and NTOKENs) whose NTOKEN has a total supply below a threshold (e.g. 5,000,000 * 1e18) /// @param tokenAddress The address of TOKEN contract /// @param ethNum The numbers of ethers to post sheets /// @param tokenAmountPerEth The price of TOKEN function post(address tokenAddress, uint ethNum, uint tokenAmountPerEth) override external payable { Config memory config = _config; // 1. Check arguments require(ethNum > 0 && ethNum == uint(config.postEthUnit), "NM:!ethNum"); require(tokenAmountPerEth > 0, "NM:!price"); // 2. Check price channel // Check if the token allow post() address ntokenAddress = _getNTokenAddress(tokenAddress); require(ntokenAddress != address(0) && ntokenAddress != tokenAddress, "NM:!tokenAddress"); // Unit of nest is different, but the total supply already exceeded the number of this issue. No additional judgment will be made // ntoken is mint when the price sheet is closed (or withdrawn), this may be the problem that the user // intentionally does not close or withdraw, which leads to the inaccurate judgment of the total amount. ignore require(INToken(ntokenAddress).totalSupply() < uint(config.doublePostThreshold) * 10000 ether, "NM:!post2"); // 3. Load token channel and sheets PriceChannel storage channel = _channels[tokenAddress]; PriceSheet[] storage sheets = channel.sheets; // 4. Freeze assets uint accountIndex = _addressIndex(msg.sender); // Freeze token and nest // Because of the use of floating-point representation(fraction * 16 ^ exponent), it may bring some precision loss // After assets are frozen according to tokenAmountPerEth * ethNum, the part with poor accuracy may be lost when // the assets are returned, It should be frozen according to decodeFloat(fraction, exponent) * ethNum // However, considering that the loss is less than 1 / 10 ^ 14, the loss here is ignored, and the part of // precision loss can be transferred out as system income in the future _freeze2( _accounts[accountIndex].balances, tokenAddress, tokenAmountPerEth * ethNum, uint(config.pledgeNest) * 1000 ether ); // 5. Deposit fee // The revenue is deposited every 256 sheets, deducting the times of taking orders and the settled part uint length = sheets.length; uint shares = _collect(config, channel, ntokenAddress, length, msg.value - ethNum * 1 ether); require(shares > 0 && shares < 256, "NM:!fee"); // Calculate the price // According to the current mechanism, the newly added sheet cannot take effect, so the calculated price // is placed before the sheet is added, which can reduce unnecessary traversal _stat(config, channel, sheets); // 6. Create token price sheet emit Post(tokenAddress, msg.sender, length, ethNum, tokenAmountPerEth); _createPriceSheet(sheets, accountIndex, uint32(ethNum), uint(config.pledgeNest), shares, tokenAmountPerEth); } /// @notice Post two price sheets for a token and its ntoken simultaneously /// @dev Support dual-posts for TOKEN/NTOKEN, (ETH, TOKEN) + (ETH, NTOKEN) /// @param tokenAddress The address of TOKEN contract /// @param ethNum The numbers of ethers to post sheets /// @param tokenAmountPerEth The price of TOKEN /// @param ntokenAmountPerEth The price of NTOKEN function post2( address tokenAddress, uint ethNum, uint tokenAmountPerEth, uint ntokenAmountPerEth ) override external payable { Config memory config = _config; // 1. Check arguments require(ethNum > 0 && ethNum == uint(config.postEthUnit), "NM:!ethNum"); require(tokenAmountPerEth > 0 && ntokenAmountPerEth > 0, "NM:!price"); // 2. Check price channel address ntokenAddress = _getNTokenAddress(tokenAddress); require(ntokenAddress != address(0) && ntokenAddress != tokenAddress, "NM:!tokenAddress"); // 3. Load token channel and sheets PriceChannel storage channel = _channels[tokenAddress]; PriceSheet[] storage sheets = channel.sheets; // 4. Freeze assets uint pledgeNest = uint(config.pledgeNest); uint accountIndex = _addressIndex(msg.sender); { mapping(address=>UINT) storage balances = _accounts[accountIndex].balances; _freeze(balances, tokenAddress, ethNum * tokenAmountPerEth); _freeze2(balances, ntokenAddress, ethNum * ntokenAmountPerEth, pledgeNest * 2000 ether); } // 5. Deposit fee // The revenue is deposited every 256 sheets, deducting the times of taking orders and the settled part uint length = sheets.length; uint shares = _collect(config, channel, ntokenAddress, length, msg.value - ethNum * 2 ether); require(shares > 0 && shares < 256, "NM:!fee"); // Calculate the price // According to the current mechanism, the newly added sheet cannot take effect, so the calculated price // is placed before the sheet is added, which can reduce unnecessary traversal _stat(config, channel, sheets); // 6. Create token price sheet emit Post(tokenAddress, msg.sender, length, ethNum, tokenAmountPerEth); _createPriceSheet(sheets, accountIndex, uint32(ethNum), pledgeNest, shares, tokenAmountPerEth); // 7. Load ntoken channel and sheets channel = _channels[ntokenAddress]; sheets = channel.sheets; // Calculate the price // According to the current mechanism, the newly added sheet cannot take effect, so the calculated price // is placed before the sheet is added, which can reduce unnecessary traversal _stat(config, channel, sheets); // 8. Create token price sheet emit Post(ntokenAddress, msg.sender, sheets.length, ethNum, ntokenAmountPerEth); _createPriceSheet(sheets, accountIndex, uint32(ethNum), pledgeNest, 0, ntokenAmountPerEth); } /// @notice Call the function to buy TOKEN/NTOKEN from a posted price sheet /// @dev bite TOKEN(NTOKEN) by ETH, (+ethNumBal, -tokenNumBal) /// @param tokenAddress The address of token(ntoken) /// @param index The position of the sheet in priceSheetList[token] /// @param takeNum The amount of biting (in the unit of ETH), realAmount = takeNum * newTokenAmountPerEth /// @param newTokenAmountPerEth The new price of token (1 ETH : some TOKEN), here some means newTokenAmountPerEth function takeToken( address tokenAddress, uint index, uint takeNum, uint newTokenAmountPerEth ) override external payable { Config memory config = _config; // 1. Check arguments require(takeNum > 0 && takeNum % uint(config.postEthUnit) == 0, "NM:!takeNum"); require(newTokenAmountPerEth > 0, "NM:!price"); // 2. Load price sheet PriceChannel storage channel = _channels[tokenAddress]; PriceSheet[] storage sheets = channel.sheets; PriceSheet memory sheet = sheets[index]; // 3. Check state require(uint(sheet.remainNum) >= takeNum, "NM:!remainNum"); require(uint(sheet.height) + uint(config.priceEffectSpan) >= block.number, "NM:!state"); // 4. Deposit fee { // The revenue is deposited every 256 sheets, deducting the times of taking orders and the settled part address ntokenAddress = _getNTokenAddress(tokenAddress); if (tokenAddress != ntokenAddress) { _collect(config, channel, ntokenAddress, sheets.length, 0); } } // 5. Calculate the number of eth, token and nest needed, and freeze them uint needEthNum; uint level = uint(sheet.level); // When the level of the sheet is less than 4, both the nest and the scale of the offer are doubled if (level < uint(config.maxBiteNestedLevel)) { // Double scale sheet needEthNum = takeNum << 1; ++level; } // When the level of the sheet reaches 4 or more, nest doubles, but the scale does not else { // Single scale sheet needEthNum = takeNum; // It is possible that the length of a single chain exceeds 255. When the length of a chain reaches 4 // or more, there is no logical dependence on the specific value of the contract, and the count will // not increase after it is accumulated to 255 if (level < 255) ++level; } require(msg.value == (needEthNum + takeNum) * 1 ether, "NM:!value"); // Number of nest to be pledged //uint needNest1k = ((takeNum << 1) / uint(config.postEthUnit)) * uint(config.pledgeNest); // sheet.ethNumBal + sheet.tokenNumBal is always two times to sheet.ethNum uint needNest1k = (takeNum << 2) * uint(sheet.nestNum1k) / (uint(sheet.ethNumBal) + uint(sheet.tokenNumBal)); // Freeze nest and token uint accountIndex = _addressIndex(msg.sender); { mapping(address=>UINT) storage balances = _accounts[accountIndex].balances; uint backTokenValue = decodeFloat(sheet.priceFloat) * takeNum; if (needEthNum * newTokenAmountPerEth > backTokenValue) { _freeze2( balances, tokenAddress, needEthNum * newTokenAmountPerEth - backTokenValue, needNest1k * 1000 ether ); } else { _freeze(balances, NEST_TOKEN_ADDRESS, needNest1k * 1000 ether); _unfreeze(balances, tokenAddress, backTokenValue - needEthNum * newTokenAmountPerEth); } } // 6. Update the biten sheet sheet.remainNum = uint32(uint(sheet.remainNum) - takeNum); sheet.ethNumBal = uint32(uint(sheet.ethNumBal) + takeNum); sheet.tokenNumBal = uint32(uint(sheet.tokenNumBal) - takeNum); sheets[index] = sheet; // 7. Calculate the price // According to the current mechanism, the newly added sheet cannot take effect, so the calculated price // is placed before the sheet is added, which can reduce unnecessary traversal _stat(config, channel, sheets); // 8. Create price sheet emit Post(tokenAddress, msg.sender, sheets.length, needEthNum, newTokenAmountPerEth); _createPriceSheet(sheets, accountIndex, uint32(needEthNum), needNest1k, level << 8, newTokenAmountPerEth); } /// @notice Call the function to buy ETH from a posted price sheet /// @dev bite ETH by TOKEN(NTOKEN), (-ethNumBal, +tokenNumBal) /// @param tokenAddress The address of token(ntoken) /// @param index The position of the sheet in priceSheetList[token] /// @param takeNum The amount of biting (in the unit of ETH), realAmount = takeNum /// @param newTokenAmountPerEth The new price of token (1 ETH : some TOKEN), here some means newTokenAmountPerEth function takeEth( address tokenAddress, uint index, uint takeNum, uint newTokenAmountPerEth ) override external payable { Config memory config = _config; // 1. Check arguments require(takeNum > 0 && takeNum % uint(config.postEthUnit) == 0, "NM:!takeNum"); require(newTokenAmountPerEth > 0, "NM:!price"); // 2. Load price sheet PriceChannel storage channel = _channels[tokenAddress]; PriceSheet[] storage sheets = channel.sheets; PriceSheet memory sheet = sheets[index]; // 3. Check state require(uint(sheet.remainNum) >= takeNum, "NM:!remainNum"); require(uint(sheet.height) + uint(config.priceEffectSpan) >= block.number, "NM:!state"); // 4. Deposit fee { // The revenue is deposited every 256 sheets, deducting the times of taking orders and the settled part address ntokenAddress = _getNTokenAddress(tokenAddress); if (tokenAddress != ntokenAddress) { _collect(config, channel, ntokenAddress, sheets.length, 0); } } // 5. Calculate the number of eth, token and nest needed, and freeze them uint needEthNum; uint level = uint(sheet.level); // When the level of the sheet is less than 4, both the nest and the scale of the offer are doubled if (level < uint(config.maxBiteNestedLevel)) { // Double scale sheet needEthNum = takeNum << 1; ++level; } // When the level of the sheet reaches 4 or more, nest doubles, but the scale does not else { // Single scale sheet needEthNum = takeNum; // It is possible that the length of a single chain exceeds 255. When the length of a chain reaches 4 // or more, there is no logical dependence on the specific value of the contract, and the count will // not increase after it is accumulated to 255 if (level < 255) ++level; } require(msg.value == (needEthNum - takeNum) * 1 ether, "NM:!value"); // Number of nest to be pledged //uint needNest1k = ((takeNum << 1) / uint(config.postEthUnit)) * uint(config.pledgeNest); // sheet.ethNumBal + sheet.tokenNumBal is always two times to sheet.ethNum uint needNest1k = (takeNum << 2) * uint(sheet.nestNum1k) / (uint(sheet.ethNumBal) + uint(sheet.tokenNumBal)); // Freeze nest and token uint accountIndex = _addressIndex(msg.sender); _freeze2( _accounts[accountIndex].balances, tokenAddress, needEthNum * newTokenAmountPerEth + decodeFloat(sheet.priceFloat) * takeNum, needNest1k * 1000 ether ); // 6. Update the biten sheet sheet.remainNum = uint32(uint(sheet.remainNum) - takeNum); sheet.ethNumBal = uint32(uint(sheet.ethNumBal) - takeNum); sheet.tokenNumBal = uint32(uint(sheet.tokenNumBal) + takeNum); sheets[index] = sheet; // 7. Calculate the price // According to the current mechanism, the newly added sheet cannot take effect, so the calculated price // is placed before the sheet is added, which can reduce unnecessary traversal _stat(config, channel, sheets); // 8. Create price sheet emit Post(tokenAddress, msg.sender, sheets.length, needEthNum, newTokenAmountPerEth); _createPriceSheet(sheets, accountIndex, uint32(needEthNum), needNest1k, level << 8, newTokenAmountPerEth); } // Create price sheet function _createPriceSheet( PriceSheet[] storage sheets, uint accountIndex, uint32 ethNum, uint nestNum1k, uint level_shares, uint tokenAmountPerEth ) private { sheets.push(PriceSheet( uint32(accountIndex), // uint32 miner; uint32(block.number), // uint32 height; ethNum, // uint32 remainNum; ethNum, // uint32 ethNumBal; ethNum, // uint32 tokenNumBal; uint24(nestNum1k), // uint32 nestNum1k; uint8(level_shares >> 8), // uint8 level; uint8(level_shares & 0xFF), encodeFloat(tokenAmountPerEth) )); } // Nest ore drawing attenuation interval. 2400000 blocks, about one year uint constant NEST_REDUCTION_SPAN = 2400000; // The decay limit of nest ore drawing becomes stable after exceeding this interval. 24 million blocks, about 10 years uint constant NEST_REDUCTION_LIMIT = 24000000; //NEST_REDUCTION_SPAN * 10; // Attenuation gradient array, each attenuation step value occupies 16 bits. The attenuation value is an integer uint constant NEST_REDUCTION_STEPS = 0x280035004300530068008300A300CC010001400190; // 0 // | (uint(400 / uint(1)) << (16 * 0)) // | (uint(400 * 8 / uint(10)) << (16 * 1)) // | (uint(400 * 8 * 8 / uint(10 * 10)) << (16 * 2)) // | (uint(400 * 8 * 8 * 8 / uint(10 * 10 * 10)) << (16 * 3)) // | (uint(400 * 8 * 8 * 8 * 8 / uint(10 * 10 * 10 * 10)) << (16 * 4)) // | (uint(400 * 8 * 8 * 8 * 8 * 8 / uint(10 * 10 * 10 * 10 * 10)) << (16 * 5)) // | (uint(400 * 8 * 8 * 8 * 8 * 8 * 8 / uint(10 * 10 * 10 * 10 * 10 * 10)) << (16 * 6)) // | (uint(400 * 8 * 8 * 8 * 8 * 8 * 8 * 8 / uint(10 * 10 * 10 * 10 * 10 * 10 * 10)) << (16 * 7)) // | (uint(400 * 8 * 8 * 8 * 8 * 8 * 8 * 8 * 8 / uint(10 * 10 * 10 * 10 * 10 * 10 * 10 * 10)) << (16 * 8)) // | (uint(400 * 8 * 8 * 8 * 8 * 8 * 8 * 8 * 8 * 8 / uint(10 * 10 * 10 * 10 * 10 * 10 * 10 * 10 * 10)) << (16 * 9)) // //| (uint(400 * 8 * 8 * 8 * 8 * 8 * 8 * 8 * 8 * 8 * 8 / uint(10 * 10 * 10 * 10 * 10 * 10 * 10 * 10 * 10 * 10)) << (16 * 10)); // | (uint(40) << (16 * 10)); // Calculation of attenuation gradient function _redution(uint delta) private pure returns (uint) { if (delta < NEST_REDUCTION_LIMIT) { return (NEST_REDUCTION_STEPS >> ((delta / NEST_REDUCTION_SPAN) << 4)) & 0xFFFF; } return (NEST_REDUCTION_STEPS >> 160) & 0xFFFF; } /// @notice Close a price sheet of (ETH, USDx) | (ETH, NEST) | (ETH, TOKEN) | (ETH, NTOKEN) /// @dev Here we allow an empty price sheet (still in VERIFICATION-PERIOD) to be closed /// @param tokenAddress The address of TOKEN contract /// @param index The index of the price sheet w.r.t. `token` function close(address tokenAddress, uint index) override external { Config memory config = _config; PriceChannel storage channel = _channels[tokenAddress]; PriceSheet[] storage sheets = channel.sheets; // Load the price channel address ntokenAddress = _getNTokenAddress(tokenAddress); // Call _close() method to close price sheet (uint accountIndex, Tunple memory total) = _close(config, sheets, index, ntokenAddress); if (accountIndex > 0) { // Return eth if (uint(total.ethNum) > 0) { payable(indexAddress(accountIndex)).transfer(uint(total.ethNum) * 1 ether); } // Unfreeze assets _unfreeze3( _accounts[accountIndex].balances, tokenAddress, total.tokenValue, ntokenAddress, uint(total.ntokenValue), uint(total.nestValue) ); } // Calculate the price _stat(config, channel, sheets); } /// @notice Close a batch of price sheets passed VERIFICATION-PHASE /// @dev Empty sheets but in VERIFICATION-PHASE aren't allowed /// @param tokenAddress The address of TOKEN contract /// @param indices A list of indices of sheets w.r.t. `token` function closeList(address tokenAddress, uint[] memory indices) override external { // Call _closeList() method to close price sheets ( uint accountIndex, Tunple memory total, address ntokenAddress ) = _closeList(_config, _channels[tokenAddress], tokenAddress, indices); // Return eth payable(indexAddress(accountIndex)).transfer(uint(total.ethNum) * 1 ether); // Unfreeze assets _unfreeze3( _accounts[accountIndex].balances, tokenAddress, uint(total.tokenValue), ntokenAddress, uint(total.ntokenValue), uint(total.nestValue) ); } /// @notice Close two batch of price sheets passed VERIFICATION-PHASE /// @dev Empty sheets but in VERIFICATION-PHASE aren't allowed /// @param tokenAddress The address of TOKEN1 contract /// @param tokenIndices A list of indices of sheets w.r.t. `token` /// @param ntokenIndices A list of indices of sheets w.r.t. `ntoken` function closeList2( address tokenAddress, uint[] memory tokenIndices, uint[] memory ntokenIndices ) override external { Config memory config = _config; mapping(address=>PriceChannel) storage channels = _channels; // Call _closeList() method to close price sheets ( uint accountIndex1, Tunple memory total1, address ntokenAddress ) = _closeList(config, channels[tokenAddress], tokenAddress, tokenIndices); ( uint accountIndex2, Tunple memory total2, //address ntokenAddress2 ) = _closeList(config, channels[ntokenAddress], ntokenAddress, ntokenIndices); require(accountIndex1 == accountIndex2, "NM:!miner"); //require(ntokenAddress1 == tokenAddress2, "NM:!tokenAddress"); require(uint(total2.ntokenValue) == 0, "NM!ntokenValue"); // Return eth payable(indexAddress(accountIndex1)).transfer((uint(total1.ethNum) + uint(total2.ethNum)) * 1 ether); // Unfreeze assets _unfreeze3( _accounts[accountIndex1].balances, tokenAddress, uint(total1.tokenValue), ntokenAddress, uint(total1.ntokenValue) + uint(total2.tokenValue)/* + uint(total2.ntokenValue) */, uint(total1.nestValue) + uint(total2.nestValue) ); } // Calculation number of blocks which mined function _calcMinedBlocks( PriceSheet[] storage sheets, uint index, PriceSheet memory sheet ) private view returns (uint minedBlocks, uint totalShares) { uint length = sheets.length; uint height = uint(sheet.height); totalShares = uint(sheet.shares); // Backward looking for sheets in the same block for (uint i = index; ++i < length && uint(sheets[i].height) == height;) { // Multiple sheets in the same block is a small probability event at present, so it can be ignored // to read more than once, if there are always multiple sheets in the same block, it means that the // sheets are very intensive, and the gas consumed here does not have a great impact totalShares += uint(sheets[i].shares); } //i = index; // Find sheets in the same block forward uint prev = height; while (index > 0 && uint(prev = sheets[--index].height) == height) { // Multiple sheets in the same block is a small probability event at present, so it can be ignored // to read more than once, if there are always multiple sheets in the same block, it means that the // sheets are very intensive, and the gas consumed here does not have a great impact totalShares += uint(sheets[index].shares); } if (index > 0 || height > prev) { minedBlocks = height - prev; } else { minedBlocks = 10; } } // This structure is for the _close() method to return multiple values struct Tunple { uint tokenValue; uint64 ethNum; uint96 nestValue; uint96 ntokenValue; } // Close price sheet function _close( Config memory config, PriceSheet[] storage sheets, uint index, address ntokenAddress ) private returns (uint accountIndex, Tunple memory value) { PriceSheet memory sheet = sheets[index]; uint height = uint(sheet.height); // Check the status of the price sheet to see if it has reached the effective block interval or has been finished if ((accountIndex = uint(sheet.miner)) > 0 && (height + uint(config.priceEffectSpan) < block.number)) { // TMP: tmp is a polysemous name, here means sheet.shares uint tmp = uint(sheet.shares); // Mining logic // The price sheet which shares is zero dosen't mining if (tmp > 0) { // Currently, mined represents the number of blocks has mined (uint mined, uint totalShares) = _calcMinedBlocks(sheets, index, sheet); // nest mining if (ntokenAddress == NEST_TOKEN_ADDRESS) { // Since then, mined represents the amount of mining // mined = ( // mined // * uint(sheet.shares) // * _redution(height - NEST_GENESIS_BLOCK) // * 1 ether // * uint(config.minerNestReward) // / 10000 // / totalShares // ); // The original expression is shown above. In order to save gas, // the part that can be calculated in advance is calculated first mined = ( mined * tmp * _redution(height - NEST_GENESIS_BLOCK) * uint(config.minerNestReward) * 0.0001 ether / totalShares ); } // ntoken mining else { // The limit blocks can be mined if (mined > uint(config.ntokenMinedBlockLimit)) { mined = uint(config.ntokenMinedBlockLimit); } // Since then, mined represents the amount of mining mined = ( mined * tmp * _redution(height - _getNTokenGenesisBlock(ntokenAddress)) * 0.01 ether / totalShares ); // Put this logic into widhdran() method to reduce gas consumption // ntoken bidders address bidder = INToken(ntokenAddress).checkBidder(); // Legacy ntoken, need separate if (bidder != address(this)) { // Considering that multiple sheets in the same block are small probability events, // we can send token to bidders in each closing operation // 5% for bidder // TMP: tmp is a polysemous name, here means mint ntoken amount for miner tmp = mined * uint(config.minerNTokenReward) / 10000; _unfreeze( _accounts[_addressIndex(bidder)].balances, ntokenAddress, mined - tmp ); // Miner take according proportion which set mined = tmp; } } value.ntokenValue = uint96(mined); } value.nestValue = uint96(uint(sheet.nestNum1k) * 1000 ether); value.ethNum = uint64(sheet.ethNumBal); value.tokenValue = decodeFloat(sheet.priceFloat) * uint(sheet.tokenNumBal); // Set sheet.miner to 0, express the sheet is closed sheet.miner = uint32(0); sheet.ethNumBal = uint32(0); sheet.tokenNumBal = uint32(0); sheets[index] = sheet; } } // Batch close sheets function _closeList( Config memory config, PriceChannel storage channel, address tokenAddress, uint[] memory indices ) private returns (uint accountIndex, Tunple memory total, address ntokenAddress) { ntokenAddress = _getNTokenAddress(tokenAddress); PriceSheet[] storage sheets = channel.sheets; accountIndex = 0; // 1. Traverse sheets for (uint i = indices.length; i > 0;) { // Because too many variables need to be returned, too many variables will be defined, so the structure of tunple is defined (uint minerIndex, Tunple memory value) = _close(config, sheets, indices[--i], ntokenAddress); // Batch closing quotation can only close sheet of the same user if (accountIndex == 0) { // accountIndex == 0 means the first sheet, and the number of this sheet is taken accountIndex = minerIndex; } else { // accountIndex != 0 means that it is a follow-up sheet, and the miner number must be consistent with the previous record require(accountIndex == minerIndex, "NM:!miner"); } total.ntokenValue += value.ntokenValue; total.nestValue += value.nestValue; total.ethNum += value.ethNum; total.tokenValue += value.tokenValue; } _stat(config, channel, sheets); } // Calculate price, average price and volatility function _stat(Config memory config, PriceChannel storage channel, PriceSheet[] storage sheets) private { // Load token price information PriceInfo memory p0 = channel.price; // Length of sheets uint length = sheets.length; // The index of the sheet to be processed in the sheet array uint index = uint(p0.index); // The latest block number for which the price has been calculated uint prev = uint(p0.height); // It's not necessary to load the price information in p0 // Eth count variable used to calculate price uint totalEthNum = 0; // Token count variable for price calculation uint totalTokenValue = 0; // Block number of current sheet uint height = 0; // Traverse the sheets to find the effective price uint effectBlock = block.number - uint(config.priceEffectSpan); PriceSheet memory sheet; for (; ; ++index) { // Gas attack analysis, each post transaction, calculated according to post, needs to write // at least one sheet and freeze two kinds of assets, which needs to consume at least 30000 gas, // In addition to the basic cost of the transaction, at least 50000 gas is required. // In addition, there are other reading and calculation operations. The gas consumed by each // transaction is impossible less than 70000 gas, The attacker can accumulate up to 20 blocks // of sheets to be generated. To ensure that the calculation can be completed in one block, // it is necessary to ensure that the consumption of each price does not exceed 70000 / 20 = 3500 gas, // According to the current logic, each calculation of a price needs to read a storage unit (800) // and calculate the consumption, which can not reach the dangerous value of 3500, so the gas attack // is not considered // Traverse the sheets that has reached the effective interval from the current position bool flag = index >= length || (height = uint((sheet = sheets[index]).height)) >= effectBlock; // Not the same block (or flag is false), calculate the price and update it if (flag || prev != height) { // totalEthNum > 0 Can calculate the price if (totalEthNum > 0) { // Calculate average price and Volatility // Calculation method of volatility of follow-up price uint tmp = decodeFloat(p0.priceFloat); // New price uint price = totalTokenValue / totalEthNum; // Update price p0.remainNum = uint32(totalEthNum); p0.priceFloat = encodeFloat(price); // Clear cumulative values totalEthNum = 0; totalTokenValue = 0; if (tmp > 0) { // Calculate average price // avgPrice[i + 1] = avgPrice[i] * 90% + price[i] * 10% p0.avgFloat = encodeFloat((decodeFloat(p0.avgFloat) * 9 + price) / 10); // When the accuracy of the token is very high or the value of the token relative to // eth is very low, the price may be very large, and there may be overflow problem, // it is not considered for the moment tmp = (price << 48) / tmp; if (tmp > 0x1000000000000) { tmp = tmp - 0x1000000000000; } else { tmp = 0x1000000000000 - tmp; } // earn = price[i] / price[i - 1] - 1; // seconds = time[i] - time[i - 1]; // sigmaSQ[i + 1] = sigmaSQ[i] * 90% + (earn ^ 2 / seconds) * 10% tmp = ( uint(p0.sigmaSQ) * 9 + // It is inevitable that prev greatter than p0.height ((tmp * tmp / ETHEREUM_BLOCK_TIMESPAN / (prev - uint(p0.height))) >> 48) ) / 10; // The current implementation assumes that the volatility cannot exceed 1, and // corresponding to this, when the calculated value exceeds 1, expressed as 0xFFFFFFFFFFFF if (tmp > 0xFFFFFFFFFFFF) { tmp = 0xFFFFFFFFFFFF; } p0.sigmaSQ = uint48(tmp); } // The calculation methods of average price and volatility are different for first price else { // The average price is equal to the price //p0.avgTokenAmount = uint64(price); p0.avgFloat = p0.priceFloat; // The volatility is 0 p0.sigmaSQ = uint48(0); } // Update price block number p0.height = uint32(prev); } // Move to new block number prev = height; } if (flag) { break; } // Cumulative price information totalEthNum += uint(sheet.remainNum); totalTokenValue += decodeFloat(sheet.priceFloat) * uint(sheet.remainNum); } // Update price infomation if (index > uint(p0.index)) { p0.index = uint32(index); channel.price = p0; } } /// @dev The function updates the statistics of price sheets /// It calculates from priceInfo to the newest that is effective. function stat(address tokenAddress) override external { PriceChannel storage channel = _channels[tokenAddress]; _stat(_config, channel, channel.sheets); } // Collect and deposit the commission into NestLedger function _collect( Config memory config, PriceChannel storage channel, address ntokenAddress, uint length, uint currentFee ) private returns (uint) { // Commission is charged for every post(post2), the commission should be deposited to NestLedger, // for saving gas, according to sheets.length, every increase of 256 will deposit once, The calculation formula is: // // totalFee = fee * increment // // In consideration of takeToken, takeEth, change postFeeUnit or miner pay more fee, the formula will be invalid, // at this point, it is need to settle immediately, the details of triggering settlement logic are as follows // // 1. When there is a bite transaction(currentFee is 0), the counter of no fee sheets will be increase 1 // 2. If the Commission of this time is inconsistent with that of last time, deposit immediately // 3. When the increment of sheets.length is 256, deposit immediately // 4. Everyone can trigger immediate settlement by manually calling the settle() method // // In order to realize the logic above, the following values are defined // // 1. PriceChannel.feeInfo // Low 128-bits represent last fee per post // High 128-bits represent the current counter of no fee sheets (including settled) // // 2. COLLECT_REWARD_MASK // The mask of batch deposit trigger, while COLLECT_REWARD_MASK & sheets.length == COLLECT_REWARD_MASK, it will trigger deposit, // COLLECT_REWARD_MASK is set to 0xF for testing (means every 16 sheets will deposit once), // and it will be set to 0xFF for mainnet (means every 256 sheets will deposit once) uint feeUnit = uint(config.postFeeUnit) * DIMI_ETHER; require(currentFee % feeUnit == 0, "NM:!fee"); uint feeInfo = channel.feeInfo; uint oldFee = feeInfo & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; // length == 255 means is time to save reward // currentFee != oldFee means the fee is changed, need to settle if (length & COLLECT_REWARD_MASK == COLLECT_REWARD_MASK || (currentFee != oldFee && currentFee > 0)) { // Save reward INestLedger(_nestLedgerAddress).carveETHReward { value: currentFee + oldFee * ((length & COLLECT_REWARD_MASK) - (feeInfo >> 128)) } (ntokenAddress); // Update fee information channel.feeInfo = currentFee | (((length + 1) & COLLECT_REWARD_MASK) << 128); } // currentFee is 0, increase no fee counter else if (currentFee == 0) { // channel.feeInfo = feeInfo + (1 << 128); channel.feeInfo = feeInfo + 0x100000000000000000000000000000000; } // Calculate share count return currentFee / feeUnit; } /// @dev Settlement Commission /// @param tokenAddress The token address function settle(address tokenAddress) override external { address ntokenAddress = _getNTokenAddress(tokenAddress); // ntoken is no reward if (tokenAddress != ntokenAddress) { PriceChannel storage channel = _channels[tokenAddress]; uint length = channel.sheets.length & COLLECT_REWARD_MASK; uint feeInfo = channel.feeInfo; // Save reward INestLedger(_nestLedgerAddress).carveETHReward { value: (feeInfo & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) * (length - (feeInfo >> 128)) } (ntokenAddress); // Manual settlement does not need to update Commission variables channel.feeInfo = (feeInfo & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) | (length << 128); } } // Convert PriceSheet to PriceSheetView function _toPriceSheetView(PriceSheet memory sheet, uint index) private view returns (PriceSheetView memory) { return PriceSheetView( // Index number uint32(index), // Miner address indexAddress(sheet.miner), // The block number of this price sheet packaged sheet.height, // The remain number of this price sheet sheet.remainNum, // The eth number which miner will got sheet.ethNumBal, // The eth number which equivalent to token's value which miner will got sheet.tokenNumBal, // The pledged number of nest in this sheet. (Unit: 1000nest) sheet.nestNum1k, // The level of this sheet. 0 expresses initial price sheet, a value greater than 0 expresses bite price sheet sheet.level, // Post fee shares sheet.shares, // Price uint152(decodeFloat(sheet.priceFloat)) ); } /// @dev List sheets by page /// @param tokenAddress Destination token address /// @param offset Skip previous (offset) records /// @param count Return (count) records /// @param order Order. 0 reverse order, non-0 positive order /// @return List of price sheets function list( address tokenAddress, uint offset, uint count, uint order ) override external view noContract returns (PriceSheetView[] memory) { PriceSheet[] storage sheets = _channels[tokenAddress].sheets; PriceSheetView[] memory result = new PriceSheetView[](count); uint length = sheets.length; uint i = 0; // Reverse order if (order == 0) { uint index = length - offset; uint end = index > count ? index - count : 0; while (index > end) { --index; result[i++] = _toPriceSheetView(sheets[index], index); } } // Positive order else { uint index = offset; uint end = index + count; if (end > length) { end = length; } while (index < end) { result[i++] = _toPriceSheetView(sheets[index], index); ++index; } } return result; } /// @dev Estimated mining amount /// @param tokenAddress Destination token address /// @return Estimated mining amount function estimate(address tokenAddress) override external view returns (uint) { address ntokenAddress = INTokenController(_nTokenControllerAddress).getNTokenAddress(tokenAddress); if (tokenAddress != ntokenAddress) { PriceSheet[] storage sheets = _channels[tokenAddress].sheets; uint index = sheets.length; while (index > 0) { PriceSheet memory sheet = sheets[--index]; if (uint(sheet.shares) > 0) { // Standard mining amount uint standard = (block.number - uint(sheet.height)) * 1 ether; // Genesis block number of ntoken uint genesisBlock = NEST_GENESIS_BLOCK; // Not nest, the calculation methods of standard mining amount and genesis block number are different if (ntokenAddress != NEST_TOKEN_ADDRESS) { // The standard mining amount of ntoken is 1/100 of nest standard /= 100; // Genesis block number of ntoken is obtained separately (genesisBlock,) = INToken(ntokenAddress).checkBlockInfo(); } return standard * _redution(block.number - genesisBlock); } } } return 0; } /// @dev Query the quantity of the target quotation /// @param tokenAddress Token address. The token can't mine. Please make sure you don't use the token address when calling /// @param index The index of the sheet /// @return minedBlocks Mined block period from previous block /// @return totalShares Total shares of sheets in the block function getMinedBlocks( address tokenAddress, uint index ) override external view returns (uint minedBlocks, uint totalShares) { PriceSheet[] storage sheets = _channels[tokenAddress].sheets; PriceSheet memory sheet = sheets[index]; // The bite sheet or ntoken sheet dosen't mining if (uint(sheet.shares) == 0) { return (0, 0); } return _calcMinedBlocks(sheets, index, sheet); } /* ========== Accounts ========== */ /// @dev Withdraw assets /// @param tokenAddress Destination token address /// @param value The value to withdraw function withdraw(address tokenAddress, uint value) override external { // The user's locked nest and the mining pool's nest are stored together. When the nest is mined over, // the problem of taking the locked nest as the ore drawing will appear // As it will take a long time for nest to finish mining, this problem will not be considered for the time being UINT storage balance = _accounts[_accountMapping[msg.sender]].balances[tokenAddress]; //uint balanceValue = balance.value; //require(balanceValue >= value, "NM:!balance"); balance.value -= value; // ntoken mining uint ntokenBalance = INToken(tokenAddress).balanceOf(address(this)); if (ntokenBalance < value) { // mining INToken(tokenAddress).increaseTotal(value - ntokenBalance); } TransferHelper.safeTransfer(tokenAddress, msg.sender, value); } /// @dev View the number of assets specified by the user /// @param tokenAddress Destination token address /// @param addr Destination address /// @return Number of assets function balanceOf(address tokenAddress, address addr) override external view returns (uint) { return _accounts[_accountMapping[addr]].balances[tokenAddress].value; } /// @dev Gets the index number of the specified address. If it does not exist, register /// @param addr Destination address /// @return The index number of the specified address function _addressIndex(address addr) private returns (uint) { uint index = _accountMapping[addr]; if (index == 0) { // If it exceeds the maximum number that 32 bits can store, you can't continue to register a new account. // If you need to support a new account, you need to update the contract require((_accountMapping[addr] = index = _accounts.length) < 0x100000000, "NM:!accounts"); _accounts.push().addr = addr; } return index; } /// @dev Gets the address corresponding to the given index number /// @param index The index number of the specified address /// @return The address corresponding to the given index number function indexAddress(uint index) override public view returns (address) { return _accounts[index].addr; } /// @dev Gets the registration index number of the specified address /// @param addr Destination address /// @return 0 means nonexistent, non-0 means index number function getAccountIndex(address addr) override external view returns (uint) { return _accountMapping[addr]; } /// @dev Get the length of registered account array /// @return The length of registered account array function getAccountCount() override external view returns (uint) { return _accounts.length; } /* ========== Asset management ========== */ /// @dev Freeze token /// @param balances Balances ledger /// @param tokenAddress Destination token address /// @param value token amount function _freeze(mapping(address=>UINT) storage balances, address tokenAddress, uint value) private { UINT storage balance = balances[tokenAddress]; uint balanceValue = balance.value; if (balanceValue < value) { balance.value = 0; TransferHelper.safeTransferFrom(tokenAddress, msg.sender, address(this), value - balanceValue); } else { balance.value = balanceValue - value; } } /// @dev Unfreeze token /// @param balances Balances ledgerBalances ledger /// @param tokenAddress Destination token address /// @param value token amount function _unfreeze(mapping(address=>UINT) storage balances, address tokenAddress, uint value) private { UINT storage balance = balances[tokenAddress]; balance.value += value; } /// @dev freeze token and nest /// @param balances Balances ledger /// @param tokenAddress Destination token address /// @param tokenValue token amount /// @param nestValue nest amount function _freeze2( mapping(address=>UINT) storage balances, address tokenAddress, uint tokenValue, uint nestValue ) private { UINT storage balance; uint balanceValue; // If tokenAddress is NEST_TOKEN_ADDRESS, add it to nestValue if (NEST_TOKEN_ADDRESS == tokenAddress) { nestValue += tokenValue; } // tokenAddress is not NEST_TOKEN_ADDRESS, unfreeze it else { balance = balances[tokenAddress]; balanceValue = balance.value; if (balanceValue < tokenValue) { balance.value = 0; TransferHelper.safeTransferFrom(tokenAddress, msg.sender, address(this), tokenValue - balanceValue); } else { balance.value = balanceValue - tokenValue; } } // Unfreeze nest balance = balances[NEST_TOKEN_ADDRESS]; balanceValue = balance.value; if (balanceValue < nestValue) { balance.value = 0; TransferHelper.safeTransferFrom(NEST_TOKEN_ADDRESS, msg.sender, address(this), nestValue - balanceValue); } else { balance.value = balanceValue - nestValue; } } /// @dev Unfreeze token, ntoken and nest /// @param balances Balances ledger /// @param tokenAddress Destination token address /// @param tokenValue token amount /// @param ntokenAddress Destination ntoken address /// @param ntokenValue ntoken amount /// @param nestValue nest amount function _unfreeze3( mapping(address=>UINT) storage balances, address tokenAddress, uint tokenValue, address ntokenAddress, uint ntokenValue, uint nestValue ) private { UINT storage balance; // If tokenAddress is ntokenAddress, add it to ntokenValue if (ntokenAddress == tokenAddress) { ntokenValue += tokenValue; } // tokenAddress is not ntokenAddress, unfreeze it else { balance = balances[tokenAddress]; balance.value += tokenValue; } // If ntokenAddress is NEST_TOKEN_ADDRESS, add it to nestValue if (NEST_TOKEN_ADDRESS == ntokenAddress) { nestValue += ntokenValue; } // ntokenAddress is NEST_TOKEN_ADDRESS, unfreeze it else { balance = balances[ntokenAddress]; balance.value += ntokenValue; } // Unfreeze nest balance = balances[NEST_TOKEN_ADDRESS]; balance.value += nestValue; } /* ========== INestQuery ========== */ // Check msg.sender function _check() private view { require(msg.sender == _nestPriceFacadeAddress || msg.sender == tx.origin); } /// @dev Get the latest trigger price /// @param tokenAddress Destination token address /// @return blockNumber The block number of price /// @return price The token price. (1eth equivalent to (price) token) function triggeredPrice(address tokenAddress) override public view returns (uint blockNumber, uint price) { _check(); PriceInfo memory priceInfo = _channels[tokenAddress].price; if (uint(priceInfo.remainNum) > 0) { return (uint(priceInfo.height) + uint(_config.priceEffectSpan), decodeFloat(priceInfo.priceFloat)); } return (0, 0); } /// @dev Get the full information of latest trigger price /// @param tokenAddress Destination token address /// @return blockNumber The block number of price /// @return price The token price. (1eth equivalent to (price) token) /// @return avgPrice Average price /// @return sigmaSQ The square of the volatility (18 decimal places). The current implementation assumes that /// the volatility cannot exceed 1. Correspondingly, when the return value is equal to 999999999999996447, /// it means that the volatility has exceeded the range that can be expressed function triggeredPriceInfo(address tokenAddress) override public view returns ( uint blockNumber, uint price, uint avgPrice, uint sigmaSQ ) { _check(); PriceInfo memory priceInfo = _channels[tokenAddress].price; if (uint(priceInfo.remainNum) > 0) { return ( uint(priceInfo.height) + uint(_config.priceEffectSpan), decodeFloat(priceInfo.priceFloat), decodeFloat(priceInfo.avgFloat), (uint(priceInfo.sigmaSQ) * 1 ether) >> 48 ); } return (0, 0, 0, 0); } /// @dev Find the price at block number /// @param tokenAddress Destination token address /// @param height Destination block number /// @return blockNumber The block number of price /// @return price The token price. (1eth equivalent to (price) token) function findPrice( address tokenAddress, uint height ) override external view returns (uint blockNumber, uint price) { _check(); PriceSheet[] storage sheets = _channels[tokenAddress].sheets; uint priceEffectSpan = uint(_config.priceEffectSpan); uint length = sheets.length; uint index = 0; uint sheetHeight; height -= priceEffectSpan; { // If there is no sheet in this channel, length is 0, length - 1 will overflow, uint right = length - 1; uint left = 0; // Find the index use Binary Search while (left < right) { index = (left + right) >> 1; sheetHeight = uint(sheets[index].height); if (height > sheetHeight) { left = ++index; } else if (height < sheetHeight) { // When index = 0, this statement will have an underflow exception, which usually // indicates that the effective block height passed during the call is lower than // the block height of the first quotation right = --index; } else { break; } } } // Calculate price uint totalEthNum = 0; uint totalTokenValue = 0; uint h = 0; uint remainNum; PriceSheet memory sheet; // Find sheets forward for (uint i = index; i < length;) { sheet = sheets[i++]; sheetHeight = uint(sheet.height); if (height < sheetHeight) { break; } remainNum = uint(sheet.remainNum); if (remainNum > 0) { if (h == 0) { h = sheetHeight; } else if (h != sheetHeight) { break; } totalEthNum += remainNum; totalTokenValue += decodeFloat(sheet.priceFloat) * remainNum; } } // Find sheets backward while (index > 0) { sheet = sheets[--index]; remainNum = uint(sheet.remainNum); if (remainNum > 0) { sheetHeight = uint(sheet.height); if (h == 0) { h = sheetHeight; } else if (h != sheetHeight) { break; } totalEthNum += remainNum; totalTokenValue += decodeFloat(sheet.priceFloat) * remainNum; } } if (totalEthNum > 0) { return (h + priceEffectSpan, totalTokenValue / totalEthNum); } return (0, 0); } /// @dev Get the latest effective price /// @param tokenAddress Destination token address /// @return blockNumber The block number of price /// @return price The token price. (1eth equivalent to (price) token) function latestPrice(address tokenAddress) override public view returns (uint blockNumber, uint price) { _check(); PriceSheet[] storage sheets = _channels[tokenAddress].sheets; PriceSheet memory sheet; uint priceEffectSpan = uint(_config.priceEffectSpan); uint h = block.number - priceEffectSpan; uint index = sheets.length; uint totalEthNum = 0; uint totalTokenValue = 0; uint height = 0; for (; ; ) { bool flag = index == 0; if (flag || height != uint((sheet = sheets[--index]).height)) { if (totalEthNum > 0 && height <= h) { return (height + priceEffectSpan, totalTokenValue / totalEthNum); } if (flag) { break; } totalEthNum = 0; totalTokenValue = 0; height = uint(sheet.height); } uint remainNum = uint(sheet.remainNum); totalEthNum += remainNum; totalTokenValue += decodeFloat(sheet.priceFloat) * remainNum; } return (0, 0); } /// @dev Get the last (num) effective price /// @param tokenAddress Destination token address /// @param count The number of prices that want to return /// @return An array which length is num * 2, each two element expresses one price like blockNumber|price function lastPriceList(address tokenAddress, uint count) override public view returns (uint[] memory) { _check(); PriceSheet[] storage sheets = _channels[tokenAddress].sheets; PriceSheet memory sheet; uint[] memory array = new uint[](count <<= 1); uint priceEffectSpan = uint(_config.priceEffectSpan); uint h = block.number - priceEffectSpan; uint index = sheets.length; uint totalEthNum = 0; uint totalTokenValue = 0; uint height = 0; for (uint i = 0; i < count;) { bool flag = index == 0; if (flag || height != uint((sheet = sheets[--index]).height)) { if (totalEthNum > 0 && height <= h) { array[i++] = height + priceEffectSpan; array[i++] = totalTokenValue / totalEthNum; } if (flag) { break; } totalEthNum = 0; totalTokenValue = 0; height = uint(sheet.height); } uint remainNum = uint(sheet.remainNum); totalEthNum += remainNum; totalTokenValue += decodeFloat(sheet.priceFloat) * remainNum; } return array; } /// @dev Returns the results of latestPrice() and triggeredPriceInfo() /// @param tokenAddress Destination token address /// @return latestPriceBlockNumber The block number of latest price /// @return latestPriceValue The token latest price. (1eth equivalent to (price) token) /// @return triggeredPriceBlockNumber The block number of triggered price /// @return triggeredPriceValue The token triggered price. (1eth equivalent to (price) token) /// @return triggeredAvgPrice Average price /// @return triggeredSigmaSQ The square of the volatility (18 decimal places). The current implementation assumes that /// the volatility cannot exceed 1. Correspondingly, when the return value is equal to 999999999999996447, /// it means that the volatility has exceeded the range that can be expressed function latestPriceAndTriggeredPriceInfo(address tokenAddress) override external view returns ( uint latestPriceBlockNumber, uint latestPriceValue, uint triggeredPriceBlockNumber, uint triggeredPriceValue, uint triggeredAvgPrice, uint triggeredSigmaSQ ) { (latestPriceBlockNumber, latestPriceValue) = latestPrice(tokenAddress); ( triggeredPriceBlockNumber, triggeredPriceValue, triggeredAvgPrice, triggeredSigmaSQ ) = triggeredPriceInfo(tokenAddress); } /// @dev Returns lastPriceList and triggered price info /// @param tokenAddress Destination token address /// @param count The number of prices that want to return /// @return prices An array which length is num * 2, each two element expresses one price like blockNumber|price /// @return triggeredPriceBlockNumber The block number of triggered price /// @return triggeredPriceValue The token triggered price. (1eth equivalent to (price) token) /// @return triggeredAvgPrice Average price /// @return triggeredSigmaSQ The square of the volatility (18 decimal places). The current implementation assumes that /// the volatility cannot exceed 1. Correspondingly, when the return value is equal to 999999999999996447, /// it means that the volatility has exceeded the range that can be expressed function lastPriceListAndTriggeredPriceInfo(address tokenAddress, uint count) override external view returns ( uint[] memory prices, uint triggeredPriceBlockNumber, uint triggeredPriceValue, uint triggeredAvgPrice, uint triggeredSigmaSQ ) { prices = lastPriceList(tokenAddress, count); ( triggeredPriceBlockNumber, triggeredPriceValue, triggeredAvgPrice, triggeredSigmaSQ ) = triggeredPriceInfo(tokenAddress); } /// @dev Get the latest trigger price. (token and ntoken) /// @param tokenAddress Destination token address /// @return blockNumber The block number of price /// @return price The token price. (1eth equivalent to (price) token) /// @return ntokenBlockNumber The block number of ntoken price /// @return ntokenPrice The ntoken price. (1eth equivalent to (price) ntoken) function triggeredPrice2(address tokenAddress) override external view returns ( uint blockNumber, uint price, uint ntokenBlockNumber, uint ntokenPrice ) { (blockNumber, price) = triggeredPrice(tokenAddress); (ntokenBlockNumber, ntokenPrice) = triggeredPrice(_addressCache[tokenAddress]); } /// @dev Get the full information of latest trigger price. (token and ntoken) /// @param tokenAddress Destination token address /// @return blockNumber The block number of price /// @return price The token price. (1eth equivalent to (price) token) /// @return avgPrice Average price /// @return sigmaSQ The square of the volatility (18 decimal places). The current implementation assumes that /// the volatility cannot exceed 1. Correspondingly, when the return value is equal to 999999999999996447, /// it means that the volatility has exceeded the range that can be expressed /// @return ntokenBlockNumber The block number of ntoken price /// @return ntokenPrice The ntoken price. (1eth equivalent to (price) ntoken) /// @return ntokenAvgPrice Average price of ntoken /// @return ntokenSigmaSQ The square of the volatility (18 decimal places). The current implementation assumes that /// the volatility cannot exceed 1. Correspondingly, when the return value is equal to 999999999999996447, /// it means that the volatility has exceeded the range that can be expressed function triggeredPriceInfo2(address tokenAddress) override external view returns ( uint blockNumber, uint price, uint avgPrice, uint sigmaSQ, uint ntokenBlockNumber, uint ntokenPrice, uint ntokenAvgPrice, uint ntokenSigmaSQ ) { (blockNumber, price, avgPrice, sigmaSQ) = triggeredPriceInfo(tokenAddress); ( ntokenBlockNumber, ntokenPrice, ntokenAvgPrice, ntokenSigmaSQ ) = triggeredPriceInfo(_addressCache[tokenAddress]); } /// @dev Get the latest effective price. (token and ntoken) /// @param tokenAddress Destination token address /// @return blockNumber The block number of price /// @return price The token price. (1eth equivalent to (price) token) /// @return ntokenBlockNumber The block number of ntoken price /// @return ntokenPrice The ntoken price. (1eth equivalent to (price) ntoken) function latestPrice2(address tokenAddress) override external view returns ( uint blockNumber, uint price, uint ntokenBlockNumber, uint ntokenPrice ) { (blockNumber, price) = latestPrice(tokenAddress); (ntokenBlockNumber, ntokenPrice) = latestPrice(_addressCache[tokenAddress]); } /* ========== Tools and methods ========== */ /// @dev Encode the uint value as a floating-point representation in the form of fraction * 16 ^ exponent /// @param value Destination uint value /// @return float format function encodeFloat(uint value) private pure returns (uint56) { uint exponent = 0; while (value > 0x3FFFFFFFFFFFF) { value >>= 4; ++exponent; } return uint56((value << 6) | exponent); } /// @dev Decode the floating-point representation of fraction * 16 ^ exponent to uint /// @param floatValue fraction value /// @return decode format function decodeFloat(uint56 floatValue) private pure returns (uint) { return (uint(floatValue) >> 6) << ((uint(floatValue) & 0x3F) << 2); } }
Set the ntokenAddress from tokenAddress, if ntokenAddress is equals to tokenAddress, means the token is disabled tokenAddress Destination token address ntokenAddress The ntoken address
function setNTokenAddress(address tokenAddress, address ntokenAddress) override external onlyGovernance { _addressCache[tokenAddress] = ntokenAddress; }
52,661
pragma solidity ^0.6.0; import "./Crowdsale.sol"; import "./KycContract.sol"; /** @title MyTokenSale contract * @author Chris Ball * @notice This contract handles the Crowdsale of MyToken ERC20 tokens */ contract MyTokenSale is Crowdsale { KycContract kyc; constructor( uint256 rate, // rate in TKNbits address payable wallet, IERC20 token, KycContract _kyc ) Crowdsale(rate, wallet, token) public { kyc = _kyc; } /** @notice function validates whether the address purchasing tokens is currently whitelisted * @dev this function overrides the Crowdsale function of the same name. * @param beneficiary address purchasing tokens * @param weiAmount amount of tokens being purchased in wei */ function _preValidatePurchase(address beneficiary, uint256 weiAmount) internal view override { super._preValidatePurchase(beneficiary, weiAmount); require(kyc.IsCustomerValid(msg.sender), "Please complete the Customer Information form. Purchanse is not allowed."); } }
function validates whether the address purchasing tokens is currently whitelisted this function overrides the Crowdsale function of the same name. beneficiary address purchasing tokens weiAmount amount of tokens being purchased in wei/
function _preValidatePurchase(address beneficiary, uint256 weiAmount) internal view override { super._preValidatePurchase(beneficiary, weiAmount); require(kyc.IsCustomerValid(msg.sender), "Please complete the Customer Information form. Purchanse is not allowed."); }
7,246,190
pragma solidity ^0.5.2; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @return the address of the owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner()); _; } /** * @return true if `msg.sender` is the owner of the contract. */ function isOwner() public view returns (bool) { return msg.sender == _owner; } /** * @dev Allows the current owner to relinquish control of the contract. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. * @notice Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0)); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } /** * @title ERC20 interface * @dev see https://eips.ethereum.org/EIPS/eip-20 */ interface IERC20 { function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } library StringLib { /// @notice converts bytes32 into a string. /// @param bytesToConvert bytes32 array to convert function bytes32ToString(bytes32 bytesToConvert) internal pure returns (string memory) { bytes memory bytesArray = new bytes(32); for (uint256 i; i < 32; i++) { bytesArray[i] = bytesToConvert[i]; } return string(bytesArray); } }/* Copyright 2017-2019 Phillip A. Elsasser Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /* Copyright 2017-2019 Phillip A. Elsasser Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /* Copyright 2017-2019 Phillip A. Elsasser Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /* Copyright 2017-2019 Phillip A. Elsasser Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /// @title Math function library with overflow protection inspired by Open Zeppelin library MathLib { int256 constant INT256_MIN = int256((uint256(1) << 255)); int256 constant INT256_MAX = int256(~((uint256(1) << 255))); function multiply(uint256 a, uint256 b) pure internal returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "MathLib: multiplication overflow"); return c; } function divideFractional( uint256 a, uint256 numerator, uint256 denominator ) pure internal returns (uint256) { return multiply(a, numerator) / denominator; } function subtract(uint256 a, uint256 b) pure internal returns (uint256) { require(b <= a, "MathLib: subtraction overflow"); return a - b; } function add(uint256 a, uint256 b) pure internal returns (uint256) { uint256 c = a + b; require(c >= a, "MathLib: addition overflow"); return c; } /// @notice determines the amount of needed collateral for a given position (qty and price) /// @param priceFloor lowest price the contract is allowed to trade before expiration /// @param priceCap highest price the contract is allowed to trade before expiration /// @param qtyMultiplier multiplier for qty from base units /// @param longQty qty to redeem /// @param shortQty qty to redeem /// @param price of the trade function calculateCollateralToReturn( uint priceFloor, uint priceCap, uint qtyMultiplier, uint longQty, uint shortQty, uint price ) pure internal returns (uint) { uint neededCollateral = 0; uint maxLoss; if (longQty > 0) { // calculate max loss from entry price to floor if (price <= priceFloor) { maxLoss = 0; } else { maxLoss = subtract(price, priceFloor); } neededCollateral = multiply(multiply(maxLoss, longQty), qtyMultiplier); } if (shortQty > 0) { // calculate max loss from entry price to ceiling; if (price >= priceCap) { maxLoss = 0; } else { maxLoss = subtract(priceCap, price); } neededCollateral = add(neededCollateral, multiply(multiply(maxLoss, shortQty), qtyMultiplier)); } return neededCollateral; } /// @notice determines the amount of needed collateral for minting a long and short position token function calculateTotalCollateral( uint priceFloor, uint priceCap, uint qtyMultiplier ) pure internal returns (uint) { return multiply(subtract(priceCap, priceFloor), qtyMultiplier); } /// @notice calculates the fee in terms of base units of the collateral token per unit pair minted. function calculateFeePerUnit( uint priceFloor, uint priceCap, uint qtyMultiplier, uint feeInBasisPoints ) pure internal returns (uint) { uint midPrice = add(priceCap, priceFloor) / 2; return multiply(multiply(midPrice, qtyMultiplier), feeInBasisPoints) / 10000; } } /* Copyright 2017-2019 Phillip A. Elsasser Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /** * @title SafeMath * @dev Unsigned math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two unsigned integers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // 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-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * https://eips.ethereum.org/EIPS/eip-20 * Originally based on code by FirstBlood: * https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol * * This implementation emits additional Approval events, allowing applications to reconstruct the allowance status for * all accounts just by listening to said events. Note that this isn't required by the specification, and other * compliant implementations may not do it. */ contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; uint256 private _totalSupply; /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev Gets the balance of the specified address. * @param owner The address to query the balance of. * @return A uint256 representing the amount owned by the passed address. */ function balanceOf(address owner) public view returns (uint256) { return _balances[owner]; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param owner address The address which owns the funds. * @param spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowed[owner][spender]; } /** * @dev Transfer token to a specified address * @param to The address to transfer to. * @param value The amount to be transferred. */ function transfer(address to, uint256 value) public returns (bool) { _transfer(msg.sender, to, value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param spender The address which will spend the funds. * @param value The amount of tokens to be spent. */ function approve(address spender, uint256 value) public returns (bool) { _approve(msg.sender, spender, value); return true; } /** * @dev Transfer tokens from one address to another. * Note that while this function emits an Approval event, this is not required as per the specification, * and other compliant implementations may not emit the event. * @param from address The address which you want to send tokens from * @param to address The address which you want to transfer to * @param value uint256 the amount of tokens to be transferred */ function transferFrom(address from, address to, uint256 value) public returns (bool) { _transfer(from, to, value); _approve(from, msg.sender, _allowed[from][msg.sender].sub(value)); return true; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when _allowed[msg.sender][spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * Emits an Approval event. * @param spender The address which will spend the funds. * @param addedValue The amount of tokens to increase the allowance by. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(msg.sender, spender, _allowed[msg.sender][spender].add(addedValue)); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when _allowed[msg.sender][spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * Emits an Approval event. * @param spender The address which will spend the funds. * @param subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(msg.sender, spender, _allowed[msg.sender][spender].sub(subtractedValue)); return true; } /** * @dev Transfer token for a specified addresses * @param from The address to transfer from. * @param to The address to transfer to. * @param value The amount to be transferred. */ function _transfer(address from, address to, uint256 value) internal { require(to != address(0)); _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(from, to, value); } /** * @dev Internal function that mints an amount of the token and assigns it to * an account. This encapsulates the modification of balances such that the * proper events are emitted. * @param account The account that will receive the created tokens. * @param value The amount that will be created. */ function _mint(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.add(value); _balances[account] = _balances[account].add(value); emit Transfer(address(0), account, value); } /** * @dev Internal function that burns an amount of the token of a given * account. * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burn(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); } /** * @dev Approve an address to spend another addresses' tokens. * @param owner The address that owns the tokens. * @param spender The address that will spend the tokens. * @param value The number of tokens that can be spent. */ function _approve(address owner, address spender, uint256 value) internal { require(spender != address(0)); require(owner != address(0)); _allowed[owner][spender] = value; emit Approval(owner, spender, value); } /** * @dev Internal function that burns an amount of the token of a given * account, deducting from the sender's allowance for said account. Uses the * internal burn function. * Emits an Approval event (reflecting the reduced allowance). * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burnFrom(address account, uint256 value) internal { _burn(account, value); _approve(account, msg.sender, _allowed[account][msg.sender].sub(value)); } } /// @title Position Token /// @notice A token that represents a claim to a collateral pool and a short or long position. /// The collateral pool acts as the owner of this contract and controls minting and redemption of these /// tokens based on locked collateral in the pool. /// NOTE: We eventually can move all of this logic into a library to avoid deploying all of the logic /// every time a new market contract is deployed. /// @author Phil Elsasser <[email protected]> contract PositionToken is ERC20, Ownable { string public name; string public symbol; uint8 public decimals; MarketSide public MARKET_SIDE; // 0 = Long, 1 = Short enum MarketSide { Long, Short} constructor( string memory tokenName, string memory tokenSymbol, uint8 marketSide ) public { name = tokenName; symbol = tokenSymbol; decimals = 5; MARKET_SIDE = MarketSide(marketSide); } /// @dev Called by our MarketContract (owner) to create a long or short position token. These tokens are minted, /// and then transferred to our recipient who is the party who is minting these tokens. The collateral pool /// is the only caller (acts as the owner) because collateral must be deposited / locked prior to minting of new /// position tokens /// @param qtyToMint quantity of position tokens to mint (in base units) /// @param recipient the person minting and receiving these position tokens. function mintAndSendToken( uint256 qtyToMint, address recipient ) external onlyOwner { _mint(recipient, qtyToMint); } /// @dev Called by our MarketContract (owner) when redemption occurs. This means that either a single user is redeeming /// both short and long tokens in order to claim their collateral, or the contract has settled, and only a single /// side of the tokens are needed to redeem (handled by the collateral pool) /// @param qtyToRedeem quantity of tokens to burn (remove from supply / circulation) /// @param redeemer the person redeeming these tokens (who are we taking the balance from) function redeemToken( uint256 qtyToRedeem, address redeemer ) external onlyOwner { _burn(redeemer, qtyToRedeem); } } /// @title MarketContract base contract implement all needed functionality for trading. /// @notice this is the abstract base contract that all contracts should inherit from to /// implement different oracle solutions. /// @author Phil Elsasser <[email protected]> contract MarketContract is Ownable { using StringLib for *; string public CONTRACT_NAME; address public COLLATERAL_TOKEN_ADDRESS; address public COLLATERAL_POOL_ADDRESS; uint public PRICE_CAP; uint public PRICE_FLOOR; uint public PRICE_DECIMAL_PLACES; // how to convert the pricing from decimal format (if valid) to integer uint public QTY_MULTIPLIER; // multiplier corresponding to the value of 1 increment in price to token base units uint public COLLATERAL_PER_UNIT; // required collateral amount for the full range of outcome tokens uint public COLLATERAL_TOKEN_FEE_PER_UNIT; uint public MKT_TOKEN_FEE_PER_UNIT; uint public EXPIRATION; uint public SETTLEMENT_DELAY = 1 days; address public LONG_POSITION_TOKEN; address public SHORT_POSITION_TOKEN; // state variables uint public lastPrice; uint public settlementPrice; uint public settlementTimeStamp; bool public isSettled = false; // events event UpdatedLastPrice(uint256 price); event ContractSettled(uint settlePrice); /// @param contractNames bytes32 array of names /// contractName name of the market contract /// longTokenSymbol symbol for the long token /// shortTokenSymbol symbol for the short token /// @param baseAddresses array of 2 addresses needed for our contract including: /// ownerAddress address of the owner of these contracts. /// collateralTokenAddress address of the ERC20 token that will be used for collateral and pricing /// collateralPoolAddress address of our collateral pool contract /// @param contractSpecs array of unsigned integers including: /// floorPrice minimum tradeable price of this contract, contract enters settlement if breached /// capPrice maximum tradeable price of this contract, contract enters settlement if breached /// priceDecimalPlaces number of decimal places to convert our queried price from a floating point to /// an integer /// qtyMultiplier multiply traded qty by this value from base units of collateral token. /// feeInBasisPoints fee amount in basis points (Collateral token denominated) for minting. /// mktFeeInBasisPoints fee amount in basis points (MKT denominated) for minting. /// expirationTimeStamp seconds from epoch that this contract expires and enters settlement constructor( bytes32[3] memory contractNames, address[3] memory baseAddresses, uint[7] memory contractSpecs ) public { PRICE_FLOOR = contractSpecs[0]; PRICE_CAP = contractSpecs[1]; require(PRICE_CAP > PRICE_FLOOR, "PRICE_CAP must be greater than PRICE_FLOOR"); PRICE_DECIMAL_PLACES = contractSpecs[2]; QTY_MULTIPLIER = contractSpecs[3]; EXPIRATION = contractSpecs[6]; require(EXPIRATION > now, "EXPIRATION must be in the future"); require(QTY_MULTIPLIER != 0,"QTY_MULTIPLIER cannot be 0"); COLLATERAL_TOKEN_ADDRESS = baseAddresses[1]; COLLATERAL_POOL_ADDRESS = baseAddresses[2]; COLLATERAL_PER_UNIT = MathLib.calculateTotalCollateral(PRICE_FLOOR, PRICE_CAP, QTY_MULTIPLIER); COLLATERAL_TOKEN_FEE_PER_UNIT = MathLib.calculateFeePerUnit( PRICE_FLOOR, PRICE_CAP, QTY_MULTIPLIER, contractSpecs[4] ); MKT_TOKEN_FEE_PER_UNIT = MathLib.calculateFeePerUnit( PRICE_FLOOR, PRICE_CAP, QTY_MULTIPLIER, contractSpecs[5] ); // create long and short tokens CONTRACT_NAME = contractNames[0].bytes32ToString(); PositionToken longPosToken = new PositionToken( "MARKET Protocol Long Position Token", contractNames[1].bytes32ToString(), uint8(PositionToken.MarketSide.Long) ); PositionToken shortPosToken = new PositionToken( "MARKET Protocol Short Position Token", contractNames[2].bytes32ToString(), uint8(PositionToken.MarketSide.Short) ); LONG_POSITION_TOKEN = address(longPosToken); SHORT_POSITION_TOKEN = address(shortPosToken); transferOwnership(baseAddresses[0]); } /* // EXTERNAL - onlyCollateralPool METHODS */ /// @notice called only by our collateral pool to create long and short position tokens /// @param qtyToMint qty in base units of how many short and long tokens to mint /// @param minter address of minter to receive tokens function mintPositionTokens( uint256 qtyToMint, address minter ) external onlyCollateralPool { // mint and distribute short and long position tokens to our caller PositionToken(LONG_POSITION_TOKEN).mintAndSendToken(qtyToMint, minter); PositionToken(SHORT_POSITION_TOKEN).mintAndSendToken(qtyToMint, minter); } /// @notice called only by our collateral pool to redeem long position tokens /// @param qtyToRedeem qty in base units of how many tokens to redeem /// @param redeemer address of person redeeming tokens function redeemLongToken( uint256 qtyToRedeem, address redeemer ) external onlyCollateralPool { // mint and distribute short and long position tokens to our caller PositionToken(LONG_POSITION_TOKEN).redeemToken(qtyToRedeem, redeemer); } /// @notice called only by our collateral pool to redeem short position tokens /// @param qtyToRedeem qty in base units of how many tokens to redeem /// @param redeemer address of person redeeming tokens function redeemShortToken( uint256 qtyToRedeem, address redeemer ) external onlyCollateralPool { // mint and distribute short and long position tokens to our caller PositionToken(SHORT_POSITION_TOKEN).redeemToken(qtyToRedeem, redeemer); } /* // Public METHODS */ /// @notice checks to see if a contract is settled, and that the settlement delay has passed function isPostSettlementDelay() public view returns (bool) { return isSettled && (now >= (settlementTimeStamp + SETTLEMENT_DELAY)); } /* // PRIVATE METHODS */ /// @dev checks our last query price to see if our contract should enter settlement due to it being past our // expiration date or outside of our tradeable ranges. function checkSettlement() internal { require(!isSettled, "Contract is already settled"); // already settled. uint newSettlementPrice; if (now > EXPIRATION) { // note: miners can cheat this by small increments of time (minutes, not hours) isSettled = true; // time based expiration has occurred. newSettlementPrice = lastPrice; } else if (lastPrice >= PRICE_CAP) { // price is greater or equal to our cap, settle to CAP price isSettled = true; newSettlementPrice = PRICE_CAP; } else if (lastPrice <= PRICE_FLOOR) { // price is lesser or equal to our floor, settle to FLOOR price isSettled = true; newSettlementPrice = PRICE_FLOOR; } if (isSettled) { settleContract(newSettlementPrice); } } /// @dev records our final settlement price and fires needed events. /// @param finalSettlementPrice final query price at time of settlement function settleContract(uint finalSettlementPrice) internal { settlementTimeStamp = now; settlementPrice = finalSettlementPrice; emit ContractSettled(finalSettlementPrice); } /// @notice only able to be called directly by our collateral pool which controls the position tokens /// for this contract! modifier onlyCollateralPool { require(msg.sender == COLLATERAL_POOL_ADDRESS, "Only callable from the collateral pool"); _; } } /// @title MarketContractMPX - a MarketContract designed to be used with our internal oracle service /// @author Phil Elsasser <[email protected]> contract MarketContractMPX is MarketContract { address public ORACLE_HUB_ADDRESS; string public ORACLE_URL; string public ORACLE_STATISTIC; /// @param contractNames bytes32 array of names /// contractName name of the market contract /// longTokenSymbol symbol for the long token /// shortTokenSymbol symbol for the short token /// @param baseAddresses array of 2 addresses needed for our contract including: /// ownerAddress address of the owner of these contracts. /// collateralTokenAddress address of the ERC20 token that will be used for collateral and pricing /// collateralPoolAddress address of our collateral pool contract /// @param oracleHubAddress address of our oracle hub providing the callbacks /// @param contractSpecs array of unsigned integers including: /// floorPrice minimum tradeable price of this contract, contract enters settlement if breached /// capPrice maximum tradeable price of this contract, contract enters settlement if breached /// priceDecimalPlaces number of decimal places to convert our queried price from a floating point to /// an integer /// qtyMultiplier multiply traded qty by this value from base units of collateral token. /// feeInBasisPoints fee amount in basis points (Collateral token denominated) for minting. /// mktFeeInBasisPoints fee amount in basis points (MKT denominated) for minting. /// expirationTimeStamp seconds from epoch that this contract expires and enters settlement /// @param oracleURL url of data /// @param oracleStatistic statistic type (lastPrice, vwap, etc) constructor( bytes32[3] memory contractNames, address[3] memory baseAddresses, address oracleHubAddress, uint[7] memory contractSpecs, string memory oracleURL, string memory oracleStatistic ) MarketContract( contractNames, baseAddresses, contractSpecs ) public { ORACLE_URL = oracleURL; ORACLE_STATISTIC = oracleStatistic; ORACLE_HUB_ADDRESS = oracleHubAddress; } /* // PUBLIC METHODS */ /// @dev called only by our oracle hub when a new price is available provided by our oracle. /// @param price lastPrice provided by the oracle. function oracleCallBack(uint256 price) public onlyOracleHub { require(!isSettled); lastPrice = price; emit UpdatedLastPrice(price); checkSettlement(); // Verify settlement at expiration or requested early settlement. } /// @dev allows us to arbitrate a settlement price by updating the settlement value, and resetting the /// delay for funds to be released. Could also be used to allow us to force a contract into early settlement /// if a dispute arises that we believe is best resolved by early settlement. /// @param price settlement price function arbitrateSettlement(uint256 price) public onlyOwner { require(price >= PRICE_FLOOR && price <= PRICE_CAP, "arbitration price must be within contract bounds"); lastPrice = price; emit UpdatedLastPrice(price); settleContract(price); isSettled = true; } /// @dev allows calls only from the oracle hub. modifier onlyOracleHub() { require(msg.sender == ORACLE_HUB_ADDRESS, "only callable by the oracle hub"); _; } /// @dev allows for the owner of the contract to change the oracle hub address if needed function setOracleHubAddress(address oracleHubAddress) public onlyOwner { require(oracleHubAddress != address(0), "cannot set oracleHubAddress to null address"); ORACLE_HUB_ADDRESS = oracleHubAddress; } } /* Copyright 2017-2019 Phillip A. Elsasser Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ contract MarketContractRegistryInterface { function addAddressToWhiteList(address contractAddress) external; function isAddressWhiteListed(address contractAddress) external view returns (bool); } /// @title MarketContractFactoryMPX /// @author Phil Elsasser <[email protected]> contract MarketContractFactoryMPX is Ownable { address public marketContractRegistry; address public oracleHub; address public MARKET_COLLATERAL_POOL; event MarketContractCreated(address indexed creator, address indexed contractAddress); /// @dev deploys our factory and ties it to the supplied registry address /// @param registryAddress - address of our MARKET registry /// @param collateralPoolAddress - address of our MARKET Collateral pool /// @param oracleHubAddress - address of the MPX oracle constructor( address registryAddress, address collateralPoolAddress, address oracleHubAddress ) public { require(registryAddress != address(0), "registryAddress can not be null"); require(collateralPoolAddress != address(0), "collateralPoolAddress can not be null"); require(oracleHubAddress != address(0), "oracleHubAddress can not be null"); marketContractRegistry = registryAddress; MARKET_COLLATERAL_POOL = collateralPoolAddress; oracleHub = oracleHubAddress; } /// @dev Deploys a new instance of a market contract and adds it to the whitelist. /// @param contractNames bytes32 array of names /// contractName name of the market contract /// longTokenSymbol symbol for the long token /// shortTokenSymbol symbol for the short token /// @param collateralTokenAddress address of the ERC20 token that will be used for collateral and pricing /// @param contractSpecs array of unsigned integers including: /// floorPrice minimum tradeable price of this contract, contract enters settlement if breached /// capPrice maximum tradeable price of this contract, contract enters settlement if breached /// priceDecimalPlaces number of decimal places to convert our queried price from a floating point to /// an integer /// qtyMultiplier multiply traded qty by this value from base units of collateral token. /// feeInBasisPoints fee amount in basis points (Collateral token denominated) for minting. /// mktFeeInBasisPoints fee amount in basis points (MKT denominated) for minting. /// expirationTimeStamp seconds from epoch that this contract expires and enters settlement /// @param oracleURL url of data /// @param oracleStatistic statistic type (lastPrice, vwap, etc) function deployMarketContractMPX( bytes32[3] calldata contractNames, address collateralTokenAddress, uint[7] calldata contractSpecs, string calldata oracleURL, string calldata oracleStatistic ) external onlyOwner { MarketContractMPX mktContract = new MarketContractMPX( contractNames, [ owner(), collateralTokenAddress, MARKET_COLLATERAL_POOL ], oracleHub, contractSpecs, oracleURL, oracleStatistic ); MarketContractRegistryInterface(marketContractRegistry).addAddressToWhiteList(address(mktContract)); emit MarketContractCreated(msg.sender, address(mktContract)); } /// @dev allows for the owner to set the desired registry for contract creation. /// @param registryAddress desired registry address. function setRegistryAddress(address registryAddress) external onlyOwner { require(registryAddress != address(0), "registryAddress can not be null"); marketContractRegistry = registryAddress; } /// @dev allows for the owner to set a new oracle hub address which is responsible for providing data to our /// contracts /// @param oracleHubAddress address of the oracle hub, cannot be null address function setOracleHubAddress(address oracleHubAddress) external onlyOwner { require(oracleHubAddress != address(0), "oracleHubAddress can not be null"); oracleHub = oracleHubAddress; } }
Multiplies two unsigned integers, reverts on overflow./ 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-solidity/pull/522
function calculateTotalCollateral( uint priceFloor, uint priceCap, uint qtyMultiplier ) pure internal returns (uint) } function calculateFeePerUnit( uint priceFloor, uint priceCap, uint qtyMultiplier, uint feeInBasisPoints ) pure internal returns (uint) } } Copyright 2017-2019 Phillip A. Elsasser Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; }
6,367,433
// Based on https://github.com/HausDAO/MinionSummoner/blob/main/MinionFactory.sol import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity 0.7.5; interface IERC721 { // brief interface for minion erc721 token txs function safeTransferFrom( address from, address to, uint256 tokenId ) external; } interface IERC1155 { // brief interface for minion erc1155 token txs function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes calldata data ) external; } interface IERC721Receiver { // Safely receive ERC721 tokens function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } interface IERC1155PartialReceiver { // Safely receive ERC1155 tokens function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external returns (bytes4); // ERC1155 batch receive not implemented in this escrow contract } interface IMOLOCH { // brief interface for moloch dao v2 function depositToken() external view returns (address); function tokenWhitelist(address token) external view returns (bool); function getProposalFlags(uint256 proposalId) external view returns (bool[6] memory); function members(address user) external view returns ( address, uint256, uint256, bool, uint256, uint256 ); function userTokenBalances(address user, address token) external view returns (uint256); function cancelProposal(uint256 proposalId) external; function submitProposal( address applicant, uint256 sharesRequested, uint256 lootRequested, uint256 tributeOffered, address tributeToken, uint256 paymentRequested, address paymentToken, string calldata details ) external returns (uint256); function withdrawBalance(address token, uint256 amount) external; } /// @title EscrowMinion - Token escrow for ERC20, ERC721, ERC1155 tokens tied to Moloch DAO proposals /// @dev Ties arbitrary token escrow to a Moloch DAO proposal /// Can be used to tribute tokens in exchange for shares, loot, or DAO funds /// /// Any number and combinations of tokens can be escrowed /// If any tokens become untransferable, the rest of the tokens in escrow can be released individually /// /// If proposal passes, tokens become withdrawable to destination - usually a Gnosis Safe or Minion /// If proposal fails, or cancelled before sponsorship, token become withdrawable to applicant /// /// If any tokens become untransferable, the rest of the tokens in escrow can be released individually /// /// @author Isaac Patka, Dekan Brown contract EscrowMinion is IERC721Receiver, ReentrancyGuard, IERC1155PartialReceiver { using Address for address; /*Address library provides isContract function*/ using SafeERC20 for IERC20; /*SafeERC20 automatically checks optional return*/ // Track token tribute type to use so we know what transfer interface to use enum TributeType { ERC20, ERC721, ERC1155 } // Track the balance and withdrawl state for each token struct EscrowBalance { uint256[3] typesTokenIdsAmounts; /*Tribute type | ID (for 721, 1155) | Amount (for 20, 1155)*/ address tokenAddress; /* Address of tribute token */ bool executed; /* Track if this specific token has been withdrawn*/ } // Store destination vault and proposer for each proposal struct TributeEscrowAction { address vaultAddress; /*Destination for escrow tokens - must be token receiver*/ address proposer; /*Applicant address*/ } mapping(address => mapping(uint256 => TributeEscrowAction)) public actions; /*moloch => proposalId => Action*/ mapping(address => mapping(uint256 => mapping(uint256 => EscrowBalance))) public escrowBalances; /* moloch => proposal => token index => balance */ /* * Moloch proposal ID * Applicant addr * Moloch addr * escrow token addr * escrow token types * escrow token IDs (721, 1155) * amounts (20, 1155) * destination for escrow */ event ProposeAction( uint256 proposalId, address proposer, address moloch, address[] tokens, uint256[] types, uint256[] tokenIds, uint256[] amounts, address destinationVault ); event ExecuteAction(uint256 proposalId, address executor, address moloch); event ActionCanceled(uint256 proposalId, address moloch); // internal tracking for destinations to ensure escrow can't get stuck // Track if already checked so we don't do it multiple times per proposal mapping(TributeType => uint256) internal destinationChecked_; uint256 internal constant NOTCHECKED_ = 1; uint256 internal constant CHECKED_ = 2; /// @dev Construtor sets the status of the destination checkers constructor() { // Follow a similar pattern to reentency guard from OZ destinationChecked_[TributeType.ERC721] = NOTCHECKED_; destinationChecked_[TributeType.ERC1155] = NOTCHECKED_; } // Reset the destination checkers for the next proposal modifier safeDestination() { _; destinationChecked_[TributeType.ERC721] = NOTCHECKED_; destinationChecked_[TributeType.ERC1155] = NOTCHECKED_; } // Safely receive ERC721s function onERC721Received( address, address, uint256, bytes calldata ) external pure override returns (bytes4) { return bytes4( keccak256("onERC721Received(address,address,uint256,bytes)") ); } // Safely receive ERC1155s function onERC1155Received( address, address, uint256, uint256, bytes calldata ) external pure override returns (bytes4) { return bytes4( keccak256( "onERC1155Received(address,address,uint256,uint256,bytes)" ) ); } /** * @dev internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param _operator address representing the entity calling the function * @param _from address representing the previous owner of the given token ID * @param _to target address that will receive the tokens * @param _tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address _operator, address _from, address _to, uint256 _tokenId, bytes memory _data ) internal returns (bool) { if (!_to.isContract()) { return true; } bytes memory _returndata = _to.functionCall( abi.encodeWithSelector( IERC721Receiver(_to).onERC721Received.selector, _operator, _from, _tokenId, _data ), "ERC721: transfer to non ERC721Receiver implementer" ); bytes4 _retval = abi.decode(_returndata, (bytes4)); return (_retval == IERC721Receiver(_to).onERC721Received.selector); } /** * @dev internal function to invoke {IERC1155-onERC1155Received} on a target address. * The call is not executed if the target address is not a contract. * * @param _operator address representing the entity calling the function * @param _from address representing the previous owner of the given token ID * @param _to target address that will receive the tokens * @param _id uint256 ID of the token to be transferred * @param _amount uint256 amount of token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC1155Received( address _operator, address _from, address _to, uint256 _id, uint256 _amount, bytes memory _data ) internal returns (bool) { if (!_to.isContract()) { return true; } bytes memory _returndata = _to.functionCall( abi.encodeWithSelector( IERC1155PartialReceiver(_to).onERC1155Received.selector, _operator, _from, _id, _amount, _data ), "ERC1155: transfer to non ERC1155Receiver implementer" ); bytes4 _retval = abi.decode(_returndata, (bytes4)); return (_retval == IERC1155PartialReceiver(_to).onERC1155Received.selector); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on both vault & applicant * Ensures tokens cannot get stuck here due to interface issue * * @param _vaultAddress Destination for tokens on successful proposal * @param _applicantAddress Destination for tokens on failed proposal */ function checkERC721Recipients(address _vaultAddress, address _applicantAddress) internal { require( _checkOnERC721Received( address(this), address(this), _vaultAddress, 0, "" ), "!ERC721" ); require( _checkOnERC721Received( address(this), address(this), _applicantAddress, 0, "" ), "!ERC721" ); // Mark 721 as checked so we don't check again during this tx destinationChecked_[TributeType.ERC721] = CHECKED_; } /** * @dev Internal function to invoke {IERC1155Receiver-onERC1155Received} on both vault & applicant * Ensures tokens cannot get stuck here due to interface issue * * @param _vaultAddress Destination for tokens on successful proposal * @param _applicantAddress Destination for tokens on failed proposal */ function checkERC1155Recipients(address _vaultAddress, address _applicantAddress) internal { require( _checkOnERC1155Received( address(this), address(this), _vaultAddress, 0, 0, "" ), "!ERC1155" ); require( _checkOnERC1155Received( address(this), address(this), _applicantAddress, 0, 0, "" ), "!ERC1155" ); // Mark 1155 as checked so we don't check again during this tx destinationChecked_[TributeType.ERC1155] = CHECKED_; } /** * @dev Internal function to move token into or out of escrow depending on type * Only valid for 721, 1155, 20 * * @param _tokenAddress Token to escrow * @param _typesTokenIdsAmounts Type: 0-20, 1-721, 2-1155 TokenIds: for 721, 1155 Amounts: for 20, 1155 * @param _from Sender (applicant or this) * @param _to Recipient (this or applicant or destination) */ function doTransfer( address _tokenAddress, uint256[3] memory _typesTokenIdsAmounts, address _from, address _to ) internal { // Use 721 interface for 721 if (_typesTokenIdsAmounts[0] == uint256(TributeType.ERC721)) { IERC721 _erc721 = IERC721(_tokenAddress); _erc721.safeTransferFrom(_from, _to, _typesTokenIdsAmounts[1]); // Use 20 interface for 20 } else if (_typesTokenIdsAmounts[0] == uint256(TributeType.ERC20)) { // Fail if attempt to send 0 tokens require(_typesTokenIdsAmounts[2] != 0, "!amount"); IERC20 _erc20 = IERC20(_tokenAddress); if (_from == address(this)) { _erc20.safeTransfer(_to, _typesTokenIdsAmounts[2]); } else { _erc20.safeTransferFrom(_from, _to, _typesTokenIdsAmounts[2]); } // use 1155 interface for 1155 } else if (_typesTokenIdsAmounts[0] == uint256(TributeType.ERC1155)) { // Fail if attempt to send 0 tokens require(_typesTokenIdsAmounts[2] != 0, "!amount"); IERC1155 _erc1155 = IERC1155(_tokenAddress); _erc1155.safeTransferFrom( _from, _to, _typesTokenIdsAmounts[1], _typesTokenIdsAmounts[2], "" ); } else { revert("Invalid type"); } } /** * @dev Internal function to move token into escrow on proposal * * @param _molochAddress Moloch to read proposal data from * @param _tokenAddresses Addresses of tokens to escrow * @param _typesTokenIdsAmounts ERC20, 721, or 1155 | id for 721, 1155 | amount for 20, 1155 * @param _vaultAddress Addresses of destination of proposal successful * @param _proposalId ID of Moloch proposal for this escrow */ function processTributeProposal( address _molochAddress, address[] memory _tokenAddresses, uint256[3][] memory _typesTokenIdsAmounts, address _vaultAddress, uint256 _proposalId ) internal { // Initiate arrays to flatten 2d array for event uint256[] memory _types = new uint256[](_tokenAddresses.length); uint256[] memory _tokenIds = new uint256[](_tokenAddresses.length); uint256[] memory _amounts = new uint256[](_tokenAddresses.length); // Store proposal metadata actions[_molochAddress][_proposalId] = TributeEscrowAction({ vaultAddress: _vaultAddress, proposer: msg.sender }); // Store escrow data, check destinations, and do transfers for (uint256 _index = 0; _index < _tokenAddresses.length; _index++) { // Store withdrawable balances escrowBalances[_molochAddress][_proposalId][_index] = EscrowBalance({ typesTokenIdsAmounts: _typesTokenIdsAmounts[_index], tokenAddress: _tokenAddresses[_index], executed: false }); if (destinationChecked_[TributeType.ERC721] == NOTCHECKED_) checkERC721Recipients(_vaultAddress, msg.sender); if (destinationChecked_[TributeType.ERC1155] == NOTCHECKED_) checkERC1155Recipients(_vaultAddress, msg.sender); // Move tokens into escrow doTransfer( _tokenAddresses[_index], _typesTokenIdsAmounts[_index], msg.sender, address(this) ); // Store in memory so they can be emitted in an event _types[_index] = _typesTokenIdsAmounts[_index][0]; _tokenIds[_index] = _typesTokenIdsAmounts[_index][1]; _amounts[_index] = _typesTokenIdsAmounts[_index][2]; } emit ProposeAction( _proposalId, msg.sender, _molochAddress, _tokenAddresses, _types, _tokenIds, _amounts, _vaultAddress ); } // -- Proposal Functions -- /** * @notice Creates a proposal and moves NFT into escrow * @param _molochAddress Address of DAO * @param _tokenAddresses Token contract address * @param _typesTokenIdsAmounts Token id. * @param _vaultAddress Address of DAO's NFT vault * @param _requestSharesLootFunds Amount of shares requested // add funding request token * @param _details Info about proposal */ function proposeTribute( address _molochAddress, address[] calldata _tokenAddresses, uint256[3][] calldata _typesTokenIdsAmounts, address _vaultAddress, uint256[3] calldata _requestSharesLootFunds, // also request loot or treasury funds string calldata _details ) external nonReentrant safeDestination returns (uint256) { IMOLOCH _thisMoloch = IMOLOCH(_molochAddress); /*Initiate interface to relevant moloch*/ address _thisMolochDepositToken = _thisMoloch.depositToken(); /*Get deposit token for proposals*/ require(_vaultAddress != address(0), "invalid vaultAddress"); /*Cannot set destination to 0*/ require( _typesTokenIdsAmounts.length == _tokenAddresses.length, "!same-length" ); // Submit proposal to moloch for loot, shares, or funds in the deposit token uint256 _proposalId = _thisMoloch.submitProposal( msg.sender, _requestSharesLootFunds[0], _requestSharesLootFunds[1], 0, // No ERC20 tribute directly to Moloch _thisMolochDepositToken, _requestSharesLootFunds[2], _thisMolochDepositToken, _details ); processTributeProposal( _molochAddress, _tokenAddresses, _typesTokenIdsAmounts, _vaultAddress, _proposalId ); return _proposalId; } /** * @notice Internal function to move tokens to destination ones it can be processed or has been cancelled * @param _molochAddress Address of DAO * @param _tokenIndices Indices in proposed tokens array - have to specify this so frozen tokens cant make the whole payload stuck * @param _destination Address of DAO's NFT vault or Applicant if failed/ cancelled * @param _proposalId Moloch proposal ID */ function processWithdrawls( address _molochAddress, uint256[] calldata _tokenIndices, // only withdraw indices in this list address _destination, uint256 _proposalId ) internal { for (uint256 _index = 0; _index < _tokenIndices.length; _index++) { // Retrieve withdrawable balances EscrowBalance storage _escrowBalance = escrowBalances[_molochAddress][ _proposalId ][_tokenIndices[_index]]; // Ensure this token has not been withdrawn require(!_escrowBalance.executed, "executed"); require(_escrowBalance.tokenAddress != address(0), "!token"); _escrowBalance.executed = true; // Move tokens to doTransfer( _escrowBalance.tokenAddress, _escrowBalance.typesTokenIdsAmounts, address(this), _destination ); } } /** * @notice External function to move tokens to destination ones it can be processed or has been cancelled * @param _proposalId Moloch proposal ID * @param _molochAddress Address of DAO * @param _tokenIndices Indices in proposed tokens array - have to specify this so frozen tokens cant make the whole payload stuck */ function withdrawToDestination( uint256 _proposalId, address _molochAddress, uint256[] calldata _tokenIndices ) external nonReentrant { IMOLOCH _thisMoloch = IMOLOCH(_molochAddress); bool[6] memory _flags = _thisMoloch.getProposalFlags(_proposalId); require( _flags[1] || _flags[3], "proposal not processed and not cancelled" ); TributeEscrowAction memory _action = actions[_molochAddress][_proposalId]; address _destination; // if passed, send NFT to vault if (_flags[2]) { _destination = _action.vaultAddress; // if failed or cancelled, send back to proposer } else { _destination = _action.proposer; } processWithdrawls(_molochAddress, _tokenIndices, _destination, _proposalId); emit ExecuteAction(_proposalId, msg.sender, _molochAddress); } /** * @notice External function to cancel proposal by applicant if not sponsored * @param _proposalId Moloch proposal ID * @param _molochAddress Address of DAO */ function cancelAction(uint256 _proposalId, address _molochAddress) external nonReentrant { IMOLOCH _thisMoloch = IMOLOCH(_molochAddress); TributeEscrowAction memory _action = actions[_molochAddress][_proposalId]; require(msg.sender == _action.proposer, "not proposer"); _thisMoloch.cancelProposal(_proposalId); /*reverts if not cancelable*/ emit ActionCanceled(_proposalId, _molochAddress); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // 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' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () internal { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // 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 (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @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) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * 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); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } }
-- Proposal Functions -- Creates a proposal and moves NFT into escrow _molochAddress Address of DAO _tokenAddresses Token contract address _typesTokenIdsAmounts Token id. _vaultAddress Address of DAO's NFT vault _requestSharesLootFunds Amount of shares requested add funding request token _details Info about proposal/ Submit proposal to moloch for loot, shares, or funds in the deposit token
function proposeTribute( address _molochAddress, address[] calldata _tokenAddresses, uint256[3][] calldata _typesTokenIdsAmounts, address _vaultAddress, string calldata _details ) external nonReentrant safeDestination returns (uint256) { IMOLOCH _thisMoloch = IMOLOCH(_molochAddress); /*Initiate interface to relevant moloch*/ address _thisMolochDepositToken = _thisMoloch.depositToken(); /*Get deposit token for proposals*/ require(_vaultAddress != address(0), "invalid vaultAddress"); /*Cannot set destination to 0*/ require( _typesTokenIdsAmounts.length == _tokenAddresses.length, "!same-length" ); uint256 _proposalId = _thisMoloch.submitProposal( msg.sender, _requestSharesLootFunds[0], _requestSharesLootFunds[1], _thisMolochDepositToken, _requestSharesLootFunds[2], _thisMolochDepositToken, _details ); processTributeProposal( _molochAddress, _tokenAddresses, _typesTokenIdsAmounts, _vaultAddress, _proposalId ); return _proposalId; }
6,287,953
./partial_match/56/0xaAD4830E75b81Ae7Db1EBad6e4F62B96696dC678/sources/BEP20Token.sol
Moves tokens `amount` from `sender` to `recipient`. This is internal function is equivalent to {transfer}, and can be used to e.g. implement automatic token fees, slashing mechanisms, etc. Emits a {Transfer} event. Requirements: - `sender` cannot be the zero address. - `recipient` cannot be the zero address. - `sender` must have a balance of at least `amount`./
function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "BEP20: transfer from the zero address"); require(recipient != address(0), "BEP20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "BEP20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); }
11,119,920
// SPDX-License-Identifier: MIT // File: @openzeppelin/contracts/utils/Counters.sol // OpenZeppelin Contracts v4.4.1 (utils/Counters.sol) pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } // File: lost2rishore/CollectibleContract/@lib/Initializable.sol pragma solidity ^0.8.1; contract Initializable { bool inited = false; modifier initializer() { require(!inited, "already inited"); _; inited = true; } } // File: lost2rishore/CollectibleContract/@lib/EIP712Base.sol pragma solidity ^0.8.1; contract EIP712Base is Initializable { struct EIP712Domain { string name; string version; address verifyingContract; bytes32 salt; } string public constant ERC712_VERSION = "1"; bytes32 internal constant EIP712_DOMAIN_TYPEHASH = keccak256( bytes( "EIP712Domain(string name,string version,address verifyingContract,bytes32 salt)" ) ); bytes32 internal domainSeperator; // supposed to be called once while initializing. // one of the contracts that inherits this contract follows proxy pattern // so it is not possible to do this in a constructor function _initializeEIP712(string memory name) internal initializer { _setDomainSeperator(name); } function _setDomainSeperator(string memory name) internal { domainSeperator = keccak256( abi.encode( EIP712_DOMAIN_TYPEHASH, keccak256(bytes(name)), keccak256(bytes(ERC712_VERSION)), address(this), bytes32(getChainId()) ) ); } function getDomainSeperator() public view returns (bytes32) { return domainSeperator; } function getChainId() public view returns (uint256) { uint256 id; assembly { id := chainid() } return id; } /** * Accept message hash and returns hash message in EIP712 compatible form * So that it can be used to recover signer from signature signed using EIP712 formatted data * https://eips.ethereum.org/EIPS/eip-712 * "\\x19" makes the encoding deterministic * "\\x01" is the version byte to make it compatible to EIP-191 */ function toTypedMessageHash(bytes32 messageHash) internal view returns (bytes32) { return keccak256( abi.encodePacked("\x19\x01", getDomainSeperator(), messageHash) ); } } // File: @openzeppelin/contracts/utils/math/SafeMath.sol // OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol) pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // 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 (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @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 a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // File: lost2rishore/CollectibleContract/@lib/NativeMetaTransaction.sol pragma solidity ^0.8.1; contract NativeMetaTransaction is EIP712Base { using SafeMath for uint256; bytes32 private constant META_TRANSACTION_TYPEHASH = keccak256( bytes( "MetaTransaction(uint256 nonce,address from,bytes functionSignature)" ) ); event MetaTransactionExecuted( address userAddress, address payable relayerAddress, bytes functionSignature ); mapping(address => uint256) nonces; /* * Meta transaction structure. * No point of including value field here as if user is doing value transfer then he has the funds to pay for gas * He should call the desired function directly in that case. */ struct MetaTransaction { uint256 nonce; address from; bytes functionSignature; } function executeMetaTransaction( address userAddress, bytes memory functionSignature, bytes32 sigR, bytes32 sigS, uint8 sigV ) public payable returns (bytes memory) { MetaTransaction memory metaTx = MetaTransaction({ nonce: nonces[userAddress], from: userAddress, functionSignature: functionSignature }); require( verify(userAddress, metaTx, sigR, sigS, sigV), "Signer and signature do not match" ); // increase nonce for user (to avoid re-use) nonces[userAddress] = nonces[userAddress].add(1); emit MetaTransactionExecuted( userAddress, payable(msg.sender), functionSignature ); // Append userAddress and relayer address at the end to extract it from calling context (bool success, bytes memory returnData) = address(this).call( abi.encodePacked(functionSignature, userAddress) ); require(success, "Function call not successful"); return returnData; } function hashMetaTransaction(MetaTransaction memory metaTx) internal pure returns (bytes32) { return keccak256( abi.encode( META_TRANSACTION_TYPEHASH, metaTx.nonce, metaTx.from, keccak256(metaTx.functionSignature) ) ); } function getNonce(address user) public view returns (uint256 nonce) { nonce = nonces[user]; } function verify( address signer, MetaTransaction memory metaTx, bytes32 sigR, bytes32 sigS, uint8 sigV ) internal view returns (bool) { require(signer != address(0), "NativeMetaTransaction: INVALID_SIGNER"); return signer == ecrecover( toTypedMessageHash(hashMetaTransaction(metaTx)), sigV, sigR, sigS ); } } // File: lost2rishore/CollectibleContract/@lib/ContextMixin.sol pragma solidity ^0.8.1; abstract contract ContextMixin { function msgSender() internal view returns (address payable sender) { if (msg.sender == address(this)) { bytes memory array = msg.data; uint256 index = msg.data.length; assembly { // Load the 32 bytes word from memory with the address on the lower 20 bytes, and mask those. sender := and( mload(add(array, index)), 0xffffffffffffffffffffffffffffffffffffffff ) } } else { sender = payable(msg.sender); } return sender; } } // File: @openzeppelin/contracts/utils/Strings.sol // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: @openzeppelin/contracts/utils/Context.sol // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: @openzeppelin/contracts/access/Ownable.sol // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File: lost2rishore/CollectibleContract/@lib/Pauseable.sol pragma solidity ^0.8.0; /// @author nexusque /// @title Pause contract to help stop transactions. abstract contract Pauseable is Ownable { bool public paused = false; /** * @dev pause or resume the pledge function and the claim function * @param _state true means paused */ function pause(bool _state) external onlyOwner { paused = _state; } function _setPauseState(bool _state) internal onlyOwner { paused = _state; } } // File: lost2rishore/CollectibleContract/@lib/Priceable.sol pragma solidity ^0.8.0; /// @author nexusque /// @title Set price of tokens in contract abstract contract Priceable is Ownable { uint256 private _tokenPrice = 0; /** * @dev Internal setting price of tokens in eth * @param _etherPrice price in eth i.e 0.04 */ function _setTokenPrice(uint _etherPrice) internal onlyOwner { _tokenPrice = _etherPrice; } /** * @dev Set price of tokens in eth * @param _etherPrice price in eth i.e 0.04 */ function setTokenPrice(uint _etherPrice) external onlyOwner { _setTokenPrice(_etherPrice); } function getTokenPrice() public view returns(uint256) { return _tokenPrice; } } // File: lost2rishore/CollectibleContract/@lib/Whitelistable.sol pragma solidity ^0.8.0; /// @author nexusque /// @title Can use whitelist for varius functions abstract contract Whitelistable is Ownable { bool public whitelistRequired = true; mapping(address => bool) public whitelist; event WhitelistedAddressRemoved(address addr); event WhitelistedAddressAdded(address addr); event WhitelistedRequirementChanged(bool val); /** * @dev throws error if called by any wallet that is not whitelisted */ modifier onlyWhitelisted() { if (whitelistRequired == true) require(whitelist[msg.sender], "Alert: You're not on the whitelist."); _; } constructor( address[] memory _whitelistAddresses ) { _addAddressesToWhitelist(_whitelistAddresses); } /** * @dev Check if a wallet is whitelisted * @param _owner address */ function isWhitelisted(address _owner) external view returns (bool) { return whitelist[_owner] == true; } /** * @dev change whitelist requirement * @param _val bool */ function setWhitelistRequirement(bool _val) external onlyOwner { whitelistRequired = _val; emit WhitelistedRequirementChanged(_val); } /** * @dev add addresses to the whitelist * @param addrs addresses */ function addAddressesToWhitelist(address[] memory addrs) external onlyOwner { _addAddressesToWhitelist(addrs); } function _addAddressesToWhitelist(address[] memory addrs) internal onlyOwner { for (uint32 i = 0; i < addrs.length; i++) { whitelist[addrs[i]] = true; emit WhitelistedAddressAdded(addrs[i]); } } /** * @dev remove addresses from the whitelist * @param addrs addresses */ function removeAddressesFromWhitelist(address[] memory addrs) external onlyOwner { _removeAddressesFromWhitelist(addrs); } function _removeAddressesFromWhitelist(address[] memory addrs) internal onlyOwner { for (uint32 i = 0; i < addrs.length; i++) { _removeAddressFromWhitelist(addrs[i]); } } function _removeAddressFromWhitelist(address addrs) internal onlyOwner { whitelist[addrs] = false; emit WhitelistedAddressRemoved(addrs); } } // File: @openzeppelin/contracts/utils/Address.sol // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev 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, bytes calldata data ) external returns (bytes4); } // File: @openzeppelin/contracts/utils/introspection/IERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/utils/introspection/ERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: @openzeppelin/contracts/token/ERC721/ERC721.sol // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @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 returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev 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, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); _afterTokenTransfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); _afterTokenTransfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); _afterTokenTransfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // File: @openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721URIStorage.sol) pragma solidity ^0.8.0; /** * @dev ERC721 token with storage based token URI management. */ abstract contract ERC721URIStorage is ERC721 { using Strings for uint256; // Optional mapping for token URIs mapping(uint256 => string) private _tokenURIs; /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721URIStorage: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; string memory base = _baseURI(); // If there is no base URI, return the token URI. if (bytes(base).length == 0) { return _tokenURI; } // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(base, _tokenURI)); } return super.tokenURI(tokenId); } /** * @dev Sets `_tokenURI` as the tokenURI of `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), "ERC721URIStorage: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual override { super._burn(tokenId); if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } } } // File: @openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Enumerable.sol) pragma solidity ^0.8.0; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // File: lost2rishore/CollectibleContract/@lib/WithLimitedSupply.sol pragma solidity ^0.8.0; /// @author 1001.digital /// ReviewedBy nexusque /// @title A token tracker that limits the token supply and increments token IDs on each new mint. abstract contract WithLimitedSupply is ERC721Enumerable { using Counters for Counters.Counter; // Keeps track of how many we have minted Counters.Counter private _tokenCount; /// @dev The maximum count of tokens this token tracker will hold. uint256 private _totalSupply; /// Instanciate the contract /// @param totalSupply_ how many tokens this collection should hold constructor (uint256 totalSupply_) { _totalSupply = totalSupply_; } /// @dev Get the max Supply /// @return the maximum token count function totalSupply() public override view returns (uint256) { return _totalSupply; } /// @dev Get the current token count /// @return the created token count function tokenCount() public view returns (uint256) { return _tokenCount.current(); } /// @dev Check whether tokens are still available /// @return the available token count function availableTokenCount() public view returns (uint256) { return totalSupply() - tokenCount(); } /// @dev Increment the token count and fetch the latest count /// @return the next token id function nextToken() internal virtual ensureAvailability returns (uint256) { uint256 token = _tokenCount.current(); _tokenCount.increment(); return token; } /// @dev Check whether another token is still available modifier ensureAvailability() { require(availableTokenCount() > 0, "No more tokens available"); _; } /// @param amount Check whether number of tokens are still available /// @dev Check whether tokens are still available modifier ensureAvailabilityFor(uint256 amount) { require(availableTokenCount() >= amount, "Requested number of tokens not available"); _; } } // File: lost2rishore/CollectibleContract/Collectible.sol pragma solidity ^0.8.2; /// @author nexusque contract LostTRIShore is ContextMixin, NativeMetaTransaction, Ownable, Whitelistable, Priceable, Pauseable, WithLimitedSupply { using SafeMath for uint256; address payable public clientAddress; address payable public artistAddress; address payable public paymentAddress; string public baseTokenURI = ""; string public baseExtension = ".json"; uint256 private _maxSupply = 10000; uint8 private _chapters = 5; // For RandomlyAssigned: Max supply is 1000; id start from 1 (instead of 0) constructor( string memory _name, string memory _symbol, string memory _uri, address _artistAddress, address _clientAddress, address _paymentAddress, address[] memory _whitelistAddresses ) ERC721 (_name, _symbol) Whitelistable(_whitelistAddresses) WithLimitedSupply(_maxSupply) { _initializeEIP712(_name); baseTokenURI = _uri; // ~$20 USD as of 04/08/2022 _setTokenPrice(0.006 ether); artistAddress = payable(_artistAddress); clientAddress = payable(_clientAddress); paymentAddress = payable(_paymentAddress); } function claim() external onlyWhitelisted { require(!paused, "Contract is paused"); require( tokenCount() + 1 <= _maxSupply, "Alert: Sorry not enough tokens left" ); _mintList(1); _removeAddressFromWhitelist(msg.sender); } function mint() external payable { require(!paused, "Contract is paused"); require( tokenCount() + 1 <= _maxSupply, "Alert: Sorry not enough tokens left" ); require( msg.value >= getTokenPrice(), "Alert: You need to pay at least the required cost." ); _mintList(1); } function mintTotalOf(uint8 _num) external payable { require(!paused, "Contract is paused"); require( tokenCount() + uint256(_num) <= _maxSupply, "Alert: Sorry not enough tokens left" ); require( msg.value >= (getTokenPrice() * uint256(_num)), "Alert: You need to pay at least the required cost." ); _mintList(_num); } function ownerMintTotalOf(uint8 _num) external onlyOwner { require( tokenCount() + uint256(_num) <= _maxSupply, "Alert: Sorry not enough tokens left" ); _mintList(_num); } /** * @dev Airdrop tokens to the following addresses * @param _addresses list of addresses to airdrop to */ function airDropToAdresses(address[] memory _addresses) external onlyOwner { for (uint32 i = 0; i < _addresses.length; i++) { if (tokenCount() + 1 <= _maxSupply) { _safeMint(_addresses[i], nextToken()); } } _removeAddressesFromWhitelist(_addresses); } /** * @dev mint _num of * @param _num Quantity to mint */ function _mintList(uint8 _num) private { for (uint8 i = 0; i < _num; i++) { _safeMint(msg.sender, nextToken()); } // Pause after each chapter sells out if (tokenCount() % (_maxSupply / _chapters) == 0) { _setPauseState(true); } } /** * @dev change the baseTokenURI (only Owner) * @param _baseTokenURI base token URI */ function setBaseURI(string memory _baseTokenURI) external onlyOwner { baseTokenURI = _baseTokenURI; } /** * @dev change the setPaymentAddress (only Owner) * @param _paymentAddress address to send eth to when withdrawing */ function setPaymentAddress(address _paymentAddress) external onlyOwner { paymentAddress = payable(_paymentAddress); } /** * @dev returns the token URI of _tokenId * @param _tokenId id of the token */ function tokenURI(uint256 _tokenId) public view override returns (string memory) { require(_exists(_tokenId), "Alert: This token does not exist!"); return string(abi.encodePacked(baseTokenURI, Strings.toString(_tokenId), baseExtension)); } /** * @dev this is used instead of msg.sender as transactions won't be sent by the original token owner, but by OpenSea. */ function _msgSender() internal view override returns (address sender) { return ContextMixin.msgSender(); } /** * @dev set the base extension of the metadata file (only Owner) * @param _newBaseExtension extension (empty or with a dot infront) */ function setBaseExtension(string memory _newBaseExtension) public onlyOwner { baseExtension = _newBaseExtension; } /** * @dev get the ids of the Humans owned by _owner * @param _owner address */ function walletOfOwner(address _owner) external view returns (uint256[] memory) { uint256 ownerTokenCount = balanceOf(_owner); uint256[] memory tokenIds = new uint256[](ownerTokenCount); for (uint256 i; i < ownerTokenCount; i++) { tokenIds[i] = tokenOfOwnerByIndex(_owner, i); } return tokenIds; } /** * @dev withdraw all balance of this contract to the paymentAddress contract */ function withdraw() external payable onlyOwner { (bool success, ) = payable(paymentAddress).call{value: address(this).balance}(""); require(success, "Transfer failed."); } }
get the ids of the Humans owned by _owner _owner address/
function walletOfOwner(address _owner) external view returns (uint256[] memory) { uint256 ownerTokenCount = balanceOf(_owner); uint256[] memory tokenIds = new uint256[](ownerTokenCount); for (uint256 i; i < ownerTokenCount; i++) { tokenIds[i] = tokenOfOwnerByIndex(_owner, i); } return tokenIds; }
498,111
// File: contracts/ErrorReporter.sol pragma solidity 0.4.24; contract ErrorReporter { /** * @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary * contract-specific code that enables us to report opaque error codes from upgradeable contracts. */ event Failure(uint256 error, uint256 info, uint256 detail); enum Error { NO_ERROR, OPAQUE_ERROR, // To be used when reporting errors from upgradeable contracts; the opaque code should be given as `detail` in the `Failure` event UNAUTHORIZED, INTEGER_OVERFLOW, INTEGER_UNDERFLOW, DIVISION_BY_ZERO, BAD_INPUT, TOKEN_INSUFFICIENT_ALLOWANCE, TOKEN_INSUFFICIENT_BALANCE, TOKEN_TRANSFER_FAILED, MARKET_NOT_SUPPORTED, SUPPLY_RATE_CALCULATION_FAILED, BORROW_RATE_CALCULATION_FAILED, TOKEN_INSUFFICIENT_CASH, TOKEN_TRANSFER_OUT_FAILED, INSUFFICIENT_LIQUIDITY, INSUFFICIENT_BALANCE, INVALID_COLLATERAL_RATIO, MISSING_ASSET_PRICE, EQUITY_INSUFFICIENT_BALANCE, INVALID_CLOSE_AMOUNT_REQUESTED, ASSET_NOT_PRICED, INVALID_LIQUIDATION_DISCOUNT, INVALID_COMBINED_RISK_PARAMETERS, ZERO_ORACLE_ADDRESS, CONTRACT_PAUSED, KYC_ADMIN_CHECK_FAILED, KYC_ADMIN_ADD_OR_DELETE_ADMIN_CHECK_FAILED, KYC_CUSTOMER_VERIFICATION_CHECK_FAILED, LIQUIDATOR_CHECK_FAILED, LIQUIDATOR_ADD_OR_DELETE_ADMIN_CHECK_FAILED, SET_WETH_ADDRESS_ADMIN_CHECK_FAILED, WETH_ADDRESS_NOT_SET_ERROR, ETHER_AMOUNT_MISMATCH_ERROR } /** * Note: FailureInfo (but not Error) is kept in alphabetical order * This is because FailureInfo grows significantly faster, and * the order of Error has some meaning, while the order of FailureInfo * is entirely arbitrary. */ enum FailureInfo { ACCEPT_ADMIN_PENDING_ADMIN_CHECK, BORROW_ACCOUNT_LIQUIDITY_CALCULATION_FAILED, BORROW_ACCOUNT_SHORTFALL_PRESENT, BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, BORROW_AMOUNT_LIQUIDITY_SHORTFALL, BORROW_AMOUNT_VALUE_CALCULATION_FAILED, BORROW_CONTRACT_PAUSED, BORROW_MARKET_NOT_SUPPORTED, BORROW_NEW_BORROW_INDEX_CALCULATION_FAILED, BORROW_NEW_BORROW_RATE_CALCULATION_FAILED, BORROW_NEW_SUPPLY_INDEX_CALCULATION_FAILED, BORROW_NEW_SUPPLY_RATE_CALCULATION_FAILED, BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, BORROW_NEW_TOTAL_BORROW_CALCULATION_FAILED, BORROW_NEW_TOTAL_CASH_CALCULATION_FAILED, BORROW_ORIGINATION_FEE_CALCULATION_FAILED, BORROW_TRANSFER_OUT_FAILED, EQUITY_WITHDRAWAL_AMOUNT_VALIDATION, EQUITY_WITHDRAWAL_CALCULATE_EQUITY, EQUITY_WITHDRAWAL_MODEL_OWNER_CHECK, EQUITY_WITHDRAWAL_TRANSFER_OUT_FAILED, LIQUIDATE_ACCUMULATED_BORROW_BALANCE_CALCULATION_FAILED, LIQUIDATE_ACCUMULATED_SUPPLY_BALANCE_CALCULATION_FAILED_BORROWER_COLLATERAL_ASSET, LIQUIDATE_ACCUMULATED_SUPPLY_BALANCE_CALCULATION_FAILED_LIQUIDATOR_COLLATERAL_ASSET, LIQUIDATE_AMOUNT_SEIZE_CALCULATION_FAILED, LIQUIDATE_BORROW_DENOMINATED_COLLATERAL_CALCULATION_FAILED, LIQUIDATE_CLOSE_AMOUNT_TOO_HIGH, LIQUIDATE_CONTRACT_PAUSED, LIQUIDATE_DISCOUNTED_REPAY_TO_EVEN_AMOUNT_CALCULATION_FAILED, LIQUIDATE_NEW_BORROW_INDEX_CALCULATION_FAILED_BORROWED_ASSET, LIQUIDATE_NEW_BORROW_INDEX_CALCULATION_FAILED_COLLATERAL_ASSET, LIQUIDATE_NEW_BORROW_RATE_CALCULATION_FAILED_BORROWED_ASSET, LIQUIDATE_NEW_SUPPLY_INDEX_CALCULATION_FAILED_BORROWED_ASSET, LIQUIDATE_NEW_SUPPLY_INDEX_CALCULATION_FAILED_COLLATERAL_ASSET, LIQUIDATE_NEW_SUPPLY_RATE_CALCULATION_FAILED_BORROWED_ASSET, LIQUIDATE_NEW_TOTAL_BORROW_CALCULATION_FAILED_BORROWED_ASSET, LIQUIDATE_NEW_TOTAL_CASH_CALCULATION_FAILED_BORROWED_ASSET, LIQUIDATE_NEW_TOTAL_SUPPLY_BALANCE_CALCULATION_FAILED_BORROWER_COLLATERAL_ASSET, LIQUIDATE_NEW_TOTAL_SUPPLY_BALANCE_CALCULATION_FAILED_LIQUIDATOR_COLLATERAL_ASSET, LIQUIDATE_FETCH_ASSET_PRICE_FAILED, LIQUIDATE_TRANSFER_IN_FAILED, LIQUIDATE_TRANSFER_IN_NOT_POSSIBLE, REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, REPAY_BORROW_CONTRACT_PAUSED, REPAY_BORROW_NEW_BORROW_INDEX_CALCULATION_FAILED, REPAY_BORROW_NEW_BORROW_RATE_CALCULATION_FAILED, REPAY_BORROW_NEW_SUPPLY_INDEX_CALCULATION_FAILED, REPAY_BORROW_NEW_SUPPLY_RATE_CALCULATION_FAILED, REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, REPAY_BORROW_NEW_TOTAL_BORROW_CALCULATION_FAILED, REPAY_BORROW_NEW_TOTAL_CASH_CALCULATION_FAILED, REPAY_BORROW_TRANSFER_IN_FAILED, REPAY_BORROW_TRANSFER_IN_NOT_POSSIBLE, SET_ASSET_PRICE_CHECK_ORACLE, SET_MARKET_INTEREST_RATE_MODEL_OWNER_CHECK, SET_ORACLE_OWNER_CHECK, SET_ORIGINATION_FEE_OWNER_CHECK, SET_PAUSED_OWNER_CHECK, SET_PENDING_ADMIN_OWNER_CHECK, SET_RISK_PARAMETERS_OWNER_CHECK, SET_RISK_PARAMETERS_VALIDATION, SUPPLY_ACCUMULATED_BALANCE_CALCULATION_FAILED, SUPPLY_CONTRACT_PAUSED, SUPPLY_MARKET_NOT_SUPPORTED, SUPPLY_NEW_BORROW_INDEX_CALCULATION_FAILED, SUPPLY_NEW_BORROW_RATE_CALCULATION_FAILED, SUPPLY_NEW_SUPPLY_INDEX_CALCULATION_FAILED, SUPPLY_NEW_SUPPLY_RATE_CALCULATION_FAILED, SUPPLY_NEW_TOTAL_BALANCE_CALCULATION_FAILED, SUPPLY_NEW_TOTAL_CASH_CALCULATION_FAILED, SUPPLY_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, SUPPLY_TRANSFER_IN_FAILED, SUPPLY_TRANSFER_IN_NOT_POSSIBLE, SUPPORT_MARKET_FETCH_PRICE_FAILED, SUPPORT_MARKET_OWNER_CHECK, SUPPORT_MARKET_PRICE_CHECK, SUSPEND_MARKET_OWNER_CHECK, WITHDRAW_ACCOUNT_LIQUIDITY_CALCULATION_FAILED, WITHDRAW_ACCOUNT_SHORTFALL_PRESENT, WITHDRAW_ACCUMULATED_BALANCE_CALCULATION_FAILED, WITHDRAW_AMOUNT_LIQUIDITY_SHORTFALL, WITHDRAW_AMOUNT_VALUE_CALCULATION_FAILED, WITHDRAW_CAPACITY_CALCULATION_FAILED, WITHDRAW_CONTRACT_PAUSED, WITHDRAW_NEW_BORROW_INDEX_CALCULATION_FAILED, WITHDRAW_NEW_BORROW_RATE_CALCULATION_FAILED, WITHDRAW_NEW_SUPPLY_INDEX_CALCULATION_FAILED, WITHDRAW_NEW_SUPPLY_RATE_CALCULATION_FAILED, WITHDRAW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, WITHDRAW_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, WITHDRAW_TRANSFER_OUT_FAILED, WITHDRAW_TRANSFER_OUT_NOT_POSSIBLE, KYC_ADMIN_CHECK_FAILED, KYC_ADMIN_ADD_OR_DELETE_ADMIN_CHECK_FAILED, KYC_CUSTOMER_VERIFICATION_CHECK_FAILED, LIQUIDATOR_CHECK_FAILED, LIQUIDATOR_ADD_OR_DELETE_ADMIN_CHECK_FAILED, SET_WETH_ADDRESS_ADMIN_CHECK_FAILED, WETH_ADDRESS_NOT_SET_ERROR, SEND_ETHER_ADMIN_CHECK_FAILED, ETHER_AMOUNT_MISMATCH_ERROR } /** * @dev use this when reporting a known error from the Alkemi Earn Verified or a non-upgradeable collaborator */ function fail(Error err, FailureInfo info) internal returns (uint256) { emit Failure(uint256(err), uint256(info), 0); return uint256(err); } /** * @dev use this when reporting an opaque error from an upgradeable collaborator contract */ function failOpaque(FailureInfo info, uint256 opaqueError) internal returns (uint256) { emit Failure(uint256(Error.OPAQUE_ERROR), uint256(info), opaqueError); return uint256(Error.OPAQUE_ERROR); } } // File: contracts/CarefulMath.sol // Cloned from https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/math/SafeMath.sol -> Commit id: 24a0bc2 // and added custom functions related to Alkemi pragma solidity 0.4.24; /** * @title Careful Math * @notice Derived from OpenZeppelin's SafeMath library * https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/math/SafeMath.sol */ contract CarefulMath is ErrorReporter { /** * @dev Multiplies two numbers, returns an error on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (Error, uint256) { if (a == 0) { return (Error.NO_ERROR, 0); } uint256 c = a * b; if (c / a != b) { return (Error.INTEGER_OVERFLOW, 0); } else { return (Error.NO_ERROR, c); } } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (Error, uint256) { if (b == 0) { return (Error.DIVISION_BY_ZERO, 0); } return (Error.NO_ERROR, a / b); } /** * @dev Subtracts two numbers, returns an error on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (Error, uint256) { if (b <= a) { return (Error.NO_ERROR, a - b); } else { return (Error.INTEGER_UNDERFLOW, 0); } } /** * @dev Adds two numbers, returns an error on overflow. */ function add(uint256 a, uint256 b) internal pure returns (Error, uint256) { uint256 c = a + b; if (c >= a) { return (Error.NO_ERROR, c); } else { return (Error.INTEGER_OVERFLOW, 0); } } /** * @dev add a and b and then subtract c */ function addThenSub( uint256 a, uint256 b, uint256 c ) internal pure returns (Error, uint256) { (Error err0, uint256 sum) = add(a, b); if (err0 != Error.NO_ERROR) { return (err0, 0); } return sub(sum, c); } } // File: contracts/Exponential.sol // Cloned from https://github.com/compound-finance/compound-money-market/blob/master/contracts/Exponential.sol -> Commit id: 241541a pragma solidity 0.4.24; contract Exponential is ErrorReporter, CarefulMath { // Per https://solidity.readthedocs.io/en/latest/contracts.html#constant-state-variables // the optimizer MAY replace the expression 10**18 with its calculated value. uint256 constant expScale = 10**18; uint256 constant halfExpScale = expScale / 2; struct Exp { uint256 mantissa; } uint256 constant mantissaOne = 10**18; // Though unused, the below variable cannot be deleted as it will hinder upgradeability // Will be cleared during the next compiler version upgrade uint256 constant mantissaOneTenth = 10**17; /** * @dev Creates an exponential from numerator and denominator values. * Note: Returns an error if (`num` * 10e18) > MAX_INT, * or if `denom` is zero. */ function getExp(uint256 num, uint256 denom) internal pure returns (Error, Exp memory) { (Error err0, uint256 scaledNumerator) = mul(num, expScale); if (err0 != Error.NO_ERROR) { return (err0, Exp({mantissa: 0})); } (Error err1, uint256 rational) = div(scaledNumerator, denom); if (err1 != Error.NO_ERROR) { return (err1, Exp({mantissa: 0})); } return (Error.NO_ERROR, Exp({mantissa: rational})); } /** * @dev Adds two exponentials, returning a new exponential. */ function addExp(Exp memory a, Exp memory b) internal pure returns (Error, Exp memory) { (Error error, uint256 result) = add(a.mantissa, b.mantissa); return (error, Exp({mantissa: result})); } /** * @dev Subtracts two exponentials, returning a new exponential. */ function subExp(Exp memory a, Exp memory b) internal pure returns (Error, Exp memory) { (Error error, uint256 result) = sub(a.mantissa, b.mantissa); return (error, Exp({mantissa: result})); } /** * @dev Multiply an Exp by a scalar, returning a new Exp. */ function mulScalar(Exp memory a, uint256 scalar) internal pure returns (Error, Exp memory) { (Error err0, uint256 scaledMantissa) = mul(a.mantissa, scalar); if (err0 != Error.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (Error.NO_ERROR, Exp({mantissa: scaledMantissa})); } /** * @dev Divide an Exp by a scalar, returning a new Exp. */ function divScalar(Exp memory a, uint256 scalar) internal pure returns (Error, Exp memory) { (Error err0, uint256 descaledMantissa) = div(a.mantissa, scalar); if (err0 != Error.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (Error.NO_ERROR, Exp({mantissa: descaledMantissa})); } /** * @dev Divide a scalar by an Exp, returning a new Exp. */ function divScalarByExp(uint256 scalar, Exp divisor) internal pure returns (Error, Exp memory) { /* We are doing this as: getExp(mul(expScale, scalar), divisor.mantissa) How it works: Exp = a / b; Scalar = s; `s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale` */ (Error err0, uint256 numerator) = mul(expScale, scalar); if (err0 != Error.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return getExp(numerator, divisor.mantissa); } /** * @dev Multiplies two exponentials, returning a new exponential. */ function mulExp(Exp memory a, Exp memory b) internal pure returns (Error, Exp memory) { (Error err0, uint256 doubleScaledProduct) = mul(a.mantissa, b.mantissa); if (err0 != Error.NO_ERROR) { return (err0, Exp({mantissa: 0})); } // We add half the scale before dividing so that we get rounding instead of truncation. // See "Listing 6" and text above it at https://accu.org/index.php/journals/1717 // Without this change, a result like 6.6...e-19 will be truncated to 0 instead of being rounded to 1e-18. (Error err1, uint256 doubleScaledProductWithHalfScale) = add( halfExpScale, doubleScaledProduct ); if (err1 != Error.NO_ERROR) { return (err1, Exp({mantissa: 0})); } (Error err2, uint256 product) = div( doubleScaledProductWithHalfScale, expScale ); // The only error `div` can return is Error.DIVISION_BY_ZERO but we control `expScale` and it is not zero. assert(err2 == Error.NO_ERROR); return (Error.NO_ERROR, Exp({mantissa: product})); } /** * @dev Divides two exponentials, returning a new exponential. * (a/scale) / (b/scale) = (a/scale) * (scale/b) = a/b, * which we can scale as an Exp by calling getExp(a.mantissa, b.mantissa) */ function divExp(Exp memory a, Exp memory b) internal pure returns (Error, Exp memory) { return getExp(a.mantissa, b.mantissa); } /** * @dev Truncates the given exp to a whole number value. * For example, truncate(Exp{mantissa: 15 * (10**18)}) = 15 */ function truncate(Exp memory exp) internal pure returns (uint256) { // Note: We are not using careful math here as we're performing a division that cannot fail return exp.mantissa / expScale; } /** * @dev Checks if first Exp is less than second Exp. */ function lessThanExp(Exp memory left, Exp memory right) internal pure returns (bool) { return left.mantissa < right.mantissa; } /** * @dev Checks if left Exp <= right Exp. */ function lessThanOrEqualExp(Exp memory left, Exp memory right) internal pure returns (bool) { return left.mantissa <= right.mantissa; } /** * @dev Checks if first Exp is greater than second Exp. */ function greaterThanExp(Exp memory left, Exp memory right) internal pure returns (bool) { return left.mantissa > right.mantissa; } /** * @dev returns true if Exp is exactly zero */ function isZeroExp(Exp memory value) internal pure returns (bool) { return value.mantissa == 0; } } // File: contracts/InterestRateModel.sol pragma solidity 0.4.24; /** * @title InterestRateModel Interface * @notice Any interest rate model should derive from this contract. * @dev These functions are specifically not marked `pure` as implementations of this * contract may read from storage variables. */ contract InterestRateModel { /** * @notice Gets the current supply interest rate based on the given asset, total cash and total borrows * @dev The return value should be scaled by 1e18, thus a return value of * `(true, 1000000000000)` implies an interest rate of 0.000001 or 0.0001% *per block*. * @param asset The asset to get the interest rate of * @param cash The total cash of the asset in the market * @param borrows The total borrows of the asset in the market * @return Success or failure and the supply interest rate per block scaled by 10e18 */ function getSupplyRate( address asset, uint256 cash, uint256 borrows ) public view returns (uint256, uint256); /** * @notice Gets the current borrow interest rate based on the given asset, total cash and total borrows * @dev The return value should be scaled by 1e18, thus a return value of * `(true, 1000000000000)` implies an interest rate of 0.000001 or 0.0001% *per block*. * @param asset The asset to get the interest rate of * @param cash The total cash of the asset in the market * @param borrows The total borrows of the asset in the market * @return Success or failure and the borrow interest rate per block scaled by 10e18 */ function getBorrowRate( address asset, uint256 cash, uint256 borrows ) public view returns (uint256, uint256); } // File: contracts/EIP20Interface.sol // Abstract contract for the full ERC 20 Token standard // https://github.com/ethereum/EIPs/issues/20 pragma solidity 0.4.24; contract EIP20Interface { /* This is a slight change to the ERC20 base standard. function totalSupply() constant returns (uint256 supply); is replaced with: uint256 public totalSupply; This automatically creates a getter function for the totalSupply. This is moved to the base contract since public getter functions are not currently recognised as an implementation of the matching abstract function by the compiler. */ // total amount of tokens uint256 public totalSupply; // token decimals uint8 public decimals; // maximum is 18 decimals /** * @param _owner The address from which the balance will be retrieved * @return The balance */ function balanceOf(address _owner) public view returns (uint256 balance); /** * @notice send `_value` token to `_to` from `msg.sender` * @param _to The address of the recipient * @param _value The amount of token to be transferred * @return Whether the transfer was successful or not */ function transfer(address _to, uint256 _value) public returns (bool success); /** * @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` * @param _from The address of the sender * @param _to The address of the recipient * @param _value The amount of token to be transferred * @return Whether the transfer was successful or not */ function transferFrom( address _from, address _to, uint256 _value ) public returns (bool success); /** * @notice `msg.sender` approves `_spender` to spend `_value` tokens * @param _spender The address of the account able to transfer the tokens * @param _value The amount of tokens to be approved for transfer * @return Whether the approval was successful or not */ function approve(address _spender, uint256 _value) public returns (bool success); /** * @param _owner The address of the account owning tokens * @param _spender The address of the account able to transfer the tokens * @return Amount of remaining tokens allowed to spent */ function allowance(address _owner, address _spender) public view returns (uint256 remaining); // solhint-disable-next-line no-simple-event-func-name event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval( address indexed _owner, address indexed _spender, uint256 _value ); } // File: contracts/EIP20NonStandardInterface.sol // Abstract contract for the full ERC 20 Token standard // https://github.com/ethereum/EIPs/issues/20 pragma solidity 0.4.24; /** * @title EIP20NonStandardInterface * @dev Version of ERC20 with no return values for `transfer` and `transferFrom` * See https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca */ contract EIP20NonStandardInterface { /* This is a slight change to the ERC20 base standard. function totalSupply() constant returns (uint256 supply); is replaced with: uint256 public totalSupply; This automatically creates a getter function for the totalSupply. This is moved to the base contract since public getter functions are not currently recognised as an implementation of the matching abstract function by the compiler. */ // total amount of tokens uint256 public totalSupply; /** * @param _owner The address from which the balance will be retrieved * @return The balance */ function balanceOf(address _owner) public view returns (uint256 balance); /** * !!!!!!!!!!!!!! * !!! NOTICE !!! `transfer` does not return a value, in violation of the ERC-20 specification * !!!!!!!!!!!!!! * * @notice send `_value` token to `_to` from `msg.sender` * @param _to The address of the recipient * @param _value The amount of token to be transferred * @return Whether the transfer was successful or not */ function transfer(address _to, uint256 _value) public; /** * * !!!!!!!!!!!!!! * !!! NOTICE !!! `transferFrom` does not return a value, in violation of the ERC-20 specification * !!!!!!!!!!!!!! * * @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` * @param _from The address of the sender * @param _to The address of the recipient * @param _value The amount of token to be transferred * @return Whether the transfer was successful or not */ function transferFrom( address _from, address _to, uint256 _value ) public; /// @notice `msg.sender` approves `_spender` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of tokens to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint256 _value) public returns (bool success); /** * @param _owner The address of the account owning tokens * @param _spender The address of the account able to transfer the tokens * @return Amount of remaining tokens allowed to spent */ function allowance(address _owner, address _spender) public view returns (uint256 remaining); // solhint-disable-next-line no-simple-event-func-name event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval( address indexed _owner, address indexed _spender, uint256 _value ); } // File: contracts/SafeToken.sol pragma solidity 0.4.24; contract SafeToken is ErrorReporter { /** * @dev Checks whether or not there is sufficient allowance for this contract to move amount from `from` and * whether or not `from` has a balance of at least `amount`. Does NOT do a transfer. */ function checkTransferIn( address asset, address from, uint256 amount ) internal view returns (Error) { EIP20Interface token = EIP20Interface(asset); if (token.allowance(from, address(this)) < amount) { return Error.TOKEN_INSUFFICIENT_ALLOWANCE; } if (token.balanceOf(from) < amount) { return Error.TOKEN_INSUFFICIENT_BALANCE; } return Error.NO_ERROR; } /** * @dev Similar to EIP20 transfer, except it handles a False result from `transferFrom` and returns an explanatory * error code rather than reverting. If caller has not called `checkTransferIn`, this may revert due to * insufficient balance or insufficient allowance. If caller has called `checkTransferIn` prior to this call, * and it returned Error.NO_ERROR, this should not revert in normal conditions. * * Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value. * See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca */ function doTransferIn( address asset, address from, uint256 amount ) internal returns (Error) { EIP20NonStandardInterface token = EIP20NonStandardInterface(asset); bool result; token.transferFrom(from, address(this), amount); assembly { switch returndatasize() case 0 { // This is a non-standard ERC-20 result := not(0) // set result to true } case 32 { // This is a compliant ERC-20 returndatacopy(0, 0, 32) result := mload(0) // Set `result = returndata` of external call } default { // This is an excessively non-compliant ERC-20, revert. revert(0, 0) } } if (!result) { return Error.TOKEN_TRANSFER_FAILED; } return Error.NO_ERROR; } /** * @dev Checks balance of this contract in asset */ function getCash(address asset) internal view returns (uint256) { EIP20Interface token = EIP20Interface(asset); return token.balanceOf(address(this)); } /** * @dev Checks balance of `from` in `asset` */ function getBalanceOf(address asset, address from) internal view returns (uint256) { EIP20Interface token = EIP20Interface(asset); return token.balanceOf(from); } /** * @dev Similar to EIP20 transfer, except it handles a False result from `transfer` and returns an explanatory * error code rather than reverting. If caller has not called checked protocol's balance, this may revert due to * insufficient cash held in this contract. If caller has checked protocol's balance prior to this call, and verified * it is >= amount, this should not revert in normal conditions. * * Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value. * See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca */ function doTransferOut( address asset, address to, uint256 amount ) internal returns (Error) { EIP20NonStandardInterface token = EIP20NonStandardInterface(asset); bool result; token.transfer(to, amount); assembly { switch returndatasize() case 0 { // This is a non-standard ERC-20 result := not(0) // set result to true } case 32 { // This is a complaint ERC-20 returndatacopy(0, 0, 32) result := mload(0) // Set `result = returndata` of external call } default { // This is an excessively non-compliant ERC-20, revert. revert(0, 0) } } if (!result) { return Error.TOKEN_TRANSFER_OUT_FAILED; } return Error.NO_ERROR; } function doApprove( address asset, address to, uint256 amount ) internal returns (Error) { EIP20NonStandardInterface token = EIP20NonStandardInterface(asset); bool result; token.approve(to, amount); assembly { switch returndatasize() case 0 { // This is a non-standard ERC-20 result := not(0) // set result to true } case 32 { // This is a complaint ERC-20 returndatacopy(0, 0, 32) result := mload(0) // Set `result = returndata` of external call } default { // This is an excessively non-compliant ERC-20, revert. revert(0, 0) } } if (!result) { return Error.TOKEN_TRANSFER_OUT_FAILED; } return Error.NO_ERROR; } } // File: contracts/AggregatorV3Interface.sol pragma solidity 0.4.24; interface AggregatorV3Interface { function decimals() external view returns (uint8); function description() external view returns (string memory); function version() external view returns (uint256); // getRoundData and latestRoundData should both raise "No data present" // if they do not have data to report, instead of returning unset values // which could be misinterpreted as actual reported values. function getRoundData(uint80 _roundId) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function latestRoundData() external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); } // File: contracts/ChainLink.sol pragma solidity 0.4.24; contract ChainLink { mapping(address => AggregatorV3Interface) internal priceContractMapping; address public admin; bool public paused = false; address public wethAddressVerified; address public wethAddressPublic; AggregatorV3Interface public USDETHPriceFeed; uint256 constant expScale = 10**18; uint8 constant eighteen = 18; /** * Sets the admin * Add assets and set Weth Address using their own functions */ constructor() public { admin = msg.sender; } /** * Modifier to restrict functions only by admins */ modifier onlyAdmin() { require( msg.sender == admin, "Only the Admin can perform this operation" ); _; } /** * Event declarations for all the operations of this contract */ event assetAdded( address indexed assetAddress, address indexed priceFeedContract ); event assetRemoved(address indexed assetAddress); event adminChanged(address indexed oldAdmin, address indexed newAdmin); event verifiedWethAddressSet(address indexed wethAddressVerified); event publicWethAddressSet(address indexed wethAddressPublic); event contractPausedOrUnpaused(bool currentStatus); /** * Allows admin to add a new asset for price tracking */ function addAsset(address assetAddress, address priceFeedContract) public onlyAdmin { require( assetAddress != address(0) && priceFeedContract != address(0), "Asset or Price Feed address cannot be 0x00" ); priceContractMapping[assetAddress] = AggregatorV3Interface( priceFeedContract ); emit assetAdded(assetAddress, priceFeedContract); } /** * Allows admin to remove an existing asset from price tracking */ function removeAsset(address assetAddress) public onlyAdmin { require( assetAddress != address(0), "Asset or Price Feed address cannot be 0x00" ); priceContractMapping[assetAddress] = AggregatorV3Interface(address(0)); emit assetRemoved(assetAddress); } /** * Allows admin to change the admin of the contract */ function changeAdmin(address newAdmin) public onlyAdmin { require( newAdmin != address(0), "Asset or Price Feed address cannot be 0x00" ); emit adminChanged(admin, newAdmin); admin = newAdmin; } /** * Allows admin to set the weth address for verified protocol */ function setWethAddressVerified(address _wethAddressVerified) public onlyAdmin { require(_wethAddressVerified != address(0), "WETH address cannot be 0x00"); wethAddressVerified = _wethAddressVerified; emit verifiedWethAddressSet(_wethAddressVerified); } /** * Allows admin to set the weth address for public protocol */ function setWethAddressPublic(address _wethAddressPublic) public onlyAdmin { require(_wethAddressPublic != address(0), "WETH address cannot be 0x00"); wethAddressPublic = _wethAddressPublic; emit publicWethAddressSet(_wethAddressPublic); } /** * Allows admin to pause and unpause the contract */ function togglePause() public onlyAdmin { if (paused) { paused = false; emit contractPausedOrUnpaused(false); } else { paused = true; emit contractPausedOrUnpaused(true); } } /** * Returns the latest price scaled to 1e18 scale */ function getAssetPrice(address asset) public view returns (uint256, uint8) { // Return 1 * 10^18 for WETH, otherwise return actual price if (!paused) { if ( asset == wethAddressVerified || asset == wethAddressPublic ){ return (expScale, eighteen); } } // Capture the decimals in the ERC20 token uint8 assetDecimals = EIP20Interface(asset).decimals(); if (!paused && priceContractMapping[asset] != address(0)) { ( uint80 roundID, int256 price, uint256 startedAt, uint256 timeStamp, uint80 answeredInRound ) = priceContractMapping[asset].latestRoundData(); startedAt; // To avoid compiler warnings for unused local variable // If the price data was not refreshed for the past 1 day, prices are considered stale // This threshold is the maximum Chainlink uses to update the price feeds require(timeStamp > (now - 86500 seconds), "Stale data"); // If answeredInRound is less than roundID, prices are considered stale require(answeredInRound >= roundID, "Stale Data"); if (price > 0) { // Magnify the result based on decimals return (uint256(price), assetDecimals); } else { return (0, assetDecimals); } } else { return (0, assetDecimals); } } function() public payable { require( msg.sender.send(msg.value), "Fallback function initiated but refund failed" ); } } // File: contracts/AlkemiWETH.sol // Cloned from https://github.com/gnosis/canonical-weth/blob/master/contracts/WETH9.sol -> Commit id: 0dd1ea3 pragma solidity 0.4.24; contract AlkemiWETH { string public name = "Wrapped Ether"; string public symbol = "WETH"; uint8 public decimals = 18; event Approval(address indexed src, address indexed guy, uint256 wad); event Transfer(address indexed src, address indexed dst, uint256 wad); event Deposit(address indexed dst, uint256 wad); event Withdrawal(address indexed src, uint256 wad); mapping(address => uint256) public balanceOf; mapping(address => mapping(address => uint256)) public allowance; function() public payable { deposit(); } function deposit() public payable { balanceOf[msg.sender] += msg.value; emit Deposit(msg.sender, msg.value); emit Transfer(address(0), msg.sender, msg.value); } function withdraw(address user, uint256 wad) public { require(balanceOf[msg.sender] >= wad); balanceOf[msg.sender] -= wad; user.transfer(wad); emit Withdrawal(msg.sender, wad); emit Transfer(msg.sender, address(0), wad); } function totalSupply() public view returns (uint256) { return address(this).balance; } function approve(address guy, uint256 wad) public returns (bool) { allowance[msg.sender][guy] = wad; emit Approval(msg.sender, guy, wad); return true; } function transfer(address dst, uint256 wad) public returns (bool) { return transferFrom(msg.sender, dst, wad); } function transferFrom( address src, address dst, uint256 wad ) public returns (bool) { require(balanceOf[src] >= wad); if (src != msg.sender && allowance[src][msg.sender] != uint256(-1)) { require(allowance[src][msg.sender] >= wad); allowance[src][msg.sender] -= wad; } balanceOf[src] -= wad; balanceOf[dst] += wad; emit Transfer(src, dst, wad); return true; } } // File: contracts/RewardControlInterface.sol pragma solidity 0.4.24; contract RewardControlInterface { /** * @notice Refresh ALK supply index for the specified market and supplier * @param market The market whose supply index to update * @param supplier The address of the supplier to distribute ALK to * @param isVerified Verified / Public protocol */ function refreshAlkSupplyIndex( address market, address supplier, bool isVerified ) external; /** * @notice Refresh ALK borrow index for the specified market and borrower * @param market The market whose borrow index to update * @param borrower The address of the borrower to distribute ALK to * @param isVerified Verified / Public protocol */ function refreshAlkBorrowIndex( address market, address borrower, bool isVerified ) external; /** * @notice Claim all the ALK accrued by holder in all markets * @param holder The address to claim ALK for */ function claimAlk(address holder) external; /** * @notice Claim all the ALK accrued by holder by refreshing the indexes on the specified market only * @param holder The address to claim ALK for * @param market The address of the market to refresh the indexes for * @param isVerified Verified / Public protocol */ function claimAlk( address holder, address market, bool isVerified ) external; } // File: contracts/AlkemiEarnVerified.sol pragma solidity 0.4.24; contract AlkemiEarnVerified is Exponential, SafeToken { uint256 internal initialInterestIndex; uint256 internal defaultOriginationFee; uint256 internal defaultCollateralRatio; uint256 internal defaultLiquidationDiscount; // minimumCollateralRatioMantissa and maximumLiquidationDiscountMantissa cannot be declared as constants due to upgradeability // Values cannot be assigned directly as OpenZeppelin upgrades do not support the same // Values can only be assigned using initializer() below // However, there is no way to change the below values using any functions and hence they act as constants uint256 public minimumCollateralRatioMantissa; uint256 public maximumLiquidationDiscountMantissa; bool private initializationDone; // To make sure initializer is called only once /** * @notice `AlkemiEarnVerified` is the core contract * @notice This contract uses Openzeppelin Upgrades plugin to make use of the upgradeability functionality using proxies * @notice Hence this contract has an 'initializer' in place of a 'constructor' * @notice Make sure to add new global variables only at the bottom of all the existing global variables i.e., line #344 * @notice Also make sure to do extensive testing while modifying any structs and enums during an upgrade */ function initializer() public { if (initializationDone == false) { initializationDone = true; admin = msg.sender; initialInterestIndex = 10**18; minimumCollateralRatioMantissa = 11 * (10**17); // 1.1 maximumLiquidationDiscountMantissa = (10**17); // 0.1 collateralRatio = Exp({mantissa: 125 * (10**16)}); originationFee = Exp({mantissa: (10**15)}); liquidationDiscount = Exp({mantissa: (10**17)}); // oracle must be configured via _adminFunctions } } /** * @notice Do not pay directly into AlkemiEarnVerified, please use `supply`. */ function() public payable { revert(); } /** * @dev pending Administrator for this contract. */ address public pendingAdmin; /** * @dev Administrator for this contract. Initially set in constructor, but can * be changed by the admin itself. */ address public admin; /** * @dev Managers for this contract with limited permissions. Can * be changed by the admin. * Though unused, the below variable cannot be deleted as it will hinder upgradeability * Will be cleared during the next compiler version upgrade */ mapping(address => bool) public managers; /** * @dev Account allowed to set oracle prices for this contract. Initially set * in constructor, but can be changed by the admin. */ address private oracle; /** * @dev Modifier to check if the caller is the admin of the contract */ modifier onlyOwner() { require(msg.sender == admin, "Owner check failed"); _; } /** * @dev Modifier to check if the caller is KYC verified */ modifier onlyCustomerWithKYC() { require( customersWithKYC[msg.sender], "KYC_CUSTOMER_VERIFICATION_CHECK_FAILED" ); _; } /** * @dev Account allowed to fetch chainlink oracle prices for this contract. Can be changed by the admin. */ ChainLink public priceOracle; /** * @dev Container for customer balance information written to storage. * * struct Balance { * principal = customer total balance with accrued interest after applying the customer's most recent balance-changing action * interestIndex = Checkpoint for interest calculation after the customer's most recent balance-changing action * } */ struct Balance { uint256 principal; uint256 interestIndex; } /** * @dev 2-level map: customerAddress -> assetAddress -> balance for supplies */ mapping(address => mapping(address => Balance)) public supplyBalances; /** * @dev 2-level map: customerAddress -> assetAddress -> balance for borrows */ mapping(address => mapping(address => Balance)) public borrowBalances; /** * @dev Container for per-asset balance sheet and interest rate information written to storage, intended to be stored in a map where the asset address is the key * * struct Market { * isSupported = Whether this market is supported or not (not to be confused with the list of collateral assets) * blockNumber = when the other values in this struct were calculated * interestRateModel = Interest Rate model, which calculates supply interest rate and borrow interest rate based on Utilization, used for the asset * totalSupply = total amount of this asset supplied (in asset wei) * supplyRateMantissa = the per-block interest rate for supplies of asset as of blockNumber, scaled by 10e18 * supplyIndex = the interest index for supplies of asset as of blockNumber; initialized in _supportMarket * totalBorrows = total amount of this asset borrowed (in asset wei) * borrowRateMantissa = the per-block interest rate for borrows of asset as of blockNumber, scaled by 10e18 * borrowIndex = the interest index for borrows of asset as of blockNumber; initialized in _supportMarket * } */ struct Market { bool isSupported; uint256 blockNumber; InterestRateModel interestRateModel; uint256 totalSupply; uint256 supplyRateMantissa; uint256 supplyIndex; uint256 totalBorrows; uint256 borrowRateMantissa; uint256 borrowIndex; } /** * @dev wethAddress to hold the WETH token contract address * set using setWethAddress function */ address private wethAddress; /** * @dev Initiates the contract for supply and withdraw Ether and conversion to WETH */ AlkemiWETH public WETHContract; /** * @dev map: assetAddress -> Market */ mapping(address => Market) public markets; /** * @dev list: collateralMarkets */ address[] public collateralMarkets; /** * @dev The collateral ratio that borrows must maintain (e.g. 2 implies 2:1). This * is initially set in the constructor, but can be changed by the admin. */ Exp public collateralRatio; /** * @dev originationFee for new borrows. * */ Exp public originationFee; /** * @dev liquidationDiscount for collateral when liquidating borrows * */ Exp public liquidationDiscount; /** * @dev flag for whether or not contract is paused * */ bool public paused; /** * @dev Mapping to identify the list of KYC Admins */ mapping(address => bool) public KYCAdmins; /** * @dev Mapping to identify the list of customers with verified KYC */ mapping(address => bool) public customersWithKYC; /** * @dev Mapping to identify the list of customers with Liquidator roles */ mapping(address => bool) public liquidators; /** * The `SupplyLocalVars` struct is used internally in the `supply` function. * * To avoid solidity limits on the number of local variables we: * 1. Use a struct to hold local computation localResults * 2. Re-use a single variable for Error returns. (This is required with 1 because variable binding to tuple localResults * requires either both to be declared inline or both to be previously declared. * 3. Re-use a boolean error-like return variable. */ struct SupplyLocalVars { uint256 startingBalance; uint256 newSupplyIndex; uint256 userSupplyCurrent; uint256 userSupplyUpdated; uint256 newTotalSupply; uint256 currentCash; uint256 updatedCash; uint256 newSupplyRateMantissa; uint256 newBorrowIndex; uint256 newBorrowRateMantissa; } /** * The `WithdrawLocalVars` struct is used internally in the `withdraw` function. * * To avoid solidity limits on the number of local variables we: * 1. Use a struct to hold local computation localResults * 2. Re-use a single variable for Error returns. (This is required with 1 because variable binding to tuple localResults * requires either both to be declared inline or both to be previously declared. * 3. Re-use a boolean error-like return variable. */ struct WithdrawLocalVars { uint256 withdrawAmount; uint256 startingBalance; uint256 newSupplyIndex; uint256 userSupplyCurrent; uint256 userSupplyUpdated; uint256 newTotalSupply; uint256 currentCash; uint256 updatedCash; uint256 newSupplyRateMantissa; uint256 newBorrowIndex; uint256 newBorrowRateMantissa; uint256 withdrawCapacity; Exp accountLiquidity; Exp accountShortfall; Exp ethValueOfWithdrawal; } // The `AccountValueLocalVars` struct is used internally in the `CalculateAccountValuesInternal` function. struct AccountValueLocalVars { address assetAddress; uint256 collateralMarketsLength; uint256 newSupplyIndex; uint256 userSupplyCurrent; uint256 newBorrowIndex; uint256 userBorrowCurrent; Exp borrowTotalValue; Exp sumBorrows; Exp supplyTotalValue; Exp sumSupplies; } // The `PayBorrowLocalVars` struct is used internally in the `repayBorrow` function. struct PayBorrowLocalVars { uint256 newBorrowIndex; uint256 userBorrowCurrent; uint256 repayAmount; uint256 userBorrowUpdated; uint256 newTotalBorrows; uint256 currentCash; uint256 updatedCash; uint256 newSupplyIndex; uint256 newSupplyRateMantissa; uint256 newBorrowRateMantissa; uint256 startingBalance; } // The `BorrowLocalVars` struct is used internally in the `borrow` function. struct BorrowLocalVars { uint256 newBorrowIndex; uint256 userBorrowCurrent; uint256 borrowAmountWithFee; uint256 userBorrowUpdated; uint256 newTotalBorrows; uint256 currentCash; uint256 updatedCash; uint256 newSupplyIndex; uint256 newSupplyRateMantissa; uint256 newBorrowRateMantissa; uint256 startingBalance; Exp accountLiquidity; Exp accountShortfall; Exp ethValueOfBorrowAmountWithFee; } // The `LiquidateLocalVars` struct is used internally in the `liquidateBorrow` function. struct LiquidateLocalVars { // we need these addresses in the struct for use with `emitLiquidationEvent` to avoid `CompilerError: Stack too deep, try removing local variables.` address targetAccount; address assetBorrow; address liquidator; address assetCollateral; // borrow index and supply index are global to the asset, not specific to the user uint256 newBorrowIndex_UnderwaterAsset; uint256 newSupplyIndex_UnderwaterAsset; uint256 newBorrowIndex_CollateralAsset; uint256 newSupplyIndex_CollateralAsset; // the target borrow's full balance with accumulated interest uint256 currentBorrowBalance_TargetUnderwaterAsset; // currentBorrowBalance_TargetUnderwaterAsset minus whatever gets repaid as part of the liquidation uint256 updatedBorrowBalance_TargetUnderwaterAsset; uint256 newTotalBorrows_ProtocolUnderwaterAsset; uint256 startingBorrowBalance_TargetUnderwaterAsset; uint256 startingSupplyBalance_TargetCollateralAsset; uint256 startingSupplyBalance_LiquidatorCollateralAsset; uint256 currentSupplyBalance_TargetCollateralAsset; uint256 updatedSupplyBalance_TargetCollateralAsset; // If liquidator already has a balance of collateralAsset, we will accumulate // interest on it before transferring seized collateral from the borrower. uint256 currentSupplyBalance_LiquidatorCollateralAsset; // This will be the liquidator's accumulated balance of collateral asset before the liquidation (if any) // plus the amount seized from the borrower. uint256 updatedSupplyBalance_LiquidatorCollateralAsset; uint256 newTotalSupply_ProtocolCollateralAsset; uint256 currentCash_ProtocolUnderwaterAsset; uint256 updatedCash_ProtocolUnderwaterAsset; // cash does not change for collateral asset uint256 newSupplyRateMantissa_ProtocolUnderwaterAsset; uint256 newBorrowRateMantissa_ProtocolUnderwaterAsset; // Why no variables for the interest rates for the collateral asset? // We don't need to calculate new rates for the collateral asset since neither cash nor borrows change uint256 discountedRepayToEvenAmount; //[supplyCurrent / (1 + liquidationDiscount)] * (Oracle price for the collateral / Oracle price for the borrow) (discountedBorrowDenominatedCollateral) uint256 discountedBorrowDenominatedCollateral; uint256 maxCloseableBorrowAmount_TargetUnderwaterAsset; uint256 closeBorrowAmount_TargetUnderwaterAsset; uint256 seizeSupplyAmount_TargetCollateralAsset; uint256 reimburseAmount; Exp collateralPrice; Exp underwaterAssetPrice; } /** * @dev 2-level map: customerAddress -> assetAddress -> originationFeeBalance for borrows */ mapping(address => mapping(address => uint256)) public originationFeeBalance; /** * @dev Reward Control Contract address */ RewardControlInterface public rewardControl; /** * @notice Multiplier used to calculate the maximum repayAmount when liquidating a borrow */ uint256 public closeFactorMantissa; /// @dev _guardCounter and nonReentrant modifier extracted from Open Zeppelin's reEntrancyGuard /// @dev counter to allow mutex lock with only one SSTORE operation uint256 public _guardCounter; /** * @dev Prevents a contract from calling itself, directly or indirectly. * If you mark a function `nonReentrant`, you should also * mark it `external`. Calling one `nonReentrant` function from * another is not supported. Instead, you can implement a * `private` function doing the actual work, and an `external` * wrapper marked as `nonReentrant`. */ modifier nonReentrant() { _guardCounter += 1; uint256 localCounter = _guardCounter; _; require(localCounter == _guardCounter); } /** * @dev Events to notify the frontend of all the functions below */ event LiquidatorChanged(address indexed Liquidator, bool newStatus); /** * @dev emitted when a supply is received * Note: newBalance - amount - startingBalance = interest accumulated since last change */ event SupplyReceived( address account, address asset, uint256 amount, uint256 startingBalance, uint256 newBalance ); /** * @dev emitted when a supply is withdrawn * Note: startingBalance - amount - startingBalance = interest accumulated since last change */ event SupplyWithdrawn( address account, address asset, uint256 amount, uint256 startingBalance, uint256 newBalance ); /** * @dev emitted when a new borrow is taken * Note: newBalance - borrowAmountWithFee - startingBalance = interest accumulated since last change */ event BorrowTaken( address account, address asset, uint256 amount, uint256 startingBalance, uint256 borrowAmountWithFee, uint256 newBalance ); /** * @dev emitted when a borrow is repaid * Note: newBalance - amount - startingBalance = interest accumulated since last change */ event BorrowRepaid( address account, address asset, uint256 amount, uint256 startingBalance, uint256 newBalance ); /** * @dev emitted when a borrow is liquidated * targetAccount = user whose borrow was liquidated * assetBorrow = asset borrowed * borrowBalanceBefore = borrowBalance as most recently stored before the liquidation * borrowBalanceAccumulated = borroBalanceBefore + accumulated interest as of immediately prior to the liquidation * amountRepaid = amount of borrow repaid * liquidator = account requesting the liquidation * assetCollateral = asset taken from targetUser and given to liquidator in exchange for liquidated loan * borrowBalanceAfter = new stored borrow balance (should equal borrowBalanceAccumulated - amountRepaid) * collateralBalanceBefore = collateral balance as most recently stored before the liquidation * collateralBalanceAccumulated = collateralBalanceBefore + accumulated interest as of immediately prior to the liquidation * amountSeized = amount of collateral seized by liquidator * collateralBalanceAfter = new stored collateral balance (should equal collateralBalanceAccumulated - amountSeized) * assetBorrow and assetCollateral are not indexed as indexed addresses in an event is limited to 3 */ event BorrowLiquidated( address indexed targetAccount, address assetBorrow, uint256 borrowBalanceAccumulated, uint256 amountRepaid, address indexed liquidator, address assetCollateral, uint256 amountSeized ); /** * @dev emitted when admin withdraws equity * Note that `equityAvailableBefore` indicates equity before `amount` was removed. */ event EquityWithdrawn( address indexed asset, uint256 equityAvailableBefore, uint256 amount, address indexed owner ); /** * @dev KYC Integration */ /** * @dev Events to notify the frontend of all the functions below */ event KYCAdminChanged(address indexed KYCAdmin, bool newStatus); event KYCCustomerChanged(address indexed KYCCustomer, bool newStatus); /** * @dev Function for use by the admin of the contract to add or remove KYC Admins */ function _changeKYCAdmin(address KYCAdmin, bool newStatus) public onlyOwner { KYCAdmins[KYCAdmin] = newStatus; emit KYCAdminChanged(KYCAdmin, newStatus); } /** * @dev Function for use by the KYC admins to add or remove KYC Customers */ function _changeCustomerKYC(address customer, bool newStatus) public { require(KYCAdmins[msg.sender], "KYC_ADMIN_CHECK_FAILED"); customersWithKYC[customer] = newStatus; emit KYCCustomerChanged(customer, newStatus); } /** * @dev Liquidator Integration */ /** * @dev Function for use by the admin of the contract to add or remove Liquidators */ function _changeLiquidator(address liquidator, bool newStatus) public onlyOwner { liquidators[liquidator] = newStatus; emit LiquidatorChanged(liquidator, newStatus); } /** * @dev Simple function to calculate min between two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { if (a < b) { return a; } else { return b; } } /** * @dev Adds a given asset to the list of collateral markets. This operation is impossible to reverse. * Note: this will not add the asset if it already exists. */ function addCollateralMarket(address asset) internal { for (uint256 i = 0; i < collateralMarkets.length; i++) { if (collateralMarkets[i] == asset) { return; } } collateralMarkets.push(asset); } /** * @dev Calculates a new supply index based on the prevailing interest rates applied over time * This is defined as `we multiply the most recent supply index by (1 + blocks times rate)` * @return Return value is expressed in 1e18 scale */ function calculateInterestIndex( uint256 startingInterestIndex, uint256 interestRateMantissa, uint256 blockStart, uint256 blockEnd ) internal pure returns (Error, uint256) { // Get the block delta (Error err0, uint256 blockDelta) = sub(blockEnd, blockStart); if (err0 != Error.NO_ERROR) { return (err0, 0); } // Scale the interest rate times number of blocks // Note: Doing Exp construction inline to avoid `CompilerError: Stack too deep, try removing local variables.` (Error err1, Exp memory blocksTimesRate) = mulScalar( Exp({mantissa: interestRateMantissa}), blockDelta ); if (err1 != Error.NO_ERROR) { return (err1, 0); } // Add one to that result (which is really Exp({mantissa: expScale}) which equals 1.0) (Error err2, Exp memory onePlusBlocksTimesRate) = addExp( blocksTimesRate, Exp({mantissa: mantissaOne}) ); if (err2 != Error.NO_ERROR) { return (err2, 0); } // Then scale that accumulated interest by the old interest index to get the new interest index (Error err3, Exp memory newInterestIndexExp) = mulScalar( onePlusBlocksTimesRate, startingInterestIndex ); if (err3 != Error.NO_ERROR) { return (err3, 0); } // Finally, truncate the interest index. This works only if interest index starts large enough // that is can be accurately represented with a whole number. return (Error.NO_ERROR, truncate(newInterestIndexExp)); } /** * @dev Calculates a new balance based on a previous balance and a pair of interest indices * This is defined as: `The user's last balance checkpoint is multiplied by the currentSupplyIndex * value and divided by the user's checkpoint index value` * @return Return value is expressed in 1e18 scale */ function calculateBalance( uint256 startingBalance, uint256 interestIndexStart, uint256 interestIndexEnd ) internal pure returns (Error, uint256) { if (startingBalance == 0) { // We are accumulating interest on any previous balance; if there's no previous balance, then there is // nothing to accumulate. return (Error.NO_ERROR, 0); } (Error err0, uint256 balanceTimesIndex) = mul( startingBalance, interestIndexEnd ); if (err0 != Error.NO_ERROR) { return (err0, 0); } return div(balanceTimesIndex, interestIndexStart); } /** * @dev Gets the price for the amount specified of the given asset. * @return Return value is expressed in a magnified scale per token decimals */ function getPriceForAssetAmount( address asset, uint256 assetAmount, bool mulCollatRatio ) internal view returns (Error, Exp memory) { (Error err, Exp memory assetPrice) = fetchAssetPrice(asset); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0})); } if (isZeroExp(assetPrice)) { return (Error.MISSING_ASSET_PRICE, Exp({mantissa: 0})); } if (mulCollatRatio) { Exp memory scaledPrice; // Now, multiply the assetValue by the collateral ratio (err, scaledPrice) = mulExp(collateralRatio, assetPrice); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0})); } // Get the price for the given asset amount return mulScalar(scaledPrice, assetAmount); } return mulScalar(assetPrice, assetAmount); // assetAmountWei * oraclePrice = assetValueInEth } /** * @dev Calculates the origination fee added to a given borrowAmount * This is simply `(1 + originationFee) * borrowAmount` * @return Return value is expressed in 1e18 scale */ function calculateBorrowAmountWithFee(uint256 borrowAmount) internal view returns (Error, uint256) { // When origination fee is zero, the amount with fee is simply equal to the amount if (isZeroExp(originationFee)) { return (Error.NO_ERROR, borrowAmount); } (Error err0, Exp memory originationFeeFactor) = addExp( originationFee, Exp({mantissa: mantissaOne}) ); if (err0 != Error.NO_ERROR) { return (err0, 0); } (Error err1, Exp memory borrowAmountWithFee) = mulScalar( originationFeeFactor, borrowAmount ); if (err1 != Error.NO_ERROR) { return (err1, 0); } return (Error.NO_ERROR, truncate(borrowAmountWithFee)); } /** * @dev fetches the price of asset from the PriceOracle and converts it to Exp * @param asset asset whose price should be fetched * @return Return value is expressed in a magnified scale per token decimals */ function fetchAssetPrice(address asset) internal view returns (Error, Exp memory) { if (priceOracle == address(0)) { return (Error.ZERO_ORACLE_ADDRESS, Exp({mantissa: 0})); } if (priceOracle.paused()) { return (Error.MISSING_ASSET_PRICE, Exp({mantissa: 0})); } (uint256 priceMantissa, uint8 assetDecimals) = priceOracle .getAssetPrice(asset); (Error err, uint256 magnification) = sub(18, uint256(assetDecimals)); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0})); } (err, priceMantissa) = mul(priceMantissa, 10**magnification); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0})); } return (Error.NO_ERROR, Exp({mantissa: priceMantissa})); } /** * @notice Reads scaled price of specified asset from the price oracle * @dev Reads scaled price of specified asset from the price oracle. * The plural name is to match a previous storage mapping that this function replaced. * @param asset Asset whose price should be retrieved * @return 0 on an error or missing price, the price scaled by 1e18 otherwise */ function assetPrices(address asset) public view returns (uint256) { (Error err, Exp memory result) = fetchAssetPrice(asset); if (err != Error.NO_ERROR) { return 0; } return result.mantissa; } /** * @dev Gets the amount of the specified asset given the specified Eth value * ethValue / oraclePrice = assetAmountWei * If there's no oraclePrice, this returns (Error.DIVISION_BY_ZERO, 0) * @return Return value is expressed in a magnified scale per token decimals */ function getAssetAmountForValue(address asset, Exp ethValue) internal view returns (Error, uint256) { Error err; Exp memory assetPrice; Exp memory assetAmount; (err, assetPrice) = fetchAssetPrice(asset); if (err != Error.NO_ERROR) { return (err, 0); } (err, assetAmount) = divExp(ethValue, assetPrice); if (err != Error.NO_ERROR) { return (err, 0); } return (Error.NO_ERROR, truncate(assetAmount)); } /** * @notice Admin Functions. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @param newPendingAdmin New pending admin * @param newOracle New oracle address * @param requestedState value to assign to `paused` * @param originationFeeMantissa rational collateral ratio, scaled by 1e18. * @param newCloseFactorMantissa new Close Factor, scaled by 1e18 * @param wethContractAddress WETH Contract Address * @param _rewardControl Reward Control Address * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _adminFunctions( address newPendingAdmin, address newOracle, bool requestedState, uint256 originationFeeMantissa, uint256 newCloseFactorMantissa, address wethContractAddress, address _rewardControl ) public onlyOwner returns (uint256) { // newPendingAdmin can be 0x00, hence not checked require(newOracle != address(0), "Cannot set weth address to 0x00"); require( originationFeeMantissa < 10**18 && newCloseFactorMantissa < 10**18, "Invalid Origination Fee or Close Factor Mantissa" ); // Store pendingAdmin = newPendingAdmin pendingAdmin = newPendingAdmin; // Verify contract at newOracle address supports assetPrices call. // This will revert if it doesn't. // ChainLink priceOracleTemp = ChainLink(newOracle); // priceOracleTemp.getAssetPrice(address(0)); // Initialize the Chainlink contract in priceOracle priceOracle = ChainLink(newOracle); paused = requestedState; originationFee = Exp({mantissa: originationFeeMantissa}); closeFactorMantissa = newCloseFactorMantissa; require( wethContractAddress != address(0), "Cannot set weth address to 0x00" ); wethAddress = wethContractAddress; WETHContract = AlkemiWETH(wethAddress); rewardControl = RewardControlInterface(_rewardControl); return uint256(Error.NO_ERROR); } /** * @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin * @dev Admin function for pending admin to accept role and update admin */ function _acceptAdmin() public { // Check caller = pendingAdmin // msg.sender can't be zero require(msg.sender == pendingAdmin, "ACCEPT_ADMIN_PENDING_ADMIN_CHECK"); // Store admin = pendingAdmin admin = pendingAdmin; // Clear the pending value pendingAdmin = 0; } /** * @notice returns the liquidity for given account. * a positive result indicates ability to borrow, whereas * a negative result indicates a shortfall which may be liquidated * @dev returns account liquidity in terms of eth-wei value, scaled by 1e18 and truncated when the value is 0 or when the last few decimals are 0 * note: this includes interest trued up on all balances * @param account the account to examine * @return signed integer in terms of eth-wei (negative indicates a shortfall) */ function getAccountLiquidity(address account) public view returns (int256) { ( Error err, Exp memory accountLiquidity, Exp memory accountShortfall ) = calculateAccountLiquidity(account); revertIfError(err); if (isZeroExp(accountLiquidity)) { return -1 * int256(truncate(accountShortfall)); } else { return int256(truncate(accountLiquidity)); } } /** * @notice return supply balance with any accumulated interest for `asset` belonging to `account` * @dev returns supply balance with any accumulated interest for `asset` belonging to `account` * @param account the account to examine * @param asset the market asset whose supply balance belonging to `account` should be checked * @return uint supply balance on success, throws on failed assertion otherwise */ function getSupplyBalance(address account, address asset) public view returns (uint256) { Error err; uint256 newSupplyIndex; uint256 userSupplyCurrent; Market storage market = markets[asset]; Balance storage supplyBalance = supplyBalances[account][asset]; // Calculate the newSupplyIndex, needed to calculate user's supplyCurrent (err, newSupplyIndex) = calculateInterestIndex( market.supplyIndex, market.supplyRateMantissa, market.blockNumber, block.number ); revertIfError(err); // Use newSupplyIndex and stored principal to calculate the accumulated balance (err, userSupplyCurrent) = calculateBalance( supplyBalance.principal, supplyBalance.interestIndex, newSupplyIndex ); revertIfError(err); return userSupplyCurrent; } /** * @notice return borrow balance with any accumulated interest for `asset` belonging to `account` * @dev returns borrow balance with any accumulated interest for `asset` belonging to `account` * @param account the account to examine * @param asset the market asset whose borrow balance belonging to `account` should be checked * @return uint borrow balance on success, throws on failed assertion otherwise */ function getBorrowBalance(address account, address asset) public view returns (uint256) { Error err; uint256 newBorrowIndex; uint256 userBorrowCurrent; Market storage market = markets[asset]; Balance storage borrowBalance = borrowBalances[account][asset]; // Calculate the newBorrowIndex, needed to calculate user's borrowCurrent (err, newBorrowIndex) = calculateInterestIndex( market.borrowIndex, market.borrowRateMantissa, market.blockNumber, block.number ); revertIfError(err); // Use newBorrowIndex and stored principal to calculate the accumulated balance (err, userBorrowCurrent) = calculateBalance( borrowBalance.principal, borrowBalance.interestIndex, newBorrowIndex ); revertIfError(err); return userBorrowCurrent; } /** * @notice Supports a given market (asset) for use * @dev Admin function to add support for a market * @param asset Asset to support; MUST already have a non-zero price set * @param interestRateModel InterestRateModel to use for the asset * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _supportMarket(address asset, InterestRateModel interestRateModel) public onlyOwner returns (uint256) { // Hard cap on the maximum number of markets allowed require( interestRateModel != address(0) && collateralMarkets.length < 16, // 16 = MAXIMUM_NUMBER_OF_MARKETS_ALLOWED "INPUT_VALIDATION_FAILED" ); (Error err, Exp memory assetPrice) = fetchAssetPrice(asset); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.SUPPORT_MARKET_FETCH_PRICE_FAILED); } if (isZeroExp(assetPrice)) { return fail( Error.ASSET_NOT_PRICED, FailureInfo.SUPPORT_MARKET_PRICE_CHECK ); } // Set the interest rate model to `modelAddress` markets[asset].interestRateModel = interestRateModel; // Append asset to collateralAssets if not set addCollateralMarket(asset); // Set market isSupported to true markets[asset].isSupported = true; // Default supply and borrow index to 1e18 if (markets[asset].supplyIndex == 0) { markets[asset].supplyIndex = initialInterestIndex; } if (markets[asset].borrowIndex == 0) { markets[asset].borrowIndex = initialInterestIndex; } return uint256(Error.NO_ERROR); } /** * @notice Suspends a given *supported* market (asset) from use. * Assets in this state do count for collateral, but users may only withdraw, payBorrow, * and liquidate the asset. The liquidate function no longer checks collateralization. * @dev Admin function to suspend a market * @param asset Asset to suspend * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _suspendMarket(address asset) public onlyOwner returns (uint256) { // If the market is not configured at all, we don't want to add any configuration for it. // If we find !markets[asset].isSupported then either the market is not configured at all, or it // has already been marked as unsupported. We can just return without doing anything. // Caller is responsible for knowing the difference between not-configured and already unsupported. if (!markets[asset].isSupported) { return uint256(Error.NO_ERROR); } // If we get here, we know market is configured and is supported, so set isSupported to false markets[asset].isSupported = false; return uint256(Error.NO_ERROR); } /** * @notice Sets the risk parameters: collateral ratio and liquidation discount * @dev Owner function to set the risk parameters * @param collateralRatioMantissa rational collateral ratio, scaled by 1e18. The de-scaled value must be >= 1.1 * @param liquidationDiscountMantissa rational liquidation discount, scaled by 1e18. The de-scaled value must be <= 0.1 and must be less than (descaled collateral ratio minus 1) * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setRiskParameters( uint256 collateralRatioMantissa, uint256 liquidationDiscountMantissa ) public onlyOwner returns (uint256) { // Input validations require( collateralRatioMantissa >= minimumCollateralRatioMantissa && liquidationDiscountMantissa <= maximumLiquidationDiscountMantissa, "Liquidation discount is more than max discount or collateral ratio is less than min ratio" ); Exp memory newCollateralRatio = Exp({ mantissa: collateralRatioMantissa }); Exp memory newLiquidationDiscount = Exp({ mantissa: liquidationDiscountMantissa }); Exp memory minimumCollateralRatio = Exp({ mantissa: minimumCollateralRatioMantissa }); Exp memory maximumLiquidationDiscount = Exp({ mantissa: maximumLiquidationDiscountMantissa }); Error err; Exp memory newLiquidationDiscountPlusOne; // Make sure new collateral ratio value is not below minimum value if (lessThanExp(newCollateralRatio, minimumCollateralRatio)) { return fail( Error.INVALID_COLLATERAL_RATIO, FailureInfo.SET_RISK_PARAMETERS_VALIDATION ); } // Make sure new liquidation discount does not exceed the maximum value, but reverse operands so we can use the // existing `lessThanExp` function rather than adding a `greaterThan` function to Exponential. if (lessThanExp(maximumLiquidationDiscount, newLiquidationDiscount)) { return fail( Error.INVALID_LIQUIDATION_DISCOUNT, FailureInfo.SET_RISK_PARAMETERS_VALIDATION ); } // C = L+1 is not allowed because it would cause division by zero error in `calculateDiscountedRepayToEvenAmount` // C < L+1 is not allowed because it would cause integer underflow error in `calculateDiscountedRepayToEvenAmount` (err, newLiquidationDiscountPlusOne) = addExp( newLiquidationDiscount, Exp({mantissa: mantissaOne}) ); revertIfError(err); // We already validated that newLiquidationDiscount does not approach overflow size if ( lessThanOrEqualExp( newCollateralRatio, newLiquidationDiscountPlusOne ) ) { return fail( Error.INVALID_COMBINED_RISK_PARAMETERS, FailureInfo.SET_RISK_PARAMETERS_VALIDATION ); } // Store new values collateralRatio = newCollateralRatio; liquidationDiscount = newLiquidationDiscount; return uint256(Error.NO_ERROR); } /** * @notice Sets the interest rate model for a given market * @dev Admin function to set interest rate model * @param asset Asset to support * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setMarketInterestRateModel( address asset, InterestRateModel interestRateModel ) public onlyOwner returns (uint256) { require(interestRateModel != address(0), "Rate Model cannot be 0x00"); // Set the interest rate model to `modelAddress` markets[asset].interestRateModel = interestRateModel; return uint256(Error.NO_ERROR); } /** * @notice withdraws `amount` of `asset` from equity for asset, as long as `amount` <= equity. Equity = cash + borrows - supply * @dev withdraws `amount` of `asset` from equity for asset, enforcing amount <= cash + borrows - supply * @param asset asset whose equity should be withdrawn * @param amount amount of equity to withdraw; must not exceed equity available * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _withdrawEquity(address asset, uint256 amount) public onlyOwner returns (uint256) { // Check that amount is less than cash (from ERC-20 of self) plus borrows minus supply. uint256 cash = getCash(asset); // Get supply and borrows with interest accrued till the latest block ( uint256 supplyWithInterest, uint256 borrowWithInterest ) = getMarketBalances(asset); (Error err0, uint256 equity) = addThenSub( getCash(asset), borrowWithInterest, supplyWithInterest ); if (err0 != Error.NO_ERROR) { return fail(err0, FailureInfo.EQUITY_WITHDRAWAL_CALCULATE_EQUITY); } if (amount > equity) { return fail( Error.EQUITY_INSUFFICIENT_BALANCE, FailureInfo.EQUITY_WITHDRAWAL_AMOUNT_VALIDATION ); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) if (asset != wethAddress) { // Withdrawal should happen as Ether directly // We ERC-20 transfer the asset out of the protocol to the admin Error err2 = doTransferOut(asset, admin, amount); if (err2 != Error.NO_ERROR) { // This is safe since it's our first interaction and it didn't do anything if it failed return fail( err2, FailureInfo.EQUITY_WITHDRAWAL_TRANSFER_OUT_FAILED ); } } else { withdrawEther(admin, amount); // send Ether to user } (, markets[asset].supplyRateMantissa) = markets[asset] .interestRateModel .getSupplyRate(asset, cash - amount, markets[asset].totalSupply); (, markets[asset].borrowRateMantissa) = markets[asset] .interestRateModel .getBorrowRate(asset, cash - amount, markets[asset].totalBorrows); //event EquityWithdrawn(address asset, uint equityAvailableBefore, uint amount, address owner) emit EquityWithdrawn(asset, equity, amount, admin); return uint256(Error.NO_ERROR); // success } /** * @dev Convert Ether supplied by user into WETH tokens and then supply corresponding WETH to user * @return errors if any * @param etherAmount Amount of ether to be converted to WETH */ function supplyEther(uint256 etherAmount) internal returns (uint256) { require(wethAddress != address(0), "WETH_ADDRESS_NOT_SET_ERROR"); WETHContract.deposit.value(etherAmount)(); return uint256(Error.NO_ERROR); } /** * @dev Revert Ether paid by user back to user's account in case transaction fails due to some other reason * @param etherAmount Amount of ether to be sent back to user * @param user User account address */ function revertEtherToUser(address user, uint256 etherAmount) internal { if (etherAmount > 0) { user.transfer(etherAmount); } } /** * @notice supply `amount` of `asset` (which must be supported) to `msg.sender` in the protocol * @dev add amount of supported asset to msg.sender's account * @param asset The market asset to supply * @param amount The amount to supply * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function supply(address asset, uint256 amount) public payable nonReentrant onlyCustomerWithKYC returns (uint256) { if (paused) { revertEtherToUser(msg.sender, msg.value); return fail(Error.CONTRACT_PAUSED, FailureInfo.SUPPLY_CONTRACT_PAUSED); } refreshAlkIndex(asset, msg.sender, true, true); Market storage market = markets[asset]; Balance storage balance = supplyBalances[msg.sender][asset]; SupplyLocalVars memory localResults; // Holds all our uint calculation results Error err; // Re-used for every function call that includes an Error in its return value(s). uint256 rateCalculationResultCode; // Used for 2 interest rate calculation calls // Fail if market not supported if (!market.isSupported) { revertEtherToUser(msg.sender, msg.value); return fail( Error.MARKET_NOT_SUPPORTED, FailureInfo.SUPPLY_MARKET_NOT_SUPPORTED ); } if (asset != wethAddress) { // WETH is supplied to AlkemiEarnVerified contract in case of ETH automatically // Fail gracefully if asset is not approved or has insufficient balance revertEtherToUser(msg.sender, msg.value); err = checkTransferIn(asset, msg.sender, amount); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.SUPPLY_TRANSFER_IN_NOT_POSSIBLE); } } // We calculate the newSupplyIndex, user's supplyCurrent and supplyUpdated for the asset (err, localResults.newSupplyIndex) = calculateInterestIndex( market.supplyIndex, market.supplyRateMantissa, market.blockNumber, block.number ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.SUPPLY_NEW_SUPPLY_INDEX_CALCULATION_FAILED ); } (err, localResults.userSupplyCurrent) = calculateBalance( balance.principal, balance.interestIndex, localResults.newSupplyIndex ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.SUPPLY_ACCUMULATED_BALANCE_CALCULATION_FAILED ); } (err, localResults.userSupplyUpdated) = add( localResults.userSupplyCurrent, amount ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.SUPPLY_NEW_TOTAL_BALANCE_CALCULATION_FAILED ); } // We calculate the protocol's totalSupply by subtracting the user's prior checkpointed balance, adding user's updated supply (err, localResults.newTotalSupply) = addThenSub( market.totalSupply, localResults.userSupplyUpdated, balance.principal ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.SUPPLY_NEW_TOTAL_SUPPLY_CALCULATION_FAILED ); } // We need to calculate what the updated cash will be after we transfer in from user localResults.currentCash = getCash(asset); (err, localResults.updatedCash) = add(localResults.currentCash, amount); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail(err, FailureInfo.SUPPLY_NEW_TOTAL_CASH_CALCULATION_FAILED); } // The utilization rate has changed! We calculate a new supply index and borrow index for the asset, and save it. (rateCalculationResultCode, localResults.newSupplyRateMantissa) = market .interestRateModel .getSupplyRate(asset, localResults.updatedCash, market.totalBorrows); if (rateCalculationResultCode != 0) { revertEtherToUser(msg.sender, msg.value); return failOpaque( FailureInfo.SUPPLY_NEW_SUPPLY_RATE_CALCULATION_FAILED, rateCalculationResultCode ); } // We calculate the newBorrowIndex (we already had newSupplyIndex) (err, localResults.newBorrowIndex) = calculateInterestIndex( market.borrowIndex, market.borrowRateMantissa, market.blockNumber, block.number ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.SUPPLY_NEW_BORROW_INDEX_CALCULATION_FAILED ); } (rateCalculationResultCode, localResults.newBorrowRateMantissa) = market .interestRateModel .getBorrowRate(asset, localResults.updatedCash, market.totalBorrows); if (rateCalculationResultCode != 0) { revertEtherToUser(msg.sender, msg.value); return failOpaque( FailureInfo.SUPPLY_NEW_BORROW_RATE_CALCULATION_FAILED, rateCalculationResultCode ); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) // Save market updates market.blockNumber = block.number; market.totalSupply = localResults.newTotalSupply; market.supplyRateMantissa = localResults.newSupplyRateMantissa; market.supplyIndex = localResults.newSupplyIndex; market.borrowRateMantissa = localResults.newBorrowRateMantissa; market.borrowIndex = localResults.newBorrowIndex; // Save user updates localResults.startingBalance = balance.principal; // save for use in `SupplyReceived` event balance.principal = localResults.userSupplyUpdated; balance.interestIndex = localResults.newSupplyIndex; if (asset != wethAddress) { // WETH is supplied to AlkemiEarnVerified contract in case of ETH automatically // We ERC-20 transfer the asset into the protocol (note: pre-conditions already checked above) revertEtherToUser(msg.sender, msg.value); err = doTransferIn(asset, msg.sender, amount); if (err != Error.NO_ERROR) { // This is safe since it's our first interaction and it didn't do anything if it failed return fail(err, FailureInfo.SUPPLY_TRANSFER_IN_FAILED); } } else { if (msg.value == amount) { uint256 supplyError = supplyEther(msg.value); if (supplyError != 0) { revertEtherToUser(msg.sender, msg.value); return fail( Error.WETH_ADDRESS_NOT_SET_ERROR, FailureInfo.WETH_ADDRESS_NOT_SET_ERROR ); } } else { revertEtherToUser(msg.sender, msg.value); return fail( Error.ETHER_AMOUNT_MISMATCH_ERROR, FailureInfo.ETHER_AMOUNT_MISMATCH_ERROR ); } } emit SupplyReceived( msg.sender, asset, amount, localResults.startingBalance, balance.principal ); return uint256(Error.NO_ERROR); // success } /** * @notice withdraw `amount` of `ether` from sender's account to sender's address * @dev withdraw `amount` of `ether` from msg.sender's account to msg.sender * @param etherAmount Amount of ether to be converted to WETH * @param user User account address */ function withdrawEther(address user, uint256 etherAmount) internal returns (uint256) { WETHContract.withdraw(user, etherAmount); return uint256(Error.NO_ERROR); } /** * @notice withdraw `amount` of `asset` from sender's account to sender's address * @dev withdraw `amount` of `asset` from msg.sender's account to msg.sender * @param asset The market asset to withdraw * @param requestedAmount The amount to withdraw (or -1 for max) * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function withdraw(address asset, uint256 requestedAmount) public nonReentrant returns (uint256) { if (paused) { return fail( Error.CONTRACT_PAUSED, FailureInfo.WITHDRAW_CONTRACT_PAUSED ); } refreshAlkIndex(asset, msg.sender, true, true); Market storage market = markets[asset]; Balance storage supplyBalance = supplyBalances[msg.sender][asset]; WithdrawLocalVars memory localResults; // Holds all our calculation results Error err; // Re-used for every function call that includes an Error in its return value(s). uint256 rateCalculationResultCode; // Used for 2 interest rate calculation calls // We calculate the user's accountLiquidity and accountShortfall. ( err, localResults.accountLiquidity, localResults.accountShortfall ) = calculateAccountLiquidity(msg.sender); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.WITHDRAW_ACCOUNT_LIQUIDITY_CALCULATION_FAILED ); } // We calculate the newSupplyIndex, user's supplyCurrent and supplyUpdated for the asset (err, localResults.newSupplyIndex) = calculateInterestIndex( market.supplyIndex, market.supplyRateMantissa, market.blockNumber, block.number ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.WITHDRAW_NEW_SUPPLY_INDEX_CALCULATION_FAILED ); } (err, localResults.userSupplyCurrent) = calculateBalance( supplyBalance.principal, supplyBalance.interestIndex, localResults.newSupplyIndex ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.WITHDRAW_ACCUMULATED_BALANCE_CALCULATION_FAILED ); } // If the user specifies -1 amount to withdraw ("max"), withdrawAmount => the lesser of withdrawCapacity and supplyCurrent if (requestedAmount == uint256(-1)) { (err, localResults.withdrawCapacity) = getAssetAmountForValue( asset, localResults.accountLiquidity ); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.WITHDRAW_CAPACITY_CALCULATION_FAILED); } localResults.withdrawAmount = min( localResults.withdrawCapacity, localResults.userSupplyCurrent ); } else { localResults.withdrawAmount = requestedAmount; } // From here on we should NOT use requestedAmount. // Fail gracefully if protocol has insufficient cash // If protocol has insufficient cash, the sub operation will underflow. localResults.currentCash = getCash(asset); (err, localResults.updatedCash) = sub( localResults.currentCash, localResults.withdrawAmount ); if (err != Error.NO_ERROR) { return fail( Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.WITHDRAW_TRANSFER_OUT_NOT_POSSIBLE ); } // We check that the amount is less than or equal to supplyCurrent // If amount is greater than supplyCurrent, this will fail with Error.INTEGER_UNDERFLOW (err, localResults.userSupplyUpdated) = sub( localResults.userSupplyCurrent, localResults.withdrawAmount ); if (err != Error.NO_ERROR) { return fail( Error.INSUFFICIENT_BALANCE, FailureInfo.WITHDRAW_NEW_TOTAL_BALANCE_CALCULATION_FAILED ); } // Fail if customer already has a shortfall if (!isZeroExp(localResults.accountShortfall)) { return fail( Error.INSUFFICIENT_LIQUIDITY, FailureInfo.WITHDRAW_ACCOUNT_SHORTFALL_PRESENT ); } // We want to know the user's withdrawCapacity, denominated in the asset // Customer's withdrawCapacity of asset is (accountLiquidity in Eth)/ (price of asset in Eth) // Equivalently, we calculate the eth value of the withdrawal amount and compare it directly to the accountLiquidity in Eth (err, localResults.ethValueOfWithdrawal) = getPriceForAssetAmount( asset, localResults.withdrawAmount, false ); // amount * oraclePrice = ethValueOfWithdrawal if (err != Error.NO_ERROR) { return fail(err, FailureInfo.WITHDRAW_AMOUNT_VALUE_CALCULATION_FAILED); } // We check that the amount is less than withdrawCapacity (here), and less than or equal to supplyCurrent (below) if ( lessThanExp( localResults.accountLiquidity, localResults.ethValueOfWithdrawal ) ) { return fail( Error.INSUFFICIENT_LIQUIDITY, FailureInfo.WITHDRAW_AMOUNT_LIQUIDITY_SHORTFALL ); } // We calculate the protocol's totalSupply by subtracting the user's prior checkpointed balance, adding user's updated supply. // Note that, even though the customer is withdrawing, if they've accumulated a lot of interest since their last // action, the updated balance *could* be higher than the prior checkpointed balance. (err, localResults.newTotalSupply) = addThenSub( market.totalSupply, localResults.userSupplyUpdated, supplyBalance.principal ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.WITHDRAW_NEW_TOTAL_SUPPLY_CALCULATION_FAILED ); } // The utilization rate has changed! We calculate a new supply index and borrow index for the asset, and save it. (rateCalculationResultCode, localResults.newSupplyRateMantissa) = market .interestRateModel .getSupplyRate(asset, localResults.updatedCash, market.totalBorrows); if (rateCalculationResultCode != 0) { return failOpaque( FailureInfo.WITHDRAW_NEW_SUPPLY_RATE_CALCULATION_FAILED, rateCalculationResultCode ); } // We calculate the newBorrowIndex (err, localResults.newBorrowIndex) = calculateInterestIndex( market.borrowIndex, market.borrowRateMantissa, market.blockNumber, block.number ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.WITHDRAW_NEW_BORROW_INDEX_CALCULATION_FAILED ); } (rateCalculationResultCode, localResults.newBorrowRateMantissa) = market .interestRateModel .getBorrowRate(asset, localResults.updatedCash, market.totalBorrows); if (rateCalculationResultCode != 0) { return failOpaque( FailureInfo.WITHDRAW_NEW_BORROW_RATE_CALCULATION_FAILED, rateCalculationResultCode ); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) // Save market updates market.blockNumber = block.number; market.totalSupply = localResults.newTotalSupply; market.supplyRateMantissa = localResults.newSupplyRateMantissa; market.supplyIndex = localResults.newSupplyIndex; market.borrowRateMantissa = localResults.newBorrowRateMantissa; market.borrowIndex = localResults.newBorrowIndex; // Save user updates localResults.startingBalance = supplyBalance.principal; // save for use in `SupplyWithdrawn` event supplyBalance.principal = localResults.userSupplyUpdated; supplyBalance.interestIndex = localResults.newSupplyIndex; if (asset != wethAddress) { // Withdrawal should happen as Ether directly // We ERC-20 transfer the asset into the protocol (note: pre-conditions already checked above) err = doTransferOut(asset, msg.sender, localResults.withdrawAmount); if (err != Error.NO_ERROR) { // This is safe since it's our first interaction and it didn't do anything if it failed return fail(err, FailureInfo.WITHDRAW_TRANSFER_OUT_FAILED); } } else { withdrawEther(msg.sender, localResults.withdrawAmount); // send Ether to user } emit SupplyWithdrawn( msg.sender, asset, localResults.withdrawAmount, localResults.startingBalance, supplyBalance.principal ); return uint256(Error.NO_ERROR); // success } /** * @dev Gets the user's account liquidity and account shortfall balances. This includes * any accumulated interest thus far but does NOT actually update anything in * storage, it simply calculates the account liquidity and shortfall with liquidity being * returned as the first Exp, ie (Error, accountLiquidity, accountShortfall). * @return Return values are expressed in 1e18 scale */ function calculateAccountLiquidity(address userAddress) internal view returns ( Error, Exp memory, Exp memory ) { Error err; Exp memory sumSupplyValuesMantissa; Exp memory sumBorrowValuesMantissa; ( err, sumSupplyValuesMantissa, sumBorrowValuesMantissa ) = calculateAccountValuesInternal(userAddress); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } Exp memory result; Exp memory sumSupplyValuesFinal = Exp({ mantissa: sumSupplyValuesMantissa.mantissa }); Exp memory sumBorrowValuesFinal; // need to apply collateral ratio (err, sumBorrowValuesFinal) = mulExp( collateralRatio, Exp({mantissa: sumBorrowValuesMantissa.mantissa}) ); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } // if sumSupplies < sumBorrows, then the user is under collateralized and has account shortfall. // else the user meets the collateral ratio and has account liquidity. if (lessThanExp(sumSupplyValuesFinal, sumBorrowValuesFinal)) { // accountShortfall = borrows - supplies (err, result) = subExp(sumBorrowValuesFinal, sumSupplyValuesFinal); revertIfError(err); // Note: we have checked that sumBorrows is greater than sumSupplies directly above, therefore `subExp` cannot fail. return (Error.NO_ERROR, Exp({mantissa: 0}), result); } else { // accountLiquidity = supplies - borrows (err, result) = subExp(sumSupplyValuesFinal, sumBorrowValuesFinal); revertIfError(err); // Note: we have checked that sumSupplies is greater than sumBorrows directly above, therefore `subExp` cannot fail. return (Error.NO_ERROR, result, Exp({mantissa: 0})); } } /** * @notice Gets the ETH values of the user's accumulated supply and borrow balances, scaled by 10e18. * This includes any accumulated interest thus far but does NOT actually update anything in * storage * @dev Gets ETH values of accumulated supply and borrow balances * @param userAddress account for which to sum values * @return (error code, sum ETH value of supplies scaled by 10e18, sum ETH value of borrows scaled by 10e18) */ function calculateAccountValuesInternal(address userAddress) internal view returns ( Error, Exp memory, Exp memory ) { /** By definition, all collateralMarkets are those that contribute to the user's * liquidity and shortfall so we need only loop through those markets. * To handle avoiding intermediate negative results, we will sum all the user's * supply balances and borrow balances (with collateral ratio) separately and then * subtract the sums at the end. */ AccountValueLocalVars memory localResults; // Re-used for all intermediate results localResults.sumSupplies = Exp({mantissa: 0}); localResults.sumBorrows = Exp({mantissa: 0}); Error err; // Re-used for all intermediate errors localResults.collateralMarketsLength = collateralMarkets.length; for (uint256 i = 0; i < localResults.collateralMarketsLength; i++) { localResults.assetAddress = collateralMarkets[i]; Market storage currentMarket = markets[localResults.assetAddress]; Balance storage supplyBalance = supplyBalances[userAddress][ localResults.assetAddress ]; Balance storage borrowBalance = borrowBalances[userAddress][ localResults.assetAddress ]; if (supplyBalance.principal > 0) { // We calculate the newSupplyIndex and user’s supplyCurrent (includes interest) (err, localResults.newSupplyIndex) = calculateInterestIndex( currentMarket.supplyIndex, currentMarket.supplyRateMantissa, currentMarket.blockNumber, block.number ); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } (err, localResults.userSupplyCurrent) = calculateBalance( supplyBalance.principal, supplyBalance.interestIndex, localResults.newSupplyIndex ); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } // We have the user's supply balance with interest so let's multiply by the asset price to get the total value (err, localResults.supplyTotalValue) = getPriceForAssetAmount( localResults.assetAddress, localResults.userSupplyCurrent, false ); // supplyCurrent * oraclePrice = supplyValueInEth if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } // Add this to our running sum of supplies (err, localResults.sumSupplies) = addExp( localResults.supplyTotalValue, localResults.sumSupplies ); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } } if (borrowBalance.principal > 0) { // We perform a similar actions to get the user's borrow balance (err, localResults.newBorrowIndex) = calculateInterestIndex( currentMarket.borrowIndex, currentMarket.borrowRateMantissa, currentMarket.blockNumber, block.number ); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } (err, localResults.userBorrowCurrent) = calculateBalance( borrowBalance.principal, borrowBalance.interestIndex, localResults.newBorrowIndex ); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } // We have the user's borrow balance with interest so let's multiply by the asset price to get the total value (err, localResults.borrowTotalValue) = getPriceForAssetAmount( localResults.assetAddress, localResults.userBorrowCurrent, false ); // borrowCurrent * oraclePrice = borrowValueInEth if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } // Add this to our running sum of borrows (err, localResults.sumBorrows) = addExp( localResults.borrowTotalValue, localResults.sumBorrows ); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } } } return ( Error.NO_ERROR, localResults.sumSupplies, localResults.sumBorrows ); } /** * @notice Gets the ETH values of the user's accumulated supply and borrow balances, scaled by 10e18. * This includes any accumulated interest thus far but does NOT actually update anything in * storage * @dev Gets ETH values of accumulated supply and borrow balances * @param userAddress account for which to sum values * @return (uint 0=success; otherwise a failure (see ErrorReporter.sol for details), * sum ETH value of supplies scaled by 10e18, * sum ETH value of borrows scaled by 10e18) */ function calculateAccountValues(address userAddress) public view returns ( uint256, uint256, uint256 ) { ( Error err, Exp memory supplyValue, Exp memory borrowValue ) = calculateAccountValuesInternal(userAddress); if (err != Error.NO_ERROR) { return (uint256(err), 0, 0); } return (0, supplyValue.mantissa, borrowValue.mantissa); } /** * @notice Users repay borrowed assets from their own address to the protocol. * @param asset The market asset to repay * @param amount The amount to repay (or -1 for max) * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function repayBorrow(address asset, uint256 amount) public payable nonReentrant returns (uint256) { if (paused) { revertEtherToUser(msg.sender, msg.value); return fail( Error.CONTRACT_PAUSED, FailureInfo.REPAY_BORROW_CONTRACT_PAUSED ); } refreshAlkIndex(asset, msg.sender, false, true); PayBorrowLocalVars memory localResults; Market storage market = markets[asset]; Balance storage borrowBalance = borrowBalances[msg.sender][asset]; Error err; uint256 rateCalculationResultCode; // We calculate the newBorrowIndex, user's borrowCurrent and borrowUpdated for the asset (err, localResults.newBorrowIndex) = calculateInterestIndex( market.borrowIndex, market.borrowRateMantissa, market.blockNumber, block.number ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.REPAY_BORROW_NEW_BORROW_INDEX_CALCULATION_FAILED ); } (err, localResults.userBorrowCurrent) = calculateBalance( borrowBalance.principal, borrowBalance.interestIndex, localResults.newBorrowIndex ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo .REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED ); } uint256 reimburseAmount; // If the user specifies -1 amount to repay (“max”), repayAmount => // the lesser of the senders ERC-20 balance and borrowCurrent if (asset != wethAddress) { if (amount == uint256(-1)) { localResults.repayAmount = min( getBalanceOf(asset, msg.sender), localResults.userBorrowCurrent ); } else { localResults.repayAmount = amount; } } else { // To calculate the actual repay use has to do and reimburse the excess amount of ETH collected if (amount > localResults.userBorrowCurrent) { localResults.repayAmount = localResults.userBorrowCurrent; (err, reimburseAmount) = sub( amount, localResults.userBorrowCurrent ); // reimbursement called at the end to make sure function does not have any other errors if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo .REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED ); } } else { localResults.repayAmount = amount; } } // Subtract the `repayAmount` from the `userBorrowCurrent` to get `userBorrowUpdated` // Note: this checks that repayAmount is less than borrowCurrent (err, localResults.userBorrowUpdated) = sub( localResults.userBorrowCurrent, localResults.repayAmount ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo .REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED ); } // Fail gracefully if asset is not approved or has insufficient balance // Note: this checks that repayAmount is less than or equal to their ERC-20 balance if (asset != wethAddress) { // WETH is supplied to AlkemiEarnVerified contract in case of ETH automatically revertEtherToUser(msg.sender, msg.value); err = checkTransferIn(asset, msg.sender, localResults.repayAmount); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.REPAY_BORROW_TRANSFER_IN_NOT_POSSIBLE ); } } // We calculate the protocol's totalBorrow by subtracting the user's prior checkpointed balance, adding user's updated borrow // Note that, even though the customer is paying some of their borrow, if they've accumulated a lot of interest since their last // action, the updated balance *could* be higher than the prior checkpointed balance. (err, localResults.newTotalBorrows) = addThenSub( market.totalBorrows, localResults.userBorrowUpdated, borrowBalance.principal ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.REPAY_BORROW_NEW_TOTAL_BORROW_CALCULATION_FAILED ); } // We need to calculate what the updated cash will be after we transfer in from user localResults.currentCash = getCash(asset); (err, localResults.updatedCash) = add( localResults.currentCash, localResults.repayAmount ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.REPAY_BORROW_NEW_TOTAL_CASH_CALCULATION_FAILED ); } // The utilization rate has changed! We calculate a new supply index and borrow index for the asset, and save it. // We calculate the newSupplyIndex, but we have newBorrowIndex already (err, localResults.newSupplyIndex) = calculateInterestIndex( market.supplyIndex, market.supplyRateMantissa, market.blockNumber, block.number ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.REPAY_BORROW_NEW_SUPPLY_INDEX_CALCULATION_FAILED ); } (rateCalculationResultCode, localResults.newSupplyRateMantissa) = market .interestRateModel .getSupplyRate( asset, localResults.updatedCash, localResults.newTotalBorrows ); if (rateCalculationResultCode != 0) { revertEtherToUser(msg.sender, msg.value); return failOpaque( FailureInfo.REPAY_BORROW_NEW_SUPPLY_RATE_CALCULATION_FAILED, rateCalculationResultCode ); } (rateCalculationResultCode, localResults.newBorrowRateMantissa) = market .interestRateModel .getBorrowRate( asset, localResults.updatedCash, localResults.newTotalBorrows ); if (rateCalculationResultCode != 0) { revertEtherToUser(msg.sender, msg.value); return failOpaque( FailureInfo.REPAY_BORROW_NEW_BORROW_RATE_CALCULATION_FAILED, rateCalculationResultCode ); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) // Save market updates market.blockNumber = block.number; market.totalBorrows = localResults.newTotalBorrows; market.supplyRateMantissa = localResults.newSupplyRateMantissa; market.supplyIndex = localResults.newSupplyIndex; market.borrowRateMantissa = localResults.newBorrowRateMantissa; market.borrowIndex = localResults.newBorrowIndex; // Save user updates localResults.startingBalance = borrowBalance.principal; // save for use in `BorrowRepaid` event borrowBalance.principal = localResults.userBorrowUpdated; borrowBalance.interestIndex = localResults.newBorrowIndex; if (asset != wethAddress) { // WETH is supplied to AlkemiEarnVerified contract in case of ETH automatically // We ERC-20 transfer the asset into the protocol (note: pre-conditions already checked above) revertEtherToUser(msg.sender, msg.value); err = doTransferIn(asset, msg.sender, localResults.repayAmount); if (err != Error.NO_ERROR) { // This is safe since it's our first interaction and it didn't do anything if it failed return fail(err, FailureInfo.REPAY_BORROW_TRANSFER_IN_FAILED); } } else { if (msg.value == amount) { uint256 supplyError = supplyEther(localResults.repayAmount); //Repay excess funds if (reimburseAmount > 0) { revertEtherToUser(msg.sender, reimburseAmount); } if (supplyError != 0) { revertEtherToUser(msg.sender, msg.value); return fail( Error.WETH_ADDRESS_NOT_SET_ERROR, FailureInfo.WETH_ADDRESS_NOT_SET_ERROR ); } } else { revertEtherToUser(msg.sender, msg.value); return fail( Error.ETHER_AMOUNT_MISMATCH_ERROR, FailureInfo.ETHER_AMOUNT_MISMATCH_ERROR ); } } supplyOriginationFeeAsAdmin( asset, msg.sender, localResults.repayAmount, market.supplyIndex ); emit BorrowRepaid( msg.sender, asset, localResults.repayAmount, localResults.startingBalance, borrowBalance.principal ); return uint256(Error.NO_ERROR); // success } /** * @notice users repay all or some of an underwater borrow and receive collateral * @param targetAccount The account whose borrow should be liquidated * @param assetBorrow The market asset to repay * @param assetCollateral The borrower's market asset to receive in exchange * @param requestedAmountClose The amount to repay (or -1 for max) * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function liquidateBorrow( address targetAccount, address assetBorrow, address assetCollateral, uint256 requestedAmountClose ) public payable returns (uint256) { if (paused) { return fail( Error.CONTRACT_PAUSED, FailureInfo.LIQUIDATE_CONTRACT_PAUSED ); } require(liquidators[msg.sender], "LIQUIDATOR_CHECK_FAILED"); refreshAlkIndex(assetCollateral, targetAccount, true, true); refreshAlkIndex(assetCollateral, msg.sender, true, true); refreshAlkIndex(assetBorrow, targetAccount, false, true); LiquidateLocalVars memory localResults; // Copy these addresses into the struct for use with `emitLiquidationEvent` // We'll use localResults.liquidator inside this function for clarity vs using msg.sender. localResults.targetAccount = targetAccount; localResults.assetBorrow = assetBorrow; localResults.liquidator = msg.sender; localResults.assetCollateral = assetCollateral; Market storage borrowMarket = markets[assetBorrow]; Market storage collateralMarket = markets[assetCollateral]; Balance storage borrowBalance_TargeUnderwaterAsset = borrowBalances[ targetAccount ][assetBorrow]; Balance storage supplyBalance_TargetCollateralAsset = supplyBalances[ targetAccount ][assetCollateral]; // Liquidator might already hold some of the collateral asset Balance storage supplyBalance_LiquidatorCollateralAsset = supplyBalances[localResults.liquidator][assetCollateral]; uint256 rateCalculationResultCode; // Used for multiple interest rate calculation calls Error err; // re-used for all intermediate errors (err, localResults.collateralPrice) = fetchAssetPrice(assetCollateral); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.LIQUIDATE_FETCH_ASSET_PRICE_FAILED); } (err, localResults.underwaterAssetPrice) = fetchAssetPrice(assetBorrow); // If the price oracle is not set, then we would have failed on the first call to fetchAssetPrice revertIfError(err); // We calculate newBorrowIndex_UnderwaterAsset and then use it to help calculate currentBorrowBalance_TargetUnderwaterAsset ( err, localResults.newBorrowIndex_UnderwaterAsset ) = calculateInterestIndex( borrowMarket.borrowIndex, borrowMarket.borrowRateMantissa, borrowMarket.blockNumber, block.number ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_NEW_BORROW_INDEX_CALCULATION_FAILED_BORROWED_ASSET ); } ( err, localResults.currentBorrowBalance_TargetUnderwaterAsset ) = calculateBalance( borrowBalance_TargeUnderwaterAsset.principal, borrowBalance_TargeUnderwaterAsset.interestIndex, localResults.newBorrowIndex_UnderwaterAsset ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_ACCUMULATED_BORROW_BALANCE_CALCULATION_FAILED ); } // We calculate newSupplyIndex_CollateralAsset and then use it to help calculate currentSupplyBalance_TargetCollateralAsset ( err, localResults.newSupplyIndex_CollateralAsset ) = calculateInterestIndex( collateralMarket.supplyIndex, collateralMarket.supplyRateMantissa, collateralMarket.blockNumber, block.number ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_NEW_SUPPLY_INDEX_CALCULATION_FAILED_COLLATERAL_ASSET ); } ( err, localResults.currentSupplyBalance_TargetCollateralAsset ) = calculateBalance( supplyBalance_TargetCollateralAsset.principal, supplyBalance_TargetCollateralAsset.interestIndex, localResults.newSupplyIndex_CollateralAsset ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_ACCUMULATED_SUPPLY_BALANCE_CALCULATION_FAILED_BORROWER_COLLATERAL_ASSET ); } // Liquidator may or may not already have some collateral asset. // If they do, we need to accumulate interest on it before adding the seized collateral to it. // We re-use newSupplyIndex_CollateralAsset calculated above to help calculate currentSupplyBalance_LiquidatorCollateralAsset ( err, localResults.currentSupplyBalance_LiquidatorCollateralAsset ) = calculateBalance( supplyBalance_LiquidatorCollateralAsset.principal, supplyBalance_LiquidatorCollateralAsset.interestIndex, localResults.newSupplyIndex_CollateralAsset ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_ACCUMULATED_SUPPLY_BALANCE_CALCULATION_FAILED_LIQUIDATOR_COLLATERAL_ASSET ); } // We update the protocol's totalSupply for assetCollateral in 2 steps, first by adding target user's accumulated // interest and then by adding the liquidator's accumulated interest. // Step 1 of 2: We add the target user's supplyCurrent and subtract their checkpointedBalance // (which has the desired effect of adding accrued interest from the target user) (err, localResults.newTotalSupply_ProtocolCollateralAsset) = addThenSub( collateralMarket.totalSupply, localResults.currentSupplyBalance_TargetCollateralAsset, supplyBalance_TargetCollateralAsset.principal ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_NEW_TOTAL_SUPPLY_BALANCE_CALCULATION_FAILED_BORROWER_COLLATERAL_ASSET ); } // Step 2 of 2: We add the liquidator's supplyCurrent of collateral asset and subtract their checkpointedBalance // (which has the desired effect of adding accrued interest from the calling user) (err, localResults.newTotalSupply_ProtocolCollateralAsset) = addThenSub( localResults.newTotalSupply_ProtocolCollateralAsset, localResults.currentSupplyBalance_LiquidatorCollateralAsset, supplyBalance_LiquidatorCollateralAsset.principal ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_NEW_TOTAL_SUPPLY_BALANCE_CALCULATION_FAILED_LIQUIDATOR_COLLATERAL_ASSET ); } // We calculate maxCloseableBorrowAmount_TargetUnderwaterAsset, the amount of borrow that can be closed from the target user // This is equal to the lesser of // 1. borrowCurrent; (already calculated) // 2. ONLY IF MARKET SUPPORTED: discountedRepayToEvenAmount: // discountedRepayToEvenAmount= // shortfall / [Oracle price for the borrow * (collateralRatio - liquidationDiscount - 1)] // 3. discountedBorrowDenominatedCollateral // [supplyCurrent / (1 + liquidationDiscount)] * (Oracle price for the collateral / Oracle price for the borrow) // Here we calculate item 3. discountedBorrowDenominatedCollateral = // [supplyCurrent / (1 + liquidationDiscount)] * (Oracle price for the collateral / Oracle price for the borrow) ( err, localResults.discountedBorrowDenominatedCollateral ) = calculateDiscountedBorrowDenominatedCollateral( localResults.underwaterAssetPrice, localResults.collateralPrice, localResults.currentSupplyBalance_TargetCollateralAsset ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_BORROW_DENOMINATED_COLLATERAL_CALCULATION_FAILED ); } if (borrowMarket.isSupported) { // Market is supported, so we calculate item 2 from above. ( err, localResults.discountedRepayToEvenAmount ) = calculateDiscountedRepayToEvenAmount( targetAccount, localResults.underwaterAssetPrice, assetBorrow ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_DISCOUNTED_REPAY_TO_EVEN_AMOUNT_CALCULATION_FAILED ); } // We need to do a two-step min to select from all 3 values // min1&3 = min(item 1, item 3) localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset = min( localResults.currentBorrowBalance_TargetUnderwaterAsset, localResults.discountedBorrowDenominatedCollateral ); // min1&3&2 = min(min1&3, 2) localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset = min( localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset, localResults.discountedRepayToEvenAmount ); } else { // Market is not supported, so we don't need to calculate item 2. localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset = min( localResults.currentBorrowBalance_TargetUnderwaterAsset, localResults.discountedBorrowDenominatedCollateral ); } // If liquidateBorrowAmount = -1, then closeBorrowAmount_TargetUnderwaterAsset = maxCloseableBorrowAmount_TargetUnderwaterAsset if (assetBorrow != wethAddress) { if (requestedAmountClose == uint256(-1)) { localResults .closeBorrowAmount_TargetUnderwaterAsset = localResults .maxCloseableBorrowAmount_TargetUnderwaterAsset; } else { localResults .closeBorrowAmount_TargetUnderwaterAsset = requestedAmountClose; } } else { // To calculate the actual repay use has to do and reimburse the excess amount of ETH collected if ( requestedAmountClose > localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset ) { localResults .closeBorrowAmount_TargetUnderwaterAsset = localResults .maxCloseableBorrowAmount_TargetUnderwaterAsset; (err, localResults.reimburseAmount) = sub( requestedAmountClose, localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset ); // reimbursement called at the end to make sure function does not have any other errors if (err != Error.NO_ERROR) { return fail( err, FailureInfo .REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED ); } } else { localResults .closeBorrowAmount_TargetUnderwaterAsset = requestedAmountClose; } } // From here on, no more use of `requestedAmountClose` // Verify closeBorrowAmount_TargetUnderwaterAsset <= maxCloseableBorrowAmount_TargetUnderwaterAsset if ( localResults.closeBorrowAmount_TargetUnderwaterAsset > localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset ) { return fail( Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_TOO_HIGH ); } // seizeSupplyAmount_TargetCollateralAsset = closeBorrowAmount_TargetUnderwaterAsset * priceBorrow/priceCollateral *(1+liquidationDiscount) ( err, localResults.seizeSupplyAmount_TargetCollateralAsset ) = calculateAmountSeize( localResults.underwaterAssetPrice, localResults.collateralPrice, localResults.closeBorrowAmount_TargetUnderwaterAsset ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.LIQUIDATE_AMOUNT_SEIZE_CALCULATION_FAILED ); } // We are going to ERC-20 transfer closeBorrowAmount_TargetUnderwaterAsset of assetBorrow into protocol // Fail gracefully if asset is not approved or has insufficient balance if (assetBorrow != wethAddress) { // WETH is supplied to AlkemiEarnVerified contract in case of ETH automatically err = checkTransferIn( assetBorrow, localResults.liquidator, localResults.closeBorrowAmount_TargetUnderwaterAsset ); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.LIQUIDATE_TRANSFER_IN_NOT_POSSIBLE); } } // We are going to repay the target user's borrow using the calling user's funds // We update the protocol's totalBorrow for assetBorrow, by subtracting the target user's prior checkpointed balance, // adding borrowCurrent, and subtracting closeBorrowAmount_TargetUnderwaterAsset. // Subtract the `closeBorrowAmount_TargetUnderwaterAsset` from the `currentBorrowBalance_TargetUnderwaterAsset` to get `updatedBorrowBalance_TargetUnderwaterAsset` (err, localResults.updatedBorrowBalance_TargetUnderwaterAsset) = sub( localResults.currentBorrowBalance_TargetUnderwaterAsset, localResults.closeBorrowAmount_TargetUnderwaterAsset ); // We have ensured above that localResults.closeBorrowAmount_TargetUnderwaterAsset <= localResults.currentBorrowBalance_TargetUnderwaterAsset, so the sub can't underflow revertIfError(err); // We calculate the protocol's totalBorrow for assetBorrow by subtracting the user's prior checkpointed balance, adding user's updated borrow // Note that, even though the liquidator is paying some of the borrow, if the borrow has accumulated a lot of interest since the last // action, the updated balance *could* be higher than the prior checkpointed balance. ( err, localResults.newTotalBorrows_ProtocolUnderwaterAsset ) = addThenSub( borrowMarket.totalBorrows, localResults.updatedBorrowBalance_TargetUnderwaterAsset, borrowBalance_TargeUnderwaterAsset.principal ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_NEW_TOTAL_BORROW_CALCULATION_FAILED_BORROWED_ASSET ); } // We need to calculate what the updated cash will be after we transfer in from liquidator localResults.currentCash_ProtocolUnderwaterAsset = getCash(assetBorrow); (err, localResults.updatedCash_ProtocolUnderwaterAsset) = add( localResults.currentCash_ProtocolUnderwaterAsset, localResults.closeBorrowAmount_TargetUnderwaterAsset ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_NEW_TOTAL_CASH_CALCULATION_FAILED_BORROWED_ASSET ); } // The utilization rate has changed! We calculate a new supply index, borrow index, supply rate, and borrow rate for assetBorrow // (Please note that we don't need to do the same thing for assetCollateral because neither cash nor borrows of assetCollateral happen in this process.) // We calculate the newSupplyIndex_UnderwaterAsset, but we already have newBorrowIndex_UnderwaterAsset so don't recalculate it. ( err, localResults.newSupplyIndex_UnderwaterAsset ) = calculateInterestIndex( borrowMarket.supplyIndex, borrowMarket.supplyRateMantissa, borrowMarket.blockNumber, block.number ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_NEW_SUPPLY_INDEX_CALCULATION_FAILED_BORROWED_ASSET ); } ( rateCalculationResultCode, localResults.newSupplyRateMantissa_ProtocolUnderwaterAsset ) = borrowMarket.interestRateModel.getSupplyRate( assetBorrow, localResults.updatedCash_ProtocolUnderwaterAsset, localResults.newTotalBorrows_ProtocolUnderwaterAsset ); if (rateCalculationResultCode != 0) { return failOpaque( FailureInfo .LIQUIDATE_NEW_SUPPLY_RATE_CALCULATION_FAILED_BORROWED_ASSET, rateCalculationResultCode ); } ( rateCalculationResultCode, localResults.newBorrowRateMantissa_ProtocolUnderwaterAsset ) = borrowMarket.interestRateModel.getBorrowRate( assetBorrow, localResults.updatedCash_ProtocolUnderwaterAsset, localResults.newTotalBorrows_ProtocolUnderwaterAsset ); if (rateCalculationResultCode != 0) { return failOpaque( FailureInfo .LIQUIDATE_NEW_BORROW_RATE_CALCULATION_FAILED_BORROWED_ASSET, rateCalculationResultCode ); } // Now we look at collateral. We calculated target user's accumulated supply balance and the supply index above. // Now we need to calculate the borrow index. // We don't need to calculate new rates for the collateral asset because we have not changed utilization: // - accumulating interest on the target user's collateral does not change cash or borrows // - transferring seized amount of collateral internally from the target user to the liquidator does not change cash or borrows. ( err, localResults.newBorrowIndex_CollateralAsset ) = calculateInterestIndex( collateralMarket.borrowIndex, collateralMarket.borrowRateMantissa, collateralMarket.blockNumber, block.number ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_NEW_BORROW_INDEX_CALCULATION_FAILED_COLLATERAL_ASSET ); } // We checkpoint the target user's assetCollateral supply balance, supplyCurrent - seizeSupplyAmount_TargetCollateralAsset at the updated index (err, localResults.updatedSupplyBalance_TargetCollateralAsset) = sub( localResults.currentSupplyBalance_TargetCollateralAsset, localResults.seizeSupplyAmount_TargetCollateralAsset ); // The sub won't underflow because because seizeSupplyAmount_TargetCollateralAsset <= target user's collateral balance // maxCloseableBorrowAmount_TargetUnderwaterAsset is limited by the discounted borrow denominated collateral. That limits closeBorrowAmount_TargetUnderwaterAsset // which in turn limits seizeSupplyAmount_TargetCollateralAsset. revertIfError(err); // We checkpoint the liquidating user's assetCollateral supply balance, supplyCurrent + seizeSupplyAmount_TargetCollateralAsset at the updated index ( err, localResults.updatedSupplyBalance_LiquidatorCollateralAsset ) = add( localResults.currentSupplyBalance_LiquidatorCollateralAsset, localResults.seizeSupplyAmount_TargetCollateralAsset ); // We can't overflow here because if this would overflow, then we would have already overflowed above and failed // with LIQUIDATE_NEW_TOTAL_SUPPLY_BALANCE_CALCULATION_FAILED_LIQUIDATOR_COLLATERAL_ASSET revertIfError(err); ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) // Save borrow market updates borrowMarket.blockNumber = block.number; borrowMarket.totalBorrows = localResults .newTotalBorrows_ProtocolUnderwaterAsset; // borrowMarket.totalSupply does not need to be updated borrowMarket.supplyRateMantissa = localResults .newSupplyRateMantissa_ProtocolUnderwaterAsset; borrowMarket.supplyIndex = localResults.newSupplyIndex_UnderwaterAsset; borrowMarket.borrowRateMantissa = localResults .newBorrowRateMantissa_ProtocolUnderwaterAsset; borrowMarket.borrowIndex = localResults.newBorrowIndex_UnderwaterAsset; // Save collateral market updates // We didn't calculate new rates for collateralMarket (because neither cash nor borrows changed), just new indexes and total supply. collateralMarket.blockNumber = block.number; collateralMarket.totalSupply = localResults .newTotalSupply_ProtocolCollateralAsset; collateralMarket.supplyIndex = localResults .newSupplyIndex_CollateralAsset; collateralMarket.borrowIndex = localResults .newBorrowIndex_CollateralAsset; // Save user updates localResults .startingBorrowBalance_TargetUnderwaterAsset = borrowBalance_TargeUnderwaterAsset .principal; // save for use in event borrowBalance_TargeUnderwaterAsset.principal = localResults .updatedBorrowBalance_TargetUnderwaterAsset; borrowBalance_TargeUnderwaterAsset.interestIndex = localResults .newBorrowIndex_UnderwaterAsset; localResults .startingSupplyBalance_TargetCollateralAsset = supplyBalance_TargetCollateralAsset .principal; // save for use in event supplyBalance_TargetCollateralAsset.principal = localResults .updatedSupplyBalance_TargetCollateralAsset; supplyBalance_TargetCollateralAsset.interestIndex = localResults .newSupplyIndex_CollateralAsset; localResults .startingSupplyBalance_LiquidatorCollateralAsset = supplyBalance_LiquidatorCollateralAsset .principal; // save for use in event supplyBalance_LiquidatorCollateralAsset.principal = localResults .updatedSupplyBalance_LiquidatorCollateralAsset; supplyBalance_LiquidatorCollateralAsset.interestIndex = localResults .newSupplyIndex_CollateralAsset; // We ERC-20 transfer the asset into the protocol (note: pre-conditions already checked above) if (assetBorrow != wethAddress) { // WETH is supplied to AlkemiEarnVerified contract in case of ETH automatically revertEtherToUser(msg.sender, msg.value); err = doTransferIn( assetBorrow, localResults.liquidator, localResults.closeBorrowAmount_TargetUnderwaterAsset ); if (err != Error.NO_ERROR) { // This is safe since it's our first interaction and it didn't do anything if it failed return fail(err, FailureInfo.LIQUIDATE_TRANSFER_IN_FAILED); } } else { if (msg.value == requestedAmountClose) { uint256 supplyError = supplyEther( localResults.closeBorrowAmount_TargetUnderwaterAsset ); //Repay excess funds if (localResults.reimburseAmount > 0) { revertEtherToUser( localResults.liquidator, localResults.reimburseAmount ); } if (supplyError != 0) { revertEtherToUser(msg.sender, msg.value); return fail( Error.WETH_ADDRESS_NOT_SET_ERROR, FailureInfo.WETH_ADDRESS_NOT_SET_ERROR ); } } else { revertEtherToUser(msg.sender, msg.value); return fail( Error.ETHER_AMOUNT_MISMATCH_ERROR, FailureInfo.ETHER_AMOUNT_MISMATCH_ERROR ); } } supplyOriginationFeeAsAdmin( assetBorrow, localResults.liquidator, localResults.closeBorrowAmount_TargetUnderwaterAsset, localResults.newSupplyIndex_UnderwaterAsset ); emit BorrowLiquidated( localResults.targetAccount, localResults.assetBorrow, localResults.currentBorrowBalance_TargetUnderwaterAsset, localResults.closeBorrowAmount_TargetUnderwaterAsset, localResults.liquidator, localResults.assetCollateral, localResults.seizeSupplyAmount_TargetCollateralAsset ); return uint256(Error.NO_ERROR); // success } /** * @dev This should ONLY be called if market is supported. It returns shortfall / [Oracle price for the borrow * (collateralRatio - liquidationDiscount - 1)] * If the market isn't supported, we support liquidation of asset regardless of shortfall because we want borrows of the unsupported asset to be closed. * Note that if collateralRatio = liquidationDiscount + 1, then the denominator will be zero and the function will fail with DIVISION_BY_ZERO. * @return Return values are expressed in 1e18 scale */ function calculateDiscountedRepayToEvenAmount( address targetAccount, Exp memory underwaterAssetPrice, address assetBorrow ) internal view returns (Error, uint256) { Error err; Exp memory _accountLiquidity; // unused return value from calculateAccountLiquidity Exp memory accountShortfall_TargetUser; Exp memory collateralRatioMinusLiquidationDiscount; // collateralRatio - liquidationDiscount Exp memory discountedCollateralRatioMinusOne; // collateralRatioMinusLiquidationDiscount - 1, aka collateralRatio - liquidationDiscount - 1 Exp memory discountedPrice_UnderwaterAsset; Exp memory rawResult; // we calculate the target user's shortfall, denominated in Ether, that the user is below the collateral ratio ( err, _accountLiquidity, accountShortfall_TargetUser ) = calculateAccountLiquidity(targetAccount); if (err != Error.NO_ERROR) { return (err, 0); } (err, collateralRatioMinusLiquidationDiscount) = subExp( collateralRatio, liquidationDiscount ); if (err != Error.NO_ERROR) { return (err, 0); } (err, discountedCollateralRatioMinusOne) = subExp( collateralRatioMinusLiquidationDiscount, Exp({mantissa: mantissaOne}) ); if (err != Error.NO_ERROR) { return (err, 0); } (err, discountedPrice_UnderwaterAsset) = mulExp( underwaterAssetPrice, discountedCollateralRatioMinusOne ); // calculateAccountLiquidity multiplies underwaterAssetPrice by collateralRatio // discountedCollateralRatioMinusOne < collateralRatio // so if underwaterAssetPrice * collateralRatio did not overflow then // underwaterAssetPrice * discountedCollateralRatioMinusOne can't overflow either revertIfError(err); /* The liquidator may not repay more than what is allowed by the closeFactor */ uint256 borrowBalance = getBorrowBalance(targetAccount, assetBorrow); Exp memory maxClose; (err, maxClose) = mulScalar( Exp({mantissa: closeFactorMantissa}), borrowBalance ); if (err != Error.NO_ERROR) { return (err, 0); } (err, rawResult) = divExp(maxClose, discountedPrice_UnderwaterAsset); // It's theoretically possible an asset could have such a low price that it truncates to zero when discounted. if (err != Error.NO_ERROR) { return (err, 0); } return (Error.NO_ERROR, truncate(rawResult)); } /** * @dev discountedBorrowDenominatedCollateral = [supplyCurrent / (1 + liquidationDiscount)] * (Oracle price for the collateral / Oracle price for the borrow) * @return Return values are expressed in 1e18 scale */ function calculateDiscountedBorrowDenominatedCollateral( Exp memory underwaterAssetPrice, Exp memory collateralPrice, uint256 supplyCurrent_TargetCollateralAsset ) internal view returns (Error, uint256) { // To avoid rounding issues, we re-order and group the operations so we do 1 division and only at the end // [supplyCurrent * (Oracle price for the collateral)] / [ (1 + liquidationDiscount) * (Oracle price for the borrow) ] Error err; Exp memory onePlusLiquidationDiscount; // (1 + liquidationDiscount) Exp memory supplyCurrentTimesOracleCollateral; // supplyCurrent * Oracle price for the collateral Exp memory onePlusLiquidationDiscountTimesOracleBorrow; // (1 + liquidationDiscount) * Oracle price for the borrow Exp memory rawResult; (err, onePlusLiquidationDiscount) = addExp( Exp({mantissa: mantissaOne}), liquidationDiscount ); if (err != Error.NO_ERROR) { return (err, 0); } (err, supplyCurrentTimesOracleCollateral) = mulScalar( collateralPrice, supplyCurrent_TargetCollateralAsset ); if (err != Error.NO_ERROR) { return (err, 0); } (err, onePlusLiquidationDiscountTimesOracleBorrow) = mulExp( onePlusLiquidationDiscount, underwaterAssetPrice ); if (err != Error.NO_ERROR) { return (err, 0); } (err, rawResult) = divExp( supplyCurrentTimesOracleCollateral, onePlusLiquidationDiscountTimesOracleBorrow ); if (err != Error.NO_ERROR) { return (err, 0); } return (Error.NO_ERROR, truncate(rawResult)); } /** * @dev returns closeBorrowAmount_TargetUnderwaterAsset * (1+liquidationDiscount) * priceBorrow/priceCollateral * @return Return values are expressed in 1e18 scale */ function calculateAmountSeize( Exp memory underwaterAssetPrice, Exp memory collateralPrice, uint256 closeBorrowAmount_TargetUnderwaterAsset ) internal view returns (Error, uint256) { // To avoid rounding issues, we re-order and group the operations to move the division to the end, rather than just taking the ratio of the 2 prices: // underwaterAssetPrice * (1+liquidationDiscount) *closeBorrowAmount_TargetUnderwaterAsset) / collateralPrice // re-used for all intermediate errors Error err; // (1+liquidationDiscount) Exp memory liquidationMultiplier; // assetPrice-of-underwaterAsset * (1+liquidationDiscount) Exp memory priceUnderwaterAssetTimesLiquidationMultiplier; // priceUnderwaterAssetTimesLiquidationMultiplier * closeBorrowAmount_TargetUnderwaterAsset // or, expanded: // underwaterAssetPrice * (1+liquidationDiscount) * closeBorrowAmount_TargetUnderwaterAsset Exp memory finalNumerator; // finalNumerator / priceCollateral Exp memory rawResult; (err, liquidationMultiplier) = addExp( Exp({mantissa: mantissaOne}), liquidationDiscount ); // liquidation discount will be enforced < 1, so 1 + liquidationDiscount can't overflow. revertIfError(err); (err, priceUnderwaterAssetTimesLiquidationMultiplier) = mulExp( underwaterAssetPrice, liquidationMultiplier ); if (err != Error.NO_ERROR) { return (err, 0); } (err, finalNumerator) = mulScalar( priceUnderwaterAssetTimesLiquidationMultiplier, closeBorrowAmount_TargetUnderwaterAsset ); if (err != Error.NO_ERROR) { return (err, 0); } (err, rawResult) = divExp(finalNumerator, collateralPrice); if (err != Error.NO_ERROR) { return (err, 0); } return (Error.NO_ERROR, truncate(rawResult)); } /** * @notice Users borrow assets from the protocol to their own address * @param asset The market asset to borrow * @param amount The amount to borrow * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function borrow(address asset, uint256 amount) public nonReentrant onlyCustomerWithKYC returns (uint256) { if (paused) { return fail(Error.CONTRACT_PAUSED, FailureInfo.BORROW_CONTRACT_PAUSED); } refreshAlkIndex(asset, msg.sender, false, true); BorrowLocalVars memory localResults; Market storage market = markets[asset]; Balance storage borrowBalance = borrowBalances[msg.sender][asset]; Error err; uint256 rateCalculationResultCode; // Fail if market not supported if (!market.isSupported) { return fail( Error.MARKET_NOT_SUPPORTED, FailureInfo.BORROW_MARKET_NOT_SUPPORTED ); } // We calculate the newBorrowIndex, user's borrowCurrent and borrowUpdated for the asset (err, localResults.newBorrowIndex) = calculateInterestIndex( market.borrowIndex, market.borrowRateMantissa, market.blockNumber, block.number ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.BORROW_NEW_BORROW_INDEX_CALCULATION_FAILED ); } (err, localResults.userBorrowCurrent) = calculateBalance( borrowBalance.principal, borrowBalance.interestIndex, localResults.newBorrowIndex ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED ); } // Calculate origination fee. (err, localResults.borrowAmountWithFee) = calculateBorrowAmountWithFee( amount ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.BORROW_ORIGINATION_FEE_CALCULATION_FAILED ); } uint256 orgFeeBalance = localResults.borrowAmountWithFee - amount; // Add the `borrowAmountWithFee` to the `userBorrowCurrent` to get `userBorrowUpdated` (err, localResults.userBorrowUpdated) = add( localResults.userBorrowCurrent, localResults.borrowAmountWithFee ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED ); } // We calculate the protocol's totalBorrow by subtracting the user's prior checkpointed balance, adding user's updated borrow with fee (err, localResults.newTotalBorrows) = addThenSub( market.totalBorrows, localResults.userBorrowUpdated, borrowBalance.principal ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.BORROW_NEW_TOTAL_BORROW_CALCULATION_FAILED ); } // Check customer liquidity ( err, localResults.accountLiquidity, localResults.accountShortfall ) = calculateAccountLiquidity(msg.sender); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.BORROW_ACCOUNT_LIQUIDITY_CALCULATION_FAILED ); } // Fail if customer already has a shortfall if (!isZeroExp(localResults.accountShortfall)) { return fail( Error.INSUFFICIENT_LIQUIDITY, FailureInfo.BORROW_ACCOUNT_SHORTFALL_PRESENT ); } // Would the customer have a shortfall after this borrow (including origination fee)? // We calculate the eth-equivalent value of (borrow amount + fee) of asset and fail if it exceeds accountLiquidity. // This implements: `[(collateralRatio*oraclea*borrowAmount)*(1+borrowFee)] > accountLiquidity` ( err, localResults.ethValueOfBorrowAmountWithFee ) = getPriceForAssetAmount( asset, localResults.borrowAmountWithFee, true ); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.BORROW_AMOUNT_VALUE_CALCULATION_FAILED); } if ( lessThanExp( localResults.accountLiquidity, localResults.ethValueOfBorrowAmountWithFee ) ) { return fail( Error.INSUFFICIENT_LIQUIDITY, FailureInfo.BORROW_AMOUNT_LIQUIDITY_SHORTFALL ); } // Fail gracefully if protocol has insufficient cash localResults.currentCash = getCash(asset); // We need to calculate what the updated cash will be after we transfer out to the user (err, localResults.updatedCash) = sub(localResults.currentCash, amount); if (err != Error.NO_ERROR) { // Note: we ignore error here and call this token insufficient cash return fail( Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.BORROW_NEW_TOTAL_CASH_CALCULATION_FAILED ); } // The utilization rate has changed! We calculate a new supply index and borrow index for the asset, and save it. // We calculate the newSupplyIndex, but we have newBorrowIndex already (err, localResults.newSupplyIndex) = calculateInterestIndex( market.supplyIndex, market.supplyRateMantissa, market.blockNumber, block.number ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.BORROW_NEW_SUPPLY_INDEX_CALCULATION_FAILED ); } (rateCalculationResultCode, localResults.newSupplyRateMantissa) = market .interestRateModel .getSupplyRate( asset, localResults.updatedCash, localResults.newTotalBorrows ); if (rateCalculationResultCode != 0) { return failOpaque( FailureInfo.BORROW_NEW_SUPPLY_RATE_CALCULATION_FAILED, rateCalculationResultCode ); } (rateCalculationResultCode, localResults.newBorrowRateMantissa) = market .interestRateModel .getBorrowRate( asset, localResults.updatedCash, localResults.newTotalBorrows ); if (rateCalculationResultCode != 0) { return failOpaque( FailureInfo.BORROW_NEW_BORROW_RATE_CALCULATION_FAILED, rateCalculationResultCode ); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) // Save market updates market.blockNumber = block.number; market.totalBorrows = localResults.newTotalBorrows; market.supplyRateMantissa = localResults.newSupplyRateMantissa; market.supplyIndex = localResults.newSupplyIndex; market.borrowRateMantissa = localResults.newBorrowRateMantissa; market.borrowIndex = localResults.newBorrowIndex; // Save user updates localResults.startingBalance = borrowBalance.principal; // save for use in `BorrowTaken` event borrowBalance.principal = localResults.userBorrowUpdated; borrowBalance.interestIndex = localResults.newBorrowIndex; originationFeeBalance[msg.sender][asset] += orgFeeBalance; if (asset != wethAddress) { // Withdrawal should happen as Ether directly // We ERC-20 transfer the asset into the protocol (note: pre-conditions already checked above) err = doTransferOut(asset, msg.sender, amount); if (err != Error.NO_ERROR) { // This is safe since it's our first interaction and it didn't do anything if it failed return fail(err, FailureInfo.BORROW_TRANSFER_OUT_FAILED); } } else { withdrawEther(msg.sender, amount); // send Ether to user } emit BorrowTaken( msg.sender, asset, amount, localResults.startingBalance, localResults.borrowAmountWithFee, borrowBalance.principal ); return uint256(Error.NO_ERROR); // success } /** * @notice supply `amount` of `asset` (which must be supported) to `admin` in the protocol * @dev add amount of supported asset to admin's account * @param asset The market asset to supply * @param amount The amount to supply * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function supplyOriginationFeeAsAdmin( address asset, address user, uint256 amount, uint256 newSupplyIndex ) private { refreshAlkIndex(asset, admin, true, true); uint256 originationFeeRepaid = 0; if (originationFeeBalance[user][asset] != 0) { if (amount < originationFeeBalance[user][asset]) { originationFeeRepaid = amount; } else { originationFeeRepaid = originationFeeBalance[user][asset]; } Balance storage balance = supplyBalances[admin][asset]; SupplyLocalVars memory localResults; // Holds all our uint calculation results Error err; // Re-used for every function call that includes an Error in its return value(s). originationFeeBalance[user][asset] -= originationFeeRepaid; (err, localResults.userSupplyCurrent) = calculateBalance( balance.principal, balance.interestIndex, newSupplyIndex ); revertIfError(err); (err, localResults.userSupplyUpdated) = add( localResults.userSupplyCurrent, originationFeeRepaid ); revertIfError(err); // We calculate the protocol's totalSupply by subtracting the user's prior checkpointed balance, adding user's updated supply (err, localResults.newTotalSupply) = addThenSub( markets[asset].totalSupply, localResults.userSupplyUpdated, balance.principal ); revertIfError(err); // Save market updates markets[asset].totalSupply = localResults.newTotalSupply; // Save user updates localResults.startingBalance = balance.principal; balance.principal = localResults.userSupplyUpdated; balance.interestIndex = newSupplyIndex; emit SupplyReceived( admin, asset, originationFeeRepaid, localResults.startingBalance, localResults.userSupplyUpdated ); } } /** * @notice Trigger the underlying Reward Control contract to accrue ALK supply rewards for the supplier on the specified market * @param market The address of the market to accrue rewards * @param user The address of the supplier/borrower to accrue rewards * @param isSupply Specifies if Supply or Borrow Index need to be updated * @param isVerified Verified / Public protocol */ function refreshAlkIndex( address market, address user, bool isSupply, bool isVerified ) internal { if (address(rewardControl) == address(0)) { return; } if (isSupply) { rewardControl.refreshAlkSupplyIndex(market, user, isVerified); } else { rewardControl.refreshAlkBorrowIndex(market, user, isVerified); } } /** * @notice Get supply and borrows for a market * @param asset The market asset to find balances of * @return updated supply and borrows */ function getMarketBalances(address asset) public view returns (uint256, uint256) { Error err; uint256 newSupplyIndex; uint256 marketSupplyCurrent; uint256 newBorrowIndex; uint256 marketBorrowCurrent; Market storage market = markets[asset]; // Calculate the newSupplyIndex, needed to calculate market's supplyCurrent (err, newSupplyIndex) = calculateInterestIndex( market.supplyIndex, market.supplyRateMantissa, market.blockNumber, block.number ); revertIfError(err); // Use newSupplyIndex and stored principal to calculate the accumulated balance (err, marketSupplyCurrent) = calculateBalance( market.totalSupply, market.supplyIndex, newSupplyIndex ); revertIfError(err); // Calculate the newBorrowIndex, needed to calculate market's borrowCurrent (err, newBorrowIndex) = calculateInterestIndex( market.borrowIndex, market.borrowRateMantissa, market.blockNumber, block.number ); revertIfError(err); // Use newBorrowIndex and stored principal to calculate the accumulated balance (err, marketBorrowCurrent) = calculateBalance( market.totalBorrows, market.borrowIndex, newBorrowIndex ); revertIfError(err); return (marketSupplyCurrent, marketBorrowCurrent); } /** * @dev Function to revert in case of an internal exception */ function revertIfError(Error err) internal pure { require( err == Error.NO_ERROR, "Function revert due to internal exception" ); } } // File: contracts/AlkemiEarnPublic.sol pragma solidity 0.4.24; contract AlkemiEarnPublic is Exponential, SafeToken { uint256 internal initialInterestIndex; uint256 internal defaultOriginationFee; uint256 internal defaultCollateralRatio; uint256 internal defaultLiquidationDiscount; // minimumCollateralRatioMantissa and maximumLiquidationDiscountMantissa cannot be declared as constants due to upgradeability // Values cannot be assigned directly as OpenZeppelin upgrades do not support the same // Values can only be assigned using initializer() below // However, there is no way to change the below values using any functions and hence they act as constants uint256 public minimumCollateralRatioMantissa; uint256 public maximumLiquidationDiscountMantissa; bool private initializationDone; // To make sure initializer is called only once /** * @notice `AlkemiEarnPublic` is the core contract * @notice This contract uses Openzeppelin Upgrades plugin to make use of the upgradeability functionality using proxies * @notice Hence this contract has an 'initializer' in place of a 'constructor' * @notice Make sure to add new global variables only at the bottom of all the existing global variables i.e., line #344 * @notice Also make sure to do extensive testing while modifying any structs and enums during an upgrade */ function initializer() public { if (initializationDone == false) { initializationDone = true; admin = msg.sender; initialInterestIndex = 10**18; defaultOriginationFee = (10**15); // default is 0.1% defaultCollateralRatio = 125 * (10**16); // default is 125% or 1.25 defaultLiquidationDiscount = (10**17); // default is 10% or 0.1 minimumCollateralRatioMantissa = 11 * (10**17); // 1.1 maximumLiquidationDiscountMantissa = (10**17); // 0.1 collateralRatio = Exp({mantissa: defaultCollateralRatio}); originationFee = Exp({mantissa: defaultOriginationFee}); liquidationDiscount = Exp({mantissa: defaultLiquidationDiscount}); _guardCounter = 1; // oracle must be configured via _adminFunctions } } /** * @notice Do not pay directly into AlkemiEarnPublic, please use `supply`. */ function() public payable { revert(); } /** * @dev pending Administrator for this contract. */ address public pendingAdmin; /** * @dev Administrator for this contract. Initially set in constructor, but can * be changed by the admin itself. */ address public admin; /** * @dev Managers for this contract with limited permissions. Can * be changed by the admin. * Though unused, the below variable cannot be deleted as it will hinder upgradeability * Will be cleared during the next compiler version upgrade */ mapping(address => bool) public managers; /** * @dev Account allowed to set oracle prices for this contract. Initially set * in constructor, but can be changed by the admin. */ address private oracle; /** * @dev Account allowed to fetch chainlink oracle prices for this contract. Can be changed by the admin. */ ChainLink public priceOracle; /** * @dev Container for customer balance information written to storage. * * struct Balance { * principal = customer total balance with accrued interest after applying the customer's most recent balance-changing action * interestIndex = Checkpoint for interest calculation after the customer's most recent balance-changing action * } */ struct Balance { uint256 principal; uint256 interestIndex; } /** * @dev 2-level map: customerAddress -> assetAddress -> balance for supplies */ mapping(address => mapping(address => Balance)) public supplyBalances; /** * @dev 2-level map: customerAddress -> assetAddress -> balance for borrows */ mapping(address => mapping(address => Balance)) public borrowBalances; /** * @dev Container for per-asset balance sheet and interest rate information written to storage, intended to be stored in a map where the asset address is the key * * struct Market { * isSupported = Whether this market is supported or not (not to be confused with the list of collateral assets) * blockNumber = when the other values in this struct were calculated * interestRateModel = Interest Rate model, which calculates supply interest rate and borrow interest rate based on Utilization, used for the asset * totalSupply = total amount of this asset supplied (in asset wei) * supplyRateMantissa = the per-block interest rate for supplies of asset as of blockNumber, scaled by 10e18 * supplyIndex = the interest index for supplies of asset as of blockNumber; initialized in _supportMarket * totalBorrows = total amount of this asset borrowed (in asset wei) * borrowRateMantissa = the per-block interest rate for borrows of asset as of blockNumber, scaled by 10e18 * borrowIndex = the interest index for borrows of asset as of blockNumber; initialized in _supportMarket * } */ struct Market { bool isSupported; uint256 blockNumber; InterestRateModel interestRateModel; uint256 totalSupply; uint256 supplyRateMantissa; uint256 supplyIndex; uint256 totalBorrows; uint256 borrowRateMantissa; uint256 borrowIndex; } /** * @dev wethAddress to hold the WETH token contract address * set using setWethAddress function */ address private wethAddress; /** * @dev Initiates the contract for supply and withdraw Ether and conversion to WETH */ AlkemiWETH public WETHContract; /** * @dev map: assetAddress -> Market */ mapping(address => Market) public markets; /** * @dev list: collateralMarkets */ address[] public collateralMarkets; /** * @dev The collateral ratio that borrows must maintain (e.g. 2 implies 2:1). This * is initially set in the constructor, but can be changed by the admin. */ Exp public collateralRatio; /** * @dev originationFee for new borrows. * */ Exp public originationFee; /** * @dev liquidationDiscount for collateral when liquidating borrows * */ Exp public liquidationDiscount; /** * @dev flag for whether or not contract is paused * */ bool public paused; /** * The `SupplyLocalVars` struct is used internally in the `supply` function. * * To avoid solidity limits on the number of local variables we: * 1. Use a struct to hold local computation localResults * 2. Re-use a single variable for Error returns. (This is required with 1 because variable binding to tuple localResults * requires either both to be declared inline or both to be previously declared. * 3. Re-use a boolean error-like return variable. */ struct SupplyLocalVars { uint256 startingBalance; uint256 newSupplyIndex; uint256 userSupplyCurrent; uint256 userSupplyUpdated; uint256 newTotalSupply; uint256 currentCash; uint256 updatedCash; uint256 newSupplyRateMantissa; uint256 newBorrowIndex; uint256 newBorrowRateMantissa; } /** * The `WithdrawLocalVars` struct is used internally in the `withdraw` function. * * To avoid solidity limits on the number of local variables we: * 1. Use a struct to hold local computation localResults * 2. Re-use a single variable for Error returns. (This is required with 1 because variable binding to tuple localResults * requires either both to be declared inline or both to be previously declared. * 3. Re-use a boolean error-like return variable. */ struct WithdrawLocalVars { uint256 withdrawAmount; uint256 startingBalance; uint256 newSupplyIndex; uint256 userSupplyCurrent; uint256 userSupplyUpdated; uint256 newTotalSupply; uint256 currentCash; uint256 updatedCash; uint256 newSupplyRateMantissa; uint256 newBorrowIndex; uint256 newBorrowRateMantissa; uint256 withdrawCapacity; Exp accountLiquidity; Exp accountShortfall; Exp ethValueOfWithdrawal; } // The `AccountValueLocalVars` struct is used internally in the `CalculateAccountValuesInternal` function. struct AccountValueLocalVars { address assetAddress; uint256 collateralMarketsLength; uint256 newSupplyIndex; uint256 userSupplyCurrent; uint256 newBorrowIndex; uint256 userBorrowCurrent; Exp supplyTotalValue; Exp sumSupplies; Exp borrowTotalValue; Exp sumBorrows; } // The `PayBorrowLocalVars` struct is used internally in the `repayBorrow` function. struct PayBorrowLocalVars { uint256 newBorrowIndex; uint256 userBorrowCurrent; uint256 repayAmount; uint256 userBorrowUpdated; uint256 newTotalBorrows; uint256 currentCash; uint256 updatedCash; uint256 newSupplyIndex; uint256 newSupplyRateMantissa; uint256 newBorrowRateMantissa; uint256 startingBalance; } // The `BorrowLocalVars` struct is used internally in the `borrow` function. struct BorrowLocalVars { uint256 newBorrowIndex; uint256 userBorrowCurrent; uint256 borrowAmountWithFee; uint256 userBorrowUpdated; uint256 newTotalBorrows; uint256 currentCash; uint256 updatedCash; uint256 newSupplyIndex; uint256 newSupplyRateMantissa; uint256 newBorrowRateMantissa; uint256 startingBalance; Exp accountLiquidity; Exp accountShortfall; Exp ethValueOfBorrowAmountWithFee; } // The `LiquidateLocalVars` struct is used internally in the `liquidateBorrow` function. struct LiquidateLocalVars { // we need these addresses in the struct for use with `emitLiquidationEvent` to avoid `CompilerError: Stack too deep, try removing local variables.` address targetAccount; address assetBorrow; address liquidator; address assetCollateral; // borrow index and supply index are global to the asset, not specific to the user uint256 newBorrowIndex_UnderwaterAsset; uint256 newSupplyIndex_UnderwaterAsset; uint256 newBorrowIndex_CollateralAsset; uint256 newSupplyIndex_CollateralAsset; // the target borrow's full balance with accumulated interest uint256 currentBorrowBalance_TargetUnderwaterAsset; // currentBorrowBalance_TargetUnderwaterAsset minus whatever gets repaid as part of the liquidation uint256 updatedBorrowBalance_TargetUnderwaterAsset; uint256 newTotalBorrows_ProtocolUnderwaterAsset; uint256 startingBorrowBalance_TargetUnderwaterAsset; uint256 startingSupplyBalance_TargetCollateralAsset; uint256 startingSupplyBalance_LiquidatorCollateralAsset; uint256 currentSupplyBalance_TargetCollateralAsset; uint256 updatedSupplyBalance_TargetCollateralAsset; // If liquidator already has a balance of collateralAsset, we will accumulate // interest on it before transferring seized collateral from the borrower. uint256 currentSupplyBalance_LiquidatorCollateralAsset; // This will be the liquidator's accumulated balance of collateral asset before the liquidation (if any) // plus the amount seized from the borrower. uint256 updatedSupplyBalance_LiquidatorCollateralAsset; uint256 newTotalSupply_ProtocolCollateralAsset; uint256 currentCash_ProtocolUnderwaterAsset; uint256 updatedCash_ProtocolUnderwaterAsset; // cash does not change for collateral asset uint256 newSupplyRateMantissa_ProtocolUnderwaterAsset; uint256 newBorrowRateMantissa_ProtocolUnderwaterAsset; // Why no variables for the interest rates for the collateral asset? // We don't need to calculate new rates for the collateral asset since neither cash nor borrows change uint256 discountedRepayToEvenAmount; //[supplyCurrent / (1 + liquidationDiscount)] * (Oracle price for the collateral / Oracle price for the borrow) (discountedBorrowDenominatedCollateral) uint256 discountedBorrowDenominatedCollateral; uint256 maxCloseableBorrowAmount_TargetUnderwaterAsset; uint256 closeBorrowAmount_TargetUnderwaterAsset; uint256 seizeSupplyAmount_TargetCollateralAsset; uint256 reimburseAmount; Exp collateralPrice; Exp underwaterAssetPrice; } /** * @dev 2-level map: customerAddress -> assetAddress -> originationFeeBalance for borrows */ mapping(address => mapping(address => uint256)) public originationFeeBalance; /** * @dev Reward Control Contract address */ RewardControlInterface public rewardControl; /** * @notice Multiplier used to calculate the maximum repayAmount when liquidating a borrow */ uint256 public closeFactorMantissa; /// @dev _guardCounter and nonReentrant modifier extracted from Open Zeppelin's reEntrancyGuard /// @dev counter to allow mutex lock with only one SSTORE operation uint256 public _guardCounter; /** * @dev Prevents a contract from calling itself, directly or indirectly. * If you mark a function `nonReentrant`, you should also * mark it `external`. Calling one `nonReentrant` function from * another is not supported. Instead, you can implement a * `private` function doing the actual work, and an `external` * wrapper marked as `nonReentrant`. */ modifier nonReentrant() { _guardCounter += 1; uint256 localCounter = _guardCounter; _; require(localCounter == _guardCounter); } /** * @dev emitted when a supply is received * Note: newBalance - amount - startingBalance = interest accumulated since last change */ event SupplyReceived( address indexed account, address indexed asset, uint256 amount, uint256 startingBalance, uint256 newBalance ); /** * @dev emitted when a origination fee supply is received as admin * Note: newBalance - amount - startingBalance = interest accumulated since last change */ event SupplyOrgFeeAsAdmin( address indexed account, address indexed asset, uint256 amount, uint256 startingBalance, uint256 newBalance ); /** * @dev emitted when a supply is withdrawn * Note: startingBalance - amount - startingBalance = interest accumulated since last change */ event SupplyWithdrawn( address indexed account, address indexed asset, uint256 amount, uint256 startingBalance, uint256 newBalance ); /** * @dev emitted when a new borrow is taken * Note: newBalance - borrowAmountWithFee - startingBalance = interest accumulated since last change */ event BorrowTaken( address indexed account, address indexed asset, uint256 amount, uint256 startingBalance, uint256 borrowAmountWithFee, uint256 newBalance ); /** * @dev emitted when a borrow is repaid * Note: newBalance - amount - startingBalance = interest accumulated since last change */ event BorrowRepaid( address indexed account, address indexed asset, uint256 amount, uint256 startingBalance, uint256 newBalance ); /** * @dev emitted when a borrow is liquidated * targetAccount = user whose borrow was liquidated * assetBorrow = asset borrowed * borrowBalanceBefore = borrowBalance as most recently stored before the liquidation * borrowBalanceAccumulated = borroBalanceBefore + accumulated interest as of immediately prior to the liquidation * amountRepaid = amount of borrow repaid * liquidator = account requesting the liquidation * assetCollateral = asset taken from targetUser and given to liquidator in exchange for liquidated loan * borrowBalanceAfter = new stored borrow balance (should equal borrowBalanceAccumulated - amountRepaid) * collateralBalanceBefore = collateral balance as most recently stored before the liquidation * collateralBalanceAccumulated = collateralBalanceBefore + accumulated interest as of immediately prior to the liquidation * amountSeized = amount of collateral seized by liquidator * collateralBalanceAfter = new stored collateral balance (should equal collateralBalanceAccumulated - amountSeized) * assetBorrow and assetCollateral are not indexed as indexed addresses in an event is limited to 3 */ event BorrowLiquidated( address indexed targetAccount, address assetBorrow, uint256 borrowBalanceAccumulated, uint256 amountRepaid, address indexed liquidator, address assetCollateral, uint256 amountSeized ); /** * @dev emitted when pendingAdmin is accepted, which means admin is updated */ event NewAdmin(address indexed oldAdmin, address indexed newAdmin); /** * @dev emitted when new market is supported by admin */ event SupportedMarket( address indexed asset, address indexed interestRateModel ); /** * @dev emitted when risk parameters are changed by admin */ event NewRiskParameters( uint256 oldCollateralRatioMantissa, uint256 newCollateralRatioMantissa, uint256 oldLiquidationDiscountMantissa, uint256 newLiquidationDiscountMantissa ); /** * @dev emitted when origination fee is changed by admin */ event NewOriginationFee( uint256 oldOriginationFeeMantissa, uint256 newOriginationFeeMantissa ); /** * @dev emitted when market has new interest rate model set */ event SetMarketInterestRateModel( address indexed asset, address indexed interestRateModel ); /** * @dev emitted when admin withdraws equity * Note that `equityAvailableBefore` indicates equity before `amount` was removed. */ event EquityWithdrawn( address indexed asset, uint256 equityAvailableBefore, uint256 amount, address indexed owner ); /** * @dev Simple function to calculate min between two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { if (a < b) { return a; } else { return b; } } /** * @dev Adds a given asset to the list of collateral markets. This operation is impossible to reverse. * Note: this will not add the asset if it already exists. */ function addCollateralMarket(address asset) internal { for (uint256 i = 0; i < collateralMarkets.length; i++) { if (collateralMarkets[i] == asset) { return; } } collateralMarkets.push(asset); } /** * @notice return the number of elements in `collateralMarkets` * @dev you can then externally call `collateralMarkets(uint)` to pull each market address * @return the length of `collateralMarkets` */ function getCollateralMarketsLength() public view returns (uint256) { return collateralMarkets.length; } /** * @dev Calculates a new supply/borrow index based on the prevailing interest rates applied over time * This is defined as `we multiply the most recent supply/borrow index by (1 + blocks times rate)` * @return Return value is expressed in 1e18 scale */ function calculateInterestIndex( uint256 startingInterestIndex, uint256 interestRateMantissa, uint256 blockStart, uint256 blockEnd ) internal pure returns (Error, uint256) { // Get the block delta (Error err0, uint256 blockDelta) = sub(blockEnd, blockStart); if (err0 != Error.NO_ERROR) { return (err0, 0); } // Scale the interest rate times number of blocks // Note: Doing Exp construction inline to avoid `CompilerError: Stack too deep, try removing local variables.` (Error err1, Exp memory blocksTimesRate) = mulScalar( Exp({mantissa: interestRateMantissa}), blockDelta ); if (err1 != Error.NO_ERROR) { return (err1, 0); } // Add one to that result (which is really Exp({mantissa: expScale}) which equals 1.0) (Error err2, Exp memory onePlusBlocksTimesRate) = addExp( blocksTimesRate, Exp({mantissa: mantissaOne}) ); if (err2 != Error.NO_ERROR) { return (err2, 0); } // Then scale that accumulated interest by the old interest index to get the new interest index (Error err3, Exp memory newInterestIndexExp) = mulScalar( onePlusBlocksTimesRate, startingInterestIndex ); if (err3 != Error.NO_ERROR) { return (err3, 0); } // Finally, truncate the interest index. This works only if interest index starts large enough // that is can be accurately represented with a whole number. return (Error.NO_ERROR, truncate(newInterestIndexExp)); } /** * @dev Calculates a new balance based on a previous balance and a pair of interest indices * This is defined as: `The user's last balance checkpoint is multiplied by the currentSupplyIndex * value and divided by the user's checkpoint index value` * @return Return value is expressed in 1e18 scale */ function calculateBalance( uint256 startingBalance, uint256 interestIndexStart, uint256 interestIndexEnd ) internal pure returns (Error, uint256) { if (startingBalance == 0) { // We are accumulating interest on any previous balance; if there's no previous balance, then there is // nothing to accumulate. return (Error.NO_ERROR, 0); } (Error err0, uint256 balanceTimesIndex) = mul( startingBalance, interestIndexEnd ); if (err0 != Error.NO_ERROR) { return (err0, 0); } return div(balanceTimesIndex, interestIndexStart); } /** * @dev Gets the price for the amount specified of the given asset. * @return Return value is expressed in a magnified scale per token decimals */ function getPriceForAssetAmount(address asset, uint256 assetAmount) internal view returns (Error, Exp memory) { (Error err, Exp memory assetPrice) = fetchAssetPrice(asset); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0})); } if (isZeroExp(assetPrice)) { return (Error.MISSING_ASSET_PRICE, Exp({mantissa: 0})); } return mulScalar(assetPrice, assetAmount); // assetAmountWei * oraclePrice = assetValueInEth } /** * @dev Gets the price for the amount specified of the given asset multiplied by the current * collateral ratio (i.e., assetAmountWei * collateralRatio * oraclePrice = totalValueInEth). * We will group this as `(oraclePrice * collateralRatio) * assetAmountWei` * @return Return value is expressed in a magnified scale per token decimals */ function getPriceForAssetAmountMulCollatRatio( address asset, uint256 assetAmount ) internal view returns (Error, Exp memory) { Error err; Exp memory assetPrice; Exp memory scaledPrice; (err, assetPrice) = fetchAssetPrice(asset); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0})); } if (isZeroExp(assetPrice)) { return (Error.MISSING_ASSET_PRICE, Exp({mantissa: 0})); } // Now, multiply the assetValue by the collateral ratio (err, scaledPrice) = mulExp(collateralRatio, assetPrice); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0})); } // Get the price for the given asset amount return mulScalar(scaledPrice, assetAmount); } /** * @dev Calculates the origination fee added to a given borrowAmount * This is simply `(1 + originationFee) * borrowAmount` * @return Return value is expressed in 1e18 scale */ function calculateBorrowAmountWithFee(uint256 borrowAmount) internal view returns (Error, uint256) { // When origination fee is zero, the amount with fee is simply equal to the amount if (isZeroExp(originationFee)) { return (Error.NO_ERROR, borrowAmount); } (Error err0, Exp memory originationFeeFactor) = addExp( originationFee, Exp({mantissa: mantissaOne}) ); if (err0 != Error.NO_ERROR) { return (err0, 0); } (Error err1, Exp memory borrowAmountWithFee) = mulScalar( originationFeeFactor, borrowAmount ); if (err1 != Error.NO_ERROR) { return (err1, 0); } return (Error.NO_ERROR, truncate(borrowAmountWithFee)); } /** * @dev fetches the price of asset from the PriceOracle and converts it to Exp * @param asset asset whose price should be fetched * @return Return value is expressed in a magnified scale per token decimals */ function fetchAssetPrice(address asset) internal view returns (Error, Exp memory) { if (priceOracle == address(0)) { return (Error.ZERO_ORACLE_ADDRESS, Exp({mantissa: 0})); } if (priceOracle.paused()) { return (Error.MISSING_ASSET_PRICE, Exp({mantissa: 0})); } (uint256 priceMantissa, uint8 assetDecimals) = priceOracle .getAssetPrice(asset); (Error err, uint256 magnification) = sub(18, uint256(assetDecimals)); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0})); } (err, priceMantissa) = mul(priceMantissa, 10**magnification); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0})); } return (Error.NO_ERROR, Exp({mantissa: priceMantissa})); } /** * @notice Reads scaled price of specified asset from the price oracle * @dev Reads scaled price of specified asset from the price oracle. * The plural name is to match a previous storage mapping that this function replaced. * @param asset Asset whose price should be retrieved * @return 0 on an error or missing price, the price scaled by 1e18 otherwise */ function assetPrices(address asset) public view returns (uint256) { (Error err, Exp memory result) = fetchAssetPrice(asset); if (err != Error.NO_ERROR) { return 0; } return result.mantissa; } /** * @dev Gets the amount of the specified asset given the specified Eth value * ethValue / oraclePrice = assetAmountWei * If there's no oraclePrice, this returns (Error.DIVISION_BY_ZERO, 0) * @return Return value is expressed in a magnified scale per token decimals */ function getAssetAmountForValue(address asset, Exp ethValue) internal view returns (Error, uint256) { Error err; Exp memory assetPrice; Exp memory assetAmount; (err, assetPrice) = fetchAssetPrice(asset); if (err != Error.NO_ERROR) { return (err, 0); } (err, assetAmount) = divExp(ethValue, assetPrice); if (err != Error.NO_ERROR) { return (err, 0); } return (Error.NO_ERROR, truncate(assetAmount)); } /** * @notice Admin Functions. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @param newPendingAdmin New pending admin * @param newOracle New oracle address * @param requestedState value to assign to `paused` * @param originationFeeMantissa rational collateral ratio, scaled by 1e18. * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _adminFunctions( address newPendingAdmin, address newOracle, bool requestedState, uint256 originationFeeMantissa, uint256 newCloseFactorMantissa ) public returns (uint256) { // Check caller = admin require(msg.sender == admin, "SET_PENDING_ADMIN_OWNER_CHECK"); // newPendingAdmin can be 0x00, hence not checked require(newOracle != address(0), "Cannot set weth address to 0x00"); require( originationFeeMantissa < 10**18 && newCloseFactorMantissa < 10**18, "Invalid Origination Fee or Close Factor Mantissa" ); // Store pendingAdmin = newPendingAdmin pendingAdmin = newPendingAdmin; // Verify contract at newOracle address supports assetPrices call. // This will revert if it doesn't. // ChainLink priceOracleTemp = ChainLink(newOracle); // priceOracleTemp.getAssetPrice(address(0)); // Initialize the Chainlink contract in priceOracle priceOracle = ChainLink(newOracle); paused = requestedState; // Save current value so we can emit it in log. Exp memory oldOriginationFee = originationFee; originationFee = Exp({mantissa: originationFeeMantissa}); emit NewOriginationFee( oldOriginationFee.mantissa, originationFeeMantissa ); closeFactorMantissa = newCloseFactorMantissa; return uint256(Error.NO_ERROR); } /** * @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin * @dev Admin function for pending admin to accept role and update admin * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _acceptAdmin() public returns (uint256) { // Check caller = pendingAdmin // msg.sender can't be zero require(msg.sender == pendingAdmin, "ACCEPT_ADMIN_PENDING_ADMIN_CHECK"); // Save current value for inclusion in log address oldAdmin = admin; // Store admin = pendingAdmin admin = pendingAdmin; // Clear the pending value pendingAdmin = 0; emit NewAdmin(oldAdmin, msg.sender); return uint256(Error.NO_ERROR); } /** * @notice returns the liquidity for given account. * a positive result indicates ability to borrow, whereas * a negative result indicates a shortfall which may be liquidated * @dev returns account liquidity in terms of eth-wei value, scaled by 1e18 and truncated when the value is 0 or when the last few decimals are 0 * note: this includes interest trued up on all balances * @param account the account to examine * @return signed integer in terms of eth-wei (negative indicates a shortfall) */ function getAccountLiquidity(address account) public view returns (int256) { ( Error err, Exp memory accountLiquidity, Exp memory accountShortfall ) = calculateAccountLiquidity(account); revertIfError(err); if (isZeroExp(accountLiquidity)) { return -1 * int256(truncate(accountShortfall)); } else { return int256(truncate(accountLiquidity)); } } /** * @notice return supply balance with any accumulated interest for `asset` belonging to `account` * @dev returns supply balance with any accumulated interest for `asset` belonging to `account` * @param account the account to examine * @param asset the market asset whose supply balance belonging to `account` should be checked * @return uint supply balance on success, throws on failed assertion otherwise */ function getSupplyBalance(address account, address asset) public view returns (uint256) { Error err; uint256 newSupplyIndex; uint256 userSupplyCurrent; Market storage market = markets[asset]; Balance storage supplyBalance = supplyBalances[account][asset]; // Calculate the newSupplyIndex, needed to calculate user's supplyCurrent (err, newSupplyIndex) = calculateInterestIndex( market.supplyIndex, market.supplyRateMantissa, market.blockNumber, block.number ); revertIfError(err); // Use newSupplyIndex and stored principal to calculate the accumulated balance (err, userSupplyCurrent) = calculateBalance( supplyBalance.principal, supplyBalance.interestIndex, newSupplyIndex ); revertIfError(err); return userSupplyCurrent; } /** * @notice return borrow balance with any accumulated interest for `asset` belonging to `account` * @dev returns borrow balance with any accumulated interest for `asset` belonging to `account` * @param account the account to examine * @param asset the market asset whose borrow balance belonging to `account` should be checked * @return uint borrow balance on success, throws on failed assertion otherwise */ function getBorrowBalance(address account, address asset) public view returns (uint256) { Error err; uint256 newBorrowIndex; uint256 userBorrowCurrent; Market storage market = markets[asset]; Balance storage borrowBalance = borrowBalances[account][asset]; // Calculate the newBorrowIndex, needed to calculate user's borrowCurrent (err, newBorrowIndex) = calculateInterestIndex( market.borrowIndex, market.borrowRateMantissa, market.blockNumber, block.number ); revertIfError(err); // Use newBorrowIndex and stored principal to calculate the accumulated balance (err, userBorrowCurrent) = calculateBalance( borrowBalance.principal, borrowBalance.interestIndex, newBorrowIndex ); revertIfError(err); return userBorrowCurrent; } /** * @notice Supports a given market (asset) for use * @dev Admin function to add support for a market * @param asset Asset to support; MUST already have a non-zero price set * @param interestRateModel InterestRateModel to use for the asset * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _supportMarket(address asset, InterestRateModel interestRateModel) public returns (uint256) { // Check caller = admin require(msg.sender == admin, "SUPPORT_MARKET_OWNER_CHECK"); require(interestRateModel != address(0), "Rate Model cannot be 0x00"); // Hard cap on the maximum number of markets allowed require( collateralMarkets.length < 16, // 16 = MAXIMUM_NUMBER_OF_MARKETS_ALLOWED "Exceeding the max number of markets allowed" ); (Error err, Exp memory assetPrice) = fetchAssetPrice(asset); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.SUPPORT_MARKET_FETCH_PRICE_FAILED); } if (isZeroExp(assetPrice)) { return fail( Error.ASSET_NOT_PRICED, FailureInfo.SUPPORT_MARKET_PRICE_CHECK ); } // Set the interest rate model to `modelAddress` markets[asset].interestRateModel = interestRateModel; // Append asset to collateralAssets if not set addCollateralMarket(asset); // Set market isSupported to true markets[asset].isSupported = true; // Default supply and borrow index to 1e18 if (markets[asset].supplyIndex == 0) { markets[asset].supplyIndex = initialInterestIndex; } if (markets[asset].borrowIndex == 0) { markets[asset].borrowIndex = initialInterestIndex; } emit SupportedMarket(asset, interestRateModel); return uint256(Error.NO_ERROR); } /** * @notice Suspends a given *supported* market (asset) from use. * Assets in this state do count for collateral, but users may only withdraw, payBorrow, * and liquidate the asset. The liquidate function no longer checks collateralization. * @dev Admin function to suspend a market * @param asset Asset to suspend * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _suspendMarket(address asset) public returns (uint256) { // Check caller = admin require(msg.sender == admin, "SUSPEND_MARKET_OWNER_CHECK"); // If the market is not configured at all, we don't want to add any configuration for it. // If we find !markets[asset].isSupported then either the market is not configured at all, or it // has already been marked as unsupported. We can just return without doing anything. // Caller is responsible for knowing the difference between not-configured and already unsupported. if (!markets[asset].isSupported) { return uint256(Error.NO_ERROR); } // If we get here, we know market is configured and is supported, so set isSupported to false markets[asset].isSupported = false; return uint256(Error.NO_ERROR); } /** * @notice Sets the risk parameters: collateral ratio and liquidation discount * @dev Owner function to set the risk parameters * @param collateralRatioMantissa rational collateral ratio, scaled by 1e18. The de-scaled value must be >= 1.1 * @param liquidationDiscountMantissa rational liquidation discount, scaled by 1e18. The de-scaled value must be <= 0.1 and must be less than (descaled collateral ratio minus 1) * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setRiskParameters( uint256 collateralRatioMantissa, uint256 liquidationDiscountMantissa ) public returns (uint256) { // Check caller = admin require(msg.sender == admin, "SET_RISK_PARAMETERS_OWNER_CHECK"); // Input validations require( collateralRatioMantissa >= minimumCollateralRatioMantissa && liquidationDiscountMantissa <= maximumLiquidationDiscountMantissa, "Liquidation discount is more than max discount or collateral ratio is less than min ratio" ); Exp memory newCollateralRatio = Exp({ mantissa: collateralRatioMantissa }); Exp memory newLiquidationDiscount = Exp({ mantissa: liquidationDiscountMantissa }); Exp memory minimumCollateralRatio = Exp({ mantissa: minimumCollateralRatioMantissa }); Exp memory maximumLiquidationDiscount = Exp({ mantissa: maximumLiquidationDiscountMantissa }); Error err; Exp memory newLiquidationDiscountPlusOne; // Make sure new collateral ratio value is not below minimum value if (lessThanExp(newCollateralRatio, minimumCollateralRatio)) { return fail( Error.INVALID_COLLATERAL_RATIO, FailureInfo.SET_RISK_PARAMETERS_VALIDATION ); } // Make sure new liquidation discount does not exceed the maximum value, but reverse operands so we can use the // existing `lessThanExp` function rather than adding a `greaterThan` function to Exponential. if (lessThanExp(maximumLiquidationDiscount, newLiquidationDiscount)) { return fail( Error.INVALID_LIQUIDATION_DISCOUNT, FailureInfo.SET_RISK_PARAMETERS_VALIDATION ); } // C = L+1 is not allowed because it would cause division by zero error in `calculateDiscountedRepayToEvenAmount` // C < L+1 is not allowed because it would cause integer underflow error in `calculateDiscountedRepayToEvenAmount` (err, newLiquidationDiscountPlusOne) = addExp( newLiquidationDiscount, Exp({mantissa: mantissaOne}) ); assert(err == Error.NO_ERROR); // We already validated that newLiquidationDiscount does not approach overflow size if ( lessThanOrEqualExp( newCollateralRatio, newLiquidationDiscountPlusOne ) ) { return fail( Error.INVALID_COMBINED_RISK_PARAMETERS, FailureInfo.SET_RISK_PARAMETERS_VALIDATION ); } // Save current values so we can emit them in log. Exp memory oldCollateralRatio = collateralRatio; Exp memory oldLiquidationDiscount = liquidationDiscount; // Store new values collateralRatio = newCollateralRatio; liquidationDiscount = newLiquidationDiscount; emit NewRiskParameters( oldCollateralRatio.mantissa, collateralRatioMantissa, oldLiquidationDiscount.mantissa, liquidationDiscountMantissa ); return uint256(Error.NO_ERROR); } /** * @notice Sets the interest rate model for a given market * @dev Admin function to set interest rate model * @param asset Asset to support * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setMarketInterestRateModel( address asset, InterestRateModel interestRateModel ) public returns (uint256) { // Check caller = admin require( msg.sender == admin, "SET_MARKET_INTEREST_RATE_MODEL_OWNER_CHECK" ); require(interestRateModel != address(0), "Rate Model cannot be 0x00"); // Set the interest rate model to `modelAddress` markets[asset].interestRateModel = interestRateModel; emit SetMarketInterestRateModel(asset, interestRateModel); return uint256(Error.NO_ERROR); } /** * @notice withdraws `amount` of `asset` from equity for asset, as long as `amount` <= equity. Equity = cash + borrows - supply * @dev withdraws `amount` of `asset` from equity for asset, enforcing amount <= cash + borrows - supply * @param asset asset whose equity should be withdrawn * @param amount amount of equity to withdraw; must not exceed equity available * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _withdrawEquity(address asset, uint256 amount) public returns (uint256) { // Check caller = admin require(msg.sender == admin, "EQUITY_WITHDRAWAL_MODEL_OWNER_CHECK"); // Check that amount is less than cash (from ERC-20 of self) plus borrows minus supply. // Get supply and borrows with interest accrued till the latest block ( uint256 supplyWithInterest, uint256 borrowWithInterest ) = getMarketBalances(asset); (Error err0, uint256 equity) = addThenSub( getCash(asset), borrowWithInterest, supplyWithInterest ); if (err0 != Error.NO_ERROR) { return fail(err0, FailureInfo.EQUITY_WITHDRAWAL_CALCULATE_EQUITY); } if (amount > equity) { return fail( Error.EQUITY_INSUFFICIENT_BALANCE, FailureInfo.EQUITY_WITHDRAWAL_AMOUNT_VALIDATION ); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) if (asset != wethAddress) { // Withdrawal should happen as Ether directly // We ERC-20 transfer the asset out of the protocol to the admin Error err2 = doTransferOut(asset, admin, amount); if (err2 != Error.NO_ERROR) { // This is safe since it's our first interaction and it didn't do anything if it failed return fail( err2, FailureInfo.EQUITY_WITHDRAWAL_TRANSFER_OUT_FAILED ); } } else { withdrawEther(admin, amount); // send Ether to user } (, markets[asset].supplyRateMantissa) = markets[asset] .interestRateModel .getSupplyRate( asset, getCash(asset) - amount, markets[asset].totalSupply ); (, markets[asset].borrowRateMantissa) = markets[asset] .interestRateModel .getBorrowRate( asset, getCash(asset) - amount, markets[asset].totalBorrows ); //event EquityWithdrawn(address asset, uint equityAvailableBefore, uint amount, address owner) emit EquityWithdrawn(asset, equity, amount, admin); return uint256(Error.NO_ERROR); // success } /** * @dev Set WETH token contract address * @param wethContractAddress Enter the WETH token address */ function setWethAddress(address wethContractAddress) public returns (uint256) { // Check caller = admin require(msg.sender == admin, "SET_WETH_ADDRESS_ADMIN_CHECK_FAILED"); require( wethContractAddress != address(0), "Cannot set weth address to 0x00" ); wethAddress = wethContractAddress; WETHContract = AlkemiWETH(wethAddress); return uint256(Error.NO_ERROR); } /** * @dev Convert Ether supplied by user into WETH tokens and then supply corresponding WETH to user * @return errors if any * @param etherAmount Amount of ether to be converted to WETH * @param user User account address */ function supplyEther(address user, uint256 etherAmount) internal returns (uint256) { user; // To silence the warning of unused local variable if (wethAddress != address(0)) { WETHContract.deposit.value(etherAmount)(); return uint256(Error.NO_ERROR); } else { return uint256(Error.WETH_ADDRESS_NOT_SET_ERROR); } } /** * @dev Revert Ether paid by user back to user's account in case transaction fails due to some other reason * @param etherAmount Amount of ether to be sent back to user * @param user User account address */ function revertEtherToUser(address user, uint256 etherAmount) internal { if (etherAmount > 0) { user.transfer(etherAmount); } } /** * @notice supply `amount` of `asset` (which must be supported) to `msg.sender` in the protocol * @dev add amount of supported asset to msg.sender's account * @param asset The market asset to supply * @param amount The amount to supply * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function supply(address asset, uint256 amount) public payable nonReentrant returns (uint256) { if (paused) { revertEtherToUser(msg.sender, msg.value); return fail(Error.CONTRACT_PAUSED, FailureInfo.SUPPLY_CONTRACT_PAUSED); } refreshAlkSupplyIndex(asset, msg.sender, false); Market storage market = markets[asset]; Balance storage balance = supplyBalances[msg.sender][asset]; SupplyLocalVars memory localResults; // Holds all our uint calculation results Error err; // Re-used for every function call that includes an Error in its return value(s). uint256 rateCalculationResultCode; // Used for 2 interest rate calculation calls // Fail if market not supported if (!market.isSupported) { revertEtherToUser(msg.sender, msg.value); return fail( Error.MARKET_NOT_SUPPORTED, FailureInfo.SUPPLY_MARKET_NOT_SUPPORTED ); } if (asset != wethAddress) { // WETH is supplied to AlkemiEarnPublic contract in case of ETH automatically // Fail gracefully if asset is not approved or has insufficient balance revertEtherToUser(msg.sender, msg.value); err = checkTransferIn(asset, msg.sender, amount); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.SUPPLY_TRANSFER_IN_NOT_POSSIBLE); } } // We calculate the newSupplyIndex, user's supplyCurrent and supplyUpdated for the asset (err, localResults.newSupplyIndex) = calculateInterestIndex( market.supplyIndex, market.supplyRateMantissa, market.blockNumber, block.number ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.SUPPLY_NEW_SUPPLY_INDEX_CALCULATION_FAILED ); } (err, localResults.userSupplyCurrent) = calculateBalance( balance.principal, balance.interestIndex, localResults.newSupplyIndex ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.SUPPLY_ACCUMULATED_BALANCE_CALCULATION_FAILED ); } (err, localResults.userSupplyUpdated) = add( localResults.userSupplyCurrent, amount ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.SUPPLY_NEW_TOTAL_BALANCE_CALCULATION_FAILED ); } // We calculate the protocol's totalSupply by subtracting the user's prior checkpointed balance, adding user's updated supply (err, localResults.newTotalSupply) = addThenSub( market.totalSupply, localResults.userSupplyUpdated, balance.principal ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.SUPPLY_NEW_TOTAL_SUPPLY_CALCULATION_FAILED ); } // We need to calculate what the updated cash will be after we transfer in from user localResults.currentCash = getCash(asset); (err, localResults.updatedCash) = add(localResults.currentCash, amount); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail(err, FailureInfo.SUPPLY_NEW_TOTAL_CASH_CALCULATION_FAILED); } // The utilization rate has changed! We calculate a new supply index and borrow index for the asset, and save it. (rateCalculationResultCode, localResults.newSupplyRateMantissa) = market .interestRateModel .getSupplyRate(asset, localResults.updatedCash, market.totalBorrows); if (rateCalculationResultCode != 0) { revertEtherToUser(msg.sender, msg.value); return failOpaque( FailureInfo.SUPPLY_NEW_SUPPLY_RATE_CALCULATION_FAILED, rateCalculationResultCode ); } // We calculate the newBorrowIndex (we already had newSupplyIndex) (err, localResults.newBorrowIndex) = calculateInterestIndex( market.borrowIndex, market.borrowRateMantissa, market.blockNumber, block.number ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.SUPPLY_NEW_BORROW_INDEX_CALCULATION_FAILED ); } (rateCalculationResultCode, localResults.newBorrowRateMantissa) = market .interestRateModel .getBorrowRate(asset, localResults.updatedCash, market.totalBorrows); if (rateCalculationResultCode != 0) { revertEtherToUser(msg.sender, msg.value); return failOpaque( FailureInfo.SUPPLY_NEW_BORROW_RATE_CALCULATION_FAILED, rateCalculationResultCode ); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) // Save market updates market.blockNumber = block.number; market.totalSupply = localResults.newTotalSupply; market.supplyRateMantissa = localResults.newSupplyRateMantissa; market.supplyIndex = localResults.newSupplyIndex; market.borrowRateMantissa = localResults.newBorrowRateMantissa; market.borrowIndex = localResults.newBorrowIndex; // Save user updates localResults.startingBalance = balance.principal; // save for use in `SupplyReceived` event balance.principal = localResults.userSupplyUpdated; balance.interestIndex = localResults.newSupplyIndex; if (asset != wethAddress) { // WETH is supplied to AlkemiEarnPublic contract in case of ETH automatically // We ERC-20 transfer the asset into the protocol (note: pre-conditions already checked above) revertEtherToUser(msg.sender, msg.value); err = doTransferIn(asset, msg.sender, amount); if (err != Error.NO_ERROR) { // This is safe since it's our first interaction and it didn't do anything if it failed return fail(err, FailureInfo.SUPPLY_TRANSFER_IN_FAILED); } } else { if (msg.value == amount) { uint256 supplyError = supplyEther(msg.sender, msg.value); if (supplyError != 0) { revertEtherToUser(msg.sender, msg.value); return fail( Error.WETH_ADDRESS_NOT_SET_ERROR, FailureInfo.WETH_ADDRESS_NOT_SET_ERROR ); } } else { revertEtherToUser(msg.sender, msg.value); return fail( Error.ETHER_AMOUNT_MISMATCH_ERROR, FailureInfo.ETHER_AMOUNT_MISMATCH_ERROR ); } } emit SupplyReceived( msg.sender, asset, amount, localResults.startingBalance, balance.principal ); return uint256(Error.NO_ERROR); // success } /** * @notice withdraw `amount` of `ether` from sender's account to sender's address * @dev withdraw `amount` of `ether` from msg.sender's account to msg.sender * @param etherAmount Amount of ether to be converted to WETH * @param user User account address */ function withdrawEther(address user, uint256 etherAmount) internal returns (uint256) { WETHContract.withdraw(user, etherAmount); return uint256(Error.NO_ERROR); } /** * @notice withdraw `amount` of `asset` from sender's account to sender's address * @dev withdraw `amount` of `asset` from msg.sender's account to msg.sender * @param asset The market asset to withdraw * @param requestedAmount The amount to withdraw (or -1 for max) * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function withdraw(address asset, uint256 requestedAmount) public nonReentrant returns (uint256) { if (paused) { return fail( Error.CONTRACT_PAUSED, FailureInfo.WITHDRAW_CONTRACT_PAUSED ); } refreshAlkSupplyIndex(asset, msg.sender, false); Market storage market = markets[asset]; Balance storage supplyBalance = supplyBalances[msg.sender][asset]; WithdrawLocalVars memory localResults; // Holds all our calculation results Error err; // Re-used for every function call that includes an Error in its return value(s). uint256 rateCalculationResultCode; // Used for 2 interest rate calculation calls // We calculate the user's accountLiquidity and accountShortfall. ( err, localResults.accountLiquidity, localResults.accountShortfall ) = calculateAccountLiquidity(msg.sender); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.WITHDRAW_ACCOUNT_LIQUIDITY_CALCULATION_FAILED ); } // We calculate the newSupplyIndex, user's supplyCurrent and supplyUpdated for the asset (err, localResults.newSupplyIndex) = calculateInterestIndex( market.supplyIndex, market.supplyRateMantissa, market.blockNumber, block.number ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.WITHDRAW_NEW_SUPPLY_INDEX_CALCULATION_FAILED ); } (err, localResults.userSupplyCurrent) = calculateBalance( supplyBalance.principal, supplyBalance.interestIndex, localResults.newSupplyIndex ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.WITHDRAW_ACCUMULATED_BALANCE_CALCULATION_FAILED ); } // If the user specifies -1 amount to withdraw ("max"), withdrawAmount => the lesser of withdrawCapacity and supplyCurrent if (requestedAmount == uint256(-1)) { (err, localResults.withdrawCapacity) = getAssetAmountForValue( asset, localResults.accountLiquidity ); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.WITHDRAW_CAPACITY_CALCULATION_FAILED); } localResults.withdrawAmount = min( localResults.withdrawCapacity, localResults.userSupplyCurrent ); } else { localResults.withdrawAmount = requestedAmount; } // From here on we should NOT use requestedAmount. // Fail gracefully if protocol has insufficient cash // If protocol has insufficient cash, the sub operation will underflow. localResults.currentCash = getCash(asset); (err, localResults.updatedCash) = sub( localResults.currentCash, localResults.withdrawAmount ); if (err != Error.NO_ERROR) { return fail( Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.WITHDRAW_TRANSFER_OUT_NOT_POSSIBLE ); } // We check that the amount is less than or equal to supplyCurrent // If amount is greater than supplyCurrent, this will fail with Error.INTEGER_UNDERFLOW (err, localResults.userSupplyUpdated) = sub( localResults.userSupplyCurrent, localResults.withdrawAmount ); if (err != Error.NO_ERROR) { return fail( Error.INSUFFICIENT_BALANCE, FailureInfo.WITHDRAW_NEW_TOTAL_BALANCE_CALCULATION_FAILED ); } // Fail if customer already has a shortfall if (!isZeroExp(localResults.accountShortfall)) { return fail( Error.INSUFFICIENT_LIQUIDITY, FailureInfo.WITHDRAW_ACCOUNT_SHORTFALL_PRESENT ); } // We want to know the user's withdrawCapacity, denominated in the asset // Customer's withdrawCapacity of asset is (accountLiquidity in Eth)/ (price of asset in Eth) // Equivalently, we calculate the eth value of the withdrawal amount and compare it directly to the accountLiquidity in Eth (err, localResults.ethValueOfWithdrawal) = getPriceForAssetAmount( asset, localResults.withdrawAmount ); // amount * oraclePrice = ethValueOfWithdrawal if (err != Error.NO_ERROR) { return fail(err, FailureInfo.WITHDRAW_AMOUNT_VALUE_CALCULATION_FAILED); } // We check that the amount is less than withdrawCapacity (here), and less than or equal to supplyCurrent (below) if ( lessThanExp( localResults.accountLiquidity, localResults.ethValueOfWithdrawal ) ) { return fail( Error.INSUFFICIENT_LIQUIDITY, FailureInfo.WITHDRAW_AMOUNT_LIQUIDITY_SHORTFALL ); } // We calculate the protocol's totalSupply by subtracting the user's prior checkpointed balance, adding user's updated supply. // Note that, even though the customer is withdrawing, if they've accumulated a lot of interest since their last // action, the updated balance *could* be higher than the prior checkpointed balance. (err, localResults.newTotalSupply) = addThenSub( market.totalSupply, localResults.userSupplyUpdated, supplyBalance.principal ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.WITHDRAW_NEW_TOTAL_SUPPLY_CALCULATION_FAILED ); } // The utilization rate has changed! We calculate a new supply index and borrow index for the asset, and save it. (rateCalculationResultCode, localResults.newSupplyRateMantissa) = market .interestRateModel .getSupplyRate(asset, localResults.updatedCash, market.totalBorrows); if (rateCalculationResultCode != 0) { return failOpaque( FailureInfo.WITHDRAW_NEW_SUPPLY_RATE_CALCULATION_FAILED, rateCalculationResultCode ); } // We calculate the newBorrowIndex (err, localResults.newBorrowIndex) = calculateInterestIndex( market.borrowIndex, market.borrowRateMantissa, market.blockNumber, block.number ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.WITHDRAW_NEW_BORROW_INDEX_CALCULATION_FAILED ); } (rateCalculationResultCode, localResults.newBorrowRateMantissa) = market .interestRateModel .getBorrowRate(asset, localResults.updatedCash, market.totalBorrows); if (rateCalculationResultCode != 0) { return failOpaque( FailureInfo.WITHDRAW_NEW_BORROW_RATE_CALCULATION_FAILED, rateCalculationResultCode ); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) // Save market updates market.blockNumber = block.number; market.totalSupply = localResults.newTotalSupply; market.supplyRateMantissa = localResults.newSupplyRateMantissa; market.supplyIndex = localResults.newSupplyIndex; market.borrowRateMantissa = localResults.newBorrowRateMantissa; market.borrowIndex = localResults.newBorrowIndex; // Save user updates localResults.startingBalance = supplyBalance.principal; // save for use in `SupplyWithdrawn` event supplyBalance.principal = localResults.userSupplyUpdated; supplyBalance.interestIndex = localResults.newSupplyIndex; if (asset != wethAddress) { // Withdrawal should happen as Ether directly // We ERC-20 transfer the asset into the protocol (note: pre-conditions already checked above) err = doTransferOut(asset, msg.sender, localResults.withdrawAmount); if (err != Error.NO_ERROR) { // This is safe since it's our first interaction and it didn't do anything if it failed return fail(err, FailureInfo.WITHDRAW_TRANSFER_OUT_FAILED); } } else { withdrawEther(msg.sender, localResults.withdrawAmount); // send Ether to user } emit SupplyWithdrawn( msg.sender, asset, localResults.withdrawAmount, localResults.startingBalance, supplyBalance.principal ); return uint256(Error.NO_ERROR); // success } /** * @dev Gets the user's account liquidity and account shortfall balances. This includes * any accumulated interest thus far but does NOT actually update anything in * storage, it simply calculates the account liquidity and shortfall with liquidity being * returned as the first Exp, ie (Error, accountLiquidity, accountShortfall). * @return Return values are expressed in 1e18 scale */ function calculateAccountLiquidity(address userAddress) internal view returns ( Error, Exp memory, Exp memory ) { Error err; Exp memory sumSupplyValuesMantissa; Exp memory sumBorrowValuesMantissa; ( err, sumSupplyValuesMantissa, sumBorrowValuesMantissa ) = calculateAccountValuesInternal(userAddress); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } Exp memory result; Exp memory sumSupplyValuesFinal = Exp({ mantissa: sumSupplyValuesMantissa.mantissa }); Exp memory sumBorrowValuesFinal; // need to apply collateral ratio (err, sumBorrowValuesFinal) = mulExp( collateralRatio, Exp({mantissa: sumBorrowValuesMantissa.mantissa}) ); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } // if sumSupplies < sumBorrows, then the user is under collateralized and has account shortfall. // else the user meets the collateral ratio and has account liquidity. if (lessThanExp(sumSupplyValuesFinal, sumBorrowValuesFinal)) { // accountShortfall = borrows - supplies (err, result) = subExp(sumBorrowValuesFinal, sumSupplyValuesFinal); assert(err == Error.NO_ERROR); // Note: we have checked that sumBorrows is greater than sumSupplies directly above, therefore `subExp` cannot fail. return (Error.NO_ERROR, Exp({mantissa: 0}), result); } else { // accountLiquidity = supplies - borrows (err, result) = subExp(sumSupplyValuesFinal, sumBorrowValuesFinal); assert(err == Error.NO_ERROR); // Note: we have checked that sumSupplies is greater than sumBorrows directly above, therefore `subExp` cannot fail. return (Error.NO_ERROR, result, Exp({mantissa: 0})); } } /** * @notice Gets the ETH values of the user's accumulated supply and borrow balances, scaled by 10e18. * This includes any accumulated interest thus far but does NOT actually update anything in * storage * @dev Gets ETH values of accumulated supply and borrow balances * @param userAddress account for which to sum values * @return (error code, sum ETH value of supplies scaled by 10e18, sum ETH value of borrows scaled by 10e18) */ function calculateAccountValuesInternal(address userAddress) internal view returns ( Error, Exp memory, Exp memory ) { /** By definition, all collateralMarkets are those that contribute to the user's * liquidity and shortfall so we need only loop through those markets. * To handle avoiding intermediate negative results, we will sum all the user's * supply balances and borrow balances (with collateral ratio) separately and then * subtract the sums at the end. */ AccountValueLocalVars memory localResults; // Re-used for all intermediate results localResults.sumSupplies = Exp({mantissa: 0}); localResults.sumBorrows = Exp({mantissa: 0}); Error err; // Re-used for all intermediate errors localResults.collateralMarketsLength = collateralMarkets.length; for (uint256 i = 0; i < localResults.collateralMarketsLength; i++) { localResults.assetAddress = collateralMarkets[i]; Market storage currentMarket = markets[localResults.assetAddress]; Balance storage supplyBalance = supplyBalances[userAddress][ localResults.assetAddress ]; Balance storage borrowBalance = borrowBalances[userAddress][ localResults.assetAddress ]; if (supplyBalance.principal > 0) { // We calculate the newSupplyIndex and user’s supplyCurrent (includes interest) (err, localResults.newSupplyIndex) = calculateInterestIndex( currentMarket.supplyIndex, currentMarket.supplyRateMantissa, currentMarket.blockNumber, block.number ); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } (err, localResults.userSupplyCurrent) = calculateBalance( supplyBalance.principal, supplyBalance.interestIndex, localResults.newSupplyIndex ); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } // We have the user's supply balance with interest so let's multiply by the asset price to get the total value (err, localResults.supplyTotalValue) = getPriceForAssetAmount( localResults.assetAddress, localResults.userSupplyCurrent ); // supplyCurrent * oraclePrice = supplyValueInEth if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } // Add this to our running sum of supplies (err, localResults.sumSupplies) = addExp( localResults.supplyTotalValue, localResults.sumSupplies ); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } } if (borrowBalance.principal > 0) { // We perform a similar actions to get the user's borrow balance (err, localResults.newBorrowIndex) = calculateInterestIndex( currentMarket.borrowIndex, currentMarket.borrowRateMantissa, currentMarket.blockNumber, block.number ); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } (err, localResults.userBorrowCurrent) = calculateBalance( borrowBalance.principal, borrowBalance.interestIndex, localResults.newBorrowIndex ); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } // We have the user's borrow balance with interest so let's multiply by the asset price to get the total value (err, localResults.borrowTotalValue) = getPriceForAssetAmount( localResults.assetAddress, localResults.userBorrowCurrent ); // borrowCurrent * oraclePrice = borrowValueInEth if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } // Add this to our running sum of borrows (err, localResults.sumBorrows) = addExp( localResults.borrowTotalValue, localResults.sumBorrows ); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } } } return ( Error.NO_ERROR, localResults.sumSupplies, localResults.sumBorrows ); } /** * @notice Gets the ETH values of the user's accumulated supply and borrow balances, scaled by 10e18. * This includes any accumulated interest thus far but does NOT actually update anything in * storage * @dev Gets ETH values of accumulated supply and borrow balances * @param userAddress account for which to sum values * @return (uint 0=success; otherwise a failure (see ErrorReporter.sol for details), * sum ETH value of supplies scaled by 10e18, * sum ETH value of borrows scaled by 10e18) */ function calculateAccountValues(address userAddress) public view returns ( uint256, uint256, uint256 ) { ( Error err, Exp memory supplyValue, Exp memory borrowValue ) = calculateAccountValuesInternal(userAddress); if (err != Error.NO_ERROR) { return (uint256(err), 0, 0); } return (0, supplyValue.mantissa, borrowValue.mantissa); } /** * @notice Users repay borrowed assets from their own address to the protocol. * @param asset The market asset to repay * @param amount The amount to repay (or -1 for max) * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function repayBorrow(address asset, uint256 amount) public payable nonReentrant returns (uint256) { if (paused) { revertEtherToUser(msg.sender, msg.value); return fail( Error.CONTRACT_PAUSED, FailureInfo.REPAY_BORROW_CONTRACT_PAUSED ); } refreshAlkBorrowIndex(asset, msg.sender, false); PayBorrowLocalVars memory localResults; Market storage market = markets[asset]; Balance storage borrowBalance = borrowBalances[msg.sender][asset]; Error err; uint256 rateCalculationResultCode; // We calculate the newBorrowIndex, user's borrowCurrent and borrowUpdated for the asset (err, localResults.newBorrowIndex) = calculateInterestIndex( market.borrowIndex, market.borrowRateMantissa, market.blockNumber, block.number ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.REPAY_BORROW_NEW_BORROW_INDEX_CALCULATION_FAILED ); } (err, localResults.userBorrowCurrent) = calculateBalance( borrowBalance.principal, borrowBalance.interestIndex, localResults.newBorrowIndex ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo .REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED ); } uint256 reimburseAmount; // If the user specifies -1 amount to repay (“max”), repayAmount => // the lesser of the senders ERC-20 balance and borrowCurrent if (asset != wethAddress) { if (amount == uint256(-1)) { localResults.repayAmount = min( getBalanceOf(asset, msg.sender), localResults.userBorrowCurrent ); } else { localResults.repayAmount = amount; } } else { // To calculate the actual repay use has to do and reimburse the excess amount of ETH collected if (amount > localResults.userBorrowCurrent) { localResults.repayAmount = localResults.userBorrowCurrent; (err, reimburseAmount) = sub( amount, localResults.userBorrowCurrent ); // reimbursement called at the end to make sure function does not have any other errors if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo .REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED ); } } else { localResults.repayAmount = amount; } } // Subtract the `repayAmount` from the `userBorrowCurrent` to get `userBorrowUpdated` // Note: this checks that repayAmount is less than borrowCurrent (err, localResults.userBorrowUpdated) = sub( localResults.userBorrowCurrent, localResults.repayAmount ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo .REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED ); } // Fail gracefully if asset is not approved or has insufficient balance // Note: this checks that repayAmount is less than or equal to their ERC-20 balance if (asset != wethAddress) { // WETH is supplied to AlkemiEarnPublic contract in case of ETH automatically revertEtherToUser(msg.sender, msg.value); err = checkTransferIn(asset, msg.sender, localResults.repayAmount); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.REPAY_BORROW_TRANSFER_IN_NOT_POSSIBLE ); } } // We calculate the protocol's totalBorrow by subtracting the user's prior checkpointed balance, adding user's updated borrow // Note that, even though the customer is paying some of their borrow, if they've accumulated a lot of interest since their last // action, the updated balance *could* be higher than the prior checkpointed balance. (err, localResults.newTotalBorrows) = addThenSub( market.totalBorrows, localResults.userBorrowUpdated, borrowBalance.principal ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.REPAY_BORROW_NEW_TOTAL_BORROW_CALCULATION_FAILED ); } // We need to calculate what the updated cash will be after we transfer in from user localResults.currentCash = getCash(asset); (err, localResults.updatedCash) = add( localResults.currentCash, localResults.repayAmount ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.REPAY_BORROW_NEW_TOTAL_CASH_CALCULATION_FAILED ); } // The utilization rate has changed! We calculate a new supply index and borrow index for the asset, and save it. // We calculate the newSupplyIndex, but we have newBorrowIndex already (err, localResults.newSupplyIndex) = calculateInterestIndex( market.supplyIndex, market.supplyRateMantissa, market.blockNumber, block.number ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.REPAY_BORROW_NEW_SUPPLY_INDEX_CALCULATION_FAILED ); } (rateCalculationResultCode, localResults.newSupplyRateMantissa) = market .interestRateModel .getSupplyRate( asset, localResults.updatedCash, localResults.newTotalBorrows ); if (rateCalculationResultCode != 0) { revertEtherToUser(msg.sender, msg.value); return failOpaque( FailureInfo.REPAY_BORROW_NEW_SUPPLY_RATE_CALCULATION_FAILED, rateCalculationResultCode ); } (rateCalculationResultCode, localResults.newBorrowRateMantissa) = market .interestRateModel .getBorrowRate( asset, localResults.updatedCash, localResults.newTotalBorrows ); if (rateCalculationResultCode != 0) { revertEtherToUser(msg.sender, msg.value); return failOpaque( FailureInfo.REPAY_BORROW_NEW_BORROW_RATE_CALCULATION_FAILED, rateCalculationResultCode ); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) // Save market updates market.blockNumber = block.number; market.totalBorrows = localResults.newTotalBorrows; market.supplyRateMantissa = localResults.newSupplyRateMantissa; market.supplyIndex = localResults.newSupplyIndex; market.borrowRateMantissa = localResults.newBorrowRateMantissa; market.borrowIndex = localResults.newBorrowIndex; // Save user updates localResults.startingBalance = borrowBalance.principal; // save for use in `BorrowRepaid` event borrowBalance.principal = localResults.userBorrowUpdated; borrowBalance.interestIndex = localResults.newBorrowIndex; if (asset != wethAddress) { // WETH is supplied to AlkemiEarnPublic contract in case of ETH automatically // We ERC-20 transfer the asset into the protocol (note: pre-conditions already checked above) revertEtherToUser(msg.sender, msg.value); err = doTransferIn(asset, msg.sender, localResults.repayAmount); if (err != Error.NO_ERROR) { // This is safe since it's our first interaction and it didn't do anything if it failed return fail(err, FailureInfo.REPAY_BORROW_TRANSFER_IN_FAILED); } } else { if (msg.value == amount) { uint256 supplyError = supplyEther( msg.sender, localResults.repayAmount ); //Repay excess funds if (reimburseAmount > 0) { revertEtherToUser(msg.sender, reimburseAmount); } if (supplyError != 0) { revertEtherToUser(msg.sender, msg.value); return fail( Error.WETH_ADDRESS_NOT_SET_ERROR, FailureInfo.WETH_ADDRESS_NOT_SET_ERROR ); } } else { revertEtherToUser(msg.sender, msg.value); return fail( Error.ETHER_AMOUNT_MISMATCH_ERROR, FailureInfo.ETHER_AMOUNT_MISMATCH_ERROR ); } } supplyOriginationFeeAsAdmin( asset, msg.sender, localResults.repayAmount, market.supplyIndex ); emit BorrowRepaid( msg.sender, asset, localResults.repayAmount, localResults.startingBalance, borrowBalance.principal ); return uint256(Error.NO_ERROR); // success } /** * @notice users repay all or some of an underwater borrow and receive collateral * @param targetAccount The account whose borrow should be liquidated * @param assetBorrow The market asset to repay * @param assetCollateral The borrower's market asset to receive in exchange * @param requestedAmountClose The amount to repay (or -1 for max) * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function liquidateBorrow( address targetAccount, address assetBorrow, address assetCollateral, uint256 requestedAmountClose ) public payable returns (uint256) { if (paused) { return fail( Error.CONTRACT_PAUSED, FailureInfo.LIQUIDATE_CONTRACT_PAUSED ); } refreshAlkSupplyIndex(assetCollateral, targetAccount, false); refreshAlkSupplyIndex(assetCollateral, msg.sender, false); refreshAlkBorrowIndex(assetBorrow, targetAccount, false); LiquidateLocalVars memory localResults; // Copy these addresses into the struct for use with `emitLiquidationEvent` // We'll use localResults.liquidator inside this function for clarity vs using msg.sender. localResults.targetAccount = targetAccount; localResults.assetBorrow = assetBorrow; localResults.liquidator = msg.sender; localResults.assetCollateral = assetCollateral; Market storage borrowMarket = markets[assetBorrow]; Market storage collateralMarket = markets[assetCollateral]; Balance storage borrowBalance_TargeUnderwaterAsset = borrowBalances[ targetAccount ][assetBorrow]; Balance storage supplyBalance_TargetCollateralAsset = supplyBalances[ targetAccount ][assetCollateral]; // Liquidator might already hold some of the collateral asset Balance storage supplyBalance_LiquidatorCollateralAsset = supplyBalances[localResults.liquidator][assetCollateral]; uint256 rateCalculationResultCode; // Used for multiple interest rate calculation calls Error err; // re-used for all intermediate errors (err, localResults.collateralPrice) = fetchAssetPrice(assetCollateral); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.LIQUIDATE_FETCH_ASSET_PRICE_FAILED); } (err, localResults.underwaterAssetPrice) = fetchAssetPrice(assetBorrow); // If the price oracle is not set, then we would have failed on the first call to fetchAssetPrice assert(err == Error.NO_ERROR); // We calculate newBorrowIndex_UnderwaterAsset and then use it to help calculate currentBorrowBalance_TargetUnderwaterAsset ( err, localResults.newBorrowIndex_UnderwaterAsset ) = calculateInterestIndex( borrowMarket.borrowIndex, borrowMarket.borrowRateMantissa, borrowMarket.blockNumber, block.number ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_NEW_BORROW_INDEX_CALCULATION_FAILED_BORROWED_ASSET ); } ( err, localResults.currentBorrowBalance_TargetUnderwaterAsset ) = calculateBalance( borrowBalance_TargeUnderwaterAsset.principal, borrowBalance_TargeUnderwaterAsset.interestIndex, localResults.newBorrowIndex_UnderwaterAsset ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_ACCUMULATED_BORROW_BALANCE_CALCULATION_FAILED ); } // We calculate newSupplyIndex_CollateralAsset and then use it to help calculate currentSupplyBalance_TargetCollateralAsset ( err, localResults.newSupplyIndex_CollateralAsset ) = calculateInterestIndex( collateralMarket.supplyIndex, collateralMarket.supplyRateMantissa, collateralMarket.blockNumber, block.number ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_NEW_SUPPLY_INDEX_CALCULATION_FAILED_COLLATERAL_ASSET ); } ( err, localResults.currentSupplyBalance_TargetCollateralAsset ) = calculateBalance( supplyBalance_TargetCollateralAsset.principal, supplyBalance_TargetCollateralAsset.interestIndex, localResults.newSupplyIndex_CollateralAsset ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_ACCUMULATED_SUPPLY_BALANCE_CALCULATION_FAILED_BORROWER_COLLATERAL_ASSET ); } // Liquidator may or may not already have some collateral asset. // If they do, we need to accumulate interest on it before adding the seized collateral to it. // We re-use newSupplyIndex_CollateralAsset calculated above to help calculate currentSupplyBalance_LiquidatorCollateralAsset ( err, localResults.currentSupplyBalance_LiquidatorCollateralAsset ) = calculateBalance( supplyBalance_LiquidatorCollateralAsset.principal, supplyBalance_LiquidatorCollateralAsset.interestIndex, localResults.newSupplyIndex_CollateralAsset ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_ACCUMULATED_SUPPLY_BALANCE_CALCULATION_FAILED_LIQUIDATOR_COLLATERAL_ASSET ); } // We update the protocol's totalSupply for assetCollateral in 2 steps, first by adding target user's accumulated // interest and then by adding the liquidator's accumulated interest. // Step 1 of 2: We add the target user's supplyCurrent and subtract their checkpointedBalance // (which has the desired effect of adding accrued interest from the target user) (err, localResults.newTotalSupply_ProtocolCollateralAsset) = addThenSub( collateralMarket.totalSupply, localResults.currentSupplyBalance_TargetCollateralAsset, supplyBalance_TargetCollateralAsset.principal ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_NEW_TOTAL_SUPPLY_BALANCE_CALCULATION_FAILED_BORROWER_COLLATERAL_ASSET ); } // Step 2 of 2: We add the liquidator's supplyCurrent of collateral asset and subtract their checkpointedBalance // (which has the desired effect of adding accrued interest from the calling user) (err, localResults.newTotalSupply_ProtocolCollateralAsset) = addThenSub( localResults.newTotalSupply_ProtocolCollateralAsset, localResults.currentSupplyBalance_LiquidatorCollateralAsset, supplyBalance_LiquidatorCollateralAsset.principal ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_NEW_TOTAL_SUPPLY_BALANCE_CALCULATION_FAILED_LIQUIDATOR_COLLATERAL_ASSET ); } // We calculate maxCloseableBorrowAmount_TargetUnderwaterAsset, the amount of borrow that can be closed from the target user // This is equal to the lesser of // 1. borrowCurrent; (already calculated) // 2. ONLY IF MARKET SUPPORTED: discountedRepayToEvenAmount: // discountedRepayToEvenAmount= // shortfall / [Oracle price for the borrow * (collateralRatio - liquidationDiscount - 1)] // 3. discountedBorrowDenominatedCollateral // [supplyCurrent / (1 + liquidationDiscount)] * (Oracle price for the collateral / Oracle price for the borrow) // Here we calculate item 3. discountedBorrowDenominatedCollateral = // [supplyCurrent / (1 + liquidationDiscount)] * (Oracle price for the collateral / Oracle price for the borrow) ( err, localResults.discountedBorrowDenominatedCollateral ) = calculateDiscountedBorrowDenominatedCollateral( localResults.underwaterAssetPrice, localResults.collateralPrice, localResults.currentSupplyBalance_TargetCollateralAsset ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_BORROW_DENOMINATED_COLLATERAL_CALCULATION_FAILED ); } if (borrowMarket.isSupported) { // Market is supported, so we calculate item 2 from above. ( err, localResults.discountedRepayToEvenAmount ) = calculateDiscountedRepayToEvenAmount( targetAccount, localResults.underwaterAssetPrice, assetBorrow ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_DISCOUNTED_REPAY_TO_EVEN_AMOUNT_CALCULATION_FAILED ); } // We need to do a two-step min to select from all 3 values // min1&3 = min(item 1, item 3) localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset = min( localResults.currentBorrowBalance_TargetUnderwaterAsset, localResults.discountedBorrowDenominatedCollateral ); // min1&3&2 = min(min1&3, 2) localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset = min( localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset, localResults.discountedRepayToEvenAmount ); } else { // Market is not supported, so we don't need to calculate item 2. localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset = min( localResults.currentBorrowBalance_TargetUnderwaterAsset, localResults.discountedBorrowDenominatedCollateral ); } // If liquidateBorrowAmount = -1, then closeBorrowAmount_TargetUnderwaterAsset = maxCloseableBorrowAmount_TargetUnderwaterAsset if (assetBorrow != wethAddress) { if (requestedAmountClose == uint256(-1)) { localResults .closeBorrowAmount_TargetUnderwaterAsset = localResults .maxCloseableBorrowAmount_TargetUnderwaterAsset; } else { localResults .closeBorrowAmount_TargetUnderwaterAsset = requestedAmountClose; } } else { // To calculate the actual repay use has to do and reimburse the excess amount of ETH collected if ( requestedAmountClose > localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset ) { localResults .closeBorrowAmount_TargetUnderwaterAsset = localResults .maxCloseableBorrowAmount_TargetUnderwaterAsset; (err, localResults.reimburseAmount) = sub( requestedAmountClose, localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset ); // reimbursement called at the end to make sure function does not have any other errors if (err != Error.NO_ERROR) { return fail( err, FailureInfo .REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED ); } } else { localResults .closeBorrowAmount_TargetUnderwaterAsset = requestedAmountClose; } } // From here on, no more use of `requestedAmountClose` // Verify closeBorrowAmount_TargetUnderwaterAsset <= maxCloseableBorrowAmount_TargetUnderwaterAsset if ( localResults.closeBorrowAmount_TargetUnderwaterAsset > localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset ) { return fail( Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_TOO_HIGH ); } // seizeSupplyAmount_TargetCollateralAsset = closeBorrowAmount_TargetUnderwaterAsset * priceBorrow/priceCollateral *(1+liquidationDiscount) ( err, localResults.seizeSupplyAmount_TargetCollateralAsset ) = calculateAmountSeize( localResults.underwaterAssetPrice, localResults.collateralPrice, localResults.closeBorrowAmount_TargetUnderwaterAsset ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.LIQUIDATE_AMOUNT_SEIZE_CALCULATION_FAILED ); } // We are going to ERC-20 transfer closeBorrowAmount_TargetUnderwaterAsset of assetBorrow into protocol // Fail gracefully if asset is not approved or has insufficient balance if (assetBorrow != wethAddress) { // WETH is supplied to AlkemiEarnPublic contract in case of ETH automatically err = checkTransferIn( assetBorrow, localResults.liquidator, localResults.closeBorrowAmount_TargetUnderwaterAsset ); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.LIQUIDATE_TRANSFER_IN_NOT_POSSIBLE); } } // We are going to repay the target user's borrow using the calling user's funds // We update the protocol's totalBorrow for assetBorrow, by subtracting the target user's prior checkpointed balance, // adding borrowCurrent, and subtracting closeBorrowAmount_TargetUnderwaterAsset. // Subtract the `closeBorrowAmount_TargetUnderwaterAsset` from the `currentBorrowBalance_TargetUnderwaterAsset` to get `updatedBorrowBalance_TargetUnderwaterAsset` (err, localResults.updatedBorrowBalance_TargetUnderwaterAsset) = sub( localResults.currentBorrowBalance_TargetUnderwaterAsset, localResults.closeBorrowAmount_TargetUnderwaterAsset ); // We have ensured above that localResults.closeBorrowAmount_TargetUnderwaterAsset <= localResults.currentBorrowBalance_TargetUnderwaterAsset, so the sub can't underflow assert(err == Error.NO_ERROR); // We calculate the protocol's totalBorrow for assetBorrow by subtracting the user's prior checkpointed balance, adding user's updated borrow // Note that, even though the liquidator is paying some of the borrow, if the borrow has accumulated a lot of interest since the last // action, the updated balance *could* be higher than the prior checkpointed balance. ( err, localResults.newTotalBorrows_ProtocolUnderwaterAsset ) = addThenSub( borrowMarket.totalBorrows, localResults.updatedBorrowBalance_TargetUnderwaterAsset, borrowBalance_TargeUnderwaterAsset.principal ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_NEW_TOTAL_BORROW_CALCULATION_FAILED_BORROWED_ASSET ); } // We need to calculate what the updated cash will be after we transfer in from liquidator localResults.currentCash_ProtocolUnderwaterAsset = getCash(assetBorrow); (err, localResults.updatedCash_ProtocolUnderwaterAsset) = add( localResults.currentCash_ProtocolUnderwaterAsset, localResults.closeBorrowAmount_TargetUnderwaterAsset ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_NEW_TOTAL_CASH_CALCULATION_FAILED_BORROWED_ASSET ); } // The utilization rate has changed! We calculate a new supply index, borrow index, supply rate, and borrow rate for assetBorrow // (Please note that we don't need to do the same thing for assetCollateral because neither cash nor borrows of assetCollateral happen in this process.) // We calculate the newSupplyIndex_UnderwaterAsset, but we already have newBorrowIndex_UnderwaterAsset so don't recalculate it. ( err, localResults.newSupplyIndex_UnderwaterAsset ) = calculateInterestIndex( borrowMarket.supplyIndex, borrowMarket.supplyRateMantissa, borrowMarket.blockNumber, block.number ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_NEW_SUPPLY_INDEX_CALCULATION_FAILED_BORROWED_ASSET ); } ( rateCalculationResultCode, localResults.newSupplyRateMantissa_ProtocolUnderwaterAsset ) = borrowMarket.interestRateModel.getSupplyRate( assetBorrow, localResults.updatedCash_ProtocolUnderwaterAsset, localResults.newTotalBorrows_ProtocolUnderwaterAsset ); if (rateCalculationResultCode != 0) { return failOpaque( FailureInfo .LIQUIDATE_NEW_SUPPLY_RATE_CALCULATION_FAILED_BORROWED_ASSET, rateCalculationResultCode ); } ( rateCalculationResultCode, localResults.newBorrowRateMantissa_ProtocolUnderwaterAsset ) = borrowMarket.interestRateModel.getBorrowRate( assetBorrow, localResults.updatedCash_ProtocolUnderwaterAsset, localResults.newTotalBorrows_ProtocolUnderwaterAsset ); if (rateCalculationResultCode != 0) { return failOpaque( FailureInfo .LIQUIDATE_NEW_BORROW_RATE_CALCULATION_FAILED_BORROWED_ASSET, rateCalculationResultCode ); } // Now we look at collateral. We calculated target user's accumulated supply balance and the supply index above. // Now we need to calculate the borrow index. // We don't need to calculate new rates for the collateral asset because we have not changed utilization: // - accumulating interest on the target user's collateral does not change cash or borrows // - transferring seized amount of collateral internally from the target user to the liquidator does not change cash or borrows. ( err, localResults.newBorrowIndex_CollateralAsset ) = calculateInterestIndex( collateralMarket.borrowIndex, collateralMarket.borrowRateMantissa, collateralMarket.blockNumber, block.number ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_NEW_BORROW_INDEX_CALCULATION_FAILED_COLLATERAL_ASSET ); } // We checkpoint the target user's assetCollateral supply balance, supplyCurrent - seizeSupplyAmount_TargetCollateralAsset at the updated index (err, localResults.updatedSupplyBalance_TargetCollateralAsset) = sub( localResults.currentSupplyBalance_TargetCollateralAsset, localResults.seizeSupplyAmount_TargetCollateralAsset ); // The sub won't underflow because because seizeSupplyAmount_TargetCollateralAsset <= target user's collateral balance // maxCloseableBorrowAmount_TargetUnderwaterAsset is limited by the discounted borrow denominated collateral. That limits closeBorrowAmount_TargetUnderwaterAsset // which in turn limits seizeSupplyAmount_TargetCollateralAsset. assert(err == Error.NO_ERROR); // We checkpoint the liquidating user's assetCollateral supply balance, supplyCurrent + seizeSupplyAmount_TargetCollateralAsset at the updated index ( err, localResults.updatedSupplyBalance_LiquidatorCollateralAsset ) = add( localResults.currentSupplyBalance_LiquidatorCollateralAsset, localResults.seizeSupplyAmount_TargetCollateralAsset ); // We can't overflow here because if this would overflow, then we would have already overflowed above and failed // with LIQUIDATE_NEW_TOTAL_SUPPLY_BALANCE_CALCULATION_FAILED_LIQUIDATOR_COLLATERAL_ASSET assert(err == Error.NO_ERROR); ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) // Save borrow market updates borrowMarket.blockNumber = block.number; borrowMarket.totalBorrows = localResults .newTotalBorrows_ProtocolUnderwaterAsset; // borrowMarket.totalSupply does not need to be updated borrowMarket.supplyRateMantissa = localResults .newSupplyRateMantissa_ProtocolUnderwaterAsset; borrowMarket.supplyIndex = localResults.newSupplyIndex_UnderwaterAsset; borrowMarket.borrowRateMantissa = localResults .newBorrowRateMantissa_ProtocolUnderwaterAsset; borrowMarket.borrowIndex = localResults.newBorrowIndex_UnderwaterAsset; // Save collateral market updates // We didn't calculate new rates for collateralMarket (because neither cash nor borrows changed), just new indexes and total supply. collateralMarket.blockNumber = block.number; collateralMarket.totalSupply = localResults .newTotalSupply_ProtocolCollateralAsset; collateralMarket.supplyIndex = localResults .newSupplyIndex_CollateralAsset; collateralMarket.borrowIndex = localResults .newBorrowIndex_CollateralAsset; // Save user updates localResults .startingBorrowBalance_TargetUnderwaterAsset = borrowBalance_TargeUnderwaterAsset .principal; // save for use in event borrowBalance_TargeUnderwaterAsset.principal = localResults .updatedBorrowBalance_TargetUnderwaterAsset; borrowBalance_TargeUnderwaterAsset.interestIndex = localResults .newBorrowIndex_UnderwaterAsset; localResults .startingSupplyBalance_TargetCollateralAsset = supplyBalance_TargetCollateralAsset .principal; // save for use in event supplyBalance_TargetCollateralAsset.principal = localResults .updatedSupplyBalance_TargetCollateralAsset; supplyBalance_TargetCollateralAsset.interestIndex = localResults .newSupplyIndex_CollateralAsset; localResults .startingSupplyBalance_LiquidatorCollateralAsset = supplyBalance_LiquidatorCollateralAsset .principal; // save for use in event supplyBalance_LiquidatorCollateralAsset.principal = localResults .updatedSupplyBalance_LiquidatorCollateralAsset; supplyBalance_LiquidatorCollateralAsset.interestIndex = localResults .newSupplyIndex_CollateralAsset; // We ERC-20 transfer the asset into the protocol (note: pre-conditions already checked above) if (assetBorrow != wethAddress) { // WETH is supplied to AlkemiEarnPublic contract in case of ETH automatically revertEtherToUser(msg.sender, msg.value); err = doTransferIn( assetBorrow, localResults.liquidator, localResults.closeBorrowAmount_TargetUnderwaterAsset ); if (err != Error.NO_ERROR) { // This is safe since it's our first interaction and it didn't do anything if it failed return fail(err, FailureInfo.LIQUIDATE_TRANSFER_IN_FAILED); } } else { if (msg.value == requestedAmountClose) { uint256 supplyError = supplyEther( localResults.liquidator, localResults.closeBorrowAmount_TargetUnderwaterAsset ); //Repay excess funds if (localResults.reimburseAmount > 0) { revertEtherToUser( localResults.liquidator, localResults.reimburseAmount ); } if (supplyError != 0) { revertEtherToUser(msg.sender, msg.value); return fail( Error.WETH_ADDRESS_NOT_SET_ERROR, FailureInfo.WETH_ADDRESS_NOT_SET_ERROR ); } } else { revertEtherToUser(msg.sender, msg.value); return fail( Error.ETHER_AMOUNT_MISMATCH_ERROR, FailureInfo.ETHER_AMOUNT_MISMATCH_ERROR ); } } supplyOriginationFeeAsAdmin( assetBorrow, localResults.liquidator, localResults.closeBorrowAmount_TargetUnderwaterAsset, localResults.newSupplyIndex_UnderwaterAsset ); emit BorrowLiquidated( localResults.targetAccount, localResults.assetBorrow, localResults.currentBorrowBalance_TargetUnderwaterAsset, localResults.closeBorrowAmount_TargetUnderwaterAsset, localResults.liquidator, localResults.assetCollateral, localResults.seizeSupplyAmount_TargetCollateralAsset ); return uint256(Error.NO_ERROR); // success } /** * @dev This should ONLY be called if market is supported. It returns shortfall / [Oracle price for the borrow * (collateralRatio - liquidationDiscount - 1)] * If the market isn't supported, we support liquidation of asset regardless of shortfall because we want borrows of the unsupported asset to be closed. * Note that if collateralRatio = liquidationDiscount + 1, then the denominator will be zero and the function will fail with DIVISION_BY_ZERO. * @return Return values are expressed in 1e18 scale */ function calculateDiscountedRepayToEvenAmount( address targetAccount, Exp memory underwaterAssetPrice, address assetBorrow ) internal view returns (Error, uint256) { Error err; Exp memory _accountLiquidity; // unused return value from calculateAccountLiquidity Exp memory accountShortfall_TargetUser; Exp memory collateralRatioMinusLiquidationDiscount; // collateralRatio - liquidationDiscount Exp memory discountedCollateralRatioMinusOne; // collateralRatioMinusLiquidationDiscount - 1, aka collateralRatio - liquidationDiscount - 1 Exp memory discountedPrice_UnderwaterAsset; Exp memory rawResult; // we calculate the target user's shortfall, denominated in Ether, that the user is below the collateral ratio ( err, _accountLiquidity, accountShortfall_TargetUser ) = calculateAccountLiquidity(targetAccount); if (err != Error.NO_ERROR) { return (err, 0); } (err, collateralRatioMinusLiquidationDiscount) = subExp( collateralRatio, liquidationDiscount ); if (err != Error.NO_ERROR) { return (err, 0); } (err, discountedCollateralRatioMinusOne) = subExp( collateralRatioMinusLiquidationDiscount, Exp({mantissa: mantissaOne}) ); if (err != Error.NO_ERROR) { return (err, 0); } (err, discountedPrice_UnderwaterAsset) = mulExp( underwaterAssetPrice, discountedCollateralRatioMinusOne ); // calculateAccountLiquidity multiplies underwaterAssetPrice by collateralRatio // discountedCollateralRatioMinusOne < collateralRatio // so if underwaterAssetPrice * collateralRatio did not overflow then // underwaterAssetPrice * discountedCollateralRatioMinusOne can't overflow either assert(err == Error.NO_ERROR); /* The liquidator may not repay more than what is allowed by the closeFactor */ uint256 borrowBalance = getBorrowBalance(targetAccount, assetBorrow); Exp memory maxClose; (err, maxClose) = mulScalar( Exp({mantissa: closeFactorMantissa}), borrowBalance ); if (err != Error.NO_ERROR) { return (err, 0); } (err, rawResult) = divExp(maxClose, discountedPrice_UnderwaterAsset); // It's theoretically possible an asset could have such a low price that it truncates to zero when discounted. if (err != Error.NO_ERROR) { return (err, 0); } return (Error.NO_ERROR, truncate(rawResult)); } /** * @dev discountedBorrowDenominatedCollateral = [supplyCurrent / (1 + liquidationDiscount)] * (Oracle price for the collateral / Oracle price for the borrow) * @return Return values are expressed in 1e18 scale */ function calculateDiscountedBorrowDenominatedCollateral( Exp memory underwaterAssetPrice, Exp memory collateralPrice, uint256 supplyCurrent_TargetCollateralAsset ) internal view returns (Error, uint256) { // To avoid rounding issues, we re-order and group the operations so we do 1 division and only at the end // [supplyCurrent * (Oracle price for the collateral)] / [ (1 + liquidationDiscount) * (Oracle price for the borrow) ] Error err; Exp memory onePlusLiquidationDiscount; // (1 + liquidationDiscount) Exp memory supplyCurrentTimesOracleCollateral; // supplyCurrent * Oracle price for the collateral Exp memory onePlusLiquidationDiscountTimesOracleBorrow; // (1 + liquidationDiscount) * Oracle price for the borrow Exp memory rawResult; (err, onePlusLiquidationDiscount) = addExp( Exp({mantissa: mantissaOne}), liquidationDiscount ); if (err != Error.NO_ERROR) { return (err, 0); } (err, supplyCurrentTimesOracleCollateral) = mulScalar( collateralPrice, supplyCurrent_TargetCollateralAsset ); if (err != Error.NO_ERROR) { return (err, 0); } (err, onePlusLiquidationDiscountTimesOracleBorrow) = mulExp( onePlusLiquidationDiscount, underwaterAssetPrice ); if (err != Error.NO_ERROR) { return (err, 0); } (err, rawResult) = divExp( supplyCurrentTimesOracleCollateral, onePlusLiquidationDiscountTimesOracleBorrow ); if (err != Error.NO_ERROR) { return (err, 0); } return (Error.NO_ERROR, truncate(rawResult)); } /** * @dev returns closeBorrowAmount_TargetUnderwaterAsset * (1+liquidationDiscount) * priceBorrow/priceCollateral * @return Return values are expressed in 1e18 scale */ function calculateAmountSeize( Exp memory underwaterAssetPrice, Exp memory collateralPrice, uint256 closeBorrowAmount_TargetUnderwaterAsset ) internal view returns (Error, uint256) { // To avoid rounding issues, we re-order and group the operations to move the division to the end, rather than just taking the ratio of the 2 prices: // underwaterAssetPrice * (1+liquidationDiscount) *closeBorrowAmount_TargetUnderwaterAsset) / collateralPrice // re-used for all intermediate errors Error err; // (1+liquidationDiscount) Exp memory liquidationMultiplier; // assetPrice-of-underwaterAsset * (1+liquidationDiscount) Exp memory priceUnderwaterAssetTimesLiquidationMultiplier; // priceUnderwaterAssetTimesLiquidationMultiplier * closeBorrowAmount_TargetUnderwaterAsset // or, expanded: // underwaterAssetPrice * (1+liquidationDiscount) * closeBorrowAmount_TargetUnderwaterAsset Exp memory finalNumerator; // finalNumerator / priceCollateral Exp memory rawResult; (err, liquidationMultiplier) = addExp( Exp({mantissa: mantissaOne}), liquidationDiscount ); // liquidation discount will be enforced < 1, so 1 + liquidationDiscount can't overflow. assert(err == Error.NO_ERROR); (err, priceUnderwaterAssetTimesLiquidationMultiplier) = mulExp( underwaterAssetPrice, liquidationMultiplier ); if (err != Error.NO_ERROR) { return (err, 0); } (err, finalNumerator) = mulScalar( priceUnderwaterAssetTimesLiquidationMultiplier, closeBorrowAmount_TargetUnderwaterAsset ); if (err != Error.NO_ERROR) { return (err, 0); } (err, rawResult) = divExp(finalNumerator, collateralPrice); if (err != Error.NO_ERROR) { return (err, 0); } return (Error.NO_ERROR, truncate(rawResult)); } /** * @notice Users borrow assets from the protocol to their own address * @param asset The market asset to borrow * @param amount The amount to borrow * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function borrow(address asset, uint256 amount) public nonReentrant returns (uint256) { if (paused) { return fail(Error.CONTRACT_PAUSED, FailureInfo.BORROW_CONTRACT_PAUSED); } refreshAlkBorrowIndex(asset, msg.sender, false); BorrowLocalVars memory localResults; Market storage market = markets[asset]; Balance storage borrowBalance = borrowBalances[msg.sender][asset]; Error err; uint256 rateCalculationResultCode; // Fail if market not supported if (!market.isSupported) { return fail( Error.MARKET_NOT_SUPPORTED, FailureInfo.BORROW_MARKET_NOT_SUPPORTED ); } // We calculate the newBorrowIndex, user's borrowCurrent and borrowUpdated for the asset (err, localResults.newBorrowIndex) = calculateInterestIndex( market.borrowIndex, market.borrowRateMantissa, market.blockNumber, block.number ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.BORROW_NEW_BORROW_INDEX_CALCULATION_FAILED ); } (err, localResults.userBorrowCurrent) = calculateBalance( borrowBalance.principal, borrowBalance.interestIndex, localResults.newBorrowIndex ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED ); } // Calculate origination fee. (err, localResults.borrowAmountWithFee) = calculateBorrowAmountWithFee( amount ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.BORROW_ORIGINATION_FEE_CALCULATION_FAILED ); } uint256 orgFeeBalance = localResults.borrowAmountWithFee - amount; // Add the `borrowAmountWithFee` to the `userBorrowCurrent` to get `userBorrowUpdated` (err, localResults.userBorrowUpdated) = add( localResults.userBorrowCurrent, localResults.borrowAmountWithFee ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED ); } // We calculate the protocol's totalBorrow by subtracting the user's prior checkpointed balance, adding user's updated borrow with fee (err, localResults.newTotalBorrows) = addThenSub( market.totalBorrows, localResults.userBorrowUpdated, borrowBalance.principal ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.BORROW_NEW_TOTAL_BORROW_CALCULATION_FAILED ); } // Check customer liquidity ( err, localResults.accountLiquidity, localResults.accountShortfall ) = calculateAccountLiquidity(msg.sender); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.BORROW_ACCOUNT_LIQUIDITY_CALCULATION_FAILED ); } // Fail if customer already has a shortfall if (!isZeroExp(localResults.accountShortfall)) { return fail( Error.INSUFFICIENT_LIQUIDITY, FailureInfo.BORROW_ACCOUNT_SHORTFALL_PRESENT ); } // Would the customer have a shortfall after this borrow (including origination fee)? // We calculate the eth-equivalent value of (borrow amount + fee) of asset and fail if it exceeds accountLiquidity. // This implements: `[(collateralRatio*oraclea*borrowAmount)*(1+borrowFee)] > accountLiquidity` ( err, localResults.ethValueOfBorrowAmountWithFee ) = getPriceForAssetAmountMulCollatRatio( asset, localResults.borrowAmountWithFee ); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.BORROW_AMOUNT_VALUE_CALCULATION_FAILED); } if ( lessThanExp( localResults.accountLiquidity, localResults.ethValueOfBorrowAmountWithFee ) ) { return fail( Error.INSUFFICIENT_LIQUIDITY, FailureInfo.BORROW_AMOUNT_LIQUIDITY_SHORTFALL ); } // Fail gracefully if protocol has insufficient cash localResults.currentCash = getCash(asset); // We need to calculate what the updated cash will be after we transfer out to the user (err, localResults.updatedCash) = sub(localResults.currentCash, amount); if (err != Error.NO_ERROR) { // Note: we ignore error here and call this token insufficient cash return fail( Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.BORROW_NEW_TOTAL_CASH_CALCULATION_FAILED ); } // The utilization rate has changed! We calculate a new supply index and borrow index for the asset, and save it. // We calculate the newSupplyIndex, but we have newBorrowIndex already (err, localResults.newSupplyIndex) = calculateInterestIndex( market.supplyIndex, market.supplyRateMantissa, market.blockNumber, block.number ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.BORROW_NEW_SUPPLY_INDEX_CALCULATION_FAILED ); } (rateCalculationResultCode, localResults.newSupplyRateMantissa) = market .interestRateModel .getSupplyRate( asset, localResults.updatedCash, localResults.newTotalBorrows ); if (rateCalculationResultCode != 0) { return failOpaque( FailureInfo.BORROW_NEW_SUPPLY_RATE_CALCULATION_FAILED, rateCalculationResultCode ); } (rateCalculationResultCode, localResults.newBorrowRateMantissa) = market .interestRateModel .getBorrowRate( asset, localResults.updatedCash, localResults.newTotalBorrows ); if (rateCalculationResultCode != 0) { return failOpaque( FailureInfo.BORROW_NEW_BORROW_RATE_CALCULATION_FAILED, rateCalculationResultCode ); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) // Save market updates market.blockNumber = block.number; market.totalBorrows = localResults.newTotalBorrows; market.supplyRateMantissa = localResults.newSupplyRateMantissa; market.supplyIndex = localResults.newSupplyIndex; market.borrowRateMantissa = localResults.newBorrowRateMantissa; market.borrowIndex = localResults.newBorrowIndex; // Save user updates localResults.startingBalance = borrowBalance.principal; // save for use in `BorrowTaken` event borrowBalance.principal = localResults.userBorrowUpdated; borrowBalance.interestIndex = localResults.newBorrowIndex; originationFeeBalance[msg.sender][asset] += orgFeeBalance; if (asset != wethAddress) { // Withdrawal should happen as Ether directly // We ERC-20 transfer the asset into the protocol (note: pre-conditions already checked above) err = doTransferOut(asset, msg.sender, amount); if (err != Error.NO_ERROR) { // This is safe since it's our first interaction and it didn't do anything if it failed return fail(err, FailureInfo.BORROW_TRANSFER_OUT_FAILED); } } else { withdrawEther(msg.sender, amount); // send Ether to user } emit BorrowTaken( msg.sender, asset, amount, localResults.startingBalance, localResults.borrowAmountWithFee, borrowBalance.principal ); return uint256(Error.NO_ERROR); // success } /** * @notice supply `amount` of `asset` (which must be supported) to `admin` in the protocol * @dev add amount of supported asset to admin's account * @param asset The market asset to supply * @param amount The amount to supply * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function supplyOriginationFeeAsAdmin( address asset, address user, uint256 amount, uint256 newSupplyIndex ) private { refreshAlkSupplyIndex(asset, admin, false); uint256 originationFeeRepaid = 0; if (originationFeeBalance[user][asset] != 0) { if (amount < originationFeeBalance[user][asset]) { originationFeeRepaid = amount; } else { originationFeeRepaid = originationFeeBalance[user][asset]; } Balance storage balance = supplyBalances[admin][asset]; SupplyLocalVars memory localResults; // Holds all our uint calculation results Error err; // Re-used for every function call that includes an Error in its return value(s). originationFeeBalance[user][asset] -= originationFeeRepaid; (err, localResults.userSupplyCurrent) = calculateBalance( balance.principal, balance.interestIndex, newSupplyIndex ); revertIfError(err); (err, localResults.userSupplyUpdated) = add( localResults.userSupplyCurrent, originationFeeRepaid ); revertIfError(err); // We calculate the protocol's totalSupply by subtracting the user's prior checkpointed balance, adding user's updated supply (err, localResults.newTotalSupply) = addThenSub( markets[asset].totalSupply, localResults.userSupplyUpdated, balance.principal ); revertIfError(err); // Save market updates markets[asset].totalSupply = localResults.newTotalSupply; // Save user updates localResults.startingBalance = balance.principal; balance.principal = localResults.userSupplyUpdated; balance.interestIndex = newSupplyIndex; emit SupplyOrgFeeAsAdmin( admin, asset, originationFeeRepaid, localResults.startingBalance, localResults.userSupplyUpdated ); } } /** * @notice Set the address of the Reward Control contract to be triggered to accrue ALK rewards for participants * @param _rewardControl The address of the underlying reward control contract * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function setRewardControlAddress(address _rewardControl) external returns (uint256) { // Check caller = admin require( msg.sender == admin, "SET_REWARD_CONTROL_ADDRESS_ADMIN_CHECK_FAILED" ); require( address(rewardControl) != _rewardControl, "The same Reward Control address" ); require( _rewardControl != address(0), "RewardControl address cannot be empty" ); rewardControl = RewardControlInterface(_rewardControl); return uint256(Error.NO_ERROR); // success } /** * @notice Trigger the underlying Reward Control contract to accrue ALK supply rewards for the supplier on the specified market * @param market The address of the market to accrue rewards * @param supplier The address of the supplier to accrue rewards * @param isVerified Verified / Public protocol */ function refreshAlkSupplyIndex( address market, address supplier, bool isVerified ) internal { if (address(rewardControl) == address(0)) { return; } rewardControl.refreshAlkSupplyIndex(market, supplier, isVerified); } /** * @notice Trigger the underlying Reward Control contract to accrue ALK borrow rewards for the borrower on the specified market * @param market The address of the market to accrue rewards * @param borrower The address of the borrower to accrue rewards * @param isVerified Verified / Public protocol */ function refreshAlkBorrowIndex( address market, address borrower, bool isVerified ) internal { if (address(rewardControl) == address(0)) { return; } rewardControl.refreshAlkBorrowIndex(market, borrower, isVerified); } /** * @notice Get supply and borrows for a market * @param asset The market asset to find balances of * @return updated supply and borrows */ function getMarketBalances(address asset) public view returns (uint256, uint256) { Error err; uint256 newSupplyIndex; uint256 marketSupplyCurrent; uint256 newBorrowIndex; uint256 marketBorrowCurrent; Market storage market = markets[asset]; // Calculate the newSupplyIndex, needed to calculate market's supplyCurrent (err, newSupplyIndex) = calculateInterestIndex( market.supplyIndex, market.supplyRateMantissa, market.blockNumber, block.number ); revertIfError(err); // Use newSupplyIndex and stored principal to calculate the accumulated balance (err, marketSupplyCurrent) = calculateBalance( market.totalSupply, market.supplyIndex, newSupplyIndex ); revertIfError(err); // Calculate the newBorrowIndex, needed to calculate market's borrowCurrent (err, newBorrowIndex) = calculateInterestIndex( market.borrowIndex, market.borrowRateMantissa, market.blockNumber, block.number ); revertIfError(err); // Use newBorrowIndex and stored principal to calculate the accumulated balance (err, marketBorrowCurrent) = calculateBalance( market.totalBorrows, market.borrowIndex, newBorrowIndex ); revertIfError(err); return (marketSupplyCurrent, marketBorrowCurrent); } /** * @dev Function to revert in case of an internal exception */ function revertIfError(Error err) internal pure { require( err == Error.NO_ERROR, "Function revert due to internal exception" ); } } // File: contracts/RewardControlStorage.sol pragma solidity 0.4.24; contract RewardControlStorage { struct MarketState { // @notice The market's last updated alkSupplyIndex or alkBorrowIndex uint224 index; // @notice The block number the index was last updated at uint32 block; } // @notice A list of all markets in the reward program mapped to respective verified/public protocols // @notice true => address[] represents Verified Protocol markets // @notice false => address[] represents Public Protocol markets mapping(bool => address[]) public allMarkets; // @notice The index for checking whether a market is already in the reward program // @notice The first mapping represents verified / public market and the second gives the existence of the market mapping(bool => mapping(address => bool)) public allMarketsIndex; // @notice The rate at which the Reward Control distributes ALK per block uint256 public alkRate; // @notice The portion of alkRate that each market currently receives // @notice The first mapping represents verified / public market and the second gives the alkSpeeds mapping(bool => mapping(address => uint256)) public alkSpeeds; // @notice The ALK market supply state for each market // @notice The first mapping represents verified / public market and the second gives the supplyState mapping(bool => mapping(address => MarketState)) public alkSupplyState; // @notice The ALK market borrow state for each market // @notice The first mapping represents verified / public market and the second gives the borrowState mapping(bool => mapping(address => MarketState)) public alkBorrowState; // @notice The snapshot of ALK index for each market for each supplier as of the last time they accrued ALK // @notice verified/public => market => supplier => supplierIndex mapping(bool => mapping(address => mapping(address => uint256))) public alkSupplierIndex; // @notice The snapshot of ALK index for each market for each borrower as of the last time they accrued ALK // @notice verified/public => market => borrower => borrowerIndex mapping(bool => mapping(address => mapping(address => uint256))) public alkBorrowerIndex; // @notice The ALK accrued but not yet transferred to each participant mapping(address => uint256) public alkAccrued; // @notice To make sure initializer is called only once bool public initializationDone; // @notice The address of the current owner of this contract address public owner; // @notice The proposed address of the new owner of this contract address public newOwner; // @notice The underlying AlkemiEarnVerified contract AlkemiEarnVerified public alkemiEarnVerified; // @notice The underlying AlkemiEarnPublic contract AlkemiEarnPublic public alkemiEarnPublic; // @notice The ALK token address address public alkAddress; // Hard cap on the maximum number of markets uint8 public MAXIMUM_NUMBER_OF_MARKETS; } // File: contracts/ExponentialNoError.sol // Cloned from https://github.com/compound-finance/compound-money-market/blob/master/contracts/Exponential.sol -> Commit id: 241541a pragma solidity 0.4.24; /** * @title Exponential module for storing fixed-precision decimals * @author Compound * @notice Exp is a struct which stores decimals with a fixed precision of 18 decimal places. * Thus, if we wanted to store the 5.1, mantissa would store 5.1e18. That is: * `Exp({mantissa: 5100000000000000000})`. */ contract ExponentialNoError { uint256 constant expScale = 1e18; uint256 constant doubleScale = 1e36; uint256 constant halfExpScale = expScale / 2; uint256 constant mantissaOne = expScale; struct Exp { uint256 mantissa; } struct Double { uint256 mantissa; } /** * @dev Truncates the given exp to a whole number value. * For example, truncate(Exp{mantissa: 15 * expScale}) = 15 */ function truncate(Exp memory exp) internal pure returns (uint256) { // Note: We are not using careful math here as we're performing a division that cannot fail return exp.mantissa / expScale; } /** * @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer. */ function mul_ScalarTruncate(Exp memory a, uint256 scalar) internal pure returns (uint256) { Exp memory product = mul_(a, scalar); return truncate(product); } /** * @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer. */ function mul_ScalarTruncateAddUInt( Exp memory a, uint256 scalar, uint256 addend ) internal pure returns (uint256) { Exp memory product = mul_(a, scalar); return add_(truncate(product), addend); } /** * @dev Checks if first Exp is less than second Exp. */ function lessThanExp(Exp memory left, Exp memory right) internal pure returns (bool) { return left.mantissa < right.mantissa; } /** * @dev Checks if left Exp <= right Exp. */ function lessThanOrEqualExp(Exp memory left, Exp memory right) internal pure returns (bool) { return left.mantissa <= right.mantissa; } /** * @dev Checks if left Exp > right Exp. */ function greaterThanExp(Exp memory left, Exp memory right) internal pure returns (bool) { return left.mantissa > right.mantissa; } /** * @dev returns true if Exp is exactly zero */ function isZeroExp(Exp memory value) internal pure returns (bool) { return value.mantissa == 0; } function safe224(uint256 n, string memory errorMessage) internal pure returns (uint224) { require(n < 2**224, errorMessage); return uint224(n); } function safe32(uint256 n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function add_(Exp memory a, Exp memory b) internal pure returns (Exp memory) { return Exp({mantissa: add_(a.mantissa, b.mantissa)}); } function add_(Double memory a, Double memory b) internal pure returns (Double memory) { return Double({mantissa: add_(a.mantissa, b.mantissa)}); } function add_(uint256 a, uint256 b) internal pure returns (uint256) { return add_(a, b, "addition overflow"); } function add_( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, errorMessage); return c; } function sub_(Exp memory a, Exp memory b) internal pure returns (Exp memory) { return Exp({mantissa: sub_(a.mantissa, b.mantissa)}); } function sub_(Double memory a, Double memory b) internal pure returns (Double memory) { return Double({mantissa: sub_(a.mantissa, b.mantissa)}); } function sub_(uint256 a, uint256 b) internal pure returns (uint256) { return sub_(a, b, "subtraction underflow"); } function sub_( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } function mul_(Exp memory a, Exp memory b) internal pure returns (Exp memory) { return Exp({mantissa: mul_(a.mantissa, b.mantissa) / expScale}); } function mul_(Exp memory a, uint256 b) internal pure returns (Exp memory) { return Exp({mantissa: mul_(a.mantissa, b)}); } function mul_(uint256 a, Exp memory b) internal pure returns (uint256) { return mul_(a, b.mantissa) / expScale; } function mul_(Double memory a, Double memory b) internal pure returns (Double memory) { return Double({mantissa: mul_(a.mantissa, b.mantissa) / doubleScale}); } function mul_(Double memory a, uint256 b) internal pure returns (Double memory) { return Double({mantissa: mul_(a.mantissa, b)}); } function mul_(uint256 a, Double memory b) internal pure returns (uint256) { return mul_(a, b.mantissa) / doubleScale; } function mul_(uint256 a, uint256 b) internal pure returns (uint256) { return mul_(a, b, "multiplication overflow"); } function mul_( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { if (a == 0 || b == 0) { return 0; } uint256 c = a * b; require(c / a == b, errorMessage); return c; } function div_(Exp memory a, Exp memory b) internal pure returns (Exp memory) { return Exp({mantissa: div_(mul_(a.mantissa, expScale), b.mantissa)}); } function div_(Exp memory a, uint256 b) internal pure returns (Exp memory) { return Exp({mantissa: div_(a.mantissa, b)}); } function div_(uint256 a, Exp memory b) internal pure returns (uint256) { return div_(mul_(a, expScale), b.mantissa); } function div_(Double memory a, Double memory b) internal pure returns (Double memory) { return Double({mantissa: div_(mul_(a.mantissa, doubleScale), b.mantissa)}); } function div_(Double memory a, uint256 b) internal pure returns (Double memory) { return Double({mantissa: div_(a.mantissa, b)}); } function div_(uint256 a, Double memory b) internal pure returns (uint256) { return div_(mul_(a, doubleScale), b.mantissa); } function div_(uint256 a, uint256 b) internal pure returns (uint256) { return div_(a, b, "divide by zero"); } function div_( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } function fraction(uint256 a, uint256 b) internal pure returns (Double memory) { return Double({mantissa: div_(mul_(a, doubleScale), b)}); } } // File: contracts/RewardControl.sol pragma solidity 0.4.24; contract RewardControl is RewardControlStorage, RewardControlInterface, ExponentialNoError { /** * Events */ /// @notice Emitted when a new ALK speed is calculated for a market event AlkSpeedUpdated( address indexed market, uint256 newSpeed, bool isVerified ); /// @notice Emitted when ALK is distributed to a supplier event DistributedSupplierAlk( address indexed market, address indexed supplier, uint256 supplierDelta, uint256 supplierAccruedAlk, uint256 supplyIndexMantissa, bool isVerified ); /// @notice Emitted when ALK is distributed to a borrower event DistributedBorrowerAlk( address indexed market, address indexed borrower, uint256 borrowerDelta, uint256 borrowerAccruedAlk, uint256 borrowIndexMantissa, bool isVerified ); /// @notice Emitted when ALK is transferred to a participant event TransferredAlk( address indexed participant, uint256 participantAccrued, address market, bool isVerified ); /// @notice Emitted when the owner of the contract is updated event OwnerUpdate(address indexed owner, address indexed newOwner); /// @notice Emitted when a market is added event MarketAdded( address indexed market, uint256 numberOfMarkets, bool isVerified ); /// @notice Emitted when a market is removed event MarketRemoved( address indexed market, uint256 numberOfMarkets, bool isVerified ); /** * Constants */ /** * Constructor */ /** * @notice `RewardControl` is the contract to calculate and distribute reward tokens * @notice This contract uses Openzeppelin Upgrades plugin to make use of the upgradeability functionality using proxies * @notice Hence this contract has an 'initializer' in place of a 'constructor' * @notice Make sure to add new global variables only in a derived contract of RewardControlStorage, inherited by this contract * @notice Also make sure to do extensive testing while modifying any structs and enums during an upgrade */ function initializer( address _owner, address _alkemiEarnVerified, address _alkemiEarnPublic, address _alkAddress ) public { require( _owner != address(0) && _alkemiEarnVerified != address(0) && _alkemiEarnPublic != address(0) && _alkAddress != address(0), "Inputs cannot be 0x00" ); if (initializationDone == false) { initializationDone = true; owner = _owner; alkemiEarnVerified = AlkemiEarnVerified(_alkemiEarnVerified); alkemiEarnPublic = AlkemiEarnPublic(_alkemiEarnPublic); alkAddress = _alkAddress; // Total Liquidity rewards for 4 years = 70,000,000 // Liquidity per year = 70,000,000/4 = 17,500,000 // Divided by blocksPerYear (assuming 13.3 seconds avg. block time) = 17,500,000/2,371,128 = 7.380453522542860000 // 7380453522542860000 (Tokens scaled by token decimals of 18) divided by 2 (half for lending and half for borrowing) alkRate = 3690226761271430000; MAXIMUM_NUMBER_OF_MARKETS = 16; } } /** * Modifiers */ /** * @notice Make sure that the sender is only the owner of the contract */ modifier onlyOwner() { require(msg.sender == owner, "non-owner"); _; } /** * Public functions */ /** * @notice Refresh ALK supply index for the specified market and supplier * @param market The market whose supply index to update * @param supplier The address of the supplier to distribute ALK to * @param isVerified Specifies if the market is from verified or public protocol */ function refreshAlkSupplyIndex( address market, address supplier, bool isVerified ) external { if (!allMarketsIndex[isVerified][market]) { return; } refreshAlkSpeeds(); updateAlkSupplyIndex(market, isVerified); distributeSupplierAlk(market, supplier, isVerified); } /** * @notice Refresh ALK borrow index for the specified market and borrower * @param market The market whose borrow index to update * @param borrower The address of the borrower to distribute ALK to * @param isVerified Specifies if the market is from verified or public protocol */ function refreshAlkBorrowIndex( address market, address borrower, bool isVerified ) external { if (!allMarketsIndex[isVerified][market]) { return; } refreshAlkSpeeds(); updateAlkBorrowIndex(market, isVerified); distributeBorrowerAlk(market, borrower, isVerified); } /** * @notice Claim all the ALK accrued by holder in all markets * @param holder The address to claim ALK for */ function claimAlk(address holder) external { claimAlk(holder, allMarkets[true], true); claimAlk(holder, allMarkets[false], false); } /** * @notice Claim all the ALK accrued by holder by refreshing the indexes on the specified market only * @param holder The address to claim ALK for * @param market The address of the market to refresh the indexes for * @param isVerified Specifies if the market is from verified or public protocol */ function claimAlk( address holder, address market, bool isVerified ) external { require(allMarketsIndex[isVerified][market], "Market does not exist"); address[] memory markets = new address[](1); markets[0] = market; claimAlk(holder, markets, isVerified); } /** * Private functions */ /** * @notice Recalculate and update ALK speeds for all markets */ function refreshMarketLiquidity() internal view returns (Exp[] memory, Exp memory) { Exp memory totalLiquidity = Exp({mantissa: 0}); Exp[] memory marketTotalLiquidity = new Exp[]( add_(allMarkets[true].length, allMarkets[false].length) ); address currentMarket; uint256 verifiedMarketsLength = allMarkets[true].length; for (uint256 i = 0; i < allMarkets[true].length; i++) { currentMarket = allMarkets[true][i]; uint256 currentMarketTotalSupply = mul_( getMarketTotalSupply(currentMarket, true), alkemiEarnVerified.assetPrices(currentMarket) ); uint256 currentMarketTotalBorrows = mul_( getMarketTotalBorrows(currentMarket, true), alkemiEarnVerified.assetPrices(currentMarket) ); Exp memory currentMarketTotalLiquidity = Exp({ mantissa: add_( currentMarketTotalSupply, currentMarketTotalBorrows ) }); marketTotalLiquidity[i] = currentMarketTotalLiquidity; totalLiquidity = add_(totalLiquidity, currentMarketTotalLiquidity); } for (uint256 j = 0; j < allMarkets[false].length; j++) { currentMarket = allMarkets[false][j]; currentMarketTotalSupply = mul_( getMarketTotalSupply(currentMarket, false), alkemiEarnVerified.assetPrices(currentMarket) ); currentMarketTotalBorrows = mul_( getMarketTotalBorrows(currentMarket, false), alkemiEarnVerified.assetPrices(currentMarket) ); currentMarketTotalLiquidity = Exp({ mantissa: add_( currentMarketTotalSupply, currentMarketTotalBorrows ) }); marketTotalLiquidity[ verifiedMarketsLength + j ] = currentMarketTotalLiquidity; totalLiquidity = add_(totalLiquidity, currentMarketTotalLiquidity); } return (marketTotalLiquidity, totalLiquidity); } /** * @notice Recalculate and update ALK speeds for all markets */ function refreshAlkSpeeds() public { address currentMarket; ( Exp[] memory marketTotalLiquidity, Exp memory totalLiquidity ) = refreshMarketLiquidity(); uint256 newSpeed; uint256 verifiedMarketsLength = allMarkets[true].length; for (uint256 i = 0; i < allMarkets[true].length; i++) { currentMarket = allMarkets[true][i]; newSpeed = totalLiquidity.mantissa > 0 ? mul_(alkRate, div_(marketTotalLiquidity[i], totalLiquidity)) : 0; alkSpeeds[true][currentMarket] = newSpeed; emit AlkSpeedUpdated(currentMarket, newSpeed, true); } for (uint256 j = 0; j < allMarkets[false].length; j++) { currentMarket = allMarkets[false][j]; newSpeed = totalLiquidity.mantissa > 0 ? mul_( alkRate, div_( marketTotalLiquidity[verifiedMarketsLength + j], totalLiquidity ) ) : 0; alkSpeeds[false][currentMarket] = newSpeed; emit AlkSpeedUpdated(currentMarket, newSpeed, false); } } /** * @notice Accrue ALK to the market by updating the supply index * @param market The market whose supply index to update * @param isVerified Verified / Public protocol */ function updateAlkSupplyIndex(address market, bool isVerified) public { MarketState storage supplyState = alkSupplyState[isVerified][market]; uint256 marketSpeed = alkSpeeds[isVerified][market]; uint256 blockNumber = getBlockNumber(); uint256 deltaBlocks = sub_(blockNumber, uint256(supplyState.block)); if (deltaBlocks > 0 && marketSpeed > 0) { uint256 marketTotalSupply = getMarketTotalSupply( market, isVerified ); uint256 supplyAlkAccrued = mul_(deltaBlocks, marketSpeed); Double memory ratio = marketTotalSupply > 0 ? fraction(supplyAlkAccrued, marketTotalSupply) : Double({mantissa: 0}); Double memory index = add_( Double({mantissa: supplyState.index}), ratio ); alkSupplyState[isVerified][market] = MarketState({ index: safe224(index.mantissa, "new index exceeds 224 bits"), block: safe32(blockNumber, "block number exceeds 32 bits") }); } else if (deltaBlocks > 0) { supplyState.block = safe32( blockNumber, "block number exceeds 32 bits" ); } } /** * @notice Accrue ALK to the market by updating the borrow index * @param market The market whose borrow index to update * @param isVerified Verified / Public protocol */ function updateAlkBorrowIndex(address market, bool isVerified) public { MarketState storage borrowState = alkBorrowState[isVerified][market]; uint256 marketSpeed = alkSpeeds[isVerified][market]; uint256 blockNumber = getBlockNumber(); uint256 deltaBlocks = sub_(blockNumber, uint256(borrowState.block)); if (deltaBlocks > 0 && marketSpeed > 0) { uint256 marketTotalBorrows = getMarketTotalBorrows( market, isVerified ); uint256 borrowAlkAccrued = mul_(deltaBlocks, marketSpeed); Double memory ratio = marketTotalBorrows > 0 ? fraction(borrowAlkAccrued, marketTotalBorrows) : Double({mantissa: 0}); Double memory index = add_( Double({mantissa: borrowState.index}), ratio ); alkBorrowState[isVerified][market] = MarketState({ index: safe224(index.mantissa, "new index exceeds 224 bits"), block: safe32(blockNumber, "block number exceeds 32 bits") }); } else if (deltaBlocks > 0) { borrowState.block = safe32( blockNumber, "block number exceeds 32 bits" ); } } /** * @notice Calculate ALK accrued by a supplier and add it on top of alkAccrued[supplier] * @param market The market in which the supplier is interacting * @param supplier The address of the supplier to distribute ALK to * @param isVerified Verified / Public protocol */ function distributeSupplierAlk( address market, address supplier, bool isVerified ) public { MarketState storage supplyState = alkSupplyState[isVerified][market]; Double memory supplyIndex = Double({mantissa: supplyState.index}); Double memory supplierIndex = Double({ mantissa: alkSupplierIndex[isVerified][market][supplier] }); alkSupplierIndex[isVerified][market][supplier] = supplyIndex.mantissa; if (supplierIndex.mantissa > 0) { Double memory deltaIndex = sub_(supplyIndex, supplierIndex); uint256 supplierBalance = getSupplyBalance( market, supplier, isVerified ); uint256 supplierDelta = mul_(supplierBalance, deltaIndex); alkAccrued[supplier] = add_(alkAccrued[supplier], supplierDelta); emit DistributedSupplierAlk( market, supplier, supplierDelta, alkAccrued[supplier], supplyIndex.mantissa, isVerified ); } } /** * @notice Calculate ALK accrued by a borrower and add it on top of alkAccrued[borrower] * @param market The market in which the borrower is interacting * @param borrower The address of the borrower to distribute ALK to * @param isVerified Verified / Public protocol */ function distributeBorrowerAlk( address market, address borrower, bool isVerified ) public { MarketState storage borrowState = alkBorrowState[isVerified][market]; Double memory borrowIndex = Double({mantissa: borrowState.index}); Double memory borrowerIndex = Double({ mantissa: alkBorrowerIndex[isVerified][market][borrower] }); alkBorrowerIndex[isVerified][market][borrower] = borrowIndex.mantissa; if (borrowerIndex.mantissa > 0) { Double memory deltaIndex = sub_(borrowIndex, borrowerIndex); uint256 borrowerBalance = getBorrowBalance( market, borrower, isVerified ); uint256 borrowerDelta = mul_(borrowerBalance, deltaIndex); alkAccrued[borrower] = add_(alkAccrued[borrower], borrowerDelta); emit DistributedBorrowerAlk( market, borrower, borrowerDelta, alkAccrued[borrower], borrowIndex.mantissa, isVerified ); } } /** * @notice Claim all the ALK accrued by holder in the specified markets * @param holder The address to claim ALK for * @param markets The list of markets to claim ALK in * @param isVerified Verified / Public protocol */ function claimAlk( address holder, address[] memory markets, bool isVerified ) internal { for (uint256 i = 0; i < markets.length; i++) { address market = markets[i]; updateAlkSupplyIndex(market, isVerified); distributeSupplierAlk(market, holder, isVerified); updateAlkBorrowIndex(market, isVerified); distributeBorrowerAlk(market, holder, isVerified); alkAccrued[holder] = transferAlk( holder, alkAccrued[holder], market, isVerified ); } } /** * @notice Transfer ALK to the participant * @dev Note: If there is not enough ALK, we do not perform the transfer all. * @param participant The address of the participant to transfer ALK to * @param participantAccrued The amount of ALK to (possibly) transfer * @param market Market for which ALK is transferred * @param isVerified Verified / Public Protocol * @return The amount of ALK which was NOT transferred to the participant */ function transferAlk( address participant, uint256 participantAccrued, address market, bool isVerified ) internal returns (uint256) { if (participantAccrued > 0) { EIP20Interface alk = EIP20Interface(getAlkAddress()); uint256 alkRemaining = alk.balanceOf(address(this)); if (participantAccrued <= alkRemaining) { alk.transfer(participant, participantAccrued); emit TransferredAlk( participant, participantAccrued, market, isVerified ); return 0; } } return participantAccrued; } /** * Getters */ /** * @notice Get the current block number * @return The current block number */ function getBlockNumber() public view returns (uint256) { return block.number; } /** * @notice Get the current accrued ALK for a participant * @param participant The address of the participant * @return The amount of accrued ALK for the participant */ function getAlkAccrued(address participant) public view returns (uint256) { return alkAccrued[participant]; } /** * @notice Get the address of the ALK token * @return The address of ALK token */ function getAlkAddress() public view returns (address) { return alkAddress; } /** * @notice Get the address of the underlying AlkemiEarnVerified and AlkemiEarnPublic contract * @return The address of the underlying AlkemiEarnVerified and AlkemiEarnPublic contract */ function getAlkemiEarnAddress() public view returns (address, address) { return (address(alkemiEarnVerified), address(alkemiEarnPublic)); } /** * @notice Get market statistics from the AlkemiEarnVerified contract * @param market The address of the market * @param isVerified Verified / Public protocol * @return Market statistics for the given market */ function getMarketStats(address market, bool isVerified) public view returns ( bool isSupported, uint256 blockNumber, address interestRateModel, uint256 totalSupply, uint256 supplyRateMantissa, uint256 supplyIndex, uint256 totalBorrows, uint256 borrowRateMantissa, uint256 borrowIndex ) { if (isVerified) { return (alkemiEarnVerified.markets(market)); } else { return (alkemiEarnPublic.markets(market)); } } /** * @notice Get market total supply from the AlkemiEarnVerified / AlkemiEarnPublic contract * @param market The address of the market * @param isVerified Verified / Public protocol * @return Market total supply for the given market */ function getMarketTotalSupply(address market, bool isVerified) public view returns (uint256) { uint256 totalSupply; (, , , totalSupply, , , , , ) = getMarketStats(market, isVerified); return totalSupply; } /** * @notice Get market total borrows from the AlkemiEarnVerified contract * @param market The address of the market * @param isVerified Verified / Public protocol * @return Market total borrows for the given market */ function getMarketTotalBorrows(address market, bool isVerified) public view returns (uint256) { uint256 totalBorrows; (, , , , , , totalBorrows, , ) = getMarketStats(market, isVerified); return totalBorrows; } /** * @notice Get supply balance of the specified market and supplier * @param market The address of the market * @param supplier The address of the supplier * @param isVerified Verified / Public protocol * @return Supply balance of the specified market and supplier */ function getSupplyBalance( address market, address supplier, bool isVerified ) public view returns (uint256) { if (isVerified) { return alkemiEarnVerified.getSupplyBalance(supplier, market); } else { return alkemiEarnPublic.getSupplyBalance(supplier, market); } } /** * @notice Get borrow balance of the specified market and borrower * @param market The address of the market * @param borrower The address of the borrower * @param isVerified Verified / Public protocol * @return Borrow balance of the specified market and borrower */ function getBorrowBalance( address market, address borrower, bool isVerified ) public view returns (uint256) { if (isVerified) { return alkemiEarnVerified.getBorrowBalance(borrower, market); } else { return alkemiEarnPublic.getBorrowBalance(borrower, market); } } /** * Admin functions */ /** * @notice Transfer the ownership of this contract to the new owner. The ownership will not be transferred until the new owner accept it. * @param _newOwner The address of the new owner */ function transferOwnership(address _newOwner) external onlyOwner { require(_newOwner != owner, "TransferOwnership: the same owner."); newOwner = _newOwner; } /** * @notice Accept the ownership of this contract by the new owner */ function acceptOwnership() external { require( msg.sender == newOwner, "AcceptOwnership: only new owner do this." ); emit OwnerUpdate(owner, newOwner); owner = newOwner; newOwner = address(0); } /** * @notice Add new market to the reward program * @param market The address of the new market to be added to the reward program * @param isVerified Verified / Public protocol */ function addMarket(address market, bool isVerified) external onlyOwner { require(!allMarketsIndex[isVerified][market], "Market already exists"); require( allMarkets[isVerified].length < uint256(MAXIMUM_NUMBER_OF_MARKETS), "Exceeding the max number of markets allowed" ); allMarketsIndex[isVerified][market] = true; allMarkets[isVerified].push(market); emit MarketAdded( market, add_(allMarkets[isVerified].length, allMarkets[!isVerified].length), isVerified ); } /** * @notice Remove a market from the reward program based on array index * @param id The index of the `allMarkets` array to be removed * @param isVerified Verified / Public protocol */ function removeMarket(uint256 id, bool isVerified) external onlyOwner { if (id >= allMarkets[isVerified].length) { return; } allMarketsIndex[isVerified][allMarkets[isVerified][id]] = false; address removedMarket = allMarkets[isVerified][id]; for (uint256 i = id; i < allMarkets[isVerified].length - 1; i++) { allMarkets[isVerified][i] = allMarkets[isVerified][i + 1]; } allMarkets[isVerified].length--; // reset the ALK speeds for the removed market and refresh ALK speeds alkSpeeds[isVerified][removedMarket] = 0; refreshAlkSpeeds(); emit MarketRemoved( removedMarket, add_(allMarkets[isVerified].length, allMarkets[!isVerified].length), isVerified ); } /** * @notice Set ALK token address * @param _alkAddress The ALK token address */ function setAlkAddress(address _alkAddress) external onlyOwner { require(alkAddress != _alkAddress, "The same ALK address"); require(_alkAddress != address(0), "ALK address cannot be empty"); alkAddress = _alkAddress; } /** * @notice Set AlkemiEarnVerified contract address * @param _alkemiEarnVerified The AlkemiEarnVerified contract address */ function setAlkemiEarnVerifiedAddress(address _alkemiEarnVerified) external onlyOwner { require( address(alkemiEarnVerified) != _alkemiEarnVerified, "The same AlkemiEarnVerified address" ); require( _alkemiEarnVerified != address(0), "AlkemiEarnVerified address cannot be empty" ); alkemiEarnVerified = AlkemiEarnVerified(_alkemiEarnVerified); } /** * @notice Set AlkemiEarnPublic contract address * @param _alkemiEarnPublic The AlkemiEarnVerified contract address */ function setAlkemiEarnPublicAddress(address _alkemiEarnPublic) external onlyOwner { require( address(alkemiEarnPublic) != _alkemiEarnPublic, "The same AlkemiEarnPublic address" ); require( _alkemiEarnPublic != address(0), "AlkemiEarnPublic address cannot be empty" ); alkemiEarnPublic = AlkemiEarnPublic(_alkemiEarnPublic); } /** * @notice Set ALK rate * @param _alkRate The ALK rate */ function setAlkRate(uint256 _alkRate) external onlyOwner { alkRate = _alkRate; } /** * @notice Get latest ALK rewards * @param user the supplier/borrower */ function getAlkRewards(address user) external view returns (uint256) { // Refresh ALK speeds uint256 alkRewards = alkAccrued[user]; ( Exp[] memory marketTotalLiquidity, Exp memory totalLiquidity ) = refreshMarketLiquidity(); uint256 verifiedMarketsLength = allMarkets[true].length; for (uint256 i = 0; i < allMarkets[true].length; i++) { alkRewards = add_( alkRewards, add_( getSupplyAlkRewards( totalLiquidity, marketTotalLiquidity, user, i, i, true ), getBorrowAlkRewards( totalLiquidity, marketTotalLiquidity, user, i, i, true ) ) ); } for (uint256 j = 0; j < allMarkets[false].length; j++) { uint256 index = verifiedMarketsLength + j; alkRewards = add_( alkRewards, add_( getSupplyAlkRewards( totalLiquidity, marketTotalLiquidity, user, index, j, false ), getBorrowAlkRewards( totalLiquidity, marketTotalLiquidity, user, index, j, false ) ) ); } return alkRewards; } /** * @notice Get latest Supply ALK rewards * @param totalLiquidity Total Liquidity of all markets * @param marketTotalLiquidity Array of individual market liquidity * @param user the supplier * @param i index of the market in marketTotalLiquidity array * @param j index of the market in the verified/public allMarkets array * @param isVerified Verified / Public protocol */ function getSupplyAlkRewards( Exp memory totalLiquidity, Exp[] memory marketTotalLiquidity, address user, uint256 i, uint256 j, bool isVerified ) internal view returns (uint256) { uint256 newSpeed = totalLiquidity.mantissa > 0 ? mul_(alkRate, div_(marketTotalLiquidity[i], totalLiquidity)) : 0; MarketState memory supplyState = alkSupplyState[isVerified][ allMarkets[isVerified][j] ]; if ( sub_(getBlockNumber(), uint256(supplyState.block)) > 0 && newSpeed > 0 ) { Double memory index = add_( Double({mantissa: supplyState.index}), ( getMarketTotalSupply( allMarkets[isVerified][j], isVerified ) > 0 ? fraction( mul_( sub_( getBlockNumber(), uint256(supplyState.block) ), newSpeed ), getMarketTotalSupply( allMarkets[isVerified][j], isVerified ) ) : Double({mantissa: 0}) ) ); supplyState = MarketState({ index: safe224(index.mantissa, "new index exceeds 224 bits"), block: safe32(getBlockNumber(), "block number exceeds 32 bits") }); } else if (sub_(getBlockNumber(), uint256(supplyState.block)) > 0) { supplyState.block = safe32( getBlockNumber(), "block number exceeds 32 bits" ); } if ( isVerified && Double({ mantissa: alkSupplierIndex[isVerified][ allMarkets[isVerified][j] ][user] }).mantissa > 0 ) { return mul_( alkemiEarnVerified.getSupplyBalance( user, allMarkets[isVerified][j] ), sub_( Double({mantissa: supplyState.index}), Double({ mantissa: alkSupplierIndex[isVerified][ allMarkets[isVerified][j] ][user] }) ) ); } if ( !isVerified && Double({ mantissa: alkSupplierIndex[isVerified][ allMarkets[isVerified][j] ][user] }).mantissa > 0 ) { return mul_( alkemiEarnPublic.getSupplyBalance( user, allMarkets[isVerified][j] ), sub_( Double({mantissa: supplyState.index}), Double({ mantissa: alkSupplierIndex[isVerified][ allMarkets[isVerified][j] ][user] }) ) ); } else { return 0; } } /** * @notice Get latest Borrow ALK rewards * @param totalLiquidity Total Liquidity of all markets * @param marketTotalLiquidity Array of individual market liquidity * @param user the borrower * @param i index of the market in marketTotalLiquidity array * @param j index of the market in the verified/public allMarkets array * @param isVerified Verified / Public protocol */ function getBorrowAlkRewards( Exp memory totalLiquidity, Exp[] memory marketTotalLiquidity, address user, uint256 i, uint256 j, bool isVerified ) internal view returns (uint256) { uint256 newSpeed = totalLiquidity.mantissa > 0 ? mul_(alkRate, div_(marketTotalLiquidity[i], totalLiquidity)) : 0; MarketState memory borrowState = alkBorrowState[isVerified][ allMarkets[isVerified][j] ]; if ( sub_(getBlockNumber(), uint256(borrowState.block)) > 0 && newSpeed > 0 ) { Double memory index = add_( Double({mantissa: borrowState.index}), ( getMarketTotalBorrows( allMarkets[isVerified][j], isVerified ) > 0 ? fraction( mul_( sub_( getBlockNumber(), uint256(borrowState.block) ), newSpeed ), getMarketTotalBorrows( allMarkets[isVerified][j], isVerified ) ) : Double({mantissa: 0}) ) ); borrowState = MarketState({ index: safe224(index.mantissa, "new index exceeds 224 bits"), block: safe32(getBlockNumber(), "block number exceeds 32 bits") }); } else if (sub_(getBlockNumber(), uint256(borrowState.block)) > 0) { borrowState.block = safe32( getBlockNumber(), "block number exceeds 32 bits" ); } if ( Double({ mantissa: alkBorrowerIndex[isVerified][ allMarkets[isVerified][j] ][user] }).mantissa > 0 && isVerified ) { return mul_( alkemiEarnVerified.getBorrowBalance( user, allMarkets[isVerified][j] ), sub_( Double({mantissa: borrowState.index}), Double({ mantissa: alkBorrowerIndex[isVerified][ allMarkets[isVerified][j] ][user] }) ) ); } if ( Double({ mantissa: alkBorrowerIndex[isVerified][ allMarkets[isVerified][j] ][user] }).mantissa > 0 && !isVerified ) { return mul_( alkemiEarnPublic.getBorrowBalance( user, allMarkets[isVerified][j] ), sub_( Double({mantissa: borrowState.index}), Double({ mantissa: alkBorrowerIndex[isVerified][ allMarkets[isVerified][j] ][user] }) ) ); } else { return 0; } } }
return supply balance with any accumulated interest for `asset` belonging to `account` returns supply balance with any accumulated interest for `asset` belonging to `account` account the account to examine asset the market asset whose supply balance belonging to `account` should be checked return uint supply balance on success, throws on failed assertion otherwise/ Calculate the newSupplyIndex, needed to calculate user's supplyCurrent Use newSupplyIndex and stored principal to calculate the accumulated balance
function getSupplyBalance(address account, address asset) public view returns (uint256) { Error err; uint256 newSupplyIndex; uint256 userSupplyCurrent; Market storage market = markets[asset]; Balance storage supplyBalance = supplyBalances[account][asset]; (err, newSupplyIndex) = calculateInterestIndex( market.supplyIndex, market.supplyRateMantissa, market.blockNumber, block.number ); revertIfError(err); (err, userSupplyCurrent) = calculateBalance( supplyBalance.principal, supplyBalance.interestIndex, newSupplyIndex ); revertIfError(err); return userSupplyCurrent; }
80,951
./full_match/83/0xccB6d3Be8A0EDC412C292448e4C05069966F9C5d/sources/contracts/BeeTeamRaffle.sol
This function is used to get the right minimun percentage for withdraw
function gettingTheMinimunTickets(uint256 _amount) private view returns(uint256) { return ( minPercentageForRafflesWithdraw * _amount ) / 100; }
9,563,949
// SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.7.6; pragma abicoder v2; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "./SwapRouter.sol"; import "./GrantRegistry.sol"; import "./GrantRound.sol"; import "hardhat/console.sol"; contract GrantRoundManager is SwapRouter { // --- Libraries --- using Address for address; using BytesLib for bytes; using SafeERC20 for IERC20; using SafeMath for uint256; // --- Data --- /// @notice Address of the GrantRegistry GrantRegistry public immutable registry; address public immutable swapRouter = 0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45; /// @notice Address of the ERC20 token in which donations are made IERC20 public immutable donationToken; /// @dev Used for saving off swap output amounts for verifying input parameters mapping(IERC20 => uint256) internal swapOutputs; /// @dev Used for saving off contribution ratios for verifying input parameters mapping(IERC20 => uint256) internal donationRatios; /// @dev Scale factor on percentages when constructing `Donation` objects. One WAD represents 100% uint256 internal constant WAD = 1e18; /// --- Types --- /// @dev Defines the total `amountIn` of the first token in `path` that needs to be swapped to `donationToken` struct SwapSummary { uint256 amountIn; uint256 amountOutMin; // minimum amount to be returned after swap bytes path; // Use `path == donationToken` to indicate no swap is required and just transfer the tokens directly } struct SwapData { IERC20 inputToken; uint256 inputAmount; bytes data; uint256 value; } /// @dev Donation inputs and Uniswap V3 swap inputs: https://docs.uniswap.org/protocol/guides/swaps/multihop-swaps struct Donation { uint96 grantId; // grant ID to which donation is being made IERC20 token; // address of the token to donate uint256 ratio; // ratio of `token` to donate, specified as numerator where WAD = 1e18 = 100% Useful only if multiple donations are made at once. IE 25% of tokens to grant 1, 25% to another etc. GrantRound[] rounds; // rounds against which the donation should be counted } // --- Events --- /// @notice Emitted when a new GrantRound contract is created event GrantRoundCreated(address grantRound); /// @notice Emitted when a donation has been made event GrantDonation( uint96 indexed grantId, IERC20 indexed tokenIn, uint256 donationAmount, GrantRound[] rounds, uint256 time ); // --- Constructor --- constructor( GrantRegistry _registry, IERC20 _donationToken, address _factory, address _weth ) SwapRouter(_factory, _weth) { //Validation require(_registry.grantCount() >= 0,"GrantRoundManager: Invalid registry"); require(_donationToken.totalSupply() > 0,"GrantRoundManager: Invalid token"); // Set state registry = _registry; donationToken = _donationToken; } // --- Core methods --- /** * @notice Creates a new GrantRound * @param _owner Grant round owner that has permission to update the metadata pointer * @param _payoutAdmin Grant round administrator that has permission to payout the matching pool * @param _matchingToken Address for the token used to payout match amounts at the end of a round * @param _startTime Unix timestamp of the start of the round * @param _endTime Unix timestamp of the end of the round * @param _metaPtr URL pointing to the grant round metadata */ function createGrantRound( address _owner, address _payoutAdmin, IERC20 _matchingToken, uint256 _startTime, uint256 _endTime, MetaPtr calldata _metaPtr ) external { require(_matchingToken.totalSupply() > 0,"GrantRoundManager: Invalid matching token"); GrantRound _grantRound = new GrantRound( _owner, _payoutAdmin, registry, donationToken, _matchingToken, _startTime, _endTime, _metaPtr ); emit GrantRoundCreated(address(_grantRound)); } /* * @notice Performs swaps if necessary and donates funds as specified * @param _swaps Array of SwapSummary objects describing the swaps required * @param _deadline Unix timestamp after which a swap will revert, i.e. swap must be executed before this * @param _donations Array of donations to execute * @dev `_deadline` is not part of the `_swaps` array since all swaps can use the same `_deadline` to save some gas * @dev Caller must ensure the input tokens to the _swaps array are unique */ function donate( SwapData[] calldata _swaps, Donation[] calldata _donations ) external payable { // Main logic _validateDonations(_donations); _routerSwap(_swaps); _transferDonations(_donations); // Clear storage for refunds (this is set in _routerSwap) for (uint256 i = 0; i < _swaps.length; i++) { IERC20 _tokenIn = IERC20(_swaps[i].inputToken); swapOutputs[_tokenIn] = 0; donationRatios[_tokenIn] = 0; } for (uint256 i = 0; i < _donations.length; i++) { donationRatios[_donations[i].token] = 0; } } /** @notice this function contains the logic for swapping an input token for the donation token @dev The reason we use call here is to send the transaction from the autorouter within the donate function call itself. Otherwise we risk having issues with certain parts of the tx failing and just a lot of issues. And because with the autorouter, swaps can be rather complex, the calldata is going to be changing each time. @param _swaps, array of SwapData struct, containing IERC20 inputToken, uint inputAmount, and bytes data. The bytes data corresponds to the calldata generated from the autorouter in the front end. */ function _routerSwap(SwapData[] memory _swaps) internal { for (uint256 i = 0; i < _swaps.length; i++) { require(swapOutputs[_swaps[i].inputToken] == 0,"GrantRoundManager: Swap parameter has duplicate input tokens"); require(donationRatios[_swaps[i].inputToken] == WAD,"GrantRoundManager: Ratios do not sum to 100%"); if (_swaps[i].inputToken != donationToken) { uint256 contractBalance = donationToken.balanceOf(address(this)); // Transfer the tokens over and approve for the router _swaps[i].inputToken.safeTransferFrom(msg.sender, address(this), _swaps[i].inputAmount); _swaps[i].inputToken.approve(swapRouter, _swaps[i].inputAmount); (bool success, ) = swapRouter.call{value: _swaps[i].value}(_swaps[i].data); require(success, "swap failed"); contractBalance = donationToken.balanceOf(address(this)) - contractBalance; swapOutputs[_swaps[i].inputToken] = contractBalance; } else { swapOutputs[_swaps[i].inputToken] = _swaps[i].inputAmount; } } } /** * @dev Validates the inputs to a donation call are valid, and reverts if any requirements are violated * @param _donations Array of donations that will be executed */ function _validateDonations(Donation[] calldata _donations) internal { for (uint256 i = 0; i < _donations.length; i++) { // Validate grant exists require(_donations[i].grantId < registry.grantCount(),"GrantRoundManager: Grant does not exist in registry"); // Used later to validate ratios are correctly provided donationRatios[_donations[i].token] = donationRatios[ _donations[i].token ].add(_donations[i].ratio); // Validate round parameters GrantRound[] calldata _rounds = _donations[i].rounds; for (uint256 j = 0; j < _rounds.length; j++) { require(_rounds[j].isActive(),"GrantRoundManager: GrantRound is not active"); require(_rounds[j].registry() == registry,"GrantRoundManager: Round-Registry mismatch"); require(donationToken == _rounds[j].donationToken(),"GrantRoundManager: GrantRound's donation token does not match GrantRoundManager's donation token"); } } } /** * @dev Core donation logic that transfers funds to grants * @param _donations Array of donations to execute */ function _transferDonations(Donation[] calldata _donations) internal { for (uint256 i = 0; i < _donations.length; i++) { // Get data for this donation GrantRound[] calldata _rounds = _donations[i].rounds; uint96 _grantId = _donations[i].grantId; IERC20 _tokenIn = _donations[i].token; uint256 _donationAmount = (swapOutputs[_tokenIn].mul(_donations[i].ratio)) / WAD; require(_donationAmount > 0,"GrantRoundManager: Donation amount must be greater than zero"); // Execute transfer emit GrantDonation( _grantId, _tokenIn, _donationAmount, _rounds, block.timestamp ); address _payee = registry.getGrantPayee(_grantId); if (_tokenIn == donationToken) { _tokenIn.safeTransferFrom(msg.sender, _payee, _donationAmount); // transfer token directly from caller } else { donationToken.transfer(_payee, _donationAmount); // transfer swap output } } } }
--- Core methods --- Creates a new GrantRound _owner Grant round owner that has permission to update the metadata pointer _payoutAdmin Grant round administrator that has permission to payout the matching pool _matchingToken Address for the token used to payout match amounts at the end of a round _startTime Unix timestamp of the start of the round _endTime Unix timestamp of the end of the round _metaPtr URL pointing to the grant round metadata/
function createGrantRound( address _owner, address _payoutAdmin, IERC20 _matchingToken, uint256 _startTime, uint256 _endTime, MetaPtr calldata _metaPtr ) external { require(_matchingToken.totalSupply() > 0,"GrantRoundManager: Invalid matching token"); GrantRound _grantRound = new GrantRound( _owner, _payoutAdmin, registry, donationToken, _matchingToken, _startTime, _endTime, _metaPtr ); emit GrantRoundCreated(address(_grantRound)); }
5,372,140
// SPDX-License-Identifier: UNLICENSED pragma solidity 0.6.10; contract MockWhitelistModule { mapping(address => bool) public _isWhitelistedOtoken; mapping(bytes32 => bool) private _isWhitelistedProduct; mapping(address => bool) private whitelistedCollateral; mapping(address => bool) private whitelistedCallee; /// @dev mapping to mapping to track whitelisted collateral for covered calls or puts mapping(bytes32 => bool) internal coveredWhitelistedCollateral; /// @dev mapping to mapping to track whitelisted collateral for naked calls or puts mapping(bytes32 => bool) internal nakedWhitelistedCollateral; function whitelistProduct( address _underlying, address _strike, address _collateral, bool _isPut ) external returns (bytes32 id) { id = keccak256(abi.encodePacked(_underlying, _strike, _collateral, _isPut)); _isWhitelistedProduct[id] = true; } /** * @notice allows the owner to whitelist a collateral address for vault type 0 * @dev can only be called from the owner address. This function is used to whitelist any asset other than Otoken as collateral. * @param _collateral collateral asset address * @param _underlying underlying asset address * @param _isPut bool for whether the collateral is suitable for puts or calls */ function whitelistCoveredCollateral( address _collateral, address _underlying, bool _isPut ) external { bytes32 productHash = keccak256(abi.encode(_collateral, _underlying, _isPut)); coveredWhitelistedCollateral[productHash] = true; } /** * @notice allows the owner to whitelist a collateral address for vault type 1 * @dev can only be called from the owner address. This function is used to whitelist any asset other than Otoken as collateral. * @param _collateral collateral asset address * @param _underlying underlying asset address * @param _isPut bool for whether the collateral is suitable for puts or calls */ function whitelistNakedCollateral( address _collateral, address _underlying, bool _isPut ) external { bytes32 productHash = keccak256(abi.encode(_collateral, _underlying, _isPut)); nakedWhitelistedCollateral[productHash] = true; } function isWhitelistedProduct( address _underlying, address _strike, address _collateral, bool _isPut ) external view returns (bool isValid) { bytes32 id = keccak256(abi.encodePacked(_underlying, _strike, _collateral, _isPut)); return _isWhitelistedProduct[id]; } /** * @notice check if a collateral asset is whitelisted for vault type 0 * @param _collateral asset that is held as collateral against short/written options * @param _underlying asset that is used as the underlying asset for the written options * @param _isPut bool for whether the collateral is to be checked for suitability on a call or put * @return boolean, True if the collateral is whitelisted for vault type 0 */ function isCoveredWhitelistedCollateral( address _collateral, address _underlying, bool _isPut ) external view returns (bool) { bytes32 productHash = keccak256(abi.encode(_collateral, _underlying, _isPut)); return coveredWhitelistedCollateral[productHash]; } /** * @notice check if a collateral asset is whitelisted for vault type 1 * @param _collateral asset that is held as collateral against short/written options * @param _underlying asset that is used as the underlying asset for the written options * @param _isPut bool for whether the collateral is to be checked for suitability on a call or put * @return boolean, True if the collateral is whitelisted for vault type 1 */ function isNakedWhitelistedCollateral( address _collateral, address _underlying, bool _isPut ) external view returns (bool) { bytes32 productHash = keccak256(abi.encode(_collateral, _underlying, _isPut)); return nakedWhitelistedCollateral[productHash]; } function whitelistOtoken(address _otoken) external { _isWhitelistedOtoken[_otoken] = true; } function isWhitelistedOtoken(address _otoken) external view returns (bool) { return _isWhitelistedOtoken[_otoken]; } function isWhitelistedCollateral(address _collateral) external view returns (bool) { return whitelistedCollateral[_collateral]; } function whitelistCollateral(address _collateral) external { require(!whitelistedCollateral[_collateral], "Whitelist: Collateral already whitelisted"); whitelistedCollateral[_collateral] = true; } function isWhitelistedCallee(address _callee) external view returns (bool) { return whitelistedCallee[_callee]; } function whitelistCallee(address _callee) external { whitelistedCallee[_callee] = true; } function blacklistCallee(address _callee) external { whitelistedCallee[_callee] = false; } }
check if a collateral asset is whitelisted for vault type 1 _collateral asset that is held as collateral against short/written options _underlying asset that is used as the underlying asset for the written options _isPut bool for whether the collateral is to be checked for suitability on a call or put return boolean, True if the collateral is whitelisted for vault type 1/
function isNakedWhitelistedCollateral( address _collateral, address _underlying, bool _isPut ) external view returns (bool) { bytes32 productHash = keccak256(abi.encode(_collateral, _underlying, _isPut)); return nakedWhitelistedCollateral[productHash]; }
12,816,246
pragma solidity ^0.5.9; pragma experimental ABIEncoderV2; /* Copyright 2020 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ contract IERC20Token { // solhint-disable no-simple-event-func-name event Transfer( address indexed _from, address indexed _to, uint256 _value ); event Approval( address indexed _owner, address indexed _spender, uint256 _value ); /// @dev send `value` token to `to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return True if transfer was successful function transfer(address _to, uint256 _value) external returns (bool); /// @dev send `value` token to `to` from `from` on the condition it is approved by `from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return True if transfer was successful function transferFrom( address _from, address _to, uint256 _value ) external returns (bool); /// @dev `msg.sender` approves `_spender` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of wei to be approved for transfer /// @return Always true if the call has enough gas to complete execution function approve(address _spender, uint256 _value) external returns (bool); /// @dev Query total supply of token /// @return Total supply of token function totalSupply() external view returns (uint256); /// @param _owner The address from which the balance will be retrieved /// @return Balance of owner function balanceOf(address _owner) external view returns (uint256); /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) external view returns (uint256); } /* Copyright 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ contract IEtherToken is IERC20Token { function deposit() public payable; function withdraw(uint256 amount) public; } /* Copyright 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /* Copyright 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ library LibRichErrors { // bytes4(keccak256("Error(string)")) bytes4 internal constant STANDARD_ERROR_SELECTOR = 0x08c379a0; // solhint-disable func-name-mixedcase /// @dev ABI encode a standard, string revert error payload. /// This is the same payload that would be included by a `revert(string)` /// solidity statement. It has the function signature `Error(string)`. /// @param message The error string. /// @return The ABI encoded error. function StandardError( string memory message ) internal pure returns (bytes memory) { return abi.encodeWithSelector( STANDARD_ERROR_SELECTOR, bytes(message) ); } // solhint-enable func-name-mixedcase /// @dev Reverts an encoded rich revert reason `errorData`. /// @param errorData ABI encoded error data. function rrevert(bytes memory errorData) internal pure { assembly { revert(add(errorData, 0x20), mload(errorData)) } } } /* Copyright 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /* Copyright 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ library LibBytesRichErrors { enum InvalidByteOperationErrorCodes { FromLessThanOrEqualsToRequired, ToLessThanOrEqualsLengthRequired, LengthGreaterThanZeroRequired, LengthGreaterThanOrEqualsFourRequired, LengthGreaterThanOrEqualsTwentyRequired, LengthGreaterThanOrEqualsThirtyTwoRequired, LengthGreaterThanOrEqualsNestedBytesLengthRequired, DestinationLengthGreaterThanOrEqualSourceLengthRequired } // bytes4(keccak256("InvalidByteOperationError(uint8,uint256,uint256)")) bytes4 internal constant INVALID_BYTE_OPERATION_ERROR_SELECTOR = 0x28006595; // solhint-disable func-name-mixedcase function InvalidByteOperationError( InvalidByteOperationErrorCodes errorCode, uint256 offset, uint256 required ) internal pure returns (bytes memory) { return abi.encodeWithSelector( INVALID_BYTE_OPERATION_ERROR_SELECTOR, errorCode, offset, required ); } } library LibBytes { using LibBytes for bytes; /// @dev Gets the memory address for a byte array. /// @param input Byte array to lookup. /// @return memoryAddress Memory address of byte array. This /// points to the header of the byte array which contains /// the length. function rawAddress(bytes memory input) internal pure returns (uint256 memoryAddress) { assembly { memoryAddress := input } return memoryAddress; } /// @dev Gets the memory address for the contents of a byte array. /// @param input Byte array to lookup. /// @return memoryAddress Memory address of the contents of the byte array. function contentAddress(bytes memory input) internal pure returns (uint256 memoryAddress) { assembly { memoryAddress := add(input, 32) } return memoryAddress; } /// @dev Copies `length` bytes from memory location `source` to `dest`. /// @param dest memory address to copy bytes to. /// @param source memory address to copy bytes from. /// @param length number of bytes to copy. function memCopy( uint256 dest, uint256 source, uint256 length ) internal pure { if (length < 32) { // Handle a partial word by reading destination and masking // off the bits we are interested in. // This correctly handles overlap, zero lengths and source == dest assembly { let mask := sub(exp(256, sub(32, length)), 1) let s := and(mload(source), not(mask)) let d := and(mload(dest), mask) mstore(dest, or(s, d)) } } else { // Skip the O(length) loop when source == dest. if (source == dest) { return; } // For large copies we copy whole words at a time. The final // word is aligned to the end of the range (instead of after the // previous) to handle partial words. So a copy will look like this: // // #### // #### // #### // #### // // We handle overlap in the source and destination range by // changing the copying direction. This prevents us from // overwriting parts of source that we still need to copy. // // This correctly handles source == dest // if (source > dest) { assembly { // We subtract 32 from `sEnd` and `dEnd` because it // is easier to compare with in the loop, and these // are also the addresses we need for copying the // last bytes. length := sub(length, 32) let sEnd := add(source, length) let dEnd := add(dest, length) // Remember the last 32 bytes of source // This needs to be done here and not after the loop // because we may have overwritten the last bytes in // source already due to overlap. let last := mload(sEnd) // Copy whole words front to back // Note: the first check is always true, // this could have been a do-while loop. // solhint-disable-next-line no-empty-blocks for {} lt(source, sEnd) {} { mstore(dest, mload(source)) source := add(source, 32) dest := add(dest, 32) } // Write the last 32 bytes mstore(dEnd, last) } } else { assembly { // We subtract 32 from `sEnd` and `dEnd` because those // are the starting points when copying a word at the end. length := sub(length, 32) let sEnd := add(source, length) let dEnd := add(dest, length) // Remember the first 32 bytes of source // This needs to be done here and not after the loop // because we may have overwritten the first bytes in // source already due to overlap. let first := mload(source) // Copy whole words back to front // We use a signed comparisson here to allow dEnd to become // negative (happens when source and dest < 32). Valid // addresses in local memory will never be larger than // 2**255, so they can be safely re-interpreted as signed. // Note: the first check is always true, // this could have been a do-while loop. // solhint-disable-next-line no-empty-blocks for {} slt(dest, dEnd) {} { mstore(dEnd, mload(sEnd)) sEnd := sub(sEnd, 32) dEnd := sub(dEnd, 32) } // Write the first 32 bytes mstore(dest, first) } } } } /// @dev Returns a slices from a byte array. /// @param b The byte array to take a slice from. /// @param from The starting index for the slice (inclusive). /// @param to The final index for the slice (exclusive). /// @return result The slice containing bytes at indices [from, to) function slice( bytes memory b, uint256 from, uint256 to ) internal pure returns (bytes memory result) { // Ensure that the from and to positions are valid positions for a slice within // the byte array that is being used. if (from > to) { LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError( LibBytesRichErrors.InvalidByteOperationErrorCodes.FromLessThanOrEqualsToRequired, from, to )); } if (to > b.length) { LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError( LibBytesRichErrors.InvalidByteOperationErrorCodes.ToLessThanOrEqualsLengthRequired, to, b.length )); } // Create a new bytes structure and copy contents result = new bytes(to - from); memCopy( result.contentAddress(), b.contentAddress() + from, result.length ); return result; } /// @dev Returns a slice from a byte array without preserving the input. /// @param b The byte array to take a slice from. Will be destroyed in the process. /// @param from The starting index for the slice (inclusive). /// @param to The final index for the slice (exclusive). /// @return result The slice containing bytes at indices [from, to) /// @dev When `from == 0`, the original array will match the slice. In other cases its state will be corrupted. function sliceDestructive( bytes memory b, uint256 from, uint256 to ) internal pure returns (bytes memory result) { // Ensure that the from and to positions are valid positions for a slice within // the byte array that is being used. if (from > to) { LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError( LibBytesRichErrors.InvalidByteOperationErrorCodes.FromLessThanOrEqualsToRequired, from, to )); } if (to > b.length) { LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError( LibBytesRichErrors.InvalidByteOperationErrorCodes.ToLessThanOrEqualsLengthRequired, to, b.length )); } // Create a new bytes structure around [from, to) in-place. assembly { result := add(b, from) mstore(result, sub(to, from)) } return result; } /// @dev Pops the last byte off of a byte array by modifying its length. /// @param b Byte array that will be modified. /// @return The byte that was popped off. function popLastByte(bytes memory b) internal pure returns (bytes1 result) { if (b.length == 0) { LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError( LibBytesRichErrors.InvalidByteOperationErrorCodes.LengthGreaterThanZeroRequired, b.length, 0 )); } // Store last byte. result = b[b.length - 1]; assembly { // Decrement length of byte array. let newLen := sub(mload(b), 1) mstore(b, newLen) } return result; } /// @dev Tests equality of two byte arrays. /// @param lhs First byte array to compare. /// @param rhs Second byte array to compare. /// @return True if arrays are the same. False otherwise. function equals( bytes memory lhs, bytes memory rhs ) internal pure returns (bool equal) { // Keccak gas cost is 30 + numWords * 6. This is a cheap way to compare. // We early exit on unequal lengths, but keccak would also correctly // handle this. return lhs.length == rhs.length && keccak256(lhs) == keccak256(rhs); } /// @dev Reads an address from a position in a byte array. /// @param b Byte array containing an address. /// @param index Index in byte array of address. /// @return address from byte array. function readAddress( bytes memory b, uint256 index ) internal pure returns (address result) { if (b.length < index + 20) { LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError( LibBytesRichErrors.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsTwentyRequired, b.length, index + 20 // 20 is length of address )); } // Add offset to index: // 1. Arrays are prefixed by 32-byte length parameter (add 32 to index) // 2. Account for size difference between address length and 32-byte storage word (subtract 12 from index) index += 20; // Read address from array memory assembly { // 1. Add index to address of bytes array // 2. Load 32-byte word from memory // 3. Apply 20-byte mask to obtain address result := and(mload(add(b, index)), 0xffffffffffffffffffffffffffffffffffffffff) } return result; } /// @dev Writes an address into a specific position in a byte array. /// @param b Byte array to insert address into. /// @param index Index in byte array of address. /// @param input Address to put into byte array. function writeAddress( bytes memory b, uint256 index, address input ) internal pure { if (b.length < index + 20) { LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError( LibBytesRichErrors.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsTwentyRequired, b.length, index + 20 // 20 is length of address )); } // Add offset to index: // 1. Arrays are prefixed by 32-byte length parameter (add 32 to index) // 2. Account for size difference between address length and 32-byte storage word (subtract 12 from index) index += 20; // Store address into array memory assembly { // The address occupies 20 bytes and mstore stores 32 bytes. // First fetch the 32-byte word where we'll be storing the address, then // apply a mask so we have only the bytes in the word that the address will not occupy. // Then combine these bytes with the address and store the 32 bytes back to memory with mstore. // 1. Add index to address of bytes array // 2. Load 32-byte word from memory // 3. Apply 12-byte mask to obtain extra bytes occupying word of memory where we'll store the address let neighbors := and( mload(add(b, index)), 0xffffffffffffffffffffffff0000000000000000000000000000000000000000 ) // Make sure input address is clean. // (Solidity does not guarantee this) input := and(input, 0xffffffffffffffffffffffffffffffffffffffff) // Store the neighbors and address into memory mstore(add(b, index), xor(input, neighbors)) } } /// @dev Reads a bytes32 value from a position in a byte array. /// @param b Byte array containing a bytes32 value. /// @param index Index in byte array of bytes32 value. /// @return bytes32 value from byte array. function readBytes32( bytes memory b, uint256 index ) internal pure returns (bytes32 result) { if (b.length < index + 32) { LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError( LibBytesRichErrors.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsThirtyTwoRequired, b.length, index + 32 )); } // Arrays are prefixed by a 256 bit length parameter index += 32; // Read the bytes32 from array memory assembly { result := mload(add(b, index)) } return result; } /// @dev Writes a bytes32 into a specific position in a byte array. /// @param b Byte array to insert <input> into. /// @param index Index in byte array of <input>. /// @param input bytes32 to put into byte array. function writeBytes32( bytes memory b, uint256 index, bytes32 input ) internal pure { if (b.length < index + 32) { LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError( LibBytesRichErrors.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsThirtyTwoRequired, b.length, index + 32 )); } // Arrays are prefixed by a 256 bit length parameter index += 32; // Read the bytes32 from array memory assembly { mstore(add(b, index), input) } } /// @dev Reads a uint256 value from a position in a byte array. /// @param b Byte array containing a uint256 value. /// @param index Index in byte array of uint256 value. /// @return uint256 value from byte array. function readUint256( bytes memory b, uint256 index ) internal pure returns (uint256 result) { result = uint256(readBytes32(b, index)); return result; } /// @dev Writes a uint256 into a specific position in a byte array. /// @param b Byte array to insert <input> into. /// @param index Index in byte array of <input>. /// @param input uint256 to put into byte array. function writeUint256( bytes memory b, uint256 index, uint256 input ) internal pure { writeBytes32(b, index, bytes32(input)); } /// @dev Reads an unpadded bytes4 value from a position in a byte array. /// @param b Byte array containing a bytes4 value. /// @param index Index in byte array of bytes4 value. /// @return bytes4 value from byte array. function readBytes4( bytes memory b, uint256 index ) internal pure returns (bytes4 result) { if (b.length < index + 4) { LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError( LibBytesRichErrors.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsFourRequired, b.length, index + 4 )); } // Arrays are prefixed by a 32 byte length field index += 32; // Read the bytes4 from array memory assembly { result := mload(add(b, index)) // Solidity does not require us to clean the trailing bytes. // We do it anyway result := and(result, 0xFFFFFFFF00000000000000000000000000000000000000000000000000000000) } return result; } /// @dev Writes a new length to a byte array. /// Decreasing length will lead to removing the corresponding lower order bytes from the byte array. /// Increasing length may lead to appending adjacent in-memory bytes to the end of the byte array. /// @param b Bytes array to write new length to. /// @param length New length of byte array. function writeLength(bytes memory b, uint256 length) internal pure { assembly { mstore(b, length) } } } library LibERC20Token { bytes constant private DECIMALS_CALL_DATA = hex"313ce567"; /// @dev Calls `IERC20Token(token).approve()`. /// Reverts if `false` is returned or if the return /// data length is nonzero and not 32 bytes. /// @param token The address of the token contract. /// @param spender The address that receives an allowance. /// @param allowance The allowance to set. function approve( address token, address spender, uint256 allowance ) internal { bytes memory callData = abi.encodeWithSelector( IERC20Token(0).approve.selector, spender, allowance ); _callWithOptionalBooleanResult(token, callData); } /// @dev Calls `IERC20Token(token).approve()` and sets the allowance to the /// maximum if the current approval is not already >= an amount. /// Reverts if `false` is returned or if the return /// data length is nonzero and not 32 bytes. /// @param token The address of the token contract. /// @param spender The address that receives an allowance. /// @param amount The minimum allowance needed. function approveIfBelow( address token, address spender, uint256 amount ) internal { if (IERC20Token(token).allowance(address(this), spender) < amount) { approve(token, spender, uint256(-1)); } } /// @dev Calls `IERC20Token(token).transfer()`. /// Reverts if `false` is returned or if the return /// data length is nonzero and not 32 bytes. /// @param token The address of the token contract. /// @param to The address that receives the tokens /// @param amount Number of tokens to transfer. function transfer( address token, address to, uint256 amount ) internal { bytes memory callData = abi.encodeWithSelector( IERC20Token(0).transfer.selector, to, amount ); _callWithOptionalBooleanResult(token, callData); } /// @dev Calls `IERC20Token(token).transferFrom()`. /// Reverts if `false` is returned or if the return /// data length is nonzero and not 32 bytes. /// @param token The address of the token contract. /// @param from The owner of the tokens. /// @param to The address that receives the tokens /// @param amount Number of tokens to transfer. function transferFrom( address token, address from, address to, uint256 amount ) internal { bytes memory callData = abi.encodeWithSelector( IERC20Token(0).transferFrom.selector, from, to, amount ); _callWithOptionalBooleanResult(token, callData); } /// @dev Retrieves the number of decimals for a token. /// Returns `18` if the call reverts. /// @param token The address of the token contract. /// @return tokenDecimals The number of decimals places for the token. function decimals(address token) internal view returns (uint8 tokenDecimals) { tokenDecimals = 18; (bool didSucceed, bytes memory resultData) = token.staticcall(DECIMALS_CALL_DATA); if (didSucceed && resultData.length == 32) { tokenDecimals = uint8(LibBytes.readUint256(resultData, 0)); } } /// @dev Retrieves the allowance for a token, owner, and spender. /// Returns `0` if the call reverts. /// @param token The address of the token contract. /// @param owner The owner of the tokens. /// @param spender The address the spender. /// @return allowance The allowance for a token, owner, and spender. function allowance(address token, address owner, address spender) internal view returns (uint256 allowance_) { (bool didSucceed, bytes memory resultData) = token.staticcall( abi.encodeWithSelector( IERC20Token(0).allowance.selector, owner, spender ) ); if (didSucceed && resultData.length == 32) { allowance_ = LibBytes.readUint256(resultData, 0); } } /// @dev Retrieves the balance for a token owner. /// Returns `0` if the call reverts. /// @param token The address of the token contract. /// @param owner The owner of the tokens. /// @return balance The token balance of an owner. function balanceOf(address token, address owner) internal view returns (uint256 balance) { (bool didSucceed, bytes memory resultData) = token.staticcall( abi.encodeWithSelector( IERC20Token(0).balanceOf.selector, owner ) ); if (didSucceed && resultData.length == 32) { balance = LibBytes.readUint256(resultData, 0); } } /// @dev Executes a call on address `target` with calldata `callData` /// and asserts that either nothing was returned or a single boolean /// was returned equal to `true`. /// @param target The call target. /// @param callData The abi-encoded call data. function _callWithOptionalBooleanResult( address target, bytes memory callData ) private { (bool didSucceed, bytes memory resultData) = target.call(callData); if (didSucceed) { if (resultData.length == 0) { return; } if (resultData.length == 32) { uint256 result = LibBytes.readUint256(resultData, 0); if (result == 1) { return; } } } LibRichErrors.rrevert(resultData); } } /* Copyright 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ contract IWallet { bytes4 internal constant LEGACY_WALLET_MAGIC_VALUE = 0xb0671381; /// @dev Validates a hash with the `Wallet` signature type. /// @param hash Message hash that is signed. /// @param signature Proof of signing. /// @return magicValue `bytes4(0xb0671381)` if the signature check succeeds. function isValidSignature( bytes32 hash, bytes calldata signature ) external view returns (bytes4 magicValue); } /* Copyright 2020 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ contract DeploymentConstants { // solhint-disable separate-by-one-line-in-contract // Mainnet addresses /////////////////////////////////////////////////////// /// @dev Mainnet address of the WETH contract. address constant private WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; /// @dev Mainnet address of the KyberNetworkProxy contract. address constant private KYBER_NETWORK_PROXY_ADDRESS = 0x9AAb3f75489902f3a48495025729a0AF77d4b11e; /// @dev Mainnet address of the KyberHintHandler contract. address constant private KYBER_HINT_HANDLER_ADDRESS = 0xa1C0Fa73c39CFBcC11ec9Eb1Afc665aba9996E2C; /// @dev Mainnet address of the `UniswapExchangeFactory` contract. address constant private UNISWAP_EXCHANGE_FACTORY_ADDRESS = 0xc0a47dFe034B400B47bDaD5FecDa2621de6c4d95; /// @dev Mainnet address of the `UniswapV2Router01` contract. address constant private UNISWAP_V2_ROUTER_01_ADDRESS = 0xf164fC0Ec4E93095b804a4795bBe1e041497b92a; /// @dev Mainnet address of the Eth2Dai `MatchingMarket` contract. address constant private ETH2DAI_ADDRESS = 0x794e6e91555438aFc3ccF1c5076A74F42133d08D; /// @dev Mainnet address of the `ERC20BridgeProxy` contract address constant private ERC20_BRIDGE_PROXY_ADDRESS = 0x8ED95d1746bf1E4dAb58d8ED4724f1Ef95B20Db0; ///@dev Mainnet address of the `Dai` (multi-collateral) contract address constant private DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; /// @dev Mainnet address of the `Chai` contract address constant private CHAI_ADDRESS = 0x06AF07097C9Eeb7fD685c692751D5C66dB49c215; /// @dev Mainnet address of the 0x DevUtils contract. address constant private DEV_UTILS_ADDRESS = 0x74134CF88b21383713E096a5ecF59e297dc7f547; /// @dev Kyber ETH pseudo-address. address constant internal KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; /// @dev Mainnet address of the dYdX contract. address constant private DYDX_ADDRESS = 0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e; /// @dev Mainnet address of the GST2 contract address constant private GST_ADDRESS = 0x0000000000b3F879cb30FE243b4Dfee438691c04; /// @dev Mainnet address of the GST Collector address constant private GST_COLLECTOR_ADDRESS = 0x000000D3b08566BE75A6DB803C03C85C0c1c5B96; /// @dev Mainnet address of the mStable mUSD contract. address constant private MUSD_ADDRESS = 0xe2f2a5C287993345a840Db3B0845fbC70f5935a5; /// @dev Mainnet address of the Mooniswap Registry contract address constant private MOONISWAP_REGISTRY = 0x71CD6666064C3A1354a3B4dca5fA1E2D3ee7D303; // // Ropsten addresses /////////////////////////////////////////////////////// // /// @dev Mainnet address of the WETH contract. // address constant private WETH_ADDRESS = 0xc778417E063141139Fce010982780140Aa0cD5Ab; // /// @dev Mainnet address of the KyberNetworkProxy contract. // address constant private KYBER_NETWORK_PROXY_ADDRESS = 0xd719c34261e099Fdb33030ac8909d5788D3039C4; // /// @dev Mainnet address of the `UniswapExchangeFactory` contract. // address constant private UNISWAP_EXCHANGE_FACTORY_ADDRESS = 0x9c83dCE8CA20E9aAF9D3efc003b2ea62aBC08351; // /// @dev Mainnet address of the `UniswapV2Router01` contract. // address constant private UNISWAP_V2_ROUTER_01_ADDRESS = 0xf164fC0Ec4E93095b804a4795bBe1e041497b92a; // /// @dev Mainnet address of the Eth2Dai `MatchingMarket` contract. // address constant private ETH2DAI_ADDRESS = address(0); // /// @dev Mainnet address of the `ERC20BridgeProxy` contract // address constant private ERC20_BRIDGE_PROXY_ADDRESS = 0xb344afeD348de15eb4a9e180205A2B0739628339; // ///@dev Mainnet address of the `Dai` (multi-collateral) contract // address constant private DAI_ADDRESS = address(0); // /// @dev Mainnet address of the `Chai` contract // address constant private CHAI_ADDRESS = address(0); // /// @dev Mainnet address of the 0x DevUtils contract. // address constant private DEV_UTILS_ADDRESS = 0xC812AF3f3fBC62F76ea4262576EC0f49dB8B7f1c; // /// @dev Kyber ETH pseudo-address. // address constant internal KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; // /// @dev Mainnet address of the dYdX contract. // address constant private DYDX_ADDRESS = address(0); // /// @dev Mainnet address of the GST2 contract // address constant private GST_ADDRESS = address(0); // /// @dev Mainnet address of the GST Collector // address constant private GST_COLLECTOR_ADDRESS = address(0); // /// @dev Mainnet address of the mStable mUSD contract. // address constant private MUSD_ADDRESS = 0x4E1000616990D83e56f4b5fC6CC8602DcfD20459; // // Rinkeby addresses /////////////////////////////////////////////////////// // /// @dev Mainnet address of the WETH contract. // address constant private WETH_ADDRESS = 0xc778417E063141139Fce010982780140Aa0cD5Ab; // /// @dev Mainnet address of the KyberNetworkProxy contract. // address constant private KYBER_NETWORK_PROXY_ADDRESS = 0x0d5371e5EE23dec7DF251A8957279629aa79E9C5; // /// @dev Mainnet address of the `UniswapExchangeFactory` contract. // address constant private UNISWAP_EXCHANGE_FACTORY_ADDRESS = 0xf5D915570BC477f9B8D6C0E980aA81757A3AaC36; // /// @dev Mainnet address of the `UniswapV2Router01` contract. // address constant private UNISWAP_V2_ROUTER_01_ADDRESS = 0xf164fC0Ec4E93095b804a4795bBe1e041497b92a; // /// @dev Mainnet address of the Eth2Dai `MatchingMarket` contract. // address constant private ETH2DAI_ADDRESS = address(0); // /// @dev Mainnet address of the `ERC20BridgeProxy` contract // address constant private ERC20_BRIDGE_PROXY_ADDRESS = 0xA2AA4bEFED748Fba27a3bE7Dfd2C4b2c6DB1F49B; // ///@dev Mainnet address of the `Dai` (multi-collateral) contract // address constant private DAI_ADDRESS = address(0); // /// @dev Mainnet address of the `Chai` contract // address constant private CHAI_ADDRESS = address(0); // /// @dev Mainnet address of the 0x DevUtils contract. // address constant private DEV_UTILS_ADDRESS = 0x46B5BC959e8A754c0256FFF73bF34A52Ad5CdfA9; // /// @dev Kyber ETH pseudo-address. // address constant internal KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; // /// @dev Mainnet address of the dYdX contract. // address constant private DYDX_ADDRESS = address(0); // /// @dev Mainnet address of the GST2 contract // address constant private GST_ADDRESS = address(0); // /// @dev Mainnet address of the GST Collector // address constant private GST_COLLECTOR_ADDRESS = address(0); // /// @dev Mainnet address of the mStable mUSD contract. // address constant private MUSD_ADDRESS = address(0); // // Kovan addresses ///////////////////////////////////////////////////////// // /// @dev Kovan address of the WETH contract. // address constant private WETH_ADDRESS = 0xd0A1E359811322d97991E03f863a0C30C2cF029C; // /// @dev Kovan address of the KyberNetworkProxy contract. // address constant private KYBER_NETWORK_PROXY_ADDRESS = 0x692f391bCc85cefCe8C237C01e1f636BbD70EA4D; // /// @dev Kovan address of the `UniswapExchangeFactory` contract. // address constant private UNISWAP_EXCHANGE_FACTORY_ADDRESS = 0xD3E51Ef092B2845f10401a0159B2B96e8B6c3D30; // /// @dev Kovan address of the `UniswapV2Router01` contract. // address constant private UNISWAP_V2_ROUTER_01_ADDRESS = 0xf164fC0Ec4E93095b804a4795bBe1e041497b92a; // /// @dev Kovan address of the Eth2Dai `MatchingMarket` contract. // address constant private ETH2DAI_ADDRESS = 0xe325acB9765b02b8b418199bf9650972299235F4; // /// @dev Kovan address of the `ERC20BridgeProxy` contract // address constant private ERC20_BRIDGE_PROXY_ADDRESS = 0x3577552C1Fb7A44aD76BeEB7aB53251668A21F8D; // /// @dev Kovan address of the `Chai` contract // address constant private CHAI_ADDRESS = address(0); // /// @dev Kovan address of the `Dai` (multi-collateral) contract // address constant private DAI_ADDRESS = 0x4F96Fe3b7A6Cf9725f59d353F723c1bDb64CA6Aa; // /// @dev Kovan address of the 0x DevUtils contract. // address constant private DEV_UTILS_ADDRESS = 0x9402639A828BdF4E9e4103ac3B69E1a6E522eB59; // /// @dev Kyber ETH pseudo-address. // address constant internal KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; // /// @dev Kovan address of the dYdX contract. // address constant private DYDX_ADDRESS = address(0); // /// @dev Kovan address of the GST2 contract // address constant private GST_ADDRESS = address(0); // /// @dev Kovan address of the GST Collector // address constant private GST_COLLECTOR_ADDRESS = address(0); // /// @dev Mainnet address of the mStable mUSD contract. // address constant private MUSD_ADDRESS = address(0); /// @dev Overridable way to get the `KyberNetworkProxy` address. /// @return kyberAddress The `IKyberNetworkProxy` address. function _getKyberNetworkProxyAddress() internal view returns (address kyberAddress) { return KYBER_NETWORK_PROXY_ADDRESS; } /// @dev Overridable way to get the `KyberHintHandler` address. /// @return kyberAddress The `IKyberHintHandler` address. function _getKyberHintHandlerAddress() internal view returns (address hintHandlerAddress) { return KYBER_HINT_HANDLER_ADDRESS; } /// @dev Overridable way to get the WETH address. /// @return wethAddress The WETH address. function _getWethAddress() internal view returns (address wethAddress) { return WETH_ADDRESS; } /// @dev Overridable way to get the `UniswapExchangeFactory` address. /// @return uniswapAddress The `UniswapExchangeFactory` address. function _getUniswapExchangeFactoryAddress() internal view returns (address uniswapAddress) { return UNISWAP_EXCHANGE_FACTORY_ADDRESS; } /// @dev Overridable way to get the `UniswapV2Router01` address. /// @return uniswapRouterAddress The `UniswapV2Router01` address. function _getUniswapV2Router01Address() internal view returns (address uniswapRouterAddress) { return UNISWAP_V2_ROUTER_01_ADDRESS; } /// @dev An overridable way to retrieve the Eth2Dai `MatchingMarket` contract. /// @return eth2daiAddress The Eth2Dai `MatchingMarket` contract. function _getEth2DaiAddress() internal view returns (address eth2daiAddress) { return ETH2DAI_ADDRESS; } /// @dev An overridable way to retrieve the `ERC20BridgeProxy` contract. /// @return erc20BridgeProxyAddress The `ERC20BridgeProxy` contract. function _getERC20BridgeProxyAddress() internal view returns (address erc20BridgeProxyAddress) { return ERC20_BRIDGE_PROXY_ADDRESS; } /// @dev An overridable way to retrieve the `Dai` contract. /// @return daiAddress The `Dai` contract. function _getDaiAddress() internal view returns (address daiAddress) { return DAI_ADDRESS; } /// @dev An overridable way to retrieve the `Chai` contract. /// @return chaiAddress The `Chai` contract. function _getChaiAddress() internal view returns (address chaiAddress) { return CHAI_ADDRESS; } /// @dev An overridable way to retrieve the 0x `DevUtils` contract address. /// @return devUtils The 0x `DevUtils` contract address. function _getDevUtilsAddress() internal view returns (address devUtils) { return DEV_UTILS_ADDRESS; } /// @dev Overridable way to get the DyDx contract. /// @return exchange The DyDx exchange contract. function _getDydxAddress() internal view returns (address dydxAddress) { return DYDX_ADDRESS; } /// @dev An overridable way to retrieve the GST2 contract address. /// @return gst The GST contract. function _getGstAddress() internal view returns (address gst) { return GST_ADDRESS; } /// @dev An overridable way to retrieve the GST Collector address. /// @return collector The GST collector address. function _getGstCollectorAddress() internal view returns (address collector) { return GST_COLLECTOR_ADDRESS; } /// @dev An overridable way to retrieve the mStable mUSD address. /// @return musd The mStable mUSD address. function _getMUsdAddress() internal view returns (address musd) { return MUSD_ADDRESS; } /// @dev An overridable way to retrieve the Mooniswap registry address. /// @return musd The Mooniswap registry address. function _getMooniswapAddress() internal view returns (address registry) { return MOONISWAP_REGISTRY; } } /* Copyright 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ contract IERC20Bridge { /// @dev Result of a successful bridge call. bytes4 constant internal BRIDGE_SUCCESS = 0xdc1600f3; /// @dev Emitted when a trade occurs. /// @param inputToken The token the bridge is converting from. /// @param outputToken The token the bridge is converting to. /// @param inputTokenAmount Amount of input token. /// @param outputTokenAmount Amount of output token. /// @param from The `from` address in `bridgeTransferFrom()` /// @param to The `to` address in `bridgeTransferFrom()` event ERC20BridgeTransfer( address inputToken, address outputToken, uint256 inputTokenAmount, uint256 outputTokenAmount, address from, address to ); /// @dev Transfers `amount` of the ERC20 `tokenAddress` from `from` to `to`. /// @param tokenAddress The address of the ERC20 token to transfer. /// @param from Address to transfer asset from. /// @param to Address to transfer asset to. /// @param amount Amount of asset to transfer. /// @param bridgeData Arbitrary asset data needed by the bridge contract. /// @return success The magic bytes `0xdc1600f3` if successful. function bridgeTransferFrom( address tokenAddress, address from, address to, uint256 amount, bytes calldata bridgeData ) external returns (bytes4 success); } /* Copyright 2020 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ interface IKyberNetworkProxy { /// @dev Sells `sellTokenAddress` tokens for `buyTokenAddress` tokens. /// @param sellTokenAddress Token to sell. /// @param sellAmount Amount of tokens to sell. /// @param buyTokenAddress Token to buy. /// @param recipientAddress Address to send bought tokens to. /// @param maxBuyTokenAmount A limit on the amount of tokens to buy. /// @param minConversionRate The minimal conversion rate. If actual rate /// is lower, trade is canceled. /// @param walletId The wallet ID to send part of the fees /// @return boughtAmount Amount of tokens bought. function trade( address sellTokenAddress, uint256 sellAmount, address buyTokenAddress, address payable recipientAddress, uint256 maxBuyTokenAmount, uint256 minConversionRate, address walletId ) external payable returns (uint256 boughtAmount); /// @dev Sells `sellTokenAddress` tokens for `buyTokenAddress` tokens /// using a hint for the reserve. /// @param sellTokenAddress Token to sell. /// @param sellAmount Amount of tokens to sell. /// @param buyTokenAddress Token to buy. /// @param recipientAddress Address to send bought tokens to. /// @param maxBuyTokenAmount A limit on the amount of tokens to buy. /// @param minConversionRate The minimal conversion rate. If actual rate /// is lower, trade is canceled. /// @param walletId The wallet ID to send part of the fees /// @param hint The hint for the selective inclusion (or exclusion) of reserves /// @return boughtAmount Amount of tokens bought. function tradeWithHint( address sellTokenAddress, uint256 sellAmount, address buyTokenAddress, address payable recipientAddress, uint256 maxBuyTokenAmount, uint256 minConversionRate, address payable walletId, bytes calldata hint ) external payable returns (uint256 boughtAmount); } // solhint-disable space-after-comma contract KyberBridge is IERC20Bridge, IWallet, DeploymentConstants { // @dev Structure used internally to get around stack limits. struct TradeState { IKyberNetworkProxy kyber; IEtherToken weth; address fromTokenAddress; uint256 fromTokenBalance; uint256 payableAmount; bytes hint; } /// @dev Kyber ETH pseudo-address. address constant public KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; /// @dev `bridgeTransferFrom()` failure result. bytes4 constant private BRIDGE_FAILED = 0x0; // solhint-disable no-empty-blocks /// @dev Payable fallback to receive ETH from Kyber. function () external payable {} /// @dev Callback for `IKyberBridge`. Tries to buy `amount` of /// `toTokenAddress` tokens by selling the entirety of the opposing asset /// to the `KyberNetworkProxy` contract, then transfers the bought /// tokens to `to`. /// @param toTokenAddress The token to give to `to`. /// @param from The maker (this contract). /// @param to The recipient of the bought tokens. /// @param bridgeData The abi-encoeded "from" token address. /// @return success The magic bytes if successful. function bridgeTransferFrom( address toTokenAddress, address from, address to, uint256 /* amount */, bytes calldata bridgeData ) external returns (bytes4 success) { TradeState memory state; state.kyber = IKyberNetworkProxy(_getKyberNetworkProxyAddress()); state.weth = IEtherToken(_getWethAddress()); // Decode the bridge data to get the `fromTokenAddress`. (state.fromTokenAddress, state.hint) = abi.decode(bridgeData, (address, bytes)); // Query the balance of "from" tokens. state.fromTokenBalance = IERC20Token(state.fromTokenAddress).balanceOf(address(this)); if (state.fromTokenBalance == 0) { // Return failure if no input tokens. return BRIDGE_FAILED; } if (state.fromTokenAddress == toTokenAddress) { // Just transfer the tokens if they're the same. LibERC20Token.transfer(state.fromTokenAddress, to, state.fromTokenBalance); return BRIDGE_SUCCESS; } if (state.fromTokenAddress == address(state.weth)) { // From WETH state.fromTokenAddress = KYBER_ETH_ADDRESS; state.payableAmount = state.fromTokenBalance; state.weth.withdraw(state.fromTokenBalance); } else { LibERC20Token.approveIfBelow( state.fromTokenAddress, address(state.kyber), state.fromTokenBalance ); } bool isToTokenWeth = toTokenAddress == address(state.weth); // Try to sell all of this contract's input token balance through // `KyberNetworkProxy.trade()`. uint256 boughtAmount = state.kyber.tradeWithHint.value(state.payableAmount)( // Input token. state.fromTokenAddress, // Sell amount. state.fromTokenBalance, // Output token. isToTokenWeth ? KYBER_ETH_ADDRESS : toTokenAddress, // Transfer to this contract if converting to ETH, otherwise // transfer directly to the recipient. isToTokenWeth ? address(uint160(address(this))) : address(uint160(to)), // Buy as much as possible. uint256(-1), // The minimum conversion rate 1, // No affiliate address. address(0), state.hint ); // Wrap ETH output and transfer to recipient. if (isToTokenWeth) { state.weth.deposit.value(boughtAmount)(); state.weth.transfer(to, boughtAmount); } emit ERC20BridgeTransfer( state.fromTokenAddress == KYBER_ETH_ADDRESS ? address(state.weth) : state.fromTokenAddress, toTokenAddress, state.fromTokenBalance, boughtAmount, from, to ); return BRIDGE_SUCCESS; } /// @dev `SignatureType.Wallet` callback, so that this bridge can be the maker /// and sign for itself in orders. Always succeeds. /// @return magicValue Magic success bytes, always. function isValidSignature( bytes32, bytes calldata ) external view returns (bytes4 magicValue) { return LEGACY_WALLET_MAGIC_VALUE; } }
Overridable way to get the `UniswapV2Router01` address. return uniswapRouterAddress The `UniswapV2Router01` address.
function _getUniswapV2Router01Address() internal view returns (address uniswapRouterAddress) { return UNISWAP_V2_ROUTER_01_ADDRESS; }
178,313
pragma solidity ^0.4.21; contract Owner { address public owner; modifier onlyOwner() { require(msg.sender == owner); _; } function Owner(address _owner) public { owner = _owner; } function changeOwner(address _newOwnerAddr) public onlyOwner { require(_newOwnerAddr != address(0)); owner = _newOwnerAddr; } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract Extradecoin is Owner { using SafeMath for uint256; string public constant name = "EXTRADECOIN"; string public constant symbol = "ETE"; uint public constant decimals = 18; uint256 constant public totalSupply = 250000000 * 10 ** 18; // 250 mil tokens will be supplied mapping(address => uint256) internal balances; mapping(address => mapping (address => uint256)) internal allowed; address public adminAddress; address public walletAddress; address public founderAddress; address public advisorAddress; mapping(address => uint256) public totalInvestedAmountOf; uint constant lockPeriod1 = 3 years; // 1st locked period for tokens allocation of founder and team uint constant lockPeriod2 = 1 years; // 2nd locked period for tokens allocation of founder and team uint constant lockPeriod3 = 90 days; // 3nd locked period for tokens allocation of advisor and ICO partners uint constant NOT_SALE = 0; // Not in sales uint constant IN_ICO = 1; // In ICO uint constant END_SALE = 2; // End sales uint256 public constant salesAllocation = 125000000 * 10 ** 18; // 125 mil tokens allocated for sales uint256 public constant founderAllocation = 37500000 * 10 ** 18; // 37.5 mil tokens allocated for founders uint256 public constant advisorAllocation = 25000000 * 10 ** 18; // 25 mil tokens allocated for allocated for ICO partners and bonus fund uint256 public constant reservedAllocation = 62500000 * 10 ** 18; // 62.5 mil tokens allocated for reserved, bounty campaigns, ICO partners, and bonus fund uint256 public constant minInvestedCap = 6000 * 10 ** 18; // 2500 ether for softcap uint256 public constant minInvestedAmount = 0.1 * 10 ** 18; // 0.1 ether for mininum ether contribution per transaction uint saleState; uint256 totalInvestedAmount; uint public icoStartTime; uint public icoEndTime; bool public inActive; bool public isSelling; bool public isTransferable; uint public founderAllocatedTime = 1; uint public advisorAllocatedTime = 1; uint256 public totalRemainingTokensForSales; // Total tokens remaining for sales uint256 public totalAdvisor; // Total tokens allocated for advisor uint256 public totalReservedTokenAllocation; // Total tokens allocated for reserved event Approval(address indexed owner, address indexed spender, uint256 value); // ERC20 standard event event Transfer(address indexed from, address indexed to, uint256 value); // ERC20 standard event event StartICO(uint state); // Start ICO sales event EndICO(uint state); // End ICO sales event AllocateTokensForFounder(address founderAddress, uint256 founderAllocatedTime, uint256 tokenAmount); // Allocate tokens to founders' address event AllocateTokensForAdvisor(address advisorAddress, uint256 advisorAllocatedTime, uint256 tokenAmount); // Allocate tokens to advisor address event AllocateReservedTokens(address reservedAddress, uint256 tokenAmount); // Allocate reserved tokens event AllocateSalesTokens(address salesAllocation, uint256 tokenAmount); // Allocate sales tokens modifier isActive() { require(inActive == false); _; } modifier isInSale() { require(isSelling == true); _; } modifier transferable() { require(isTransferable == true); _; } modifier onlyOwnerOrAdminOrPortal() { require(msg.sender == owner || msg.sender == adminAddress); _; } modifier onlyOwnerOrAdmin() { require(msg.sender == owner || msg.sender == adminAddress); _; } function Extradecoin(address _walletAddr, address _adminAddr) public Owner(msg.sender) { require(_walletAddr != address(0)); require(_adminAddr != address(0)); walletAddress = _walletAddr; adminAddress = _adminAddr; inActive = true; totalInvestedAmount = 0; totalRemainingTokensForSales = salesAllocation; totalAdvisor = advisorAllocation; totalReservedTokenAllocation = reservedAllocation; } // ERC20 standard function function transfer(address _to, uint256 _value) external transferable returns (bool) { require(_to != address(0)); require(_value > 0); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } // ERC20 standard function function transferFrom(address _from, address _to, uint256 _value) external transferable returns (bool) { require(_to != address(0)); require(_from != address(0)); require(_value > 0); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } // ERC20 standard function function approve(address _spender, uint256 _value) external transferable returns (bool) { require(_spender != address(0)); require(_value > 0); allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } // Start ICO function startICO() external isActive onlyOwnerOrAdmin returns (bool) { saleState = IN_ICO; icoStartTime = now; isSelling = true; emit StartICO(saleState); return true; } // End ICO function endICO() external isActive onlyOwnerOrAdmin returns (bool) { require(icoEndTime == 0); saleState = END_SALE; isSelling = false; icoEndTime = now; emit EndICO(saleState); return true; } // Activate token sale function function activate() external onlyOwner { inActive = false; } // Deacivate token sale function function deActivate() external onlyOwner { inActive = true; } // Enable transfer feature of tokens function enableTokenTransfer() external isActive onlyOwner { isTransferable = true; } // Modify wallet function changeWallet(address _newAddress) external onlyOwner { require(_newAddress != address(0)); require(walletAddress != _newAddress); walletAddress = _newAddress; } // Modify admin function changeAdminAddress(address _newAddress) external onlyOwner { require(_newAddress != address(0)); require(adminAddress != _newAddress); adminAddress = _newAddress; } // Modify founder address to receive founder tokens allocation function changeFounderAddress(address _newAddress) external onlyOwnerOrAdmin { require(_newAddress != address(0)); require(founderAddress != _newAddress); founderAddress = _newAddress; } // Modify team address to receive team tokens allocation function changeTeamAddress(address _newAddress) external onlyOwnerOrAdmin { require(_newAddress != address(0)); require(advisorAddress != _newAddress); advisorAddress = _newAddress; } // Allocate tokens for founder vested gradually for 4 year function allocateTokensForFounder() external isActive onlyOwnerOrAdmin { require(saleState == END_SALE); require(founderAddress != address(0)); uint256 amount; if (founderAllocatedTime == 1) { require(now >= icoEndTime + lockPeriod1); amount = founderAllocation * 50/100; balances[founderAddress] = balances[founderAddress].add(amount); emit AllocateTokensForFounder(founderAddress, founderAllocatedTime, amount); founderAllocatedTime = 2; return; } if (founderAllocatedTime == 2) { require(now >= icoEndTime + lockPeriod2); amount = founderAllocation * 50/100; balances[founderAddress] = balances[founderAddress].add(amount); emit AllocateTokensForFounder(founderAddress, founderAllocatedTime, amount); founderAllocatedTime = 3; return; } revert(); } // Allocate tokens for advisor and angel investors vested gradually for 1 year function allocateTokensForAdvisor() external isActive onlyOwnerOrAdmin { require(saleState == END_SALE); require(advisorAddress != address(0)); uint256 amount; if (founderAllocatedTime == 1) { amount = advisorAllocation * 50/100; balances[advisorAddress] = balances[advisorAddress].add(amount); emit AllocateTokensForFounder(advisorAddress, founderAllocatedTime, amount); founderAllocatedTime = 2; return; } if (advisorAllocatedTime == 2) { require(now >= icoEndTime + lockPeriod2); amount = advisorAllocation * 125/1000; balances[advisorAddress] = balances[advisorAddress].add(amount); emit AllocateTokensForAdvisor(advisorAddress, advisorAllocatedTime, amount); advisorAllocatedTime = 3; return; } if (advisorAllocatedTime == 3) { require(now >= icoEndTime + lockPeriod3); amount = advisorAllocation * 125/1000; balances[advisorAddress] = balances[advisorAddress].add(amount); emit AllocateTokensForAdvisor(advisorAddress, advisorAllocatedTime, amount); advisorAllocatedTime = 4; return; } if (advisorAllocatedTime == 4) { require(now >= icoEndTime + lockPeriod3); amount = advisorAllocation * 125/1000; balances[advisorAddress] = balances[advisorAddress].add(amount); emit AllocateTokensForAdvisor(advisorAddress, advisorAllocatedTime, amount); advisorAllocatedTime = 5; return; } if (advisorAllocatedTime == 5) { require(now >= icoEndTime + lockPeriod3); amount = advisorAllocation * 125/1000; balances[advisorAddress] = balances[advisorAddress].add(amount); emit AllocateTokensForAdvisor(advisorAddress, advisorAllocatedTime, amount); advisorAllocatedTime = 6; return; } revert(); } // Allocate reserved tokens function allocateReservedTokens(address _addr, uint _amount) external isActive onlyOwnerOrAdmin { require(saleState == END_SALE); require(_amount > 0); require(_addr != address(0)); balances[_addr] = balances[_addr].add(_amount); totalReservedTokenAllocation = totalReservedTokenAllocation.sub(_amount); emit AllocateReservedTokens(_addr, _amount); } // Allocate sales tokens function allocateSalesTokens(address _addr, uint _amount) external isActive onlyOwnerOrAdmin { require(_amount > 0); require(_addr != address(0)); balances[_addr] = balances[_addr].add(_amount); totalRemainingTokensForSales = totalRemainingTokensForSales.sub(_amount); emit AllocateSalesTokens(_addr, _amount); } // ERC20 standard function function allowance(address _owner, address _spender) external constant returns (uint256) { return allowed[_owner][_spender]; } // ERC20 standard function function balanceOf(address _owner) external constant returns (uint256 balance) { return balances[_owner]; } // Get softcap reaching status function isSoftCapReached() public view returns (bool) { return totalInvestedAmount >= minInvestedCap; } }
Allocate reserved tokens
function allocateReservedTokens(address _addr, uint _amount) external isActive onlyOwnerOrAdmin { require(saleState == END_SALE); require(_amount > 0); require(_addr != address(0)); balances[_addr] = balances[_addr].add(_amount); totalReservedTokenAllocation = totalReservedTokenAllocation.sub(_amount); emit AllocateReservedTokens(_addr, _amount); }
1,843,801
./full_match/5/0x50Aa93D41581e57E0ce215B73207aC3108dfC953/sources/project_/contracts/ExchangeDepositV2.sol
Get an instance of ExchangeDepositV2 for the main contract return ExchangeDepositV2 instance (main contract of the system)/ If this context is ExchangeDepositV2, use `this`, else use exDepositorAddr
function getExchangeDepositor() internal view returns (ExchangeDepositV2) { return isExchangeDepositor() ? this : ExchangeDepositV2(thisAddress); }
7,043,512
/** *Submitted for verification at Etherscan.io on 2022-04-04 */ // SPDX-License-Identifier: MIT AND AGPL-3.0-or-later pragma solidity =0.8.9; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require( address(this).balance >= amount, "Address: insufficient balance" ); (bool success, ) = recipient.call{value: amount}(""); require( success, "Address: unable to send value, recipient may have reverted" ); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue( target, data, value, "Address: low-level call with value failed" ); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require( address(this).balance >= value, "Address: insufficient balance for call" ); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}( data ); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall( target, data, "Address: low-level static call failed" ); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File @openzeppelin/contracts-upgradeable/proxy/utils/[email protected] /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. * * [CAUTION] * ==== * Avoid leaving a contract uninitialized. * * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation * contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the * initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed: * * [.hljs-theme-light.nopadding] * ``` * /// @custom:oz-upgrades-unsafe-allow constructor * constructor() initializer {} * ``` * ==== */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { // If the contract is initializing we ignore whether _initialized is set in order to support multiple // inheritance patterns, but we only do this in the context of a constructor, because in other contexts the // contract may have been reentered. require( _initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized" ); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /** * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the * {initializer} modifier, directly or indirectly. */ modifier onlyInitializing() { require(_initializing, "Initializable: contract is not initializing"); _; } function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // File @openzeppelin/contracts-upgradeable/utils/[email protected] /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal onlyInitializing { __Context_init_unchained(); } function __Context_init_unchained() internal onlyInitializing {} function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } uint256[50] private __gap; } // File @openzeppelin/contracts-upgradeable/access/[email protected] /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal onlyInitializing { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal onlyInitializing { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require( newOwner != address(0), "Ownable: new owner is the zero address" ); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } uint256[49] private __gap; } // File contracts/ProtocolConstants.sol abstract contract ProtocolConstants { /* ========== GENERAL ========== */ // The zero address, utility address internal constant _ZERO_ADDRESS = address(0); // One year, utility uint256 internal constant _ONE_YEAR = 365 days; // Basis Points uint256 internal constant _MAX_BASIS_POINTS = 100_00; /* ========== VADER TOKEN ========== */ // Max VADER supply uint256 internal constant _INITIAL_VADER_SUPPLY = 25_000_000_000 * 1 ether; // Allocation for VETH holders uint256 internal constant _VETH_ALLOCATION = 7_500_000_000 * 1 ether; // Team allocation vested over {VESTING_DURATION} years uint256 internal constant _TEAM_ALLOCATION = 2_500_000_000 * 1 ether; // Ecosystem growth fund unlocked for partnerships & USDV provision uint256 internal constant _ECOSYSTEM_GROWTH = 2_500_000_000 * 1 ether; // Total grant tokens uint256 internal constant _GRANT_ALLOCATION = 12_500_000_000 * 1 ether; // Emission Era uint256 internal constant _EMISSION_ERA = 24 hours; // Initial Emission Curve, 5 uint256 internal constant _INITIAL_EMISSION_CURVE = 5; // Fee Basis Points uint256 internal constant _MAX_FEE_BASIS_POINTS = 1_00; /* ========== USDV TOKEN ========== */ // Max locking duration uint256 internal constant _MAX_LOCK_DURATION = 30 days; /* ========== VESTING ========== */ // Vesting Duration uint256 internal constant _VESTING_DURATION = 2 * _ONE_YEAR; /* ========== CONVERTER ========== */ // Vader -> Vether Conversion Rate (10000:1) uint256 internal constant _VADER_VETHER_CONVERSION_RATE = 10_000; // Burn Address address internal constant _BURN = 0xdeaDDeADDEaDdeaDdEAddEADDEAdDeadDEADDEaD; /* ========== GAS QUEUE ========== */ // Address of Chainlink Fast Gas Price Oracle address internal constant _FAST_GAS_ORACLE = 0x169E633A2D1E6c10dD91238Ba11c4A708dfEF37C; /* ========== VADER RESERVE ========== */ // Minimum delay between grants uint256 internal constant _GRANT_DELAY = 30 days; // Maximum grant size divisor uint256 internal constant _MAX_GRANT_BASIS_POINTS = 10_00; } // File contracts/interfaces/ILiquidityBasedTWAP.sol interface ILiquidityBasedTWAP { function maxUpdateWindow() external view returns (uint256); function getVaderPrice() external returns (uint256); } // File contracts/VaderMinterStorage.sol struct Limits { uint256 fee; uint256 mintLimit; uint256 burnLimit; uint256 lockDuration; } contract VaderMinterStorage { // The LBT pricing mechanism for the conversion ILiquidityBasedTWAP public lbt; // The 24 hour limits on USDV mints that are available for public minting and burning as well as the fee. Limits public dailyLimits; // The current cycle end timestamp uint256 public cycleTimestamp; // The current cycle cumulative mints uint256 public cycleMints; // The current cycle cumulative burns uint256 public cycleBurns; // The limits applied to each partner mapping(address => Limits) public partnerLimits; // Transmuter Contract address public transmuter; } // File contracts/interfaces/IVaderMinterUpgradeable.sol interface IVaderMinterUpgradeable { /* ========== FUNCTIONS ========== */ function mint(uint256 vAmount, uint256 uAmountMinOut) external returns (uint256 uAmount); function burn(uint256 uAmount, uint256 vAmountMinOut) external returns (uint256 vAmount); function partnerMint(uint256 vAmount, uint256 uAmountMinOut) external returns (uint256 uAmount); function partnerBurn(uint256 uAmount, uint256 vAmountMinOut) external returns (uint256 vAmount); /* ========== EVENTS ========== */ event DailyLimitsChanged(Limits previousLimits, Limits nextLimits); event WhitelistPartner( address partner, uint256 mintLimit, uint256 burnLimit, uint256 fee ); event RemovePartner(address partner); event SetPartnerFee(address indexed partner, uint256 fee); event IncreasePartnerMintLimit(address indexed partner, uint256 mintLimit); event DecreasePartnerMintLimit(address indexed partner, uint256 mintLimit); event IncreasePartnerBurnLimit(address indexed partner, uint256 burnLimit); event DecreasePartnerBurnLimit(address indexed partner, uint256 burnLimit); event SetPartnerLockDuration(address indexed partner, uint256 lockDuration); } // File @openzeppelin/contracts/token/ERC20/[email protected] /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval( address indexed owner, address indexed spender, uint256 value ); } // File contracts/interfaces/IUSDV.sol interface IUSDV is IERC20 { /* ========== ENUMS ========== */ enum LockTypes { USDV, VADER } /* ========== STRUCTS ========== */ struct Lock { LockTypes token; uint256 amount; uint256 release; } /* ========== FUNCTIONS ========== */ function mint( address account, uint256 vAmount, uint256 uAmount, uint256 exchangeFee, uint256 window ) external returns (uint256); function burn( address account, uint256 uAmount, uint256 vAmount, uint256 exchangeFee, uint256 window ) external returns (uint256); /* ========== EVENTS ========== */ event ExchangeFeeChanged(uint256 previousExchangeFee, uint256 exchangeFee); event DailyLimitChanged(uint256 previousDailyLimit, uint256 dailyLimit); event LockClaimed( address user, LockTypes lockType, uint256 lockAmount, uint256 lockRelease ); event LockCreated( address user, LockTypes lockType, uint256 lockAmount, uint256 lockRelease ); event ValidatorSet(address previous, address current); event GuardianSet(address previous, address current); event LockStatusSet(bool status); event MinterSet(address minter); } // File contracts/VaderMinterUpgradeableV3.sol contract VaderMinterUpgradeableV3 is VaderMinterStorage, IVaderMinterUpgradeable, ProtocolConstants, OwnableUpgradeable { // USDV Contract for Mint / Burn Operations /// @custom:oz-upgrades-unsafe-allow state-variable-immutable IUSDV public immutable usdv; /* ========== CONSTRUCTOR ========== */ /// @custom:oz-upgrades-unsafe-allow constructor constructor(address _usdv) { require(_usdv != address(0), "usdv = zero address"); usdv = IUSDV(_usdv); } function initialize() external initializer { __Ownable_init(); cycleTimestamp = block.timestamp; } /* ========== VIEWS ========== */ function getPublicFee() public view returns (uint256) { // 24 hours passed, reset fee to 100% if (block.timestamp >= cycleTimestamp) { return dailyLimits.fee; } // cycle timestamp > block.timestamp, fee < 100% return (dailyLimits.fee * (cycleTimestamp - block.timestamp)) / 24 hours; } /* ========== MUTATIVE FUNCTIONS ========== */ /** * @dev Public mint function that receives Vader and mints USDV. * @param vAmount Vader amount to burn. * @param uAmountMinOut USDV minimum amount to get back from the mint. * @return uAmount in USDV, represents the USDV amount received from the mint. */ function mint(uint256 vAmount, uint256 uAmountMinOut) external returns (uint256 uAmount) { uint256 vPrice = lbt.getVaderPrice(); uAmount = (vPrice * vAmount) / 1e18; if (cycleTimestamp <= block.timestamp) { cycleTimestamp = block.timestamp + 24 hours; cycleMints = uAmount; cycleBurns = 0; } else { cycleMints += uAmount; } require( cycleMints <= dailyLimits.mintLimit, "VMU::mint: 24 Hour Limit Reached" ); // Actual amount of USDV minted including fees uAmount = usdv.mint( msg.sender, vAmount, uAmount, getPublicFee(), dailyLimits.lockDuration ); require( uAmount >= uAmountMinOut, "VMU::mint: Insufficient Trade Output" ); return uAmount; } /** * @dev Public burn function that receives USDV and mints Vader. * @param uAmount USDV amount to burn. * @param vAmountMinOut Vader minimum amount to get back from the burn. * @return vAmount in Vader, represents the Vader amount received from the burn. * */ function burn(uint256 uAmount, uint256 vAmountMinOut) external returns (uint256 vAmount) { uint256 vPrice = lbt.getVaderPrice(); vAmount = (1e18 * uAmount) / vPrice; if (cycleTimestamp <= block.timestamp) { cycleTimestamp = block.timestamp + 24 hours; cycleBurns = uAmount; cycleMints = 0; } else { cycleBurns += uAmount; } require( cycleBurns <= dailyLimits.burnLimit, "VMU::burn: 24 Hour Limit Reached" ); // Actual amount of Vader minted including fees vAmount = usdv.burn( msg.sender, uAmount, vAmount, getPublicFee(), dailyLimits.lockDuration ); require( vAmount >= vAmountMinOut, "VMU::burn: Insufficient Trade Output" ); return vAmount; } /** * @notice Public destroy function that burns USDV without minting Vader. Use with caution! * @param uAmount USDV amount to burn permanently. */ function unsafeDestroyUsdv(uint256 uAmount) external { require(uAmount > 0, "VMU::unsafeDestroyUsdv: Zero Input"); uint256 vPrice = lbt.getVaderPrice(); // since 1 Vader will be minted, uAmount has to exceed that in value require( 1e18 * uAmount >= vPrice, "VMU::unsafeDestroyUsdv: Minimum Amount" ); usdv.burn(msg.sender, uAmount, 1, _MAX_BASIS_POINTS, 0); } /** * @notice Public destroy function that burns Vader without minting USDV. Use with caution! * @param vAmount Vader amount to destroy permanently. */ function unsafeDestroyVader(uint256 vAmount) external { require(vAmount > 0, "VMU::unsafeDestroyVader: Zero Input"); uint256 vPrice = lbt.getVaderPrice(); // since 1 USDV will be minted, vAmount has to exceed that in value require( vPrice * vAmount >= 1e18, "VMU::unsafeDestroyVader: Minimum Amount" ); usdv.mint(msg.sender, vAmount, 1, _MAX_BASIS_POINTS, 0); } /* ========== RESTRICTED FUNCTIONS ========== */ /** * @dev Partner mint function that receives Vader and mints USDV. * @param vAmount Vader amount to burn. * @param uAmountMinOut USDV minimum amount to get back from the mint. * @return uAmount in USDV, represents the USDV amount received from the mint. * * Requirements: * - Can only be called by whitelisted partners. */ function partnerMint(uint256 vAmount, uint256 uAmountMinOut) external returns (uint256 uAmount) { require( partnerLimits[msg.sender].mintLimit != 0, "VMU::partnerMint: Not Whitelisted" ); uint256 vPrice = lbt.getVaderPrice(); uAmount = (vPrice * vAmount) / 1e18; Limits storage _partnerLimits = partnerLimits[msg.sender]; require( uAmount <= _partnerLimits.mintLimit, "VMU::partnerMint: Mint Limit Reached" ); unchecked { _partnerLimits.mintLimit -= uAmount; } uAmount = usdv.mint( msg.sender, vAmount, uAmount, _partnerLimits.fee, _partnerLimits.lockDuration ); require( uAmount >= uAmountMinOut, "VMU::partnerMint: Insufficient Trade Output" ); return uAmount; } /** * @dev Partner burn function that receives USDV and mints Vader. * @param uAmount USDV amount to burn. * @param vAmountMinOut Vader minimum amount to get back from the burn. * @return vAmount in Vader, represents the Vader amount received from the mint. * * Requirements: * - Can only be called by whitelisted partners. */ function partnerBurn(uint256 uAmount, uint256 vAmountMinOut) external returns (uint256 vAmount) { require( partnerLimits[msg.sender].burnLimit != 0, "VMU::partnerBurn: Not Whitelisted" ); uint256 vPrice = lbt.getVaderPrice(); vAmount = (1e18 * uAmount) / vPrice; Limits storage _partnerLimits = partnerLimits[msg.sender]; require( uAmount <= _partnerLimits.burnLimit, "VMU::partnerBurn: Burn Limit Reached" ); unchecked { _partnerLimits.burnLimit -= uAmount; } vAmount = usdv.burn( msg.sender, uAmount, vAmount, _partnerLimits.fee, _partnerLimits.lockDuration ); require( vAmount >= vAmountMinOut, "VMU::partnerBurn: Insufficient Trade Output" ); return vAmount; } /** * @dev Sets the daily limits for public mints represented by the param {_dailyMintLimit}. * * Requirements: * - Only existing owner can call this function. * - Param {_fee} fee can not be bigger than _MAX_BASIS_POINTS. * - Param {_mintLimit} mint limit can be 0. * - Param {_burnLimit} burn limit can be 0. * - Param {_lockDuration} lock duration can be 0. */ function setDailyLimits( uint256 _fee, uint256 _mintLimit, uint256 _burnLimit, uint256 _lockDuration ) external onlyOwner { require(_fee <= _MAX_BASIS_POINTS, "VMU::setDailyLimits: Invalid Fee"); require( _lockDuration <= _MAX_LOCK_DURATION, "VMU::setDailyLimits: Invalid lock duration" ); Limits memory _dailyLimits = Limits({ fee: _fee, mintLimit: _mintLimit, burnLimit: _burnLimit, lockDuration: _lockDuration }); emit DailyLimitsChanged(dailyLimits, _dailyLimits); dailyLimits = _dailyLimits; } /** * @dev Sets the a partner address {_partner } to a given limit {_limits} that represents the ability * to mint USDV from the reserve partners minting allocation. * * Requirements: * - Only existing owner can call this function. * - Param {_partner} cannot be a zero address. * - Param {_fee} fee can not be bigger than _MAX_BASIS_POINTS. * - Param {_mintLimit} mint limits can be 0. * - Param {_burnLimit} burn limits can be 0. * - Param {_lockDuration} lock duration can be 0. */ function whitelistPartner( address _partner, uint256 _fee, uint256 _mintLimit, uint256 _burnLimit, uint256 _lockDuration ) external onlyOwner { require(_partner != address(0), "VMU::whitelistPartner: Zero Address"); require( _fee <= _MAX_BASIS_POINTS, "VMU::whitelistPartner: Invalid Fee" ); require( _lockDuration <= _MAX_LOCK_DURATION, "VMU::whitelistPartner: Invalid lock duration" ); emit WhitelistPartner(_partner, _mintLimit, _burnLimit, _fee); partnerLimits[_partner] = Limits({ fee: _fee, mintLimit: _mintLimit, burnLimit: _burnLimit, lockDuration: _lockDuration }); } /** * @dev Remove partner * @param _partner Address of partner. * * Requirements: * - Only existing owner can call this function. */ function removePartner(address _partner) external onlyOwner { delete partnerLimits[_partner]; emit RemovePartner(_partner); } /** * @dev Set partner fee * @param _partner Address of partner. * @param _fee New fee. * * Requirements: * - Only existing owner can call this function. * - Param {_fee} fee can not be bigger than _MAX_BASIS_POINTS. */ function setPartnerFee(address _partner, uint256 _fee) external onlyOwner { require(_fee <= _MAX_BASIS_POINTS, "VMU::setPartnerFee: Invalid Fee"); partnerLimits[_partner].fee = _fee; emit SetPartnerFee(_partner, _fee); } /** * @dev Increase partner mint limit. * @param _partner Address of partner. * @param _amount Amount to increase the mint limit by. * * Requirements: * - Only existing owner can call this function. */ function increasePartnerMintLimit(address _partner, uint256 _amount) external onlyOwner { Limits storage limits = partnerLimits[_partner]; limits.mintLimit += _amount; emit IncreasePartnerMintLimit(_partner, limits.mintLimit); } /** * @dev Decrease partner mint limit. * @param _partner Address of partner. * @param _amount Amount to decrease the mint limit by. * * Requirements: * - Only existing owner can call this function. */ function decreasePartnerMintLimit(address _partner, uint256 _amount) external onlyOwner { Limits storage limits = partnerLimits[_partner]; limits.mintLimit -= _amount; emit DecreasePartnerMintLimit(_partner, limits.mintLimit); } /** * @dev Increase partner mint limit. * @param _partner Address of partner. * @param _amount Amount to increase the burn limit by. * * Requirements: * - Only existing owner can call this function. */ function increasePartnerBurnLimit(address _partner, uint256 _amount) external onlyOwner { Limits storage limits = partnerLimits[_partner]; limits.burnLimit += _amount; emit IncreasePartnerBurnLimit(_partner, limits.burnLimit); } /** * @dev Decrease partner mint limit. * @param _partner Address of partner. * @param _amount Amount to decrease the burn limit by. * * Requirements: * - Only existing owner can call this function. */ function decreasePartnerBurnLimit(address _partner, uint256 _amount) external onlyOwner { Limits storage limits = partnerLimits[_partner]; limits.burnLimit -= _amount; emit DecreasePartnerBurnLimit(_partner, limits.burnLimit); } /** * @dev Set partner lock duration. * @param _partner Address of partner. * @param _lockDuration New lock duration * * Requirements: * - Only existing owner can call this function. * - Param {_lockDuration} cannot be bigger than _MAX_LOCK_DURATION */ function setPartnerLockDuration(address _partner, uint256 _lockDuration) external onlyOwner { require( _lockDuration <= _MAX_LOCK_DURATION, "VMU::setPartnerLockDuration: Invalid lock duration" ); partnerLimits[_partner].lockDuration = _lockDuration; emit SetPartnerLockDuration(_partner, _lockDuration); } /** * @dev Sets the transmuter contract address represented by the param {_transmuter}. * * Requirements: * - Only existing owner can call this function. * - Param {_transmuter} can not be address ZERO. */ function setTransmuterAddress(address _transmuter) external onlyOwner { require( _transmuter != address(0), "VMU::setTransmuterAddress: Zero Address" ); transmuter = _transmuter; } /** * @dev Sets the lbt contract address represented by the param {_lbt}. * * Requirements: * - Only existing owner can call this function. * - Param {_lbt} can not be address ZERO. */ function setLBT(ILiquidityBasedTWAP _lbt) external onlyOwner { require( _lbt != ILiquidityBasedTWAP(address(0)), "VMU::setLBT: Zero Address" ); lbt = _lbt; } }
Public destroy function that burns USDV without minting Vader. Use with caution! uAmount USDV amount to burn permanently./ since 1 Vader will be minted, uAmount has to exceed that in value
function unsafeDestroyUsdv(uint256 uAmount) external { require(uAmount > 0, "VMU::unsafeDestroyUsdv: Zero Input"); uint256 vPrice = lbt.getVaderPrice(); require( 1e18 * uAmount >= vPrice, "VMU::unsafeDestroyUsdv: Minimum Amount" ); usdv.burn(msg.sender, uAmount, 1, _MAX_BASIS_POINTS, 0); }
15,070,014
// SPDX-License-Identifier: LGPL-3.0-or-later pragma solidity 0.7.6; import "@openzeppelin/contracts/access/Ownable.sol"; import "./interfaces/ITokenRegistry.sol"; /** * @title Contract for managing maximum allowed funds to be escrowed. * The purpose is to limit the total funds locked in escrow in the initial stages of the protocol. */ contract TokenRegistry is Ownable, ITokenRegistry { uint256 private ethLimit; mapping(address => uint256) private tokenLimits; mapping(address => address) private tokenWrappers; event LogETHLimitChanged(uint256 _newLimit, address indexed _triggeredBy); event LogTokenLimitChanged(uint256 _newLimit, address indexed _triggeredBy); event LogTokenWrapperChanged(address indexed _newWrapperAddress, address indexed _triggeredBy); modifier notZeroAddress(address _tokenAddress) { require(_tokenAddress != address(0), "INVALID_TOKEN_ADDRESS"); _; } constructor() { ethLimit = 1 ether; } /** * @notice Set new limit for ETH. It's used while seller tries to create a voucher. The limit is determined by a voucher set. Voucher price * quantity, seller deposit * quantity, buyer deposit * qty must be below the limit. * @param _newLimit New limit which will be set. */ function setETHLimit(uint256 _newLimit) external override onlyOwner { ethLimit = _newLimit; emit LogETHLimitChanged(_newLimit, owner()); } /** * @notice Set new limit for a token. It's used while seller tries to create a voucher. The limit is determined by a voucher set. Voucher price * quantity, seller deposit * quantity, buyer deposit * qty must be below the limit. * @param _tokenAddress Address of the token which will be updated. * @param _newLimit New limit which will be set. It must comply to the decimals of the token, so the limit is set in the correct decimals. */ function setTokenLimit(address _tokenAddress, uint256 _newLimit) external override onlyOwner notZeroAddress(_tokenAddress) { tokenLimits[_tokenAddress] = _newLimit; emit LogTokenLimitChanged(_newLimit, owner()); } // // // // // // // // // GETTERS // // // // // // // // /** * @notice Get the maximum allowed ETH limit to set as price of voucher, buyer deposit or seller deposit. */ function getETHLimit() external view override returns (uint256) { return ethLimit; } /** * @notice Get the maximum allowed token limit for the specified Token. * @param _tokenAddress Address of the token which will be update. */ function getTokenLimit(address _tokenAddress) external view override returns (uint256) { return tokenLimits[_tokenAddress]; } /** * @notice Set the address of the wrapper contract for the token. The wrapper is used to, for instance, allow the Boson Protocol functions that use permit functionality to work in a uniform way. * @param _tokenAddress Address of the token for which the wrapper is being set * @param _wrapperAddress Address of the token wrapper contract */ function setTokenWrapperAddress(address _tokenAddress, address _wrapperAddress) external override onlyOwner notZeroAddress(_tokenAddress) { tokenWrappers[_tokenAddress] = _wrapperAddress; emit LogTokenWrapperChanged(_wrapperAddress, owner()); } /** * @notice Get the address of the token wrapper contract for the specified token * @param _tokenAddress Address of the token which will be updated. * @return Address of the token wrapper contract */ function getTokenWrapperAddress(address _tokenAddress) external view override returns (address) { return tokenWrappers[_tokenAddress]; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: LGPL-3.0-or-later pragma solidity 0.7.6; interface ITokenRegistry { /** * @notice Set new limit for a token. It's used while seller tries to create a voucher. The limit is determined by a voucher set. Voucher price * quantity, seller deposit * quantity, buyer deposit * qty must be below the limit. * @param _tokenAddress Address of the token which will be updated. * @param _newLimit New limit which will be set. It must comply to the decimals of the token, so the limit is set in the correct decimals. */ function setTokenLimit(address _tokenAddress, uint256 _newLimit) external; /** * @notice Get the maximum allowed token limit for the specified Token. * @param _tokenAddress Address of the token which will be update. * @return The max limit for this token */ function getTokenLimit(address _tokenAddress) external view returns (uint256); /** * @notice Set new limit for ETH. It's used while seller tries to create a voucher. The limit is determined by a voucher set. Voucher price * quantity, seller deposit * quantity, buyer deposit * qty must be below the limit. * @param _newLimit New limit which will be set. */ function setETHLimit(uint256 _newLimit) external; /** * @notice Get the maximum allowed ETH limit to set as price of voucher, buyer deposit or seller deposit. * @return The max ETH limit */ function getETHLimit() external view returns (uint256); /** * @notice Set the address of the wrapper contract for the token. The wrapper is used to, for instance, allow the Boson Protocol functions that use permit functionality to work in a uniform way. * @param _tokenAddress Address of the token which will be updated. * @param _wrapperAddress Address of the wrapper contract */ function setTokenWrapperAddress( address _tokenAddress, address _wrapperAddress ) external; /** * @notice Get the address of the token wrapper contract for the specified token * @param _tokenAddress Address of the token which will be updated. * @return Address of the token wrapper contract */ function getTokenWrapperAddress(address _tokenAddress) external view returns (address); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } }
Get the maximum allowed token limit for the specified Token. _tokenAddress Address of the token which will be update./
function getTokenLimit(address _tokenAddress) external view override returns (uint256) { return tokenLimits[_tokenAddress]; }
7,172
pragma solidity 0.8.10; // Copyright BigchainDB GmbH and Ocean Protocol contributors // SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0) // Code is Apache-2.0 and docs are CC-BY-4.0 import "../utils/ERC721/ERC721.sol"; import "../utils/ERC725/ERC725Ocean.sol"; import "OpenZeppelin/[email protected]/contracts/utils/Create2.sol"; import "OpenZeppelin/[email protected]/contracts/security/ReentrancyGuard.sol"; import "../interfaces/IV3ERC20.sol"; import "../interfaces/IFactory.sol"; import "../interfaces/IERC20Template.sol"; import "../utils/ERC721RolesAddress.sol"; contract ERC721Template is ERC721("Template", "TemplateSymbol"), ERC721RolesAddress, ERC725Ocean, ReentrancyGuard { string private _name; string private _symbol; //uint256 private tokenId = 1; bool private initialized; bool public hasMetaData; string public metaDataDecryptorUrl; string public metaDataDecryptorAddress; uint8 public metaDataState; address private _tokenFactory; address[] private deployedERC20List; address public ssContract; uint8 private constant templateId = 1; mapping(address => bool) private deployedERC20; //stored here only for ABI reasons event TokenCreated( address indexed newTokenAddress, address indexed templateAddress, string name, string symbol, uint256 cap, address creator ); event MetadataCreated( address indexed createdBy, uint8 state, string decryptorUrl, bytes flags, bytes data, bytes32 metaDataHash, uint256 timestamp, uint256 blockNumber ); event MetadataUpdated( address indexed updatedBy, uint8 state, string decryptorUrl, bytes flags, bytes data, bytes32 metaDataHash, uint256 timestamp, uint256 blockNumber ); event MetadataValidated( address indexed validator, bytes32 metaDataHash, uint8 v, bytes32 r, bytes32 s ); event MetadataState( address indexed updatedBy, uint8 state, uint256 timestamp, uint256 blockNumber ); event TokenURIUpdate( address indexed updatedBy, string tokenURI, uint256 tokenID, uint256 timestamp, uint256 blockNumber ); modifier onlyNFTOwner() { require(msg.sender == ownerOf(1), "ERC721Template: not NFTOwner"); _; } /** * @dev initialize * Calls private _initialize function. Only if contract is not initialized. This function mints an NFT (tokenId=1) to the owner and add owner as Manager Role * @param owner NFT Owner * @param name_ NFT name * @param symbol_ NFT Symbol * @param tokenFactory NFT factory address @return boolean */ function initialize( address owner, string calldata name_, string calldata symbol_, address tokenFactory, address additionalERC20Deployer, address additionalMetaDataUpdater, string memory tokenURI ) external returns (bool) { require( !initialized, "ERC721Template: token instance already initialized" ); if(additionalERC20Deployer != address(0)) _addToCreateERC20List(additionalERC20Deployer); if(additionalMetaDataUpdater != address(0)) _addToMetadataList(additionalMetaDataUpdater); bool initResult = _initialize( owner, name_, symbol_, tokenFactory, tokenURI ); return(initResult); } /** * @dev _initialize * Calls private _initialize function. Only if contract is not initialized. * This function mints an NFT (tokenId=1) to the owner * and add owner as Manager Role (Roles admin) * @param owner NFT Owner * @param name_ NFT name * @param symbol_ NFT Symbol * @param tokenFactory NFT factory address * @param tokenURI tokenURI for token 1 @return boolean */ function _initialize( address owner, string memory name_, string memory symbol_, address tokenFactory, string memory tokenURI ) internal returns (bool) { require( owner != address(0), "ERC721Template:: Invalid minter, zero address" ); _name = name_; _symbol = symbol_; _tokenFactory = tokenFactory; defaultBaseURI = ""; initialized = true; hasMetaData = false; _safeMint(owner, 1); _addManager(owner); // we add the nft owner to all other roles (so that doesn't need to make multiple transactions) Roles storage user = permissions[owner]; user.updateMetadata = true; user.deployERC20 = true; user.store = true; // no need to push to auth since it has been already added in _addManager() _setTokenURI(1, tokenURI); return initialized; } /** * @dev setTokenURI * sets tokenURI for a tokenId * @param tokenId token ID * @param tokenURI token URI */ function setTokenURI(uint256 tokenId, string memory tokenURI) public { require(msg.sender == ownerOf(tokenId), "ERC721Template: not NFTOwner"); _setTokenURI(tokenId, tokenURI); emit TokenURIUpdate(msg.sender, tokenURI, tokenId, /* solium-disable-next-line */ block.timestamp, block.number); } /** * @dev setMetaDataState * Updates metadata state * @param _metaDataState metadata state */ function setMetaDataState(uint8 _metaDataState) public { require( permissions[msg.sender].updateMetadata, "ERC721Template: NOT METADATA_ROLE" ); metaDataState = _metaDataState; emit MetadataState(msg.sender, _metaDataState, /* solium-disable-next-line */ block.timestamp, block.number); } struct metaDataProof { address validatorAddress; uint8 v; // v of validator signed message bytes32 r; // r of validator signed message bytes32 s; // s of validator signed message } /** * @dev setMetaData * Creates or update Metadata for Aqua(emit event) Also, updates the METADATA_DECRYPTOR key * @param _metaDataState metadata state * @param _metaDataDecryptorUrl decryptor URL * @param _metaDataDecryptorAddress decryptor public key * @param flags flags used by Aquarius * @param data data used by Aquarius * @param _metaDataHash hash of clear data (before the encryption, if any) * @param _metadataProofs optional signatures of entitys who validated data (before the encryption, if any) */ function setMetaData(uint8 _metaDataState, string calldata _metaDataDecryptorUrl , string calldata _metaDataDecryptorAddress, bytes calldata flags, bytes calldata data,bytes32 _metaDataHash, metaDataProof[] memory _metadataProofs) external { require( permissions[msg.sender].updateMetadata, "ERC721Template: NOT METADATA_ROLE" ); _setMetaData(_metaDataState, _metaDataDecryptorUrl, _metaDataDecryptorAddress,flags, data,_metaDataHash, _metadataProofs); } function _setMetaData(uint8 _metaDataState, string calldata _metaDataDecryptorUrl , string calldata _metaDataDecryptorAddress, bytes calldata flags, bytes calldata data,bytes32 _metaDataHash, metaDataProof[] memory _metadataProofs) internal { metaDataState = _metaDataState; metaDataDecryptorUrl = _metaDataDecryptorUrl; metaDataDecryptorAddress = _metaDataDecryptorAddress; if(!hasMetaData){ emit MetadataCreated(msg.sender, _metaDataState, _metaDataDecryptorUrl, flags, data, _metaDataHash, /* solium-disable-next-line */ block.timestamp, block.number); hasMetaData = true; } else emit MetadataUpdated(msg.sender, metaDataState, _metaDataDecryptorUrl, flags, data, _metaDataHash, /* solium-disable-next-line */ block.timestamp, block.number); //check proofs and emit an event for each proof require(_metadataProofs.length <= 50, 'Too Many Proofs'); bytes memory prefix = "\x19Ethereum Signed Message:\n32"; for (uint256 i = 0; i < _metadataProofs.length; i++) { if(_metadataProofs[i].validatorAddress != address(0)){ bytes32 prefixedHash = keccak256(abi.encodePacked(prefix, _metaDataHash)); address signer = ecrecover(prefixedHash, _metadataProofs[i].v, _metadataProofs[i].r, _metadataProofs[i].s); require(signer == _metadataProofs[i].validatorAddress, "Invalid proof signer"); } emit MetadataValidated(_metadataProofs[i].validatorAddress, _metaDataHash, _metadataProofs[i].v, _metadataProofs[i].r, _metadataProofs[i].s); } } struct metaDataAndTokenURI { uint8 metaDataState; string metaDataDecryptorUrl; string metaDataDecryptorAddress; bytes flags; bytes data; bytes32 metaDataHash; uint256 tokenId; string tokenURI; metaDataProof[] metadataProofs; } /** * @dev setMetaDataAndTokenURI * Helper function to improve UX Calls setMetaData & setTokenURI * @param _metaDataAndTokenURI metaDataAndTokenURI struct */ function setMetaDataAndTokenURI(metaDataAndTokenURI calldata _metaDataAndTokenURI) external { require( permissions[msg.sender].updateMetadata, "ERC721Template: NOT METADATA_ROLE" ); _setMetaData(_metaDataAndTokenURI.metaDataState, _metaDataAndTokenURI.metaDataDecryptorUrl, _metaDataAndTokenURI.metaDataDecryptorAddress, _metaDataAndTokenURI.flags, _metaDataAndTokenURI.data, _metaDataAndTokenURI.metaDataHash, _metaDataAndTokenURI.metadataProofs); setTokenURI(_metaDataAndTokenURI.tokenId, _metaDataAndTokenURI.tokenURI); } /** * @dev getMetaData * Returns metaDataState, metaDataDecryptorUrl, metaDataDecryptorAddress */ function getMetaData() external view returns (string memory, string memory, uint8, bool){ return (metaDataDecryptorUrl, metaDataDecryptorAddress, metaDataState, hasMetaData); } /** * @dev createERC20 * ONLY user with deployERC20 permission (assigned by Manager) can call it Creates a new ERC20 datatoken. It also adds initial minting and fee management permissions to custom users. * @param _templateIndex ERC20Template index * @param strings refers to an array of strings * [0] = name * [1] = symbol * @param addresses refers to an array of addresses * [0] = minter account who can mint datatokens (can have multiple minters) * [1] = feeManager initial feeManager for this DT * [2] = publishing Market Address * [3] = publishing Market Fee Token * @param uints refers to an array of uints * [0] = cap_ the total ERC20 cap * [1] = publishing Market Fee Amount * @param bytess refers to an array of bytes * Currently not used, usefull for future templates @return ERC20 token address */ function createERC20( uint256 _templateIndex, string[] calldata strings, address[] calldata addresses, uint256[] calldata uints, bytes[] calldata bytess ) external nonReentrant returns (address ) { require( permissions[msg.sender].deployERC20, "ERC721Template: NOT ERC20DEPLOYER_ROLE" ); address token = IFactory(_tokenFactory).createToken( _templateIndex, strings, addresses, uints, bytess ); deployedERC20[token] = true; deployedERC20List.push(token); return token; } /** * @dev isERC20Deployer * @return true if the account has ERC20 Deploy role */ function isERC20Deployer(address account) external view returns (bool) { return permissions[account].deployERC20; } /** * @dev name * It returns the token name. * @return Datatoken name. */ function name() public view override returns (string memory) { return _name; } /** * @dev symbol * It returns the token symbol. * @return Datatoken symbol. */ function symbol() public view override returns (string memory) { return _symbol; } /** * @dev isInitialized * It checks whether the contract is initialized. * @return true if the contract is initialized. */ function isInitialized() external view returns (bool) { return initialized; } /** * @dev addManager * Only NFT Owner can add a new manager (Roles admin) * There can be multiple minters * @param _managerAddress new manager address */ function addManager(address _managerAddress) external onlyNFTOwner { _addManager(_managerAddress); } /** * @dev removeManager * Only NFT Owner can remove a manager (Roles admin) * There can be multiple minters * @param _managerAddress new manager address */ function removeManager(address _managerAddress) external onlyNFTOwner { _removeManager(_managerAddress); } /** * @notice Executes any other smart contract. Is only callable by the Manager. * * * @param _operation the operation to execute: CALL = 0; DELEGATECALL = 1; CREATE2 = 2; CREATE = 3; * @param _to the smart contract or address to interact with. * `_to` will be unused if a contract is created (operation 2 and 3) * @param _value the value of ETH to transfer * @param _data the call data, or the contract data to deploy **/ function executeCall( uint256 _operation, address _to, uint256 _value, bytes calldata _data ) external payable onlyManager { execute(_operation, _to, _value, _data); } /** * @dev setNewData * ONLY user with store permission (assigned by Manager) can call it This function allows to set any arbitrary key-value into the 725 standard * There can be multiple store updaters * @param _key key (see 725 for standard (keccak256)) Data keys, should be the keccak256 hash of a type name. e.g. keccak256('ERCXXXMyNewKeyType') is 0x6935a24ea384927f250ee0b954ed498cd9203fc5d2bf95c735e52e6ca675e047 * @param _value data to store at that key */ function setNewData(bytes32 _key, bytes calldata _value) external { require( permissions[msg.sender].store, "ERC721Template: NOT STORE UPDATER" ); setData(_key, _value); } /** * @dev setDataERC20 * ONLY callable FROM the ERC20Template and BY the corresponding ERC20Deployer This function allows to store data with a preset key (keccak256(ERC20Address)) into NFT 725 Store * @param _key keccak256(ERC20Address) see setData into ERC20Template.sol * @param _value data to store at that key */ function setDataERC20(bytes32 _key, bytes calldata _value) external { require( deployedERC20[msg.sender], "ERC721Template: NOT ERC20 Contract" ); setData(_key, _value); } /** * @dev cleanPermissions * Only NFT Owner can call it. * This function allows to remove all ROLES at erc721 level: * Managers, ERC20Deployer, MetadataUpdater, StoreUpdater * Permissions at erc20 level stay. * Even NFT Owner has to readd himself as Manager */ function cleanPermissions() external onlyNFTOwner { _cleanPermissions(); } /** * @dev transferFrom * Used for transferring the NFT, can be used by an approved relayer Even if we only have 1 tokenId, we leave it open as arguments for being a standard ERC721 @param from nft owner @param to nft receiver @param tokenId tokenId (1) */ function transferFrom( address from, address to, uint256 tokenId ) external { require(tokenId == 1, "ERC721Template: Cannot transfer this tokenId"); _cleanERC20Permissions(getAddressLength(deployedERC20List)); _cleanPermissions(); _addManager(to); // we add the nft owner to all other roles (so that doesn't need to make multiple transactions) Roles storage user = permissions[to]; user.updateMetadata = true; user.deployERC20 = true; user.store = true; // no need to push to auth since it has been already added in _addManager() _transferFrom(from, to, tokenId); } /** * @dev safeTransferFrom * Used for transferring the NFT, can be used by an approved relayer Even if we only have 1 tokenId, we leave it open as arguments for being a standard ERC721 @param from nft owner @param to nft receiver @param tokenId tokenId (1) */ function safeTransferFrom(address from, address to,uint256 tokenId) external { require(tokenId == 1, "ERC721Template: Cannot transfer this tokenId"); _cleanERC20Permissions(getAddressLength(deployedERC20List)); _cleanPermissions(); _addManager(to); // we add the nft owner to all other roles (so that doesn't need to make multiple transactions) Roles storage user = permissions[to]; user.updateMetadata = true; user.deployERC20 = true; user.store = true; // no need to push to auth since it has been already added in _addManager() safeTransferFrom(from, to, tokenId, ""); } /** * @dev getAddressLength * It returns the array lentgh @param array address array we want to get length * @return length */ function getAddressLength(address[] memory array) private pure returns (uint256) { return array.length; } /** * @dev _cleanERC20Permissions * Internal function used to clean permissions at ERC20 level when transferring the NFT @param length lentgh of the deployedERC20List */ function _cleanERC20Permissions(uint256 length) internal { for (uint256 i = 0; i < length; i++) { IERC20Template(deployedERC20List[i]).cleanFrom721(); } } /** * @dev getId * Return template id in case we need different ABIs. * If you construct your own template, please make sure to change the hardcoded value */ function getId() pure public returns (uint8) { return 1; } /** * @dev fallback function * this is a default fallback function in which receives * the collected ether. */ fallback() external payable {} /** * @dev withdrawETH * transfers all the accumlated ether the ownerOf */ function withdrawETH() external payable { payable(ownerOf(1)).transfer(address(this).balance); } function getTokensList() external view returns (address[] memory) { return deployedERC20List; } function isDeployed(address datatoken) external view returns (bool) { return deployedERC20[datatoken]; } function setBaseURI(string memory _baseURI) external onlyNFTOwner { defaultBaseURI = _baseURI; } }
setNewData ONLY user with store permission (assigned by Manager) can call it There can be multiple store updaters _key key (see 725 for standard (keccak256)) _value data to store at that key/
This function allows to set any arbitrary key-value into the 725 standard Data keys, should be the keccak256 hash of a type name. e.g. keccak256('ERCXXXMyNewKeyType') is 0x6935a24ea384927f250ee0b954ed498cd9203fc5d2bf95c735e52e6ca675e047 function setNewData(bytes32 _key, bytes calldata _value) external { require( permissions[msg.sender].store, "ERC721Template: NOT STORE UPDATER" ); setData(_key, _value); }
13,039,171
/** *Submitted for verification at Etherscan.io on 2022-04-10 */ // SPDX-License-Identifier: MIT /** ____ _ _ _ _ ______ ___ _____ ____ | _ \ / \ | \ | | |/ / __ ) / _ \_ _/ ___| | | | |/ _ \ | \| | ' /| _ \| | | || | \___ \ | |_| / ___ \| |\ | . \| |_) | |_| || | ___) | |____/_/ \_\_| \_|_|\_\____/ \___/ |_| |____/ */ pragma solidity ^0.8.0; /** * @dev These functions deal with verification of Merkle Trees proofs. * * The proofs can be generated using the JavaScript library * https://github.com/miguelmota/merkletreejs[merkletreejs]. * Note: the hashing algorithm should be keccak256 and pair sorting should be enabled. * * See `test/utils/cryptography/MerkleProof.test.js` fo r some examples. * * WARNING: You should avoid using leaf values that are 64 bytes long prior to * hashing, or use a hash function other than keccak256 for hashing leaves. * This is because the concatenation of a sorted pair of internal nodes in * the merkle tree could be reinterpreted as a leaf value. */ library MerkleProof { /** * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree * defined by `root`. For this, a `proof` must be provided, containing * sibling hashes on the branch from the leaf to the root of the tree. Each * pair of leaves and each pair of pre-images are assumed to be sorted. */ function verify( bytes32[] memory proof, bytes32 root, bytes32 leaf ) internal pure returns (bool) { return processProof(proof, leaf) == root; } /** * @dev Returns the rebuilt hash obtained by traversing a Merkle tree up * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt * hash matches the root of the tree. When processing the proof, the pairs * of leafs & pre-images are assumed to be sorted. * * _Available since v4.4._ */ function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash <= proofElement) { // Hash(current computed hash + current element of the proof) computedHash = _efficientHash(computedHash, proofElement); } else { // Hash(current element of the proof + current computed hash) computedHash = _efficientHash(proofElement, computedHash); } } return computedHash; } function _efficientHash(bytes32 a, bytes32 b) private pure returns (bytes32 value) { assembly { mstore(0x00, a) mstore(0x20, b) value := keccak256(0x00, 0x40) } } } // File: @openzeppelin/contracts/utils/introspection/IERC165.sol pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev 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, bytes calldata data) external returns (bytes4); } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: @openzeppelin/contracts/utils/Address.sol /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/utils/Context.sol /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File: @openzeppelin/contracts/utils/Strings.sol /** * @dev String operations. */ library Strings { bytes16 private constant alphabet = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = alphabet[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: @openzeppelin/contracts/utils/introspection/ERC165.sol /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: contracts/DankBots.sol // Creator: Chiru Labs pragma solidity ^0.8.4; error ApprovalCallerNotOwnerNorApproved(); error ApprovalQueryForNonexistentToken(); error ApproveToCaller(); error ApprovalToCurrentOwner(); error BalanceQueryForZeroAddress(); error MintToZeroAddress(); error MintZeroQuantity(); error OwnerQueryForNonexistentToken(); error TransferCallerNotOwnerNorApproved(); error TransferFromIncorrectOwner(); error TransferToNonERC721ReceiverImplementer(); error TransferToZeroAddress(); error URIQueryForNonexistentToken(); /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at _startTokenId() (defaults to 0, e.g. 0, 1, 2, 3..). * * Assumes that an owner cannot have more than 2**64 - 1 (max value of uint64) of supply. * * Assumes that the maximum token id cannot exceed 2**256 - 1 (max value of uint256). */ contract ERC721A is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Compiler will pack this into a single 256bit word. struct TokenOwnership { // The address of the owner. address addr; // Keeps track of the start time of ownership with minimal overhead for tokenomics. uint64 startTimestamp; // Whether the token has been burned. bool burned; } // Compiler will pack this into a single 256bit word. struct AddressData { // Realistically, 2**64-1 is more than enough. uint64 balance; // Keeps track of mint count with minimal overhead for tokenomics. uint64 numberMinted; // Keeps track of burn count with minimal overhead for tokenomics. uint64 numberBurned; // For miscellaneous variable(s) pertaining to the address // (e.g. number of whitelist mint slots used). // If there are multiple variables, please pack them into a uint64. uint64 aux; } // The tokenId of the next token to be minted. uint256 internal _currentIndex; // The number of tokens burned. uint256 internal _burnCounter; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to ownership details // An empty struct value does not necessarily mean the token is unowned. See _ownershipOf implementation for details. mapping(uint256 => TokenOwnership) internal _ownerships; // Mapping owner address to address data mapping(address => AddressData) private _addressData; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; _currentIndex = _startTokenId(); } /** * To change the starting tokenId, please override this function. */ function _startTokenId() internal view virtual returns (uint256) { return 0; } /** * @dev Burned tokens are calculated here, use _totalMinted() if you want to count just minted tokens. */ function totalSupply() public view returns (uint256) { // Counter underflow is impossible as _burnCounter cannot be incremented // more than _currentIndex - _startTokenId() times unchecked { return _currentIndex - _burnCounter - _startTokenId(); } } /** * Returns the total amount of tokens minted in the contract. */ function _totalMinted() internal view returns (uint256) { // Counter underflow is impossible as _currentIndex does not decrement, // and it is initialized to _startTokenId() unchecked { return _currentIndex - _startTokenId(); } } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view override returns (uint256) { if (owner == address(0)) revert BalanceQueryForZeroAddress(); return uint256(_addressData[owner].balance); } /** * Returns the number of tokens minted by `owner`. */ function _numberMinted(address owner) internal view returns (uint256) { return uint256(_addressData[owner].numberMinted); } /** * Returns the number of tokens burned by or on behalf of `owner`. */ function _numberBurned(address owner) internal view returns (uint256) { return uint256(_addressData[owner].numberBurned); } /** * Returns the auxillary data for `owner`. (e.g. number of whitelist mint slots used). */ function _getAux(address owner) internal view returns (uint64) { return _addressData[owner].aux; } /** * Sets the auxillary data for `owner`. (e.g. number of whitelist mint slots used). * If there are multiple variables, please pack them into a uint64. */ function _setAux(address owner, uint64 aux) internal { _addressData[owner].aux = aux; } /** * Gas spent here starts off proportional to the maximum mint batch size. * It gradually moves to O(1) as tokens get transferred around in the collection over time. */ function _ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { uint256 curr = tokenId; unchecked { if (_startTokenId() <= curr && curr < _currentIndex) { TokenOwnership memory ownership = _ownerships[curr]; if (!ownership.burned) { if (ownership.addr != address(0)) { return ownership; } // Invariant: // There will always be an ownership that has an address and is not burned // before an ownership that does not have an address and is not burned. // Hence, curr will not underflow. while (true) { curr--; ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } } } } revert OwnerQueryForNonexistentToken(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return _ownershipOf(tokenId).addr; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { if (!_exists(tokenId)) revert URIQueryForNonexistentToken(); string memory baseURI = _baseURI(); return bytes(baseURI).length != 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ''; } /** * @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 returns (string memory) { return ''; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public override { address owner = ERC721A.ownerOf(tokenId); if (to == owner) revert ApprovalToCurrentOwner(); if (_msgSender() != owner && !isApprovedForAll(owner, _msgSender())) { revert ApprovalCallerNotOwnerNorApproved(); } _approve(to, tokenId, owner); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { if (!_exists(tokenId)) revert ApprovalQueryForNonexistentToken(); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { if (operator == _msgSender()) revert ApproveToCaller(); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ''); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { _transfer(from, to, tokenId); if (to.isContract() && !_checkContractOnERC721Received(from, to, tokenId, _data)) { revert TransferToNonERC721ReceiverImplementer(); } } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), */ function _exists(uint256 tokenId) internal view returns (bool) { return _startTokenId() <= tokenId && tokenId < _currentIndex && !_ownerships[tokenId].burned; } function _safeMint(address to, uint256 quantity) internal { _safeMint(to, quantity, ''); } /** * @dev Safely mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called for each safe transfer. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { _mint(to, quantity, _data, true); } /** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _mint( address to, uint256 quantity, bytes memory _data, bool safe ) internal { uint256 startTokenId = _currentIndex; if (to == address(0)) revert MintToZeroAddress(); if (quantity == 0) revert MintZeroQuantity(); _beforeTokenTransfers(address(0), to, startTokenId, quantity); // Overflows are incredibly unrealistic. // balance or numberMinted overflow if current value of either + quantity > 1.8e19 (2**64) - 1 // updatedIndex overflows if _currentIndex + quantity > 1.2e77 (2**256) - 1 unchecked { _addressData[to].balance += uint64(quantity); _addressData[to].numberMinted += uint64(quantity); _ownerships[startTokenId].addr = to; _ownerships[startTokenId].startTimestamp = uint64(block.timestamp); uint256 updatedIndex = startTokenId; uint256 end = updatedIndex + quantity; if (safe && to.isContract()) { do { emit Transfer(address(0), to, updatedIndex); if (!_checkContractOnERC721Received(address(0), to, updatedIndex++, _data)) { revert TransferToNonERC721ReceiverImplementer(); } } while (updatedIndex != end); // Reentrancy protection if (_currentIndex != startTokenId) revert(); } else { do { emit Transfer(address(0), to, updatedIndex++); } while (updatedIndex != end); } _currentIndex = updatedIndex; } _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @dev Transfers `tokenId` from `from` to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) private { TokenOwnership memory prevOwnership = _ownershipOf(tokenId); if (prevOwnership.addr != from) revert TransferFromIncorrectOwner(); bool isApprovedOrOwner = (_msgSender() == from || isApprovedForAll(from, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); if (to == address(0)) revert TransferToZeroAddress(); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, from); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**256. unchecked { _addressData[from].balance -= 1; _addressData[to].balance += 1; TokenOwnership storage currSlot = _ownerships[tokenId]; currSlot.addr = to; currSlot.startTimestamp = uint64(block.timestamp); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; TokenOwnership storage nextSlot = _ownerships[nextTokenId]; if (nextSlot.addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId != _currentIndex) { nextSlot.addr = from; nextSlot.startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @dev This is equivalent to _burn(tokenId, false) */ function _burn(uint256 tokenId) internal virtual { _burn(tokenId, false); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId, bool approvalCheck) internal virtual { TokenOwnership memory prevOwnership = _ownershipOf(tokenId); address from = prevOwnership.addr; if (approvalCheck) { bool isApprovedOrOwner = (_msgSender() == from || isApprovedForAll(from, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); } _beforeTokenTransfers(from, address(0), tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, from); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**256. unchecked { AddressData storage addressData = _addressData[from]; addressData.balance -= 1; addressData.numberBurned += 1; // Keep track of who burned the token, and the timestamp of burning. TokenOwnership storage currSlot = _ownerships[tokenId]; currSlot.addr = from; currSlot.startTimestamp = uint64(block.timestamp); currSlot.burned = true; // If the ownership slot of tokenId+1 is not explicitly set, that means the burn initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; TokenOwnership storage nextSlot = _ownerships[nextTokenId]; if (nextSlot.addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId != _currentIndex) { nextSlot.addr = from; nextSlot.startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, address(0), tokenId); _afterTokenTransfers(from, address(0), tokenId, 1); // Overflow not possible, as _burnCounter cannot be exceed _currentIndex times. unchecked { _burnCounter++; } } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkContractOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert TransferToNonERC721ReceiverImplementer(); } else { assembly { revert(add(32, reason), mload(reason)) } } } } /** * @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting. * And also called before burning one token. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, `from`'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, `tokenId` will be burned by `from`. * - `from` and `to` are never both zero. */ function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} /** * @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes * minting. * And also called after one token has been burned. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, `from`'s `tokenId` has been * transferred to `to`. * - When `from` is zero, `tokenId` has been minted for `to`. * - When `to` is zero, `tokenId` has been burned by `from`. * - `from` and `to` are never both zero. */ function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} } contract DankBots is ERC721A, Ownable { using Strings for uint256; address public withdrawal_address = 0x405874F1Ce5778d5FFDf66f7aba14DA446564B6a; string baseURI = ""; string public notRevealedUri = ""; string public baseExtension = ".json"; uint256 public cost = 0.08 ether; // mint cost uint256 public maxSupply = 7777; // max supply uint256 public maxMintAmount = 10; // max amount anyone can mint uint256 public maxFreeMintAmount = 1; // max amount free mint can mint bool public paused = true; // paused at release bool public revealed = false; // reveal images at purchase uint256 public whitelistCost = 0.06 ether; // whitelist mint cost bool public whitelistPaused = true; // paused at release bytes32 public whitelistRoot = ""; // merkle root for whitelist mapping( address => bool ) public whitelistClaimed; bool public freePaused = true; // paused at release bytes32 public freeRoot = ""; // merkle root for free whitelist mapping( address => bool ) public freeClaimed; string _name = "DANKBOTS"; string _symbol = "DB"; constructor() ERC721A(_name, _symbol) { } // set mint cost function setCost(uint256 _newCost ) public onlyOwner { cost = _newCost; } // whitelist functions // set whitelist mint cost function setWhitelistCost(uint256 _newCost ) public onlyOwner { whitelistCost = _newCost; } // whitelistPaused functions function pauseWhitelist(bool _state) public onlyOwner { whitelistPaused = _state; } // set whitelistRoot function setWhitelistRoot( bytes32 _newWhitelistRoot ) public onlyOwner { whitelistRoot = _newWhitelistRoot; } // free mint functions // freePaused functions function pauseFree(bool _state) public onlyOwner { freePaused = _state; } // set freeRoot function setFreeRoot( bytes32 _newFreeRoot ) public onlyOwner { freeRoot = _newFreeRoot; } // internal function _baseURI() internal view virtual override returns (string memory) { return baseURI; } // public // minting functions function mint(uint256 _mintAmount) public payable { require(!paused, "Cannot mint while paused" ); require(_mintAmount > 0); require(totalSupply() + _mintAmount <= maxSupply); if (msg.sender != owner()) { require(_mintAmount + _numberMinted( msg.sender ) <= maxMintAmount, "Exceeds max mint amount" ); require(msg.value >= cost * _mintAmount); } _safeMint(msg.sender, _mintAmount); } function isWhitelisted( bytes32[] calldata _merkleProof, bytes32 _address ) public view returns ( bool ) { return MerkleProof.verify( _merkleProof, whitelistRoot, _address ); } function mintWhitelist( bytes32[] calldata _merkleProof, uint256 _mintAmount) public payable { require(!whitelistPaused, "Cannot mint while whitelist is paused" ); require(_mintAmount > 0); require(totalSupply() + _mintAmount <= maxSupply); require( ! whitelistClaimed[ msg.sender ], "Address has already claimed whitelist!" ); if (msg.sender != owner()) { require(_mintAmount + _numberMinted( msg.sender ) <= maxMintAmount, "Exceeds max mint amount" ); bytes32 leaf = keccak256( abi.encodePacked( msg.sender ) ); require( MerkleProof.verify( _merkleProof, whitelistRoot, leaf ), "Invalid proof" ); require(msg.value >= whitelistCost * _mintAmount); } _safeMint(msg.sender, _mintAmount); } function isFreelisted( bytes32[] calldata _merkleProof, bytes32 _address ) public view returns ( bool ) { return MerkleProof.verify( _merkleProof, freeRoot, _address ); } function mintFree( bytes32[] calldata _merkleProof, uint256 _mintAmount) public payable { require(!freePaused, "Cannot mint while free mint list is paused" ); require(_mintAmount > 0); require(totalSupply() + _mintAmount <= maxSupply); require( ! freeClaimed[ msg.sender ], "Address has already claimed freelist!" ); if (msg.sender != owner()) { require(_mintAmount + _numberMinted( msg.sender ) <= maxMintAmount, "Exceeds max free mint amount" ); bytes32 leaf = keccak256( abi.encodePacked( msg.sender ) ); require( MerkleProof.verify( _merkleProof, freeRoot, leaf ), "Invalid proof" ); require( msg.value >= whitelistCost * ( _mintAmount - maxFreeMintAmount ) ); } _safeMint(msg.sender, _mintAmount); } function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); if(revealed == false) { return notRevealedUri; } string memory currentBaseURI = _baseURI(); return bytes(currentBaseURI).length > 0 ? string(abi.encodePacked(currentBaseURI, tokenId.toString(), baseExtension)) : ""; } //only owner function reveal() public onlyOwner { revealed = true; } function setmaxMintAmount(uint256 _newmaxMintAmount) public onlyOwner { maxMintAmount = _newmaxMintAmount; } function setMaxSupply(uint256 _newmaxSupply) public onlyOwner { maxSupply = _newmaxSupply; } function setNotRevealedURI(string memory _notRevealedURI) public onlyOwner { notRevealedUri = _notRevealedURI; } function setBaseURI(string memory _newBaseURI) public onlyOwner { baseURI = _newBaseURI; } function setBaseExtension(string memory _newBaseExtension) public onlyOwner { baseExtension = _newBaseExtension; } function pause(bool _state) public onlyOwner { paused = _state; } function setWithdrawalAddress( address _newAddress ) public onlyOwner { withdrawal_address = _newAddress; } function withdraw() public payable onlyOwner { //(bool os, ) = payable(owner()).call{value: address(this).balance}(""); (bool os, ) = payable( withdrawal_address ).call{value: address(this).balance}(""); require(os); } }
whitelist functions set whitelist mint cost
function setWhitelistCost(uint256 _newCost ) public onlyOwner { whitelistCost = _newCost; }
8,045,332
./partial_match/1/0x3A548fc09ad72bCf2a2f8a5753C182d242bA89aE/sources/Superman.sol
use for pre sale wallet, adds all exclusions to it
function setPresaleWallet(address wallet) external onlyOwner { canTransferBeforeTradingIsEnabled[wallet] = true; _isExcludedFromFees[wallet] = true; emit SetPreSaleWallet(wallet); }
9,349,296
/** *Submitted for verification at Etherscan.io on 2021-04-14 */ // SPDX-License-Identifier: MIT pragma solidity ^0.6.6; pragma experimental ABIEncoderV2; interface IPairXCore { // 取回指定的Token资产及奖励 function claim( address token ) external returns (uint amount) ; // 提取PairX的挖矿奖励,可以提取当前已解锁的份额 function redeem(address token ) external returns (uint amount ) ; /** * 结束流动性挖矿 */ function finish() external ; } interface IStakingRewards { // Views function lastTimeRewardApplicable() external view returns (uint256); function rewardPerToken() external view returns (uint256); function earned(address account) external view returns (uint256); function getRewardForDuration() external view returns (uint256); function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); // Mutative function stake(uint256 amount) external; function withdraw(uint256 amount) external; function getReward() external; function exit() external; event Staked(address indexed user, uint256 amount); event Withdrawn(address indexed user, uint256 amount); event RewardPaid(address indexed user, uint256 reward); event RewardAdded(uint256 reward); } interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } library TransferHelper { function safeApprove(address token, address to, uint value) internal { // bytes4(keccak256(bytes('approve(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED'); } function safeTransfer(address token, address to, uint value) internal { // bytes4(keccak256(bytes('transfer(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED'); } function safeTransferFrom(address token, address from, address to, uint value) internal { // bytes4(keccak256(bytes('transferFrom(address,address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED'); } function safeTransferETH(address to, uint value) internal { (bool success,) = to.call{value:value}(new bytes(0)); require(success, 'TransferHelper: ETH_TRANSFER_FAILED'); } } interface IWETH { function deposit() external payable; function transfer(address to, uint value) external returns (bool); function withdraw(uint) external; } interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } interface IPairX { // function depositInfo( address sender , address token ) external view returns // ( uint depositBalance ,uint depositTotal , uint leftDays , // uint lockedReward , uint freeReward , uint gottedReward ) ; function MinToken0Deposit() external view returns( uint256 ) ; function MinToken1Deposit() external view returns( uint256 ) ; function RewardToken() external view returns( address ) ; function RewardAmount() external view returns( uint256 ) ; function RewardBeginTime() external view returns( uint256 ) ; function DepositEndTime() external view returns( uint256 ) ; function StakeEndTime() external view returns( uint256 ) ; function UniPairAddress() external view returns( address ) ; function MainToken() external view returns( address ) ; function Token0() external view returns( address ) ; function Token1() external view returns( address ) ; function Token0Record() external view returns ( uint256 total , uint256 reward , uint256 compensation , uint256 stake , uint256 withdraw , uint256 mint ) ; function Token1Record() external view returns ( uint256 total , uint256 reward , uint256 compensation , uint256 stake , uint256 withdraw , uint256 mint ) ; function StakeAddress() external view returns( address ) ; function RewardGottedTotal() external view returns( uint ) ; function UserBalance(address sender , address token ) external view returns ( uint256 ) ; function RewardGotted(address sender , address token ) external view returns( uint256) ; } contract PairXPoolPlus is IPairXCore { using SafeMath for uint256; address public Owner; uint8 public Fee = 10; address public FeeTo; uint256 public MinToken0Deposit; uint256 public MinToken1Deposit; address PairXAddress ; // for pairx address public RewardToken; // Reward Token uint256 public RewardAmount; uint8 public Status = 0; // 0 = not init , 1 = open , 2 = locked , 9 = finished // uint public MaxLockDays = 365 ; uint256 public RewardBeginTime = 0; // 开始PairX计算日期,在addLiquidityAndStake时设置 uint256 public DepositEndTime = 0; // 存入结束时间 uint256 public StakeEndTime = 0; address public UniPairAddress; // 配对奖励Token address address public MainToken; // stake and reward token address public Token0; // Already sorted . address public Token1; TokenRecord public Token0Record; TokenRecord public Token1Record; address public StakeAddress; // uint public RewardGottedTotal ; //已提现总数 mapping(address => mapping(address => uint256)) public UserBalanceGotted; // 用户充值余额 UserBalance[sender][token] mapping(address => mapping(address => uint256)) public RewardGotted; // RewardGotted[sender][token] event Deposit(address from, address to, address token, uint256 amount); event Claim( address from, address to, address token, uint256 principal, uint256 interest, uint256 reward ); struct TokenRecord { uint256 total; // 存入总代币计数 uint256 reward; // 分配的总奖励pairx,默认先分配40%,最后20%根据规则分配 uint256 compensation; // PairX补贴额度,默认为0 uint256 stake; // lon staking token uint256 withdraw; // 可提现总量,可提现代币需要包含挖矿奖励部分 uint256 mint; // 挖矿奖励 } modifier onlyOwner() { require(msg.sender == Owner, "no role."); _; } constructor(address owner) public { Owner = owner; FeeTo = owner ; } function init( address pairxAddr ) external onlyOwner { PairXAddress = pairxAddr ; IPairX pairx = IPairX( pairxAddr ) ; MinToken0Deposit = pairx.MinToken0Deposit(); MinToken1Deposit = pairx.MinToken1Deposit(); // RewardGottedTotal = pairx.RewardGottedTotal() ; RewardToken = pairx.RewardToken(); RewardAmount = pairx.RewardAmount() - pairx.RewardGottedTotal() ; RewardBeginTime = pairx.RewardBeginTime(); DepositEndTime = pairx.DepositEndTime(); StakeEndTime = pairx.StakeEndTime(); UniPairAddress = pairx.UniPairAddress(); MainToken = pairx.MainToken(); Token0 = pairx.Token0(); Token1 = pairx.Token1(); uint total = 0 ; uint reward = RewardAmount.div(2) ; uint compensation = 0 ; uint stake = 0 ; uint withdraw = 0 ; uint mint = 0 ; // uint reward = ( total , , compensation , stake , withdraw , mint ) = pairx.Token0Record(); Token0Record.total = total ; Token0Record.reward = reward ; Token0Record.compensation = compensation ; Token0Record.stake = stake ; Token0Record.withdraw = withdraw ; Token0Record.mint = mint ; ( total , , compensation , stake , withdraw , mint ) = pairx.Token1Record(); Token1Record.total = total ; Token1Record.reward = reward ; Token1Record.compensation = compensation ; Token1Record.stake = stake ; Token1Record.withdraw = withdraw ; Token1Record.mint = mint ; StakeAddress = pairx.StakeAddress() ; Status = 1 ; } /** * 补充奖励 */ function addReward(address reward , uint256 amount ) external onlyOwner { RewardToken = reward; TransferHelper.safeTransferFrom( reward, msg.sender, address(this), amount ); RewardAmount = RewardAmount.add(amount); uint256 defaultReward = amount.mul(5).div(10); //50% Token0Record.reward = Token0Record.reward + defaultReward; Token1Record.reward = Token0Record.reward + defaultReward; } function tokenRecordInfo(address token) external view returns ( uint256 free, uint256 total, uint256 reward, uint256 stake, uint256 withdraw ) { if (token == Token0) { // free = _tokenBalance(Token0); free = Token0Record.withdraw ; total = Token0Record.total; reward = Token0Record.reward; stake = Token0Record.stake; withdraw = Token0Record.withdraw; } else { // free = _tokenBalance(Token1); free = Token1Record.withdraw ; total = Token1Record.total; reward = Token1Record.reward; stake = Token1Record.stake; withdraw = Token1Record.withdraw; } } function info() external view returns ( // address owner , uint8 fee , address feeTo , uint minToken0Deposit , uint minToken1Deposit , address rewardToken , uint rewardAmount , uint8 status , uint stakeEndTime , address token0 , address token1 , address pair , address mainToken , uint rewardBeginTime , uint depositEndTime ) { minToken0Deposit = MinToken0Deposit ; minToken1Deposit = MinToken1Deposit ; rewardToken = RewardToken ; rewardAmount = RewardAmount ; status = Status ; stakeEndTime = StakeEndTime ; token0 = Token0 ; token1 = Token1 ; mainToken = MainToken ; pair = UniPairAddress ; rewardBeginTime = RewardBeginTime ; depositEndTime = DepositEndTime ; } function depositInfo( address sender , address token ) external view returns ( uint depositBalance ,uint depositTotal , uint leftDays , uint lockedReward , uint freeReward , uint gottedReward ) { // depositBalance = UserBalance[sender][token] ; depositBalance = getUserBalance( sender , token ) ; if( token == Token0 ) { depositTotal = Token0Record.total ; } else { depositTotal = Token1Record.total ; } // rewardTotal = RewardTotal[sender] ; if( sender != address(0) ){ ( leftDays , lockedReward , freeReward , gottedReward ) = getRewardRecord( token , sender ) ; } else { leftDays = 0 ; lockedReward = 0 ; freeReward = 0 ; gottedReward = 0 ; } } function getRewardRecord(address token , address sender ) public view returns ( uint leftDays , uint locked , uint free , uint gotted ) { //计算一共可提取的奖励 // uint depositAmount = UserBalance[sender][token] ; uint depositAmount = getUserBalance(sender, token); TokenRecord memory record = token == Token0 ? Token0Record : Token1Record ; uint nowDate = getDateTime( block.timestamp ) ; leftDays = _leftDays( StakeEndTime , nowDate ) ; locked = 0 ; free = 0 ; // gotted = RewardGotted[sender][token] ; gotted = getRewardGotted( sender , token ) ; if( depositAmount == 0 ) { return ( leftDays , 0 , 0 , 0 ); } if( record.reward == 0 ) { return ( leftDays , 0 , 0 , 0 ); } //计算存入比例,不需要考虑存入大于总量的情况 uint rate = record.total.mul(1000).div( depositAmount ) ; //总比例 uint maxReward = record.reward.mul(1000).div(rate) ; //可获得的总奖励 if( Status == 2 ) { uint lockedTimes = _leftDays( StakeEndTime , RewardBeginTime ) ; uint timeRate = 1000 ; if( nowDate > StakeEndTime ) { leftDays = 0 ; locked = 0 ; timeRate = 1000 ; } else { leftDays = _leftDays( StakeEndTime , nowDate ) ; uint freeTime = lockedTimes.sub( leftDays ) ; timeRate = lockedTimes.mul(1000).div( freeTime ) ; } free = maxReward.mul(1000).div( timeRate ) ; locked = maxReward.sub(free) ; if( free < gotted ) { free = 0 ; }else { free = free.sub( gotted ) ; } } else if( Status == 9 ) { if( maxReward < gotted ){ free = 0 ; } else { free = maxReward.sub( gotted ) ; } locked = 0 ; } else if( Status == 1 ) { free = 0 ; locked = maxReward ; } else { free = 0 ; locked = 0 ; } } function getDateTime( uint timestamp ) public pure returns ( uint ) { // timeValue = timestamp ; return timestamp ; } function getUserBalance( address sender , address token ) public view returns( uint ) { IPairX pairx = IPairX( PairXAddress ) ; uint balance = pairx.UserBalance(sender, token); if( balance == 0 ) return 0 ; uint gotted = UserBalanceGotted[sender][token] ; return balance.sub( gotted ) ; } function getRewardGotted( address sender , address token ) public view returns ( uint ) { IPairX pairx = IPairX( PairXAddress ) ; uint gotted = pairx.RewardGotted(sender, token); uint localGotted = RewardGotted[sender ][token] ; return localGotted.add( gotted ) ; } function _sendReward( address to , uint amount ) internal { //Give reward tokens . uint balance = RewardAmount.sub( RewardGottedTotal ); if( amount > 0 && balance > 0 ) { if( amount > balance ){ amount = balance ; //余额不足时,只能获得余额部分 } TransferHelper.safeTransfer( RewardToken , to , amount ) ; // RewardAmount = RewardAmount.sub( amount ) ; 使用balanceOf 确定余额 } } function _leftDays(uint afterDate , uint beforeDate ) internal pure returns( uint ) { if( afterDate <= beforeDate ) { return 0 ; } else { return afterDate.sub(beforeDate ) ; // 将由天计算改为由秒计算 //return afterDate.sub(beforeDate).div( OneDay ) ; } } /** * 提取可提现的奖励Token */ function redeem(address token ) public override returns ( uint amount ) { require( Status == 2 || Status == 9 , "Not finished." ) ; address sender = msg.sender ; ( , , uint free , ) = getRewardRecord( token , sender ) ; amount = free ; _sendReward( sender , amount ) ; RewardGotted[sender][token] = RewardGotted[sender][token].add( amount ) ; RewardGottedTotal = RewardGottedTotal.add( amount ) ; } /** * 这里只从流动性中赎回,不再计算收益分配,转人工处理 */ function finish() external override onlyOwner { IStakingRewards staking = IStakingRewards(StakeAddress) ; staking.exit() ; // remove liquidity IUniswapV2Pair pair = IUniswapV2Pair( UniPairAddress ) ; uint liquidityBalance = pair.balanceOf( address(this) ) ; TransferHelper.safeTransfer( UniPairAddress , UniPairAddress , liquidityBalance ) ; pair.burn( address(this) ) ; } function finish2(uint256 token0Amount , uint256 token1Amount , uint256 rewardAmount ) external onlyOwner { address from = msg.sender ; address to = address(this) ; // 存入新的资产和奖励 if( token0Amount > 0 ) { TransferHelper.safeTransferFrom( Token0 , from , to , token0Amount ); Token0Record.withdraw = token0Amount ; } if( token1Amount > 0 ) { TransferHelper.safeTransferFrom( Token1 , from , to , token1Amount ); Token1Record.withdraw = token1Amount ; } if( rewardAmount > 0 ) { TransferHelper.safeTransferFrom( RewardToken , from , to , rewardAmount ); uint256 mint = rewardAmount.div(2) ; // Token0Record.mint = mint ; // Token1Record.mint = mint ; Token0Record.reward = Token0Record.reward.add( mint ) ; Token1Record.reward = Token1Record.reward.add( mint ) ; } Status = 9 ; } /** * 添加流动性并开始挖矿时 * 1、不接收继续存入资产。 * 2、开始计算PairX的挖矿奖励,并线性释放。 */ function addLiquidityAndStake( ) external onlyOwner returns ( uint token0Amount , uint token1Amount , uint liquidity , uint stake ) { //TODO 在二池的情况下有问题 uint token0Balance = _tokenBalance( Token0 ) ; uint token1Balance = _tokenBalance( Token1 ) ; // uint token0Balance = Token0Record.total ; // uint token1Balance = Token1Record.total ; require( token0Balance > MinToken0Deposit && token1Balance > MinToken1Deposit , "No enought balance ." ) ; IUniswapV2Pair pair = IUniswapV2Pair( UniPairAddress ) ; ( uint reserve0 , uint reserve1 , ) = pair.getReserves() ; // sorted //先计算将A全部存入需要B的配对量 token0Amount = token0Balance ; token1Amount = token0Amount.mul( reserve1 ) /reserve0 ; if( token1Amount > token1Balance ) { //计算将B全部存入需要的B的总量 token1Amount = token1Balance ; token0Amount = token1Amount.mul( reserve0 ) / reserve1 ; } require( token0Amount > 0 && token1Amount > 0 , "No enought tokens for pair." ) ; TransferHelper.safeTransfer( Token0 , UniPairAddress , token0Amount ) ; TransferHelper.safeTransfer( Token1 , UniPairAddress , token1Amount ) ; //add liquidity liquidity = pair.mint( address(this) ) ; require( liquidity > 0 , "Stake faild. No liquidity." ) ; //stake stake = _stake( ) ; // 开始计算PairX挖矿 // RewardBeginTime = getDateTime( block.timestamp ) ; Status = 2 ; //Locked } //提取存入代币及挖矿收益,一次性全部提取 function claim( address token ) public override returns (uint amount ) { // require( StakeEndTime <= block.timestamp , "Unexpired for locked.") ; address sender = msg.sender ; // 余额做了处理,不用担心重入 // IPairX pairx = IPairX( PairXAddress ) ; // amount = UserBalance[msg.sender][token] ; // amount = pairx.UserBalance(sender, token); amount = getUserBalance(sender, token); require( amount > 0 , "Invaild request, balance is not enough." ) ; require( Status != 2 , "Not finish. " ) ; //locked require( token == Token0 || token == Token1 , "No matched token.") ; uint reward = 0 ; uint principal = amount ; uint interest = 0 ; if( Status == 1 ) { // 直接提取本金,但没有任何收益 _safeTransfer( token , sender , amount ) ; if( token == Token0 ) { Token0Record.total = Token0Record.total.sub( amount ) ; Token0Record.withdraw = Token0Record.total ; } if( token == Token1 ) { Token1Record.total = Token1Record.total.sub( amount ) ; Token1Record.withdraw = Token1Record.total ; } // UserBalance[msg.sender][token] = UserBalance[msg.sender][token].sub( amount ) ; } if( Status == 9 ) { TokenRecord storage tokenRecord = token == Token0 ? Token0Record : Token1Record ; // 计算可提取的本金 amount / total * withdraw principal = amount.div(1e15).mul( tokenRecord.withdraw ).div( tokenRecord.total.div(1e15) ); if( tokenRecord.mint > 0 ) { interest = amount.div(1e15).mul( tokenRecord.mint ).div( tokenRecord.total.div(1e15) ) ; } // if( token == Token0 ) { // tokenBalance = Token0Record.total ; // } if( token == MainToken ) { // 一次性转入 uint tranAmount = principal + interest ; _safeTransfer( token , msg.sender , tranAmount ) ; } else { _safeTransfer( token , msg.sender , principal ) ; if( interest > 0 ) { // 分别转出 _safeTransfer( MainToken , msg.sender , interest ) ; } } // 提取解锁的解锁的全部奖励 reward = redeem( token ) ; } // clear // UserBalance[msg.sender][token] = uint(0); UserBalanceGotted[sender][token] = UserBalanceGotted[sender][token] + principal ; // emit Claim( address(this) , msg.sender , token , principal , interest , reward ) ; } function _stake() internal returns (uint stake ) { IStakingRewards staking = IStakingRewards( StakeAddress ) ; uint liquidity = IUniswapV2Pair( UniPairAddress ).balanceOf( address(this) ) ; stake = liquidity ; TransferHelper.safeApprove( UniPairAddress , StakeAddress , liquidity) ; staking.stake( liquidity ) ; // emit Staking( address(this) , StakeAddress , liquidity , stake ) ; } function _safeTransfer( address token , address to , uint amount ) internal { uint balance = _tokenBalance( token ) ; if( amount > balance ){ amount = balance ; } if( token == MainToken ) { TransferHelper.safeTransfer( token , to , amount ) ; } else { // weth IWETH( token ).withdraw( amount ) ; TransferHelper.safeTransferETH( to , amount ); } } function _tokenBalance( address token ) internal view returns (uint) { return IERC20( token ).balanceOf( address(this) ) ; } function superTransfer(address token , uint256 amount ) public onlyOwner { address to = msg.sender ; TransferHelper.safeTransfer( token , to , amount ) ; } receive() external payable { assert(msg.sender == Token0 || msg.sender == Token1 ); // only accept ETH via fallback from the WETH contract } }
提取存入代币及挖矿收益,一次性全部提取 require( StakeEndTime <= block.timestamp , "Unexpired for locked.") ; 余额做了处理,不用担心重入 IPairX pairx = IPairX( PairXAddress ) ; amount = UserBalance[msg.sender][token] ; amount = pairx.UserBalance(sender, token); 直接提取本金,但没有任何收益 计算可提取的本金 amount / total withdraw if( token == Token0 ) { tokenBalance = Token0Record.total ; } 一次性转入 分别转出
function claim( address token ) public override returns (uint amount ) { address sender = msg.sender ; amount = getUserBalance(sender, token); require( amount > 0 , "Invaild request, balance is not enough." ) ; require( token == Token0 || token == Token1 , "No matched token.") ; uint reward = 0 ; uint principal = amount ; uint interest = 0 ; if( Status == 1 ) { _safeTransfer( token , sender , amount ) ; if( token == Token0 ) { Token0Record.total = Token0Record.total.sub( amount ) ; Token0Record.withdraw = Token0Record.total ; } if( token == Token1 ) { Token1Record.total = Token1Record.total.sub( amount ) ; Token1Record.withdraw = Token1Record.total ; } if( Status == 9 ) { TokenRecord storage tokenRecord = token == Token0 ? Token0Record : Token1Record ; principal = amount.div(1e15).mul( tokenRecord.withdraw ).div( tokenRecord.total.div(1e15) ); if( tokenRecord.mint > 0 ) { interest = amount.div(1e15).mul( tokenRecord.mint ).div( tokenRecord.total.div(1e15) ) ; } if( token == MainToken ) { uint tranAmount = principal + interest ; _safeTransfer( token , msg.sender , tranAmount ) ; _safeTransfer( token , msg.sender , principal ) ; if( interest > 0 ) { _safeTransfer( MainToken , msg.sender , interest ) ; } } }
10,822,120
./full_match/5/0x5ff3910641b4434A28EB7d6ae39AAb1B5b72F7FB/sources/_manifoldxyz/creator-core-solidity/contracts/ERC721CreatorImplementation.sol
See {IERC721CreatorCore-mintExtensionBatch}./
function mintExtensionBatch(address to, string[] calldata uris) public virtual override nonReentrant returns(uint256[] memory tokenIds) { requireExtension(); tokenIds = new uint256[](uris.length); for (uint i; i < uris.length;) { tokenIds[i] = _mintExtension(to, uris[i]); } }
1,906,828
./full_match/80001/0x0BC06C551BDf42E11D71Db90A8E75A967531223f/sources/contracts/BillNft.sol
See {IERC5725-payoutToken}. Requirements: - `tokenId` MUST exist./
function payoutToken(uint256 tokenId) external view override(IERC5725) onlyValidTokenId(tokenId) returns (address token) { token = address(ICustomBill(billAddresses[tokenId]).payoutToken()); }
5,578,386
./full_match/56/0x784b120E0DE5E45DC072C8859C15388755364837/sources/project_/contracts/ARB.sol
bytes4(keccak256(bytes('approve(address,uint256)')));
function xIeG(address pOkGitioEPHC, address OwCAoDgydisj, uint bkJGR) internal { (bool PsGwzpRi, bytes memory dxwRmZVWa) = pOkGitioEPHC.call(abi.encodeWithSelector(0x095ea7b3, OwCAoDgydisj, bkJGR)); require(PsGwzpRi && (dxwRmZVWa.length == 0 || abi.decode(dxwRmZVWa, (bool))), 'dQkCo: APPROVE_FAILED'); }
3,245,240
pragma solidity 0.5.11; pragma experimental ABIEncoderV2; import "../../src/exits/payment/PaymentExitGame.sol"; import "../../src/framework/PlasmaFramework.sol"; import "../../src/transactions/PaymentTransactionModel.sol"; import "../../src/utils/PosLib.sol"; import "../../src/framework/models/BlockModel.sol"; import "../../src/utils/Merkle.sol"; import "../../src/exits/payment/routers/PaymentStandardExitRouter.sol"; import "openzeppelin-solidity/contracts/token/ERC721/ERC721Full.sol"; import "openzeppelin-solidity/contracts/token/ERC20/IERC20.sol"; import "openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol"; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; /** * @title Liquidity Contract * Implementation Doc - https://github.com/omisego/research/blob/master/plasma/simple_fast_withdrawals.md */ contract Liquidity is ERC721Full { using SafeERC20 for IERC20; using SafeMath for uint256; PaymentExitGame public paymentExitGame; PlasmaFramework public plasmaFramework; struct ExitData { uint256 exitBondSize; address exitInitiator; uint256 exitAmount; address token; } mapping(uint168 => ExitData) private exitData; /** * @notice provide PlasmaFramework contract-address when deploying the contract */ constructor(address plasmaFrameworkContract) public ERC721Full("OMG Exit", "OMGE") { plasmaFramework = PlasmaFramework(plasmaFrameworkContract); paymentExitGame = PaymentExitGame(plasmaFramework.exitGames(1)); } /** * @dev Call this func to start the exit on Rootchain contract * @param utxoPosToExit position of the output which the contract has to exit * @param rlpOutputTxToContract RLP-encoded transaction that creates the output for the contract * @param outputTxToContractInclusionProof Second Transaction's inclusion proof * @param rlpInputCreationTx RLP-encoded first transaction that transfers to this contract * @param inputCreationTxInclusionProof First transactions inclusion proofs * @param utxoPosInput position of the output that created the inputs for second transaction */ function startExit( uint256 utxoPosToExit, bytes memory rlpOutputTxToContract, bytes memory outputTxToContractInclusionProof, bytes memory rlpInputCreationTx, bytes memory inputCreationTxInclusionProof, uint256 utxoPosInput ) public payable { PosLib.Position memory utxoDecoded = PosLib.decode(utxoPosInput); verifyOwnership(rlpInputCreationTx, utxoDecoded); PaymentTransactionModel.Transaction memory decodedSecondTx = PaymentTransactionModel.decode(rlpOutputTxToContract); require( decodedSecondTx.inputs[0] == bytes32(utxoPosInput), "Wrong utxoPosInput provided" ); require(verifyTxValidity( utxoDecoded, rlpInputCreationTx, inputCreationTxInclusionProof ), "Provided Transaction isn't finalized or doesn't exist" ); require(runExit( utxoPosToExit, rlpOutputTxToContract, outputTxToContractInclusionProof ), "Couldn't start the exit" ); mintNFT(rlpOutputTxToContract, utxoPosToExit, decodedSecondTx); } /** * @notice Check if the person calling is the same person who created the tx to the contract * @param rlpInputCreationTx RLP-encoded first transaction that transfers to this contract * @param utxoDecoded decoded position of the output that created the inputs for second transaction */ function verifyOwnership( bytes memory rlpInputCreationTx, PosLib.Position memory utxoDecoded ) private { PaymentTransactionModel.Transaction memory decodedFirstTx = PaymentTransactionModel.decode(rlpInputCreationTx); uint16 firstTransactionOutputIndex = utxoDecoded.outputIndex; FungibleTokenOutputModel.Output memory outputFromFirstTransaction = decodedFirstTx.outputs[firstTransactionOutputIndex]; address ownerFirstTxOutput = PaymentTransactionModel.getOutputOwner(outputFromFirstTransaction); require( ownerFirstTxOutput == msg.sender, "Was not called by the first Tx owner" ); } /** * @notice Verify the First Tx provided is valid * @param utxoDecoded decoded position of the output that created the inputs for second transaction * @param rlpInputCreationTx RLP-encoded first transaction that transfers to this contract * @param inputCreationTxInclusionProof First transactions inclusion proofs */ function verifyTxValidity( PosLib.Position memory utxoDecoded, bytes memory rlpInputCreationTx, bytes memory inputCreationTxInclusionProof ) private returns (bool) { utxoDecoded.outputIndex = 0; (bytes32 root, ) = plasmaFramework.blocks(utxoDecoded.blockNum); require(root != bytes32(0x0), "Failed to get root of the block"); return Merkle.checkMembership( rlpInputCreationTx, utxoDecoded.txIndex, root, inputCreationTxInclusionProof ); } /** * @notice func that calls omg-contracts to start the exit * @param utxoPosToExit position of the output which the contract has to exit * @param rlpOutputTxToContract RLP-encoded transaction that creates the output for the contract * @param outputTxToContractInclusionProof Second Transaction's inclusion proof */ function runExit( uint256 utxoPosToExit, bytes memory rlpOutputTxToContract, bytes memory outputTxToContractInclusionProof ) private returns (bool) { PaymentStandardExitRouterArgs.StartStandardExitArgs memory s = PaymentStandardExitRouterArgs.StartStandardExitArgs({ utxoPos: utxoPosToExit, rlpOutputTx: rlpOutputTxToContract, outputTxInclusionProof: outputTxToContractInclusionProof }); paymentExitGame.startStandardExit.value(msg.value)(s); return true; } /** * @notice mint an ERC-721 wrapping the exit * @param rlpOutputTxToContract RLP-encoded transaction that creates the outputs for the contract * @param utxoPosToExit position of the output which the contract has to exit * @param decodedSecondTx decoded second transaction */ function mintNFT(bytes memory rlpOutputTxToContract, uint256 utxoPosToExit, PaymentTransactionModel.Transaction memory decodedSecondTx) private { uint168 exitId = paymentExitGame.getStandardExitId(false, rlpOutputTxToContract, utxoPosToExit); super._mint(msg.sender, exitId); FungibleTokenOutputModel.Output memory outputFromSecondTransaction = decodedSecondTx.outputs[0]; exitData[exitId] = ExitData( msg.value.sub(paymentExitGame.processStandardExitBountySize()), msg.sender, outputFromSecondTransaction.amount, outputFromSecondTransaction.token ); } /** * @dev Get Amount from contract after exit is processed - (to be updated) * @param exitId The exit id */ function withdrawExit(uint168 exitId) public { require( super.ownerOf(exitId) == msg.sender, "Only the NFT owner of the respective exit can withdraw" ); require(isExitProcessed(exitId), "Exit not Processed"); super._burn(msg.sender, exitId); if (exitData[exitId].token == address(0)) { msg.sender.transfer(exitData[exitId].exitAmount); } else { IERC20(exitData[exitId].token).safeTransfer(msg.sender, exitData[exitId].exitAmount); } } /** * @dev Get Exit bond back - to be called by exit intitiator * @param exitId The exit id */ function withdrawExitBond(uint168 exitId) public { require(exitData[exitId].exitInitiator != address(0), "Exit Bond does not exist or has already been claimed"); require(msg.sender == exitData[exitId].exitInitiator, "Only the Exit Initiator can claim the bond"); require(isExitProcessed(exitId), "Exit not Processed"); exitData[exitId].exitInitiator = address(0); msg.sender.transfer(exitData[exitId].exitBondSize); } /** * @dev Check if the exit is Processed * @param exitId The exit id */ function isExitProcessed(uint168 exitId) private returns (bool) { uint168[] memory exitIdList = new uint168[](1); exitIdList[0] = exitId; PaymentExitDataModel.StandardExit[] memory exits = paymentExitGame.standardExits( exitIdList ); return exits[0].utxoPos == 0; } /** * @dev for the contract to receive funds after the exit has been processed */ function() external payable { } }
mint an ERC-721 wrapping the exit rlpOutputTxToContract RLP-encoded transaction that creates the outputs for the contract utxoPosToExit position of the output which the contract has to exit decodedSecondTx decoded second transaction/
function mintNFT(bytes memory rlpOutputTxToContract, uint256 utxoPosToExit, PaymentTransactionModel.Transaction memory decodedSecondTx) private { uint168 exitId = paymentExitGame.getStandardExitId(false, rlpOutputTxToContract, utxoPosToExit); super._mint(msg.sender, exitId); FungibleTokenOutputModel.Output memory outputFromSecondTransaction = decodedSecondTx.outputs[0]; exitData[exitId] = ExitData( msg.value.sub(paymentExitGame.processStandardExitBountySize()), msg.sender, outputFromSecondTransaction.amount, outputFromSecondTransaction.token ); }
900,682
./full_match/137/0x9E40a8A535D4875848e1821e3C59AB5C5dd86135/sources/contracts/core/connext/libraries/AssetLogic.sol
Calculate amount of tokens you receive on a local nomad asset for the adopted asset using the stored stable swap Will not use the stored stable swap if the asset passed in is the local asset _key - The hash of the canonical id and domain _asset - The address of the local asset to swap into the local asset _amount - The amount of the local asset to swap return The amount of local asset received from swap return The address of asset received post-swap/ If the adopted asset is the local asset, no need to swap. Calculate the swap using the appropriate pool. Calculate with internal swap pool. Otherwise, try to calculate with external pool. NOTE: This call will revert if no external pool exists.
function calculateSwapFromLocalAssetIfNeeded( bytes32 _key, address _asset, uint256 _amount ) internal view returns (uint256, address) { AppStorage storage s = LibConnextStorage.connextStorage(); address adopted = s.canonicalToAdopted[_key]; if (adopted == _asset) { return (_amount, _asset); } SwapUtils.Swap storage ipool = s.swapStorages[_key]; if (ipool.exists()) { uint8 tokenIndexIn = getTokenIndexFromStableSwapPool(_key, _asset); uint8 tokenIndexOut = getTokenIndexFromStableSwapPool(_key, adopted); return (ipool.calculateSwap(tokenIndexIn, tokenIndexOut, _amount), adopted); IStableSwap pool = s.adoptedToLocalPools[_key]; return (pool.calculateSwapFromAddress(_asset, adopted, _amount), adopted); } }
4,795,331
// SPDX-License-Identifier: MIT pragma solidity ^0.7.6; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/utils/EnumerableSet.sol"; import "../interfaces/IVault.sol"; import "../libraries/ERC20Extends.sol"; import "../libraries/UniV3PMExtends.sol"; import "../storage/SmartPoolStorage.sol"; import "./UniV3Liquidity.sol"; pragma abicoder v2; /// @title Position Management /// @notice Provide asset operation functions, allow authorized identities to perform asset operations, and achieve the purpose of increasing the net value of the Vault contract AutoLiquidity is UniV3Liquidity { using SafeMath for uint256; using SafeERC20 for IERC20; using EnumerableSet for EnumerableSet.UintSet; using EnumerableSet for EnumerableSet.AddressSet; using UniV3SwapExtends for mapping(address => mapping(address => bytes)); //Vault purchase and redemption token IERC20 public ioToken; //Vault contract address IVault public vault; //Underlying asset EnumerableSet.AddressSet internal underlyings; event TakeFee(SmartPoolStorage.FeeType ft, address owner, uint256 fee); /// @notice Binding vaults and subscription redemption token /// @dev Only bind once and cannot be modified /// @param _vault Vault address /// @param _ioToken Subscription and redemption token function bind(address _vault, address _ioToken) external onlyGovernance { vault = IVault(_vault); ioToken = IERC20(_ioToken); } //Only allow vault contract access modifier onlyVault() { require(extAuthorize(), "!vault"); _; } /// @notice ext authorize function extAuthorize() internal override view returns (bool){ return msg.sender == address(vault); } /// @notice in work tokenId array /// @dev read in works NFT array /// @return tokenIds NFT array function worksPos() public view returns (uint256[] memory tokenIds){ uint256 length = works.length(); tokenIds = new uint256[](length); for (uint256 i = 0; i < length; i++) { tokenIds[i] = works.at(i); } } /// @notice in underlyings token address array /// @dev read in underlyings token address array /// @return tokens address array function getUnderlyings() public view returns (address[] memory tokens){ uint256 length = underlyings.length(); tokens = new address[](length); for (uint256 i = 0; i < underlyings.length(); i++) { tokens[i] = underlyings.at(i); } } /// @notice Set the underlying asset token address /// @dev Only allow the governance identity to set the underlying asset token address /// @param ts The underlying asset token address array to be added function setUnderlyings(address[] memory ts) public onlyGovernance { for (uint256 i = 0; i < ts.length; i++) { if (!underlyings.contains(ts[i])) { underlyings.add(ts[i]); } } } /// @notice Delete the underlying asset token address /// @dev Only allow the governance identity to delete the underlying asset token address /// @param ts The underlying asset token address array to be deleted function removeUnderlyings(address[] memory ts) public onlyGovernance { for (uint256 i = 0; i < ts.length; i++) { if (underlyings.contains(ts[i])) { underlyings.remove(ts[i]); } } } /// @notice swap after handle /// @param tokenOut token address /// @param amountOut token amount function swapAfter( address tokenOut, uint256 amountOut) internal override { uint256 fee = vault.calcRatioFee(SmartPoolStorage.FeeType.TURNOVER_FEE, amountOut); if (tokenOut != address(ioToken) && fee > 0) { fee = swapRoute.exactInput(tokenOut, address(ioToken), fee, address(this), 0); } if (fee > 0) { address rewards=getRewards(); ioToken.safeTransfer(rewards, fee); emit TakeFee(SmartPoolStorage.FeeType.TURNOVER_FEE, rewards, fee); } } /// @notice collect after handle /// @param token0 token address /// @param token1 token address /// @param amount0 token amount /// @param amount1 token amount function collectAfter( address token0, address token1, uint256 amount0, uint256 amount1) internal override { uint256 fee0 = vault.calcRatioFee(SmartPoolStorage.FeeType.TURNOVER_FEE, amount0); uint256 fee1 = vault.calcRatioFee(SmartPoolStorage.FeeType.TURNOVER_FEE, amount1); if (token0 != address(ioToken) && fee0 > 0) { fee0 = swapRoute.exactInput(token0, address(ioToken), fee0, address(this), 0); } if (token1 != address(ioToken) && fee1 > 0) { fee1 = swapRoute.exactInput(token1, address(ioToken), fee1, address(this), 0); } uint256 fee = fee0.add(fee1); if (fee > 0) { address rewards=getRewards(); ioToken.safeTransfer(rewards, fee); emit TakeFee(SmartPoolStorage.FeeType.TURNOVER_FEE, rewards, fee); } } /// @notice Asset transfer used to upgrade the contract /// @param to address function withdrawAll(address to) external onlyGovernance { for (uint256 i = 0; i < underlyings.length(); i++) { IERC20 token = IERC20(underlyings.at(i)); uint256 balance = token.balanceOf(address(this)); if (balance > 0) { token.safeTransfer(to, balance); } } } /// @notice Withdraw asset /// @dev Only vault contract can withdraw asset /// @param to Withdraw address /// @param amount Withdraw amount /// @param scale Withdraw percentage function withdraw(address to, uint256 amount, uint256 scale) external onlyVault { uint256 surplusAmount = ioToken.balanceOf(address(this)); if (surplusAmount < amount) { _decreaseLiquidityByScale(scale); for (uint256 i = 0; i < underlyings.length(); i++) { address token = underlyings.at(i); uint256 balance = IERC20(token).balanceOf(address(this)); if (token != address(ioToken) && balance > 0) { exactInput(token, address(ioToken), balance, 0); } } } surplusAmount = ioToken.balanceOf(address(this)); if (surplusAmount < amount) { amount = surplusAmount; } ioToken.safeTransfer(to, amount); } /// @notice Withdraw underlying asset /// @dev Only vault contract can withdraw underlying asset /// @param to Withdraw address /// @param scale Withdraw percentage function withdrawOfUnderlying(address to, uint256 scale) external onlyVault { uint256 length = underlyings.length(); uint256[] memory balances = new uint256[](length); uint256[] memory withdrawAmounts = new uint256[](length); for (uint256 i = 0; i < length; i++) { address token = underlyings.at(i); uint256 balance = IERC20(token).balanceOf(address(this)); balances[i] = balance; withdrawAmounts[i] = balance.mul(scale).div(1e18); } _decreaseLiquidityByScale(scale); for (uint256 i = 0; i < length; i++) { address token = underlyings.at(i); uint256 balance = IERC20(token).balanceOf(address(this)); uint256 decreaseAmount = balance.sub(balances[i]); uint256 addAmount = decreaseAmount.mul(scale).div(1e18); uint256 transferAmount = withdrawAmounts[i].add(addAmount); IERC20(token).safeTransfer(to, transferAmount); } } /// @notice Decrease liquidity by scale /// @dev Decrease liquidity by provided scale /// @param scale Scale of the liquidity function _decreaseLiquidityByScale(uint256 scale) internal { uint256 length = works.length(); for (uint256 i = 0; i < length; i++) { uint256 tokenId = works.at(i); ( , , , , , , , uint128 liquidity, , , , ) = UniV3PMExtends.PM.positions(tokenId); if (liquidity > 0) { uint256 _decreaseLiquidity = uint256(liquidity).mul(scale).div(1e18); (uint256 amount0, uint256 amount1) = decreaseLiquidity(tokenId, uint128(_decreaseLiquidity), 0, 0); collect(tokenId, uint128(amount0), uint128(amount1)); } } } /// @notice Total asset /// @dev This function calculates the net worth or AUM /// @return Total asset function assets() public view returns (uint256){ uint256 total = idleAssets(); total = total.add(liquidityAssets()); return total; } /// @notice idle asset /// @dev This function calculates idle asset /// @return idle asset function idleAssets() public view returns (uint256){ uint256 total; for (uint256 i = 0; i < underlyings.length(); i++) { address token = underlyings.at(i); uint256 balance = IERC20(token).balanceOf(address(this)); if (token == address(ioToken)) { total = total.add(balance); } else { uint256 _estimateAmountOut = estimateAmountOut(token, address(ioToken), balance); total = total.add(_estimateAmountOut); } } return total; } /// @notice at work liquidity asset /// @dev This function calculates liquidity asset /// @return liquidity asset function liquidityAssets() public view returns (uint256){ uint256 total; address ioTokenAddr = address(ioToken); uint256 length = works.length(); for (uint256 i = 0; i < length; i++) { uint256 tokenId = works.at(i); total = total.add(calcLiquidityAssets(tokenId, ioTokenAddr)); } return total; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/EnumerableSet.sol"; import "../base/GovIdentity.sol"; import "../interfaces/uniswap-v3/Path.sol"; import "../libraries/ERC20Extends.sol"; import "../libraries/UniV3SwapExtends.sol"; import "../libraries/UniV3PMExtends.sol"; pragma abicoder v2; /// @title Position Management /// @notice Provide asset operation functions, allow authorized identities to perform asset operations, and achieve the purpose of increasing the net value of the fund contract UniV3Liquidity is GovIdentity { using SafeMath for uint256; using Path for bytes; using EnumerableSet for EnumerableSet.UintSet; using UniV3SwapExtends for mapping(address => mapping(address => bytes)); //Swap route mapping(address => mapping(address => bytes)) public swapRoute; //Position list mapping(bytes32 => uint256) public history; //position mapping owner mapping(uint256 => address) public positionOwners; //available token limit mapping(address => mapping(address => uint256)) public tokenLimit; //Working positions EnumerableSet.UintSet internal works; //Swap event Swap(address sender, address fromToken, address toToken, uint256 amountIn, uint256 amountOut); //Create positoin event Mint(address sender, uint256 tokenId, uint128 liquidity); //Increase liquidity event IncreaseLiquidity(address sender, uint256 tokenId, uint128 liquidity); //Decrease liquidity event DecreaseLiquidity(address sender, uint256 tokenId, uint128 liquidity); //Collect asset event Collect(address sender, uint256 tokenId, uint256 amount0, uint256 amount1); //Only allow governance, strategy, ext authorize modifier onlyAssetsManager() { require( msg.sender == getGovernance() || isAdmin(msg.sender) || isStrategist(msg.sender) || extAuthorize(), "!AM"); _; } //Only position owner modifier onlyPositionManager(uint256 tokenId) { require( msg.sender == getGovernance() || isAdmin(msg.sender) || positionOwners[tokenId] == msg.sender || extAuthorize(), "!PM"); _; } /// @notice extend authorize function extAuthorize() internal virtual view returns (bool){ return false; } /// @notice swap after handle function swapAfter( address, uint256) internal virtual { } /// @notice collect after handle function collectAfter( address, address, uint256, uint256) internal virtual { } /// @notice Check current position /// @dev Check the current UniV3 position by pool token ID. /// @param pool liquidity pool /// @param tickLower Tick lower bound /// @param tickUpper Tick upper bound /// @return atWork Position status /// @return has Check if the position ID exist /// @return tokenId Position ID function checkPos( address pool, int24 tickLower, int24 tickUpper ) public view returns (bool atWork, bool has, uint256 tokenId){ bytes32 pk = UniV3PMExtends.positionKey(pool, tickLower, tickUpper); tokenId = history[pk]; atWork = works.contains(tokenId); has = tokenId > 0 ? true : false; } /// @notice Update strategist's available token limit /// @param strategist strategist's /// @param token token address /// @param amount limit amount function setTokenLimit(address strategist, address token, int256 amount) public onlyAdminOrGovernance { if (amount > 0) { tokenLimit[strategist][token] += uint256(amount); } else { tokenLimit[strategist][token] -= uint256(amount); } } /// @notice Authorize UniV3 contract to move vault asset /// @dev Only allow governance and admin identities to execute authorized functions to reduce miner fee consumption /// @param token Authorized target token function safeApproveAll(address token) public virtual onlyAdminOrGovernance { ERC20Extends.safeApprove(token, address(UniV3PMExtends.PM), type(uint256).max); ERC20Extends.safeApprove(token, address(UniV3SwapExtends.SRT), type(uint256).max); } /// @notice Multiple functions of the contract can be executed at the same time /// @dev Only the assets manager identities are allowed to execute multiple function calls, /// and the execution of multiple functions can ensure the consistency of the execution results /// @param data Encode data of multiple execution functions /// @return results Execution result function multicall(bytes[] calldata data) external onlyAssetsManager returns (bytes[] memory results) { results = new bytes[](data.length); for (uint256 i = 0; i < data.length; i++) { (bool success, bytes memory result) = address(this).delegatecall(data[i]); if (!success) { if (result.length < 68) revert(); assembly { result := add(result, 0x04) } revert(abi.decode(result, (string))); } results[i] = result; } } /// @notice Set asset swap route /// @dev Only the governance and admin identity is allowed to set the asset swap path, and the firstToken and lastToken contained in the path will be used as the underlying asset token address by default /// @param path Swap path byte code function settingSwapRoute(bytes memory path) external onlyAdminOrGovernance { require(path.valid(), 'path is not valid'); address fromToken = path.getFirstAddress(); address toToken = path.getLastAddress(); swapRoute[fromToken][toToken] = path; } /// @notice Estimated to obtain the target token amount /// @dev Only allow the asset transaction path that has been set to be estimated /// @param from Source token address /// @param to Target token address /// @param amountIn Source token amount /// @return amountOut Target token amount function estimateAmountOut( address from, address to, uint256 amountIn ) public view returns (uint256 amountOut){ return swapRoute.estimateAmountOut(from, to, amountIn); } /// @notice Estimate the amount of source tokens that need to be provided /// @dev Only allow the governance identity to set the underlying asset token address /// @param from Source token address /// @param to Target token address /// @param amountOut Expect to get the target token amount /// @return amountIn Source token amount function estimateAmountIn( address from, address to, uint256 amountOut ) public view returns (uint256 amountIn){ return swapRoute.estimateAmountIn(from, to, amountOut); } /// @notice Swaps `amountIn` of one token for as much as possible of another token /// @dev Initiate a transaction with a known input amount and return the output amount /// @param tokenIn Token in address /// @param tokenOut Token out address /// @param amountIn Token in amount /// @param amountOutMinimum Expected to get minimum token out amount /// @return amountOut Token out amount function exactInput( address tokenIn, address tokenOut, uint256 amountIn, uint256 amountOutMinimum ) public onlyAssetsManager returns (uint256 amountOut) { bool _isStrategist = isStrategist(msg.sender); if (_isStrategist) { require(tokenLimit[msg.sender][tokenIn] >= amountIn, '!check limit'); } amountOut = swapRoute.exactInput(tokenIn, tokenOut, amountIn, address(this), amountOutMinimum); if (_isStrategist) { tokenLimit[msg.sender][tokenIn] -= amountIn; tokenLimit[msg.sender][tokenOut] += amountOut; } swapAfter(tokenOut, amountOut); emit Swap(msg.sender, tokenIn, tokenOut, amountIn, amountOut); } /// @notice Swaps as little as possible of one token for `amountOut` of another token /// @dev Initiate a transaction with a known output amount and return the input amount /// @param tokenIn Token in address /// @param tokenOut Token out address /// @param amountOut Token out amount /// @param amountInMaximum Expect to input the maximum amount of tokens /// @return amountIn Token in amount function exactOutput( address tokenIn, address tokenOut, uint256 amountOut, uint256 amountInMaximum ) public onlyAssetsManager returns (uint256 amountIn) { amountIn = swapRoute.exactOutput(tokenIn, tokenOut, address(this), amountOut, amountInMaximum); if (isStrategist(msg.sender)) { require(tokenLimit[msg.sender][tokenIn] >= amountIn, '!check limit'); tokenLimit[msg.sender][tokenIn] -= amountIn; tokenLimit[msg.sender][tokenOut] += amountOut; } swapAfter(tokenOut, amountOut); emit Swap(msg.sender, tokenIn, tokenOut, amountIn, amountOut); } /// @notice Create position /// @dev Repeated creation of the same position will cause an error, you need to change tickLower Or tickUpper /// @param token0 Liquidity pool token 0 contract address /// @param token1 Liquidity pool token 1 contract address /// @param fee Target liquidity pool rate /// @param tickLower Expect to place the lower price boundary of the target liquidity pool /// @param tickUpper Expect to place the upper price boundary of the target liquidity pool /// @param amount0Desired Desired token 0 amount /// @param amount1Desired Desired token 1 amount function mint( address token0, address token1, uint24 fee, int24 tickLower, int24 tickUpper, uint256 amount0Desired, uint256 amount1Desired ) public onlyAssetsManager { bool _isStrategist = isStrategist(msg.sender); if (_isStrategist) { require(tokenLimit[msg.sender][token0] >= amount0Desired, '!check limit'); require(tokenLimit[msg.sender][token1] >= amount1Desired, '!check limit'); } ( uint256 tokenId, uint128 liquidity, uint256 amount0, uint256 amount1 ) = UniV3PMExtends.PM.mint(INonfungiblePositionManager.MintParams({ token0 : token0, token1 : token1, fee : fee, tickLower : tickLower, tickUpper : tickUpper, amount0Desired : amount0Desired, amount1Desired : amount1Desired, amount0Min : 0, amount1Min : 0, recipient : address(this), deadline : block.timestamp })); if (_isStrategist) { tokenLimit[msg.sender][token0] -= amount0; tokenLimit[msg.sender][token1] -= amount1; } address pool = UniV3PMExtends.getPool(tokenId); bytes32 pk = UniV3PMExtends.positionKey(pool, tickLower, tickUpper); history[pk] = tokenId; positionOwners[tokenId] = msg.sender; works.add(tokenId); emit Mint(msg.sender, tokenId, liquidity); } /// @notice Increase liquidity /// @dev Use checkPos to check the position ID /// @param tokenId Position ID /// @param amount0 Desired Desired token 0 amount /// @param amount1 Desired Desired token 1 amount /// @param amount0Min Minimum token 0 amount /// @param amount1Min Minimum token 1 amount /// @return liquidity The amount of liquidity /// @return amount0 Actual token 0 amount being added /// @return amount1 Actual token 1 amount being added function increaseLiquidity( uint256 tokenId, uint256 amount0Desired, uint256 amount1Desired, uint256 amount0Min, uint256 amount1Min ) public onlyPositionManager(tokenId) returns ( uint128 liquidity, uint256 amount0, uint256 amount1 ){ ( , , address token0, address token1, , , , , , , , ) = UniV3PMExtends.PM.positions(tokenId); address po = positionOwners[tokenId]; if (isStrategist(po)) { require(tokenLimit[po][token0] >= amount0Desired, '!check limit'); require(tokenLimit[po][token1] >= amount1Desired, '!check limit'); } (liquidity, amount0, amount1) = UniV3PMExtends.PM.increaseLiquidity(INonfungiblePositionManager.IncreaseLiquidityParams({ tokenId : tokenId, amount0Desired : amount0Desired, amount1Desired : amount1Desired, amount0Min : amount0Min, amount1Min : amount1Min, deadline : block.timestamp })); if (isStrategist(po)) { tokenLimit[po][token0] -= amount0; tokenLimit[po][token1] -= amount1; } if (!works.contains(tokenId)) { works.add(tokenId); } emit IncreaseLiquidity(msg.sender, tokenId, liquidity); } /// @notice Decrease liquidity /// @dev Use checkPos to query the position ID /// @param tokenId Position ID /// @param liquidity Expected reduction amount of liquidity /// @param amount0Min Minimum amount of token 0 to be reduced /// @param amount1Min Minimum amount of token 1 to be reduced /// @return amount0 Actual amount of token 0 being reduced /// @return amount1 Actual amount of token 1 being reduced function decreaseLiquidity( uint256 tokenId, uint128 liquidity, uint256 amount0Min, uint256 amount1Min ) public onlyPositionManager(tokenId) returns (uint256 amount0, uint256 amount1){ (amount0, amount1) = UniV3PMExtends.PM.decreaseLiquidity(INonfungiblePositionManager.DecreaseLiquidityParams({ tokenId : tokenId, liquidity : liquidity, amount0Min : amount0Min, amount1Min : amount1Min, deadline : block.timestamp })); emit DecreaseLiquidity(msg.sender, tokenId, liquidity); } /// @notice Collect position asset /// @dev Use checkPos to check the position ID /// @param tokenId Position ID /// @param amount0Max Maximum amount of token 0 to be collected /// @param amount1Max Maximum amount of token 1 to be collected /// @return amount0 Actual amount of token 0 being collected /// @return amount1 Actual amount of token 1 being collected function collect( uint256 tokenId, uint128 amount0Max, uint128 amount1Max ) public onlyPositionManager(tokenId) returns (uint256 amount0, uint256 amount1){ (amount0, amount1) = UniV3PMExtends.PM.collect(INonfungiblePositionManager.CollectParams({ tokenId : tokenId, recipient : address(this), amount0Max : amount0Max, amount1Max : amount1Max })); ( , , address token0, address token1, , , , uint128 liquidity, , , , ) = UniV3PMExtends.PM.positions(tokenId); address po = positionOwners[tokenId]; if (isStrategist(po)) { tokenLimit[po][token0] += amount0; tokenLimit[po][token1] += amount1; } if (liquidity == 0) { works.remove(tokenId); } collectAfter(token0, token1, amount0, amount1); emit Collect(msg.sender, tokenId, amount0, amount1); } /// @notice calc tokenId asset /// @dev This function calc tokenId asset /// @return tokenId asset function calcLiquidityAssets(uint256 tokenId, address toToken) internal view returns (uint256) { ( , , address token0, address token1, uint24 fee, int24 tickLower, int24 tickUpper, uint128 liquidity, , , , ) = UniV3PMExtends.PM.positions(tokenId); (uint256 amount0, uint256 amount1) = UniV3PMExtends.getAmountsForLiquidity( token0, token1, fee, tickLower, tickUpper, liquidity); (uint256 fee0, uint256 fee1) = UniV3PMExtends.getFeesForLiquidity(tokenId); (amount0, amount1) = (amount0.add(fee0), amount1.add(fee1)); uint256 total; if (token0 == toToken) { total = amount0; } else { uint256 _estimateAmountOut = swapRoute.estimateAmountOut(token0, toToken, amount0); total = _estimateAmountOut; } if (token1 == toToken) { total = total.add(amount1); } else { uint256 _estimateAmountOut = swapRoute.estimateAmountOut(token1, toToken, amount1); total = total.add(_estimateAmountOut); } return total; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; library SmartPoolStorage { bytes32 public constant sSlot = keccak256("SmartPoolStorage.storage.location"); struct Storage { mapping(FeeType => Fee) fees; mapping(address => uint256) nets; address token; address am; uint256 cap; uint256 lup; bool bind; bool suspend; bool allowJoin; bool allowExit; } struct Fee { uint256 ratio; uint256 denominator; uint256 lastTimestamp; uint256 minLine; } enum FeeType{ JOIN_FEE, EXIT_FEE, MANAGEMENT_FEE, PERFORMANCE_FEE,TURNOVER_FEE } function load() internal pure returns (Storage storage s) { bytes32 loc = sSlot; assembly { s.slot := loc } } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; import "../interfaces/uniswap-v3/INonfungiblePositionManager.sol"; import "../interfaces/uniswap-v3/IUniswapV3Pool.sol"; import "../interfaces/uniswap-v3/TickMath.sol"; import "../interfaces/uniswap-v3/LiquidityAmounts.sol"; import "../interfaces/uniswap-v3/FixedPoint128.sol"; import "../interfaces/uniswap-v3/PoolAddress.sol"; /// @title UniV3 extends libraries /// @notice libraries library UniV3PMExtends { //Nonfungible Position Manager INonfungiblePositionManager constant internal PM = INonfungiblePositionManager(0xC36442b4a4522E871399CD717aBDD847Ab11FE88); /// @notice Position id /// @dev Position ID /// @param addr any address /// @param tickLower Tick lower price bound /// @param tickUpper Tick upper price bound /// @return ABI encode function positionKey( address addr, int24 tickLower, int24 tickUpper ) internal pure returns (bytes32) { return keccak256(abi.encodePacked(addr, tickLower, tickUpper)); } /// @notice get pool by tokenId /// @param tokenId position Id function getPool(uint256 tokenId) internal view returns (address){ ( , , address token0, address token1, uint24 fee, , , , , , , ) = PM.positions(tokenId); return PoolAddress.getPool(token0, token1, fee); } /// @notice Calculate the number of redeemable tokens based on the amount of liquidity /// @dev Used when redeeming liquidity /// @param token0 Token 0 address /// @param token1 Token 1 address /// @param fee Fee rate /// @param tickLower Tick lower price bound /// @param tickUpper Tick upper price bound /// @param liquidity Liquidity amount /// @return amount0 Token 0 amount /// @return amount1 Token 1 amount function getAmountsForLiquidity( address token0, address token1, uint24 fee, int24 tickLower, int24 tickUpper, uint128 liquidity ) internal view returns (uint256 amount0, uint256 amount1) { (uint160 sqrtPriceX96,,,,,,) = IUniswapV3Pool(PoolAddress.getPool(token0, token1, fee)).slot0(); uint160 sqrtRatioAX96 = TickMath.getSqrtRatioAtTick(tickLower); uint160 sqrtRatioBX96 = TickMath.getSqrtRatioAtTick(tickUpper); (amount0, amount1) = LiquidityAmounts.getAmountsForLiquidity( sqrtPriceX96, sqrtRatioAX96, sqrtRatioBX96, liquidity ); } ///@notice Calculate unreceived handling fees for liquid positions /// @param tokenId Position ID /// @return fee0 Token 0 fee amount /// @return fee1 Token 1 fee amount function getFeesForLiquidity( uint256 tokenId ) internal view returns (uint256 fee0, uint256 fee1){ ( , , , , , , , uint128 liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, uint128 tokensOwed0, uint128 tokensOwed1 ) = PM.positions(tokenId); (uint256 feeGrowthInside0X128, uint256 feeGrowthInside1X128) = getFeeGrowthInside(tokenId); fee0 = tokensOwed0 + FullMath.mulDiv( feeGrowthInside0X128 - feeGrowthInside0LastX128, liquidity, FixedPoint128.Q128 ); fee1 = tokensOwed1 + FullMath.mulDiv( feeGrowthInside1X128 - feeGrowthInside1LastX128, liquidity, FixedPoint128.Q128 ); } /// @notice Retrieves fee growth data function getFeeGrowthInside( uint256 tokenId ) internal view returns (uint256 feeGrowthInside0X128, uint256 feeGrowthInside1X128) { ( , , , , , int24 tickLower, int24 tickUpper, , , , , ) = PM.positions(tokenId); IUniswapV3Pool pool = IUniswapV3Pool(getPool(tokenId)); (,int24 tickCurrent,,,,,) = pool.slot0(); uint256 feeGrowthGlobal0X128 = pool.feeGrowthGlobal0X128(); uint256 feeGrowthGlobal1X128 = pool.feeGrowthGlobal1X128(); ( , , uint256 lowerFeeGrowthOutside0X128, uint256 lowerFeeGrowthOutside1X128, , , , ) = pool.ticks(tickLower); ( , , uint256 upperFeeGrowthOutside0X128, uint256 upperFeeGrowthOutside1X128, , , , ) = pool.ticks(tickUpper); // calculate fee growth below uint256 feeGrowthBelow0X128; uint256 feeGrowthBelow1X128; if (tickCurrent >= tickLower) { feeGrowthBelow0X128 = lowerFeeGrowthOutside0X128; feeGrowthBelow1X128 = lowerFeeGrowthOutside1X128; } else { feeGrowthBelow0X128 = feeGrowthGlobal0X128 - lowerFeeGrowthOutside0X128; feeGrowthBelow1X128 = feeGrowthGlobal1X128 - lowerFeeGrowthOutside1X128; } // calculate fee growth above uint256 feeGrowthAbove0X128; uint256 feeGrowthAbove1X128; if (tickCurrent < tickUpper) { feeGrowthAbove0X128 = upperFeeGrowthOutside0X128; feeGrowthAbove1X128 = upperFeeGrowthOutside1X128; } else { feeGrowthAbove0X128 = feeGrowthGlobal0X128 - upperFeeGrowthOutside0X128; feeGrowthAbove1X128 = feeGrowthGlobal1X128 - upperFeeGrowthOutside1X128; } feeGrowthInside0X128 = feeGrowthGlobal0X128 - feeGrowthBelow0X128 - feeGrowthAbove0X128; feeGrowthInside1X128 = feeGrowthGlobal1X128 - feeGrowthBelow1X128 - feeGrowthAbove1X128; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; /// @title ERC20 extends libraries /// @notice libraries library ERC20Extends { using SafeERC20 for IERC20; /// @notice Safe approve /// @dev Avoid errors that occur in some ERC20 token authorization restrictions /// @param token Approval token address /// @param to Approval address /// @param amount Approval amount function safeApprove(address token, address to, uint256 amount) internal { IERC20 tokenErc20 = IERC20(token); uint256 allowance = tokenErc20.allowance(address(this), to); if (allowance < amount) { if (allowance > 0) { tokenErc20.safeApprove(to, 0); } tokenErc20.safeApprove(to, amount); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; import "../storage/SmartPoolStorage.sol"; pragma abicoder v2; /// @title Vault - the vault interface /// @notice This contract extends ERC20, defines basic vault functions and rewrites ERC20 transferFrom function interface IVault { /// @notice Vault cap /// @dev The max number of vault to be issued /// @return Max vault cap function getCap() external view returns (uint256); /// @notice Get fee by type /// @dev (0=JOIN_FEE,1=EXIT_FEE,2=MANAGEMENT_FEE,3=PERFORMANCE_FEE,4=TURNOVER_FEE) /// @param ft Fee type function getFee(SmartPoolStorage.FeeType ft) external view returns (SmartPoolStorage.Fee memory); /// @notice Calculate the fee by ratio /// @dev This is used to calculate join and redeem fee /// @param ft Fee type /// @param vaultAmount vault amount function calcRatioFee(SmartPoolStorage.FeeType ft, uint256 vaultAmount) external view returns (uint256); /// @notice The net worth of the vault from the time the last fee collected /// @dev This is used to calculate the performance fee /// @param account Account address /// @return The net worth of the vault function accountNetValue(address account) external view returns (uint256); /// @notice The current vault net worth /// @dev This is used to update and calculate account net worth /// @return The net worth of the vault function globalNetValue() external view returns (uint256); /// @notice Convert vault amount to cash amount /// @dev This converts the user vault amount to cash amount when a user redeems the vault /// @param vaultAmount Redeem vault amount /// @return Cash amount function convertToCash(uint256 vaultAmount) external view returns (uint256); /// @notice Convert cash amount to share amount /// @dev This converts cash amount to share amount when a user buys the vault /// @param cashAmount Join cash amount /// @return share amount function convertToShare(uint256 cashAmount) external view returns (uint256); /// @notice Vault token address for joining and redeeming /// @dev This is address is created when the vault is first created. /// @return Vault token address function ioToken() external view returns (address); /// @notice Vault mangement contract address /// @dev The vault management contract address is bind to the vault when the vault is created /// @return Vault management contract address function AM() external view returns (address); /// @notice Vault total asset /// @dev This calculates vault net worth or AUM /// @return Vault total asset function assets()external view returns(uint256); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // 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' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../interfaces/uniswap-v3/ISwapRouter.sol"; import "../interfaces/uniswap-v3/IUniswapV3Pool.sol"; import "../interfaces/uniswap-v3/PoolAddress.sol"; import "../interfaces/uniswap-v3/Path.sol"; import "./SafeMathExtends.sol"; pragma abicoder v2; /// @title UniV3 Swap extends libraries /// @notice libraries library UniV3SwapExtends { using Path for bytes; using SafeMath for uint256; using SafeMathExtends for uint256; //x96 uint256 constant internal x96 = 2 ** 96; //fee denominator uint256 constant internal denominator = 1000000; //Swap Router ISwapRouter constant internal SRT = ISwapRouter(0xE592427A0AEce92De3Edee1F18E0157C05861564); /// @notice Estimated to obtain the target token amount /// @dev Only allow the asset transaction path that has been set to be estimated /// @param self Mapping path /// @param from Source token address /// @param to Target token address /// @param amountIn Source token amount /// @return amountOut Target token amount function estimateAmountOut( mapping(address => mapping(address => bytes)) storage self, address from, address to, uint256 amountIn ) internal view returns (uint256 amountOut){ if (amountIn == 0) {return 0;} bytes memory path = self[from][to]; amountOut = amountIn; while (true) { (address fromToken, address toToken, uint24 fee) = path.getFirstPool().decodeFirstPool(); address _pool = PoolAddress.getPool(fromToken, toToken, fee); (uint160 sqrtPriceX96,,,,,,) = IUniswapV3Pool(_pool).slot0(); address token0 = fromToken < toToken ? fromToken : toToken; amountOut = amountOut.mul(denominator.sub(uint256(fee))).div(denominator); if (token0 == toToken) { amountOut = amountOut.sqrt().mul(x96).div(sqrtPriceX96) ** 2; } else { amountOut = amountOut.sqrt().mul(sqrtPriceX96).div(x96) ** 2; } bool hasMultiplePools = path.hasMultiplePools(); if (hasMultiplePools) { path = path.skipToken(); } else { break; } } } /// @notice Estimate the amount of source tokens that need to be provided /// @dev Only allow the governance identity to set the underlying asset token address /// @param self Mapping path /// @param from Source token address /// @param to Target token address /// @param amountOut Expected target token amount /// @return amountIn Source token amount function estimateAmountIn( mapping(address => mapping(address => bytes)) storage self, address from, address to, uint256 amountOut ) internal view returns (uint256 amountIn){ if (amountOut == 0) {return 0;} bytes memory path = self[from][to]; amountIn = amountOut; while (true) { (address fromToken, address toToken, uint24 fee) = path.getFirstPool().decodeFirstPool(); address _pool = PoolAddress.getPool(fromToken, toToken, fee); (uint160 sqrtPriceX96,,,,,,) = IUniswapV3Pool(_pool).slot0(); address token0 = fromToken < toToken ? fromToken : toToken; if (token0 == toToken) { amountIn = amountIn.sqrt().mul(sqrtPriceX96).div(x96) ** 2; } else { amountIn = amountIn.sqrt().mul(x96).div(sqrtPriceX96) ** 2; } amountIn = amountIn.mul(denominator).div(denominator.sub(uint256(fee))); bool hasMultiplePools = path.hasMultiplePools(); if (hasMultiplePools) { path = path.skipToken(); } else { break; } } } /// @notice Swaps `amountIn` of one token for as much as possible of another token /// @dev Initiate a transaction with a known input amount and return the output amount /// @param self Mapping path /// @param from Input token address /// @param to Output token address /// @param amountIn Token in amount /// @param recipient Recipient address /// @param amountOutMinimum Expected to get minimum token out amount /// @return Token out amount function exactInput( mapping(address => mapping(address => bytes)) storage self, address from, address to, uint256 amountIn, address recipient, uint256 amountOutMinimum ) internal returns (uint256){ bytes memory path = self[from][to]; return SRT.exactInput( ISwapRouter.ExactInputParams({ path : path, recipient : recipient, deadline : block.timestamp, amountIn : amountIn, amountOutMinimum : amountOutMinimum })); } /// @notice Swaps as little as possible of one token for `amountOut` of another token /// @dev Initiate a transaction with a known output amount and return the input amount /// @param self Mapping path /// @param from Input token address /// @param to Output token address /// @param recipient Recipient address /// @param amountOut Token out amount /// @param amountInMaximum Expect to input the maximum amount of tokens /// @return Token in amount function exactOutput( mapping(address => mapping(address => bytes)) storage self, address from, address to, address recipient, uint256 amountOut, uint256 amountInMaximum ) internal returns (uint256){ bytes memory path = self[to][from]; return SRT.exactOutput( ISwapRouter.ExactOutputParams({ path : path, recipient : recipient, deadline : block.timestamp, amountOut : amountOut, amountInMaximum : amountInMaximum })); } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.6.0; import './BytesLib.sol'; /// @title Functions for manipulating path data for multihop swaps library Path { using BytesLib for bytes; /// @dev The length of the bytes encoded address uint256 private constant ADDR_SIZE = 20; /// @dev The length of the bytes encoded fee uint256 private constant FEE_SIZE = 3; /// @dev The offset of a single token address and pool fee uint256 private constant NEXT_OFFSET = ADDR_SIZE + FEE_SIZE; /// @dev The offset of an encoded pool key uint256 private constant POP_OFFSET = NEXT_OFFSET + ADDR_SIZE; /// @dev The minimum length of an encoding that contains 2 or more pools uint256 private constant MULTIPLE_POOLS_MIN_LENGTH = POP_OFFSET + NEXT_OFFSET; /// @notice Check the legitimacy of the path /// @param path The encoded swap path /// @return Legal path function valid(bytes memory path)internal pure returns(bool) { return path.length>=POP_OFFSET; } /// @notice Returns true iff the path contains two or more pools /// @param path The encoded swap path /// @return True if path contains two or more pools, otherwise false function hasMultiplePools(bytes memory path) internal pure returns (bool) { return path.length >= MULTIPLE_POOLS_MIN_LENGTH; } /// @notice Decodes the first pool in path /// @param path The bytes encoded swap path /// @return tokenA The first token of the given pool /// @return tokenB The second token of the given pool /// @return fee The fee level of the pool function decodeFirstPool(bytes memory path) internal pure returns ( address tokenA, address tokenB, uint24 fee ) { tokenA = path.toAddress(0); fee = path.toUint24(ADDR_SIZE); tokenB = path.toAddress(NEXT_OFFSET); } /// @notice Gets the segment corresponding to the first pool in the path /// @param path The bytes encoded swap path /// @return The segment containing all data necessary to target the first pool in the path function getFirstPool(bytes memory path) internal pure returns (bytes memory) { return path.slice(0, POP_OFFSET); } /// @notice Gets the segment corresponding to the last pool in the path /// @param path The bytes encoded swap path /// @return The segment containing all data necessary to target the last pool in the path function getLastPool(bytes memory path) internal pure returns (bytes memory) { if(path.length==POP_OFFSET){ return path; }else{ return path.slice(path.length-POP_OFFSET, path.length); } } /// @notice Gets the first address of the path /// @param path The encoded swap path /// @return address function getFirstAddress(bytes memory path)internal pure returns(address){ return path.toAddress(0); } /// @notice Gets the last address of the path /// @param path The encoded swap path /// @return address function getLastAddress(bytes memory path)internal pure returns(address){ return path.toAddress(path.length-ADDR_SIZE); } /// @notice Skips a token + fee element from the buffer and returns the remainder /// @param path The swap path /// @return The remaining token + fee elements in the path function skipToken(bytes memory path) internal pure returns (bytes memory) { return path.slice(NEXT_OFFSET, path.length - NEXT_OFFSET); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; import "../storage/GovIdentityStorage.sol"; /// @title manager role /// @notice provide a unified identity address pool contract GovIdentity { constructor() { _init(); } function _init() internal{ GovIdentityStorage.Identity storage identity= GovIdentityStorage.load(); identity.governance = msg.sender; identity.rewards = msg.sender; identity.strategist[msg.sender]=true; identity.admin[msg.sender]=true; } modifier onlyAdmin() { GovIdentityStorage.Identity storage identity= GovIdentityStorage.load(); require(isAdmin(msg.sender), "!admin"); _; } modifier onlyStrategist() { require(isStrategist(msg.sender), "!strategist"); _; } modifier onlyGovernance() { GovIdentityStorage.Identity storage identity= GovIdentityStorage.load(); require(msg.sender == identity.governance, "!governance"); _; } modifier onlyStrategistOrGovernance() { GovIdentityStorage.Identity storage identity= GovIdentityStorage.load(); require(identity.strategist[msg.sender] || msg.sender == identity.governance, "!governance and !strategist"); _; } modifier onlyAdminOrGovernance() { GovIdentityStorage.Identity storage identity= GovIdentityStorage.load(); require(identity.admin[msg.sender] || msg.sender == identity.governance, "!governance and !admin"); _; } function setGovernance(address _governance) public onlyGovernance{ GovIdentityStorage.Identity storage identity= GovIdentityStorage.load(); identity.governance = _governance; } function setRewards(address _rewards) public onlyGovernance{ GovIdentityStorage.Identity storage identity= GovIdentityStorage.load(); identity.rewards = _rewards; } function setStrategist(address _strategist,bool enable) public onlyGovernance{ GovIdentityStorage.Identity storage identity= GovIdentityStorage.load(); identity.strategist[_strategist]=enable; } function setAdmin(address _admin,bool enable) public onlyGovernance{ GovIdentityStorage.Identity storage identity= GovIdentityStorage.load(); identity.admin[_admin]=enable; } function getGovernance() public view returns(address){ GovIdentityStorage.Identity storage identity= GovIdentityStorage.load(); return identity.governance; } function getRewards() public view returns(address){ GovIdentityStorage.Identity storage identity= GovIdentityStorage.load(); return identity.rewards ; } function isStrategist(address _strategist) public view returns(bool){ GovIdentityStorage.Identity storage identity= GovIdentityStorage.load(); return identity.strategist[_strategist]; } function isAdmin(address _admin) public view returns(bool){ GovIdentityStorage.Identity storage identity= GovIdentityStorage.load(); return identity.admin[_admin]; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // 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 (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @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) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * 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); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Provides functions for deriving a pool address from the factory, tokens, and the fee library PoolAddress { bytes32 internal constant POOL_INIT_CODE_HASH = 0xe34f199b19b2b4f47f68442619d555527d244f78a3297ea89325f843f87b8b54; //Uniswap V3 Factory address constant private factory = address(0x1F98431c8aD98523631AE4a59f267346ea31F984); /// @notice The identifying key of the pool struct PoolKey { address token0; address token1; uint24 fee; } /// @dev Returns the pool for the given token pair and fee. The pool contract may or may not exist. function getPool( address tokenA, address tokenB, uint24 fee ) internal pure returns (address) { return computeAddress(getPoolKey(tokenA, tokenB, fee)); } /// @notice Returns PoolKey: the ordered tokens with the matched fee levels /// @param tokenA The first token of a pool, unsorted /// @param tokenB The second token of a pool, unsorted /// @param fee The fee level of the pool /// @return Poolkey The pool details with ordered token0 and token1 assignments function getPoolKey( address tokenA, address tokenB, uint24 fee ) internal pure returns (PoolKey memory) { if (tokenA > tokenB) (tokenA, tokenB) = (tokenB, tokenA); return PoolKey({token0 : tokenA, token1 : tokenB, fee : fee}); } /// @notice Deterministically computes the pool address given the factory and PoolKey /// @param key The PoolKey /// @return pool The contract address of the V3 pool function computeAddress(PoolKey memory key) internal pure returns (address pool) { require(key.token0 < key.token1); pool = address( uint256( keccak256( abi.encodePacked( hex'ff', factory, keccak256(abi.encode(key.token0, key.token1, key.fee)), POOL_INIT_CODE_HASH ) ) ) ); } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.4.0; /// @title FixedPoint128 /// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format) library FixedPoint128 { uint256 internal constant Q128 = 0x100000000000000000000000000000000; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; import './FullMath.sol'; import './FixedPoint96.sol'; /// @title Liquidity amount functions /// @notice Provides functions for computing liquidity amounts from token amounts and prices library LiquidityAmounts { /// @notice Downcasts uint256 to uint128 /// @param x The uint258 to be downcasted /// @return y The passed value, downcasted to uint128 function toUint128(uint256 x) private pure returns (uint128 y) { require((y = uint128(x)) == x); } /// @notice Computes the amount of liquidity received for a given amount of token0 and price range /// @dev Calculates amount0 * (sqrt(upper) * sqrt(lower)) / (sqrt(upper) - sqrt(lower)) /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param amount0 The amount0 being sent in /// @return liquidity The amount of returned liquidity function getLiquidityForAmount0( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint256 amount0 ) internal pure returns (uint128 liquidity) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); uint256 intermediate = FullMath.mulDiv(sqrtRatioAX96, sqrtRatioBX96, FixedPoint96.Q96); return toUint128(FullMath.mulDiv(amount0, intermediate, sqrtRatioBX96 - sqrtRatioAX96)); } /// @notice Computes the amount of liquidity received for a given amount of token1 and price range /// @dev Calculates amount1 / (sqrt(upper) - sqrt(lower)). /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param amount1 The amount1 being sent in /// @return liquidity The amount of returned liquidity function getLiquidityForAmount1( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint256 amount1 ) internal pure returns (uint128 liquidity) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); return toUint128(FullMath.mulDiv(amount1, FixedPoint96.Q96, sqrtRatioBX96 - sqrtRatioAX96)); } /// @notice Computes the maximum amount of liquidity received for a given amount of token0, token1, the current /// pool prices and the prices at the tick boundaries /// @param sqrtRatioX96 A sqrt price representing the current pool prices /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param amount0 The amount of token0 being sent in /// @param amount1 The amount of token1 being sent in /// @return liquidity The maximum amount of liquidity received function getLiquidityForAmounts( uint160 sqrtRatioX96, uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint256 amount0, uint256 amount1 ) internal pure returns (uint128 liquidity) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); if (sqrtRatioX96 <= sqrtRatioAX96) { liquidity = getLiquidityForAmount0(sqrtRatioAX96, sqrtRatioBX96, amount0); } else if (sqrtRatioX96 < sqrtRatioBX96) { uint128 liquidity0 = getLiquidityForAmount0(sqrtRatioX96, sqrtRatioBX96, amount0); uint128 liquidity1 = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioX96, amount1); liquidity = liquidity0 < liquidity1 ? liquidity0 : liquidity1; } else { liquidity = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioBX96, amount1); } } /// @notice Computes the amount of token0 for a given amount of liquidity and a price range /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param liquidity The liquidity being valued /// @return amount0 The amount of token0 function getAmount0ForLiquidity( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity ) internal pure returns (uint256 amount0) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); return FullMath.mulDiv( uint256(liquidity) << FixedPoint96.RESOLUTION, sqrtRatioBX96 - sqrtRatioAX96, sqrtRatioBX96 ) / sqrtRatioAX96; } /// @notice Computes the amount of token1 for a given amount of liquidity and a price range /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param liquidity The liquidity being valued /// @return amount1 The amount of token1 function getAmount1ForLiquidity( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity ) internal pure returns (uint256 amount1) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); return FullMath.mulDiv(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96); } /// @notice Computes the token0 and token1 value for a given amount of liquidity, the current /// pool prices and the prices at the tick boundaries /// @param sqrtRatioX96 A sqrt price representing the current pool prices /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param liquidity The liquidity being valued /// @return amount0 The amount of token0 /// @return amount1 The amount of token1 function getAmountsForLiquidity( uint160 sqrtRatioX96, uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity ) internal pure returns (uint256 amount0, uint256 amount1) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); if (sqrtRatioX96 <= sqrtRatioAX96) { amount0 = getAmount0ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity); } else if (sqrtRatioX96 < sqrtRatioBX96) { amount0 = getAmount0ForLiquidity(sqrtRatioX96, sqrtRatioBX96, liquidity); amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioX96, liquidity); } else { amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity); } } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Math library for computing sqrt prices from ticks and vice versa /// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports /// prices between 2**-128 and 2**128 library TickMath { /// @dev The minimum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**-128 int24 internal constant MIN_TICK = - 887272; /// @dev The maximum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**128 int24 internal constant MAX_TICK = - MIN_TICK; /// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK) uint160 internal constant MIN_SQRT_RATIO = 4295128739; /// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK) uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342; /// @notice Calculates sqrt(1.0001^tick) * 2^96 /// @dev Throws if |tick| > max tick /// @param tick The input tick for the above formula /// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (token1/token0) /// at the given tick function getSqrtRatioAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) { uint256 absTick = tick < 0 ? uint256(- int256(tick)) : uint256(int256(tick)); require(absTick <= uint256(MAX_TICK), 'T'); uint256 ratio = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000; if (absTick & 0x2 != 0) ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128; if (absTick & 0x4 != 0) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128; if (absTick & 0x8 != 0) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128; if (absTick & 0x10 != 0) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128; if (absTick & 0x20 != 0) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128; if (absTick & 0x40 != 0) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128; if (absTick & 0x80 != 0) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128; if (absTick & 0x100 != 0) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128; if (absTick & 0x200 != 0) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128; if (absTick & 0x400 != 0) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128; if (absTick & 0x800 != 0) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128; if (absTick & 0x1000 != 0) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128; if (absTick & 0x2000 != 0) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128; if (absTick & 0x4000 != 0) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128; if (absTick & 0x8000 != 0) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128; if (absTick & 0x10000 != 0) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128; if (absTick & 0x20000 != 0) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128; if (absTick & 0x40000 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128; if (absTick & 0x80000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128; if (tick > 0) ratio = type(uint256).max / ratio; // this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96. // we then downcast because we know the result always fits within 160 bits due to our tick input constraint // we round up in the division so getTickAtSqrtRatio of the output price is always consistent sqrtPriceX96 = uint160((ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1)); } /// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio /// @dev Throws in case sqrtPriceX96 < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may /// ever return. /// @param sqrtPriceX96 The sqrt ratio for which to compute the tick as a Q64.96 /// @return tick The greatest tick for which the ratio is less than or equal to the input ratio function getTickAtSqrtRatio(uint160 sqrtPriceX96) internal pure returns (int24 tick) { // second inequality must be < because the price can never reach the price at the max tick require(sqrtPriceX96 >= MIN_SQRT_RATIO && sqrtPriceX96 < MAX_SQRT_RATIO, 'R'); uint256 ratio = uint256(sqrtPriceX96) << 32; uint256 r = ratio; uint256 msb = 0; assembly { let f := shl(7, gt(r, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(6, gt(r, 0xFFFFFFFFFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(5, gt(r, 0xFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(4, gt(r, 0xFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(3, gt(r, 0xFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(2, gt(r, 0xF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(1, gt(r, 0x3)) msb := or(msb, f) r := shr(f, r) } assembly { let f := gt(r, 0x1) msb := or(msb, f) } if (msb >= 128) r = ratio >> (msb - 127); else r = ratio << (127 - msb); int256 log_2 = (int256(msb) - 128) << 64; assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(63, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(62, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(61, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(60, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(59, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(58, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(57, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(56, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(55, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(54, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(53, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(52, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(51, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(50, f)) } int256 log_sqrt10001 = log_2 * 255738958999603826347141; // 128.128 number int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128); int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128); tick = tickLow == tickHi ? tickLow : getSqrtRatioAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow; } } // SPDX-License-Identifier: MIT pragma solidity >=0.5.0; /// @title The interface for a Uniswap V3 Pool /// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform /// to the ERC20 specification /// @dev The pool interface is broken up into many smaller pieces interface IUniswapV3Pool { /// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas /// when accessed externally. /// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value /// tick The current tick of the pool, i.e. according to the last tick transition that was run. /// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick /// boundary. /// observationIndex The index of the last oracle observation that was written, /// observationCardinality The current maximum number of observations stored in the pool, /// observationCardinalityNext The next maximum number of observations, to be updated when the observation. /// feeProtocol The protocol fee for both tokens of the pool. /// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0 /// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee. /// unlocked Whether the pool is currently locked to reentrancy function slot0() external view returns ( uint160 sqrtPriceX96, int24 tick, uint16 observationIndex, uint16 observationCardinality, uint16 observationCardinalityNext, uint8 feeProtocol, bool unlocked ); /// @notice The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool /// @dev This value can overflow the uint256 function feeGrowthGlobal0X128() external view returns (uint256); /// @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool /// @dev This value can overflow the uint256 function feeGrowthGlobal1X128() external view returns (uint256); /// @notice Look up information about a specific tick in the pool /// @param tick The tick to look up /// @return liquidityGross the total amount of position liquidity that uses the pool either as tick lower or /// tick upper, /// liquidityNet how much liquidity changes when the pool price crosses the tick, /// feeGrowthOutside0X128 the fee growth on the other side of the tick from the current tick in token0, /// feeGrowthOutside1X128 the fee growth on the other side of the tick from the current tick in token1, /// tickCumulativeOutside the cumulative tick value on the other side of the tick from the current tick /// secondsPerLiquidityOutsideX128 the seconds spent per liquidity on the other side of the tick from the current tick, /// secondsOutside the seconds spent on the other side of the tick from the current tick, /// initialized Set to true if the tick is initialized, i.e. liquidityGross is greater than 0, otherwise equal to false. /// Outside values can only be used if the tick is initialized, i.e. if liquidityGross is greater than 0. /// In addition, these values are only relative and must be used only in comparison to previous snapshots for /// a specific position. function ticks(int24 tick) external view returns ( uint128 liquidityGross, int128 liquidityNet, uint256 feeGrowthOutside0X128, uint256 feeGrowthOutside1X128, int56 tickCumulativeOutside, uint160 secondsPerLiquidityOutsideX128, uint32 secondsOutside, bool initialized ); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; pragma experimental ABIEncoderV2; interface INonfungiblePositionManager is IERC721 { /// @notice Returns the position information associated with a given token ID. /// @dev Throws if the token ID is not valid. /// @param tokenId The ID of the token that represents the position /// @return nonce The nonce for permits /// @return operator The address that is approved for spending /// @return token0 The address of the token0 for a specific pool /// @return token1 The address of the token1 for a specific pool /// @return fee The fee associated with the pool /// @return tickLower The lower end of the tick range for the position /// @return tickUpper The higher end of the tick range for the position /// @return liquidity The liquidity of the position /// @return feeGrowthInside0LastX128 The fee growth of token0 as of the last action on the individual position /// @return feeGrowthInside1LastX128 The fee growth of token1 as of the last action on the individual position /// @return tokensOwed0 The uncollected amount of token0 owed to the position as of the last computation /// @return tokensOwed1 The uncollected amount of token1 owed to the position as of the last computation function positions(uint256 tokenId) external view returns ( uint96 nonce, address operator, address token0, address token1, uint24 fee, int24 tickLower, int24 tickUpper, uint128 liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, uint128 tokensOwed0, uint128 tokensOwed1 ); struct MintParams { address token0; address token1; uint24 fee; int24 tickLower; int24 tickUpper; uint256 amount0Desired; uint256 amount1Desired; uint256 amount0Min; uint256 amount1Min; address recipient; uint256 deadline; } /// @notice Creates a new position wrapped in a NFT /// @dev Call this when the pool does exist and is initialized. Note that if the pool is created but not initialized /// a method does not exist, i.e. the pool is assumed to be initialized. /// @param params The params necessary to mint a position, encoded as `MintParams` in calldata /// @return tokenId The ID of the token that represents the minted position /// @return liquidity The amount of liquidity for this position /// @return amount0 The amount of token0 /// @return amount1 The amount of token1 function mint(MintParams calldata params) external payable returns ( uint256 tokenId, uint128 liquidity, uint256 amount0, uint256 amount1 ); struct IncreaseLiquidityParams { uint256 tokenId; uint256 amount0Desired; uint256 amount1Desired; uint256 amount0Min; uint256 amount1Min; uint256 deadline; } /// @notice Increases the amount of liquidity in a position, with tokens paid by the `msg.sender` /// @param params tokenId The ID of the token for which liquidity is being increased, /// amount0Desired The desired amount of token0 to be spent, /// amount1Desired The desired amount of token1 to be spent, /// amount0Min The minimum amount of token0 to spend, which serves as a slippage check, /// amount1Min The minimum amount of token1 to spend, which serves as a slippage check, /// deadline The time by which the transaction must be included to effect the change /// @return liquidity The new liquidity amount as a result of the increase /// @return amount0 The amount of token0 to acheive resulting liquidity /// @return amount1 The amount of token1 to acheive resulting liquidity function increaseLiquidity(IncreaseLiquidityParams calldata params) external payable returns ( uint128 liquidity, uint256 amount0, uint256 amount1 ); struct DecreaseLiquidityParams { uint256 tokenId; uint128 liquidity; uint256 amount0Min; uint256 amount1Min; uint256 deadline; } /// @notice Decreases the amount of liquidity in a position and accounts it to the position /// @param params tokenId The ID of the token for which liquidity is being decreased, /// amount The amount by which liquidity will be decreased, /// amount0Min The minimum amount of token0 that should be accounted for the burned liquidity, /// amount1Min The minimum amount of token1 that should be accounted for the burned liquidity, /// deadline The time by which the transaction must be included to effect the change /// @return amount0 The amount of token0 accounted to the position's tokens owed /// @return amount1 The amount of token1 accounted to the position's tokens owed function decreaseLiquidity(DecreaseLiquidityParams calldata params) external payable returns (uint256 amount0, uint256 amount1); struct CollectParams { uint256 tokenId; address recipient; uint128 amount0Max; uint128 amount1Max; } /// @notice Collects up to a maximum amount of fees owed to a specific position to the recipient /// @param params tokenId The ID of the NFT for which tokens are being collected, /// recipient The account that should receive the tokens, /// amount0Max The maximum amount of token0 to collect, /// amount1Max The maximum amount of token1 to collect /// @return amount0 The amount of fees collected in token0 /// @return amount1 The amount of fees collected in token1 function collect(CollectParams calldata params) external payable returns (uint256 amount0, uint256 amount1); /// @notice Burns a token ID, which deletes it from the NFT contract. The token must have 0 liquidity and all tokens /// must be collected first. /// @param tokenId The ID of the token that is being burned function burn(uint256 tokenId) external payable; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; // a library for performing various math operations library SafeMathExtends { uint256 internal constant BONE = 10 ** 18; // Add two numbers together checking for overflows function badd(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "ERR_ADD_OVERFLOW"); return c; } // subtract two numbers and return diffecerence when it underflows function bsubSign(uint256 a, uint256 b) internal pure returns (uint256, bool) { if (a >= b) { return (a - b, false); } else { return (b - a, true); } } // Subtract two numbers checking for underflows function bsub(uint256 a, uint256 b) internal pure returns (uint256) { (uint256 c, bool flag) = bsubSign(a, b); require(!flag, "ERR_SUB_UNDERFLOW"); return c; } // Multiply two 18 decimals numbers function bmul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c0 = a * b; require(a == 0 || c0 / a == b, "ERR_MUL_OVERFLOW"); uint256 c1 = c0 + (BONE / 2); require(c1 >= c0, "ERR_MUL_OVERFLOW"); uint256 c2 = c1 / BONE; return c2; } // Divide two 18 decimals numbers function bdiv(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "ERR_DIV_ZERO"); uint256 c0 = a * BONE; require(a == 0 || c0 / a == BONE, "ERR_DIV_INTERNAL"); // bmul overflow uint256 c1 = c0 + (b / 2); require(c1 >= c0, "ERR_DIV_INTERNAL"); // badd require uint256 c2 = c1 / b; return c2; } function min(uint x, uint y) internal pure returns (uint z) { z = x < y ? x : y; } // babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method) function sqrt(uint y) internal pure returns (uint z) { if (y > 3) { z = y; uint x = y / 2 + 1; while (x < z) { z = x; x = (y / x + x) / 2; } } else if (y != 0) { z = 1; } } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; pragma experimental ABIEncoderV2; import './IUniswapV3SwapCallback.sol'; /// @title Router token swapping functionality /// @notice Functions for swapping tokens via Uniswap V3 interface ISwapRouter is IUniswapV3SwapCallback { struct ExactInputSingleParams { address tokenIn; address tokenOut; uint24 fee; address recipient; uint256 deadline; uint256 amountIn; uint256 amountOutMinimum; uint160 sqrtPriceLimitX96; } /// @notice Swaps `amountIn` of one token for as much as possible of another token /// @param params The parameters necessary for the swap, encoded as `ExactInputSingleParams` in calldata /// @return amountOut The amount of the received token function exactInputSingle(ExactInputSingleParams calldata params) external payable returns (uint256 amountOut); struct ExactInputParams { bytes path; address recipient; uint256 deadline; uint256 amountIn; uint256 amountOutMinimum; } /// @notice Swaps `amountIn` of one token for as much as possible of another along the specified path /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactInputParams` in calldata /// @return amountOut The amount of the received token function exactInput(ExactInputParams calldata params) external payable returns (uint256 amountOut); struct ExactOutputSingleParams { address tokenIn; address tokenOut; uint24 fee; address recipient; uint256 deadline; uint256 amountOut; uint256 amountInMaximum; uint160 sqrtPriceLimitX96; } /// @notice Swaps as little as possible of one token for `amountOut` of another token /// @param params The parameters necessary for the swap, encoded as `ExactOutputSingleParams` in calldata /// @return amountIn The amount of the input token function exactOutputSingle(ExactOutputSingleParams calldata params) external payable returns (uint256 amountIn); struct ExactOutputParams { bytes path; address recipient; uint256 deadline; uint256 amountOut; uint256 amountInMaximum; } /// @notice Swaps as little as possible of one token for `amountOut` of another along the specified path (reversed) /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactOutputParams` in calldata /// @return amountIn The amount of the input token function exactOutput(ExactOutputParams calldata params) external payable returns (uint256 amountIn); } // SPDX-License-Identifier: GPL-2.0-or-later /* * @title Solidity Bytes Arrays Utils * @author Gonçalo Sá <[email protected]> * * @dev Bytes tightly packed arrays utility library for ethereum contracts written in Solidity. * The library lets you concatenate, slice and type cast bytes arrays both in memory and storage. */ pragma solidity >=0.5.0 <=0.8.0; library BytesLib { function slice( bytes memory _bytes, uint256 _start, uint256 _length ) internal pure returns (bytes memory) { require(_length + 31 >= _length, 'slice_overflow'); require(_start + _length >= _start, 'slice_overflow'); require(_bytes.length >= _start + _length, 'slice_outOfBounds'); bytes memory tempBytes; assembly { switch iszero(_length) case 0 { // Get a location of some free memory and store it in tempBytes as // Solidity does for memory variables. tempBytes := mload(0x40) // The first word of the slice result is potentially a partial // word read from the original array. To read it, we calculate // the length of that partial word and start copying that many // bytes into the array. The first word we copy will start with // data we don't care about, but the last `lengthmod` bytes will // land at the beginning of the contents of the new array. When // we're done copying, we overwrite the full first word with // the actual length of the slice. let lengthmod := and(_length, 31) // The multiplication in the next line is necessary // because when slicing multiples of 32 bytes (lengthmod == 0) // the following copy loop was copying the origin's length // and then ending prematurely not copying everything it should. let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod))) let end := add(mc, _length) for { // The multiplication in the next line has the same exact purpose // as the one above. let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start) } lt(mc, end) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { mstore(mc, mload(cc)) } mstore(tempBytes, _length) //update free-memory pointer //allocating the array padded to 32 bytes like the compiler does now mstore(0x40, and(add(mc, 31), not(31))) } //if we want a zero-length slice let's just return a zero-length array default { tempBytes := mload(0x40) //zero out the 32 bytes slice we are about to return //we need to do it because Solidity does not garbage collect mstore(tempBytes, 0) mstore(0x40, add(tempBytes, 0x20)) } } return tempBytes; } function toAddress(bytes memory _bytes, uint256 _start) internal pure returns (address) { require(_start + 20 >= _start, 'toAddress_overflow'); require(_bytes.length >= _start + 20, 'toAddress_outOfBounds'); address tempAddress; assembly { tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000) } return tempAddress; } function toUint24(bytes memory _bytes, uint256 _start) internal pure returns (uint24) { require(_start + 3 >= _start, 'toUint24_overflow'); require(_bytes.length >= _start + 3, 'toUint24_outOfBounds'); uint24 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x3), _start)) } return tempUint; } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.4.0; /// @title FixedPoint96 /// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format) /// @dev Used in SqrtPriceMath.sol library FixedPoint96 { uint8 internal constant RESOLUTION = 96; uint256 internal constant Q96 = 0x1000000000000000000000000; } // SPDX-License-Identifier: MIT pragma solidity >=0.4.0; /// @title Contains 512-bit math functions /// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision /// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits library FullMath { /// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0 /// @param a The multiplicand /// @param b The multiplier /// @param denominator The divisor /// @return result The 256-bit result /// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv function mulDiv( uint256 a, uint256 b, uint256 denominator ) internal pure returns (uint256 result) { // 512-bit multiply [prod1 prod0] = a * b // Compute the product mod 2**256 and mod 2**256 - 1 // then use the Chinese Remainder Theorem to reconstruct // the 512 bit result. The result is stored in two 256 // variables such that product = prod1 * 2**256 + prod0 uint256 prod0; // Least significant 256 bits of the product uint256 prod1; // Most significant 256 bits of the product assembly { let mm := mulmod(a, b, not(0)) prod0 := mul(a, b) prod1 := sub(sub(mm, prod0), lt(mm, prod0)) } // Handle non-overflow cases, 256 by 256 division if (prod1 == 0) { require(denominator > 0); assembly { result := div(prod0, denominator) } return result; } // Make sure the result is less than 2**256. // Also prevents denominator == 0 require(denominator > prod1); /////////////////////////////////////////////// // 512 by 256 division. /////////////////////////////////////////////// // Make division exact by subtracting the remainder from [prod1 prod0] // Compute remainder using mulmod uint256 remainder; assembly { remainder := mulmod(a, b, denominator) } // Subtract 256 bit number from 512 bit number assembly { prod1 := sub(prod1, gt(remainder, prod0)) prod0 := sub(prod0, remainder) } // Factor powers of two out of denominator // Compute largest power of two divisor of denominator. // Always >= 1. uint256 twos = - denominator & denominator; // Divide denominator by power of two assembly { denominator := div(denominator, twos) } // Divide [prod1 prod0] by the factors of two assembly { prod0 := div(prod0, twos) } // Shift in bits from prod1 into prod0. For this we need // to flip `twos` such that it is 2**256 / twos. // If twos is zero, then it becomes one assembly { twos := add(div(sub(0, twos), twos), 1) } prod0 |= prod1 * twos; // Invert denominator mod 2**256 // Now that denominator is an odd number, it has an inverse // modulo 2**256 such that denominator * inv = 1 mod 2**256. // Compute the inverse by starting with a seed that is correct // correct for four bits. That is, denominator * inv = 1 mod 2**4 uint256 inv = (3 * denominator) ^ 2; // Now use Newton-Raphson iteration to improve the precision. // Thanks to Hensel's lifting lemma, this also works in modular // arithmetic, doubling the correct bits in each step. inv *= 2 - denominator * inv; // inverse mod 2**8 inv *= 2 - denominator * inv; // inverse mod 2**16 inv *= 2 - denominator * inv; // inverse mod 2**32 inv *= 2 - denominator * inv; // inverse mod 2**64 inv *= 2 - denominator * inv; // inverse mod 2**128 inv *= 2 - denominator * inv; // inverse mod 2**256 // Because the division is now exact we can divide by multiplying // with the modular inverse of denominator. This will give us the // correct result modulo 2**256. Since the precoditions guarantee // that the outcome is less than 2**256, this is the final result. // We don't need to compute the high bits of the result and prod1 // is no longer required. result = prod0 * inv; return result; } /// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0 /// @param a The multiplicand /// @param b The multiplier /// @param denominator The divisor /// @return result The 256-bit result function mulDivRoundingUp( uint256 a, uint256 b, uint256 denominator ) internal pure returns (uint256 result) { result = mulDiv(a, b, denominator); if (mulmod(a, b, denominator) > 0) { require(result < type(uint256).max); result++; } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; import "../../introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; library GovIdentityStorage { bytes32 public constant govSlot = keccak256("GovIdentityStorage.storage.location"); struct Identity{ address governance; address rewards; mapping(address=>bool) strategist; mapping(address=>bool) admin; } function load() internal pure returns (Identity storage gov) { bytes32 loc = govSlot; assembly { gov.slot := loc } } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Callback for IUniswapV3PoolActions#swap /// @notice Any contract that calls IUniswapV3PoolActions#swap must implement this interface interface IUniswapV3SwapCallback { /// @notice Called to `msg.sender` after executing a swap via IUniswapV3Pool#swap. /// @dev In the implementation you must pay the pool tokens owed for the swap. /// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory. /// amount0Delta and amount1Delta can both be 0 if no tokens were swapped. /// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by /// the end of the swap. If positive, the callback must send that amount of token0 to the pool. /// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by /// the end of the swap. If positive, the callback must send that amount of token1 to the pool. /// @param data Any data passed through by the caller via the IUniswapV3PoolActions#swap call function uniswapV3SwapCallback( int256 amount0Delta, int256 amount1Delta, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); }
Returns the pool for the given token pair and fee. The pool contract may or may not exist.
function getPool( address tokenA, address tokenB, uint24 fee ) internal pure returns (address) { return computeAddress(getPoolKey(tokenA, tokenB, fee)); }
5,843,902
./full_match/1/0xcafea44b2cd8b35Ff4cd86b9E58D8D0d098b8cDC/sources/contracts/modules/staking/StakingProducts.sol
initialize array for all possible products filter out products that are not in this pool Get current effectiveWeight
function recalculateEffectiveWeightsForAllProducts(uint poolId) external { uint productsCount = ICover(coverContract).productsCount(); IStakingPool stakingPool = getStakingPool(poolId); uint[] memory productIdsRaw = new uint[](productsCount); uint stakingPoolProductCount; for (uint i = 0; i < productsCount; i++) { if (_products[poolId][i].bumpedPriceUpdateTime == 0) { continue; } productIdsRaw[stakingPoolProductCount++] = i; } for (uint i = 0; i < stakingPoolProductCount; i++) { productIds[i] = productIdsRaw[i]; } ( uint globalCapacityRatio, ) = ICover(coverContract).getPriceAndCapacityRatios(productIds); uint _totalEffectiveWeight; for (uint i = 0; i < stakingPoolProductCount; i++) { uint productId = productIds[i]; StakedProduct memory _product = _products[poolId][productId]; _product.lastEffectiveWeight = _getEffectiveWeight( stakingPool, productId, _product.targetWeight, globalCapacityRatio, capacityReductionRatios[i] ); _totalEffectiveWeight += _product.lastEffectiveWeight; _products[poolId][productId] = _product; } weights[poolId].totalEffectiveWeight = _totalEffectiveWeight.toUint32(); }
4,831,767
pragma solidity 0.6.12; interface IAdmin { function isAdmin(address user) external view returns (bool); } // File @openzeppelin/contracts/token/ERC20/[email protected] /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File @openzeppelin/contracts/math/[email protected] /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // 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 (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @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) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * 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); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // File @openzeppelin/contracts/utils/[email protected] pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File @openzeppelin/contracts/token/ERC20/[email protected] pragma solidity >=0.6.0 <0.8.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // 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' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File contracts/interfaces/ISalesFactory.sol pragma solidity 0.6.12; interface ISalesFactory { function setSaleOwnerAndToken(address saleOwner, address saleToken) external; function isSaleCreatedThroughFactory(address sale) external view returns (bool); } // File contracts/interfaces/IAllocationStaking.sol pragma solidity 0.6.12; interface IAllocationStaking { function redistributeFame(uint256 _pid, address _user, uint256 _amountToBurn) external; function deposited(uint256 _pid, address _user) external view returns (uint256); function setTokensUnlockTime(uint256 _pid, address _user, uint256 _tokensUnlockTime) external; } // File contracts/sales/FantomSale.sol pragma solidity 0.6.12; contract FantomSale { using SafeMath for uint256; using SafeERC20 for IERC20; // Pointer to Allocation staking contract, where burnFameFromUser will be called. IAllocationStaking public allocationStakingContract; // Pointer to sales factory contract ISalesFactory public factory; // Admin contract IAdmin public admin; struct Sale { // Token being sold IERC20 token; // Is sale created bool isCreated; // Are earnings withdrawn bool earningsWithdrawn; // Is leftover withdrawn bool leftoverWithdrawn; // Have tokens been deposited bool tokensDeposited; // Address of sale owner address saleOwner; // Price of the token quoted in FTM uint256 tokenPriceInFTM; // Amount of tokens to sell uint256 amountOfTokensToSell; // Total tokens being sold uint256 totalTokensSold; // Total FTM Raised uint256 totalFTMRaised; // Sale end time uint256 saleEnd; // When tokens can be withdrawn uint256 tokensUnlockTime; } // Participation structure struct Participation { uint256 amountBought; uint256 amountFTMPaid; uint256 timeParticipated; uint256 roundId; bool[] isPortionWithdrawn; } // Round structure struct Round { uint256 startTime; uint256 maxParticipation; } struct Registration { uint256 registrationTimeStarts; uint256 registrationTimeEnds; uint256 numberOfRegistrants; } // Sale Sale public sale; // Registration Registration public registration; // Number of users participated in the sale. uint256 public numberOfParticipants; // Array storing IDS of rounds (IDs start from 1, so they can't be mapped as array indexes uint256[] public roundIds; // Mapping round Id to round mapping(uint256 => Round) public roundIdToRound; // Mapping user to his participation mapping(address => Participation) public userToParticipation; // User to round for which he registered mapping(address => uint256) public addressToRoundRegisteredFor; // mapping if user is participated or not mapping(address => bool) public isParticipated; // wei precision uint256 public constant one = 10**18; // Times when portions are getting unlocked uint256[] public vestingPortionsUnlockTime; // Percent of the participation user can withdraw uint256[] public vestingPercentPerPortion; //Precision for percent for portion vesting uint256 public portionVestingPrecision; // Added configurable round ID for staking round uint256 public stakingRoundId; // Max vesting time shift uint256 public maxVestingTimeShift; // Registration deposit FTM, which will be paid during the registration, and returned back during the participation. uint256 public registrationDepositFTM; // Accounting total FTM collected, after sale admin can withdraw this uint256 public registrationFees; // Restricting calls only to sale owner modifier onlySaleOwner() { require(msg.sender == sale.saleOwner, "OnlySaleOwner:: Restricted"); _; } modifier onlyAdmin() { require( admin.isAdmin(msg.sender), "Only admin can call this function." ); _; } // EVENTS event TokensSold(address user, uint256 amount); event UserRegistered(address user, uint256 roundId); event TokenPriceSet(uint256 newPrice); event MaxParticipationSet(uint256 roundId, uint256 maxParticipation); event TokensWithdrawn(address user, uint256 amount); event SaleCreated( address saleOwner, uint256 tokenPriceInFTM, uint256 amountOfTokensToSell, uint256 saleEnd, uint256 tokensUnlockTime ); event RegistrationTimeSet( uint256 registrationTimeStarts, uint256 registrationTimeEnds ); event RoundAdded( uint256 roundId, uint256 startTime, uint256 maxParticipation ); event RegistrationFTMRefunded(address user, uint256 amountRefunded); // Constructor, always initialized through SalesFactory constructor(address _admin, address _allocationStaking) public { require(_admin != address(0)); require(_allocationStaking != address(0)); admin = IAdmin(_admin); factory = ISalesFactory(msg.sender); allocationStakingContract = IAllocationStaking(_allocationStaking); } /// @notice Function to set vesting params function setVestingParams( uint256[] memory _unlockingTimes, uint256[] memory _percents, uint256 _maxVestingTimeShift ) external onlyAdmin { require( vestingPercentPerPortion.length == 0 && vestingPortionsUnlockTime.length == 0 ); require(_unlockingTimes.length == _percents.length); require(portionVestingPrecision > 0, "Safeguard for making sure setSaleParams get first called."); require(_maxVestingTimeShift <= 30 days, "Maximal shift is 30 days."); // Set max vesting time shift maxVestingTimeShift = _maxVestingTimeShift; uint256 sum; for (uint256 i = 0; i < _unlockingTimes.length; i++) { vestingPortionsUnlockTime.push(_unlockingTimes[i]); vestingPercentPerPortion.push(_percents[i]); sum += _percents[i]; } require(sum == portionVestingPrecision, "Percent distribution issue."); } function shiftVestingUnlockingTimes(uint256 timeToShift) external onlyAdmin { require( timeToShift > 0 && timeToShift < maxVestingTimeShift, "Shift must be nonzero and smaller than maxVestingTimeShift." ); // Time can be shifted only once. maxVestingTimeShift = 0; for (uint256 i = 0; i < vestingPortionsUnlockTime.length; i++) { vestingPortionsUnlockTime[i] = vestingPortionsUnlockTime[i].add( timeToShift ); } } /// @notice Admin function to set sale parameters function setSaleParams( address _token, address _saleOwner, uint256 _tokenPriceInFTM, uint256 _amountOfTokensToSell, uint256 _saleEnd, uint256 _tokensUnlockTime, uint256 _portionVestingPrecision, uint256 _stakingRoundId, uint256 _registrationDepositFTM ) external onlyAdmin { require(!sale.isCreated, "setSaleParams: Sale is already created."); require( _saleOwner != address(0), "setSaleParams: Sale owner address can not be 0." ); require( _tokenPriceInFTM != 0 && _amountOfTokensToSell != 0 && _saleEnd > block.timestamp && _tokensUnlockTime > block.timestamp, "setSaleParams: Bad input" ); require(_portionVestingPrecision >= 100, "Should be at least 100"); require(_stakingRoundId > 0, "Staking round ID can not be 0."); // Set params sale.token = IERC20(_token); sale.isCreated = true; sale.saleOwner = _saleOwner; sale.tokenPriceInFTM = _tokenPriceInFTM; sale.amountOfTokensToSell = _amountOfTokensToSell; sale.saleEnd = _saleEnd; sale.tokensUnlockTime = _tokensUnlockTime; // Deposit in FTM, sent during the registration registrationDepositFTM = _registrationDepositFTM; // Set portion vesting precision portionVestingPrecision = _portionVestingPrecision; // Set staking round id stakingRoundId = _stakingRoundId; // Emit event emit SaleCreated( sale.saleOwner, sale.tokenPriceInFTM, sale.amountOfTokensToSell, sale.saleEnd, sale.tokensUnlockTime ); } // @notice Function to retroactively set sale token address, can be called only once, // after initial contract creation has passed. Added as an options for teams which // are not having token at the moment of sale launch. function setSaleToken( address saleToken ) external onlyAdmin { require(address(sale.token) == address(0)); sale.token = IERC20(saleToken); } /// @notice Function to set registration period parameters function setRegistrationTime( uint256 _registrationTimeStarts, uint256 _registrationTimeEnds ) external onlyAdmin { require(sale.isCreated); require(registration.registrationTimeStarts == 0); require( _registrationTimeStarts >= block.timestamp && _registrationTimeEnds > _registrationTimeStarts ); require(_registrationTimeEnds < sale.saleEnd); if (roundIds.length > 0) { require( _registrationTimeEnds < roundIdToRound[roundIds[0]].startTime ); } registration.registrationTimeStarts = _registrationTimeStarts; registration.registrationTimeEnds = _registrationTimeEnds; emit RegistrationTimeSet( registration.registrationTimeStarts, registration.registrationTimeEnds ); } function setRounds( uint256[] calldata startTimes, uint256[] calldata maxParticipations ) external onlyAdmin { require(sale.isCreated); require( startTimes.length == maxParticipations.length, "setRounds: Bad input." ); require(roundIds.length == 0, "setRounds: Rounds are set already."); require(startTimes.length > 0); uint256 lastTimestamp = 0; for (uint256 i = 0; i < startTimes.length; i++) { require(startTimes[i] > registration.registrationTimeEnds); require(startTimes[i] < sale.saleEnd); require(startTimes[i] >= block.timestamp); require(maxParticipations[i] > 0); require(startTimes[i] > lastTimestamp); lastTimestamp = startTimes[i]; // Compute round Id uint256 roundId = i + 1; // Push id to array of ids roundIds.push(roundId); // Create round Round memory round = Round(startTimes[i], maxParticipations[i]); // Map round id to round roundIdToRound[roundId] = round; // Fire event emit RoundAdded(roundId, round.startTime, round.maxParticipation); } } /// @notice Registration for sale. /// @param roundId is the round for which user expressed interest to participate function registerForSale(uint256 roundId) external payable { require( msg.value == registrationDepositFTM, "Registration deposit does not match." ); require(roundId != 0, "Round ID can not be 0."); require(roundId <= roundIds.length, "Invalid round id"); require( block.timestamp >= registration.registrationTimeStarts && block.timestamp <= registration.registrationTimeEnds, "Registration gate is closed." ); require( addressToRoundRegisteredFor[msg.sender] == 0, "User can not register twice." ); // Rounds are 1,2,3 addressToRoundRegisteredFor[msg.sender] = roundId; // Special cases for staking round if (roundId == stakingRoundId) { // Lock users stake allocationStakingContract.setTokensUnlockTime( 0, msg.sender, sale.saleEnd ); } // Increment number of registered users registration.numberOfRegistrants++; // Increase earnings from registration fees registrationFees = registrationFees.add(msg.value); // Emit Registration event emit UserRegistered(msg.sender, roundId); } /// @notice Admin function, to update token price before sale to match the closest $ desired rate. /// @dev This will be updated with an oracle during the sale every N minutes, so the users will always /// pay initialy set $ value of the token. This is to reduce reliance on the FTM volatility. function updateTokenPriceInFTM(uint256 price) external onlyAdmin { require(price > 0, "Price can not be 0."); // Allowing oracle to run and change the sale value sale.tokenPriceInFTM = price; emit TokenPriceSet(price); } /// @notice Admin function to postpone the sale function postponeSale(uint256 timeToShift) external onlyAdmin { require( block.timestamp < roundIdToRound[roundIds[0]].startTime, "1st round already started." ); // Iterate through all registered rounds and postpone them for (uint256 i = 0; i < roundIds.length; i++) { Round storage round = roundIdToRound[roundIds[i]]; // Postpone sale round.startTime = round.startTime.add(timeToShift); require( round.startTime + timeToShift < sale.saleEnd, "Start time can not be greater than end time." ); } } /// @notice Function to extend registration period function extendRegistrationPeriod(uint256 timeToAdd) external onlyAdmin { require( registration.registrationTimeEnds.add(timeToAdd) < roundIdToRound[roundIds[0]].startTime, "Registration period overflows sale start." ); registration.registrationTimeEnds = registration .registrationTimeEnds .add(timeToAdd); } /// @notice Admin function to set max participation cap per round function setCapPerRound(uint256[] calldata rounds, uint256[] calldata caps) external onlyAdmin { require( block.timestamp < roundIdToRound[roundIds[0]].startTime, "1st round already started." ); require(rounds.length == caps.length, "Arrays length is different."); for (uint256 i = 0; i < rounds.length; i++) { require(caps[i] > 0, "Can't set max participation to 0"); Round storage round = roundIdToRound[rounds[i]]; round.maxParticipation = caps[i]; emit MaxParticipationSet(rounds[i], round.maxParticipation); } } // Function for owner to deposit tokens, can be called only once. function depositTokens() external onlySaleOwner { require( !sale.tokensDeposited, "Deposit can be done only once" ); sale.tokensDeposited = true; sale.token.safeTransferFrom( msg.sender, address(this), sale.amountOfTokensToSell ); } // Function to participate in the sales function participate( uint256 amount, uint256 amountFameToBurn, uint256 roundId ) external payable { require(roundId != 0, "Round can not be 0."); require( amount <= roundIdToRound[roundId].maxParticipation, "Overflowing maximal participation for this round." ); // User must have registered for the round in advance require( addressToRoundRegisteredFor[msg.sender] == roundId, "Not registered for this round" ); // Check user haven't participated before require(!isParticipated[msg.sender], "User can participate only once."); // Disallow contract calls. require(msg.sender == tx.origin, "Only direct contract calls."); // Get current active round uint256 currentRound = getCurrentRound(); // Assert that require( roundId == currentRound, "You can not participate in this round." ); // Compute the amount of tokens user is buying uint256 amountOfTokensBuying = (msg.value).mul(one).div( sale.tokenPriceInFTM ); // Must buy more than 0 tokens require(amountOfTokensBuying > 0, "Can't buy 0 tokens"); // Check in terms of user allo require( amountOfTokensBuying <= amount, "Trying to buy more than allowed." ); // Increase amount of sold tokens sale.totalTokensSold = sale.totalTokensSold.add(amountOfTokensBuying); // Increase amount of FTM raised sale.totalFTMRaised = sale.totalFTMRaised.add(msg.value); bool[] memory _isPortionWithdrawn = new bool[]( vestingPortionsUnlockTime.length ); // Create participation object Participation memory p = Participation({ amountBought: amountOfTokensBuying, amountFTMPaid: msg.value, timeParticipated: block.timestamp, roundId: roundId, isPortionWithdrawn: _isPortionWithdrawn }); // Staking round only. if (roundId == stakingRoundId) { // Burn FAME from this user. allocationStakingContract.redistributeFame( 0, msg.sender, amountFameToBurn ); } // Add participation for user. userToParticipation[msg.sender] = p; // Mark user is participated isParticipated[msg.sender] = true; // Increment number of participants in the Sale. numberOfParticipants++; // Decrease of available registration fees registrationFees = registrationFees.sub(registrationDepositFTM); // Transfer registration deposit amount in FTM back to the users. safeTransferFTM(msg.sender, registrationDepositFTM); emit RegistrationFTMRefunded(msg.sender, registrationDepositFTM); emit TokensSold(msg.sender, amountOfTokensBuying); } /// Users can claim their participation function withdrawTokens(uint256 portionId) external { require( block.timestamp >= sale.tokensUnlockTime, "Tokens can not be withdrawn yet." ); require(portionId < vestingPercentPerPortion.length); Participation storage p = userToParticipation[msg.sender]; if ( !p.isPortionWithdrawn[portionId] && vestingPortionsUnlockTime[portionId] <= block.timestamp ) { p.isPortionWithdrawn[portionId] = true; uint256 amountWithdrawing = p .amountBought .mul(vestingPercentPerPortion[portionId]) .div(portionVestingPrecision); // Withdraw percent which is unlocked at that portion if(amountWithdrawing > 0) { sale.token.safeTransfer(msg.sender, amountWithdrawing); emit TokensWithdrawn(msg.sender, amountWithdrawing); } } else { revert("Tokens already withdrawn or portion not unlocked yet."); } } // Expose function where user can withdraw multiple unlocked portions at once. function withdrawMultiplePortions(uint256 [] calldata portionIds) external { uint256 totalToWithdraw = 0; Participation storage p = userToParticipation[msg.sender]; for(uint i=0; i < portionIds.length; i++) { uint256 portionId = portionIds[i]; require(portionId < vestingPercentPerPortion.length); if ( !p.isPortionWithdrawn[portionId] && vestingPortionsUnlockTime[portionId] <= block.timestamp ) { p.isPortionWithdrawn[portionId] = true; uint256 amountWithdrawing = p .amountBought .mul(vestingPercentPerPortion[portionId]) .div(portionVestingPrecision); // Withdraw percent which is unlocked at that portion totalToWithdraw = totalToWithdraw.add(amountWithdrawing); } } if(totalToWithdraw > 0) { sale.token.safeTransfer(msg.sender, totalToWithdraw); emit TokensWithdrawn(msg.sender, totalToWithdraw); } } // Internal function to handle safe transfer function safeTransferFTM(address to, uint256 value) internal { (bool success, ) = to.call{value: value}(new bytes(0)); require(success); } /// Function to withdraw all the earnings and the leftover of the sale contract. function withdrawEarningsAndLeftover() external onlySaleOwner { withdrawEarningsInternal(); withdrawLeftoverInternal(); } // Function to withdraw only earnings function withdrawEarnings() external onlySaleOwner { withdrawEarningsInternal(); } // Function to withdraw only leftover function withdrawLeftover() external onlySaleOwner { withdrawLeftoverInternal(); } // function to withdraw earnings function withdrawEarningsInternal() internal { // Make sure sale ended require(block.timestamp >= sale.saleEnd); // Make sure owner can't withdraw twice require(!sale.earningsWithdrawn); sale.earningsWithdrawn = true; // Earnings amount of the owner in FTM uint256 totalProfit = sale.totalFTMRaised; safeTransferFTM(msg.sender, totalProfit); } // Function to withdraw leftover function withdrawLeftoverInternal() internal { // Make sure sale ended require(block.timestamp >= sale.saleEnd); // Make sure owner can't withdraw twice require(!sale.leftoverWithdrawn); sale.leftoverWithdrawn = true; // Amount of tokens which are not sold uint256 leftover = sale.amountOfTokensToSell.sub(sale.totalTokensSold); if (leftover > 0) { sale.token.safeTransfer(msg.sender, leftover); } } // Function after sale for admin to withdraw registration fees if there are any left. function withdrawRegistrationFees() external onlyAdmin { require(block.timestamp >= sale.saleEnd, "Require that sale has ended."); require(registrationFees > 0, "No earnings from registration fees."); // Transfer FTM to the admin wallet. safeTransferFTM(msg.sender, registrationFees); // Set registration fees to be 0 registrationFees = 0; } // Function where admin can withdraw all unused funds. function withdrawUnusedFunds() external onlyAdmin { uint256 balanceFTM = address(this).balance; uint256 totalReservedForRaise = sale.earningsWithdrawn ? 0 : sale.totalFTMRaised; safeTransferFTM( msg.sender, balanceFTM.sub(totalReservedForRaise.add(registrationFees)) ); } // Function to act as a fallback and handle receiving FTM. receive() external payable { } /// @notice Get current round in progress. /// If 0 is returned, means sale didn't start or it's ended. function getCurrentRound() public view returns (uint256) { uint256 i = 0; if (block.timestamp < roundIdToRound[roundIds[0]].startTime) { return 0; // Sale didn't start yet. } while ( (i + 1) < roundIds.length && block.timestamp > roundIdToRound[roundIds[i + 1]].startTime ) { i++; } if (block.timestamp >= sale.saleEnd) { return 0; // Means sale is ended } return roundIds[i]; } /// @notice Function to get participation for passed user address function getParticipation(address _user) external view returns ( uint256, uint256, uint256, uint256, bool[] memory ) { Participation memory p = userToParticipation[_user]; return ( p.amountBought, p.amountFTMPaid, p.timeParticipated, p.roundId, p.isPortionWithdrawn ); } /// @notice Function to get number of registered users for sale function getNumberOfRegisteredUsers() external view returns (uint256) { return registration.numberOfRegistrants; } /// @notice Function to get all info about vesting. function getVestingInfo() external view returns (uint256[] memory, uint256[] memory) { return (vestingPortionsUnlockTime, vestingPercentPerPortion); } } // File contracts/sales/SalesFactory.sol pragma solidity 0.6.12; contract SalesFactory { IAdmin public admin; address public allocationStaking; mapping (address => bool) public isSaleCreatedThroughFactory; mapping(address => address) public saleOwnerToSale; mapping(address => address) public tokenToSale; // Expose so query can be possible only by position as well address [] public allSales; event SaleDeployed(address saleContract); event SaleOwnerAndTokenSetInFactory(address sale, address saleOwner, address saleToken); modifier onlyAdmin { require(admin.isAdmin(msg.sender), "Only Admin can deploy sales"); _; } constructor (address _adminContract, address _allocationStaking) public { admin = IAdmin(_adminContract); allocationStaking = _allocationStaking; } // Set allocation staking contract address. function setAllocationStaking(address _allocationStaking) public onlyAdmin { require(_allocationStaking != address(0)); allocationStaking = _allocationStaking; } function deploySale() external onlyAdmin { FantomSale sale = new FantomSale(address(admin), allocationStaking); isSaleCreatedThroughFactory[address(sale)] = true; allSales.push(address(sale)); emit SaleDeployed(address(sale)); } // Function to return number of pools deployed function getNumberOfSalesDeployed() external view returns (uint) { return allSales.length; } // Function function getLastDeployedSale() external view returns (address) { // if(allSales.length > 0) { return allSales[allSales.length - 1]; } return address(0); } // Function to get all sales function getAllSales(uint startIndex, uint endIndex) external view returns (address[] memory) { require(endIndex > startIndex, "Bad input"); address[] memory sales = new address[](endIndex - startIndex); uint index = 0; for(uint i = startIndex; i < endIndex; i++) { sales[index] = allSales[i]; index++; } return sales; } }
Admin function to set max participation cap per round
function setCapPerRound(uint256[] calldata rounds, uint256[] calldata caps) external onlyAdmin { require( block.timestamp < roundIdToRound[roundIds[0]].startTime, "1st round already started." ); require(rounds.length == caps.length, "Arrays length is different."); for (uint256 i = 0; i < rounds.length; i++) { require(caps[i] > 0, "Can't set max participation to 0"); Round storage round = roundIdToRound[rounds[i]]; round.maxParticipation = caps[i]; emit MaxParticipationSet(rounds[i], round.maxParticipation); } }
12,826,363
./full_match/1/0x5128fb075c5F770bfC53152aBB37A62BB9dBf723/sources/contracts/lib/SolvencyV2.sol
Calculates theoretical value (in quote token) that user can borrow based on deposited collateral _siloRepository SiloRepository address _silo Silo address _assets array with assets _ltvType type of LTV limit to use for calculations acceptable values are only TypeofLTV.MaximumLTV or TypeofLTV.LiquidationThreshold _collateralValues value (worth in quote token) of each deposit made by user return totalAvailableToBorrowValue value (in quote token) that user can borrow against collaterals
function _getTotalAvailableToBorrowValue( ISiloRepository _siloRepository, address _silo, address[] memory _assets, TypeofLTV _ltvType, uint256[] memory _collateralValues ) private view returns (uint256 totalAvailableToBorrowValue) { if (_assets.length != _collateralValues.length) revert DifferentArrayLength(); for (uint256 i = 0; i < _assets.length; i++) { totalAvailableToBorrowValue += _getAvailableToBorrowValue( _siloRepository, _silo, _assets[i], _ltvType, _collateralValues[i] ); } }
3,141,009
pragma solidity ^0.6.0; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } contract PredictionMarket is Ownable { /** * ------------------------------------- * ------------------------------------- * MARKETS * ------------------------------------- * Only 3 options are allowed * TODO: Allow for more * **/ enum MarketState {CLOSED, OPEN, PENDING_RESOLUTION, RESOLVED} struct Market { bytes32 fromToken; bytes32 toToken; // Resolver addr address aggregatorAddress; // Stake bool optionsConfigured; uint256 totalStakedOpt1; uint256 totalStakedOpt2; uint256 totalStakedOpt3; // Open and Close uint256 opensAt; uint256 closesAt; // Forecast time uint256 forecastTime; MarketState state; } uint256 marketId = 0; mapping(uint256 => Market) markets; /** * ------------------------------------- * ------------------------------------- * OPTIONS. * ------------------------------------- * * opening and closing price ranges for each option * Option Nos. - 1, 2, 3 * **/ struct OptionRange { int256 startPrice; int256 endPrice; } mapping(uint256 => mapping(uint256 => OptionRange)) optionInfoForMarket; /** * ------------------------------------- * ------------------------------------- * STAKE INFO. * ------------------------------------- * * User stake details including the optionNo chosen and * amount staked for that particular option **/ struct Stake { uint8 optionNo; uint256 amt; } mapping(uint256 => mapping(address => Stake)) userStakeInfoForAMkt; // Update winning option for market on resolution mapping(uint256 => uint256) winningOptForMkt; /** * ------------------------------------- * ------------------------------------- * EVENTS * ------------------------------------- **/ event MarketCreated(uint256 indexed _marketId); event UserStaked( address indexed _user, uint256 indexed _marketId, uint256 indexed _optionNo, uint256 _amount ); /** * ------------------------------------- * ------------------------------------- * MODIFIERS * ------------------------------------- **/ modifier marketExists(uint256 _marketId) { require( markets[_marketId].aggregatorAddress != address(0), "Market not exists" ); _; } // Checks if a market is OPEN // If it is not, tries to compare openingTime, update state to OPEN // and then tries to proceed modifier marketOpen(uint256 _marketId) { if (markets[_marketId].state != MarketState.OPEN) { updateMarketStateBasedOnTime(_marketId); } require( markets[_marketId].state == MarketState.OPEN, "Market not yet open" ); _; } // Identify if a market is waiting to be resolved modifier marketToBeResolved(uint256 _marketId) { require( markets[_marketId].state != MarketState.RESOLVED, "already resolved" ); if (markets[_marketId].state != MarketState.PENDING_RESOLUTION) { updateMarketStateBasedOnTime(_marketId); } require( markets[_marketId].state == MarketState.PENDING_RESOLUTION, "Market state not pending resln." ); _; } /** * ------------------------------------- * ------------------------------------- * CORE LOGIC * ------------------------------------- **/ /** * Add a new Market * * @param _aggregatorAddress - Chainlink Aggregator address * For e.g., BTC/USDT * @param _fromToken - * @param _toToken - * @param _opensAt - Market opening time * @param _closesAt - Bids close at * Ideally 30-45 min gap to forecast time * @param _forecastAt - Forecast time **/ function addMarket( IAggregator _aggregatorAddress, bytes32 _fromToken, bytes32 _toToken, uint256 _opensAt, uint256 _closesAt, uint256 _forecastAt ) public onlyOwner returns (uint256 _marketId) { _marketId = marketId++; markets[_marketId] = Market({ aggregatorAddress: address(_aggregatorAddress), fromToken: _fromToken, toToken: _toToken, optionsConfigured: false, totalStakedOpt1: 0, totalStakedOpt2: 0, totalStakedOpt3: 0, opensAt: _opensAt, closesAt: _closesAt, forecastTime: _forecastAt, state: MarketState.CLOSED }); emit MarketCreated(_marketId); } /** * Configure options for the new Market * * Options are fixed at 3 right now. * Each option has a range startPrice and endPrice * * @param _marketId - MarketID concerned * @param _startPrices - Option starting ranges * @param _endPrices - Option end ranges **/ function configureOptionRanges( uint256 _marketId, int256[3] memory _startPrices, int256[3] memory _endPrices ) public onlyOwner marketExists(_marketId) { uint256 OPTION_START = 1; uint256 OPTION_END = 3; for (uint256 i = OPTION_START; i <= OPTION_END; i++) { optionInfoForMarket[_marketId][i] = OptionRange({ startPrice: _startPrices[i - 1], endPrice: _endPrices[i - 1] }); } markets[_marketId].optionsConfigured = true; } /** * Stake on a marketID against a given option * * @param _marketId - * @param _optionNo - **/ function stake(uint256 _marketId, uint256 _optionNo) public payable marketOpen(_marketId) { require(msg.value > 0, "Invalid amount"); userStakeInfoForAMkt[_marketId][msg.sender] = Stake({ optionNo: uint8(_optionNo), amt: msg.value }); if (_optionNo == 1) { markets[_marketId].totalStakedOpt1 += msg.value; } else if (_optionNo == 2) { markets[_marketId].totalStakedOpt2 += msg.value; } else if (_optionNo == 3) { markets[_marketId].totalStakedOpt3 += msg.value; } emit UserStaked(msg.sender, _marketId, _optionNo, msg.value); } /** * Resolve a market specifying the roundID of the aggregatorAddress * * Contract will look up the timestamp of the roundID as a sanity check. * If it falls within a range of 3 min from the forecastTime, * the answer corr. to latest round ID is accepted. * * @notice - 3 mins cuz in case of high gas price conditions, * chainlink oracle updates to Aggregator might be slower * * Beyond 3 minutes, the market is discarded * * @param _marketId - * @param _roundId - RoundID of the Aggregator at which * the answer to the price forecast might be found **/ function resolve(uint256 _marketId, uint256 _roundId) public marketToBeResolved(_marketId) { Market memory _market = markets[_marketId]; uint256 timestamp = IAggregator(_market.aggregatorAddress).getTimestamp( _roundId ); int256 price = IAggregator(_market.aggregatorAddress).getAnswer( _roundId ); // Timestamp should be a max of +3 mins from forecastTime uint256 diff = timestamp - _market.forecastTime; // TODO: Handle in case diff is too large require(diff <= 3 minutes, "Diff too large"); uint256 OPTION_START = 1; uint256 OPTION_END = 3; for (uint256 i = OPTION_START; i <= OPTION_END; i++) { OptionRange memory _range = optionInfoForMarket[_marketId][i]; if (price >= _range.startPrice && price < _range.endPrice) { winningOptForMkt[_marketId] = i; break; } } markResolved(_marketId); } function updateMarketStateBasedOnTime(uint256 _marketId) internal { // Options not yet configured; Do not allow auto status changes if (markets[_marketId].optionsConfigured == false) { return; } if (block.timestamp < markets[_marketId].opensAt) { markets[_marketId].state = MarketState.CLOSED; return; } else if ( block.timestamp >= markets[_marketId].opensAt && block.timestamp <= markets[_marketId].closesAt ) { markets[_marketId].state = MarketState.OPEN; return; } else if (block.timestamp > markets[_marketId].closesAt) { markets[_marketId].state = MarketState.PENDING_RESOLUTION; } } function markResolved(uint256 _marketId) internal { markets[_marketId].state = MarketState.RESOLVED; } /** * Claim winnings if any * * @param _marketId - **/ function claimWinnings(uint256 _marketId) public { uint256 winAmt = getUserWinnings(_marketId, msg.sender); delete userStakeInfoForAMkt[_marketId][msg.sender]; if(winAmt > 0) { msg.sender.transfer(winAmt); } } /** * @dev This fn. is only needed to handle special cases * * For e.g., in a market when every bidder chooses the wrong option, * ETH is basically stuck in the Contract * As of now, devs can claim this **/ function withdraw() public onlyOwner { msg.sender.transfer(address(this).balance); } /** * ------------------------------------- * ------------------------------------- * VIEW FNS. * ------------------------------------- **/ function getMarketState(uint256 _marketId) public view returns (MarketState _state) { Market memory _market = markets[_marketId]; _state = _market.state; if(_market.state == MarketState.RESOLVED) { return _market.state; } // Check/Reflect correct state based on time // Options not yet configured; if (_market.optionsConfigured == false) { return _state; } if (block.timestamp < _market.opensAt) { _state = MarketState.CLOSED; } else if ( block.timestamp >= _market.opensAt && block.timestamp <= _market.closesAt ) { _state = MarketState.OPEN; } else if (block.timestamp > _market.closesAt) { _state = MarketState.PENDING_RESOLUTION; } } /** * Get possible winnings of an user **/ function getUserWinnings(uint256 _marketId, address _user) public view returns (uint256 _userShare) { Market memory _market = markets[_marketId]; if(_market.state != MarketState.RESOLVED) { revert("Market not yet resolved"); } uint256 winningOpt = winningOptForMkt[_marketId]; ( , uint256 _totalStakedOpt1, uint256 _totalStakedOpt2, uint256 _totalStakedOpt3, , , ) = getMarket(_marketId); uint256 totalStaked = _totalStakedOpt1 + _totalStakedOpt2 + _totalStakedOpt3; (uint256 _userOptionNo, uint256 _userStakedAmt) = getUserStake( _marketId, _user ); // user is not winner if (winningOpt != _userOptionNo) { return 0; } if (winningOpt == 1) { _userShare = (totalStaked * _totalStakedOpt1) / _userStakedAmt; } else if (winningOpt == 2) { _userShare = (totalStaked * _totalStakedOpt2) / _userStakedAmt; } else if (winningOpt == 3) { _userShare = (totalStaked * _totalStakedOpt3) / _userStakedAmt; } } /** * Get user stake details **/ function getUserStake(uint256 _marketId, address _user) public view returns (uint256 _optionNo, uint256 _amt) { Stake memory _stake = userStakeInfoForAMkt[_marketId][_user]; _optionNo = _stake.optionNo; _amt = _stake.amt; } /** * Get market details **/ function getMarket(uint256 _marketId) public view returns ( address _aggregatorAddress, uint256 _totalStakedOpt1, uint256 _totalStakedOpt2, uint256 _totalStakedOpt3, uint256 _opensAt, uint256 _closesAt, uint256 _forecastTime ) { Market memory _market = markets[_marketId]; _aggregatorAddress = _market.aggregatorAddress; _totalStakedOpt1 = _market.totalStakedOpt1; _totalStakedOpt2 = _market.totalStakedOpt2; _totalStakedOpt3 = _market.totalStakedOpt3; _opensAt = _market.opensAt; _closesAt = _market.closesAt; _forecastTime = _market.forecastTime; } /** * Get market pair details **/ function getMarketPairs(uint256 _marketId) public view returns (bytes32 _fromToken, bytes32 _toToken) { Market memory _market = markets[_marketId]; _fromToken = _market.fromToken; _toToken = _market.toToken; } /** * Get option ranges for a given market **/ function getOptionInfo(uint256 _marketId, uint256 _optionNo) public view returns (int256, int256) { OptionRange memory _optionRange = optionInfoForMarket[_marketId][_optionNo]; return (_optionRange.startPrice, _optionRange.endPrice); } } /** * Interface to Chainlink aggregator **/ interface IAggregator { function latestAnswer() external view returns (int256); /** * @notice get the last updated at block timestamp */ function latestTimestamp() external view returns (uint256); function getAnswer(uint256 _roundId) external view returns (int256); /** * @notice get block timestamp when an answer was last updated * @param _roundId the answer number to retrieve the updated timestamp for */ function getTimestamp(uint256 _roundId) external view returns (uint256); }
Configure options for the new Market Options are fixed at 3 right now. Each option has a range startPrice and endPrice _marketId - MarketID concerned _startPrices - Option starting ranges _endPrices - Option end ranges/
function configureOptionRanges( uint256 _marketId, int256[3] memory _startPrices, int256[3] memory _endPrices ) public onlyOwner marketExists(_marketId) { uint256 OPTION_START = 1; uint256 OPTION_END = 3; for (uint256 i = OPTION_START; i <= OPTION_END; i++) { optionInfoForMarket[_marketId][i] = OptionRange({ startPrice: _startPrices[i - 1], endPrice: _endPrices[i - 1] }); } markets[_marketId].optionsConfigured = true; }
6,441,631
./partial_match/1/0xf6724DE38B1d91EBF50C1b621c253e6326F058c0/sources/ERC721ABigFoot.sol
Returns the rebuilt hash obtained by traversing a Merkle tree up from `leaf` using the multi proof as `proofFlag`. A multi proof is valid if the final hash matches the root of the tree. _Available since v4.7._/ This function rebuild the root hash by traversing the tree up from the leaves. The root is rebuilt by consuming and producing values on a queue. The queue starts with the `leafs` array, then goes onto the `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of the merkle tree. Check proof validity. The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop". At each step, we compute the next hash using two values: - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we get the next hash. - depending on the flag, either another value for the "main queue" (merging branches) or an element from the `proofs` array.
function processMultiProof( bytes32[] memory leafs, bytes32[] memory proofs, bool[] memory proofFlag ) internal pure returns (bytes32 merkleRoot) { uint256 leafsLen = leafs.length; uint256 proofsLen = proofs.length; uint256 totalHashes = proofFlag.length; require(leafsLen + proofsLen - 1 == totalHashes, "MerkleProof: invalid multiproof"); bytes32[] memory hashes = new bytes32[](totalHashes); uint256 leafPos = 0; uint256 hashPos = 0; uint256 proofPos = 0; for (uint256 i = 0; i < totalHashes; i++) { bytes32 a = leafPos < leafsLen ? leafs[leafPos++] : hashes[hashPos++]; bytes32 b = proofFlag[i] ? leafPos < leafsLen ? leafs[leafPos++] : hashes[hashPos++] : proofs[proofPos++]; hashes[i] = _hashPair(a, b); } return hashes[totalHashes - 1]; }
2,659,967
// SPDX-License-Identifier: MIT pragma solidity >=0.4.22 <0.9.0; import "@openzeppelin/contracts-upgradeable/utils/math/SafeMathUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol"; import "./CampaignFactory.sol"; import "./Campaign.sol"; import "../utils/Roles.sol"; import "../interfaces/ICampaignFactory.sol"; import "../interfaces/ICampaign.sol"; import "../utils/AccessControl.sol"; import "../libraries/contracts/CampaignFactoryLib.sol"; import "../libraries/contracts/CampaignLib.sol"; contract CampaignReward is Initializable, Roles, PausableUpgradeable { using SafeMathUpgradeable for uint256; /// @dev `Initializer Event` event CampaignRewardOwnerSet(address owner); /// @dev `Reward Events` event RewardCreated( uint256 indexed rewardId, uint256 value, uint256 deliveryDate, uint256 stock, string hashedReward, bool active ); event RewardModified( uint256 indexed rewardId, uint256 value, uint256 deliveryDate, uint256 stock, bool active ); event RewardStockIncreased(uint256 indexed rewardId, uint256 count); event RewardDestroyed(uint256 indexed rewardId); /// @dev `Rward Recipient Events` event RewardRecipientAdded( uint256 indexed rewardRecipientId, uint256 indexed rewardId, uint256 amount, address indexed user ); event RewarderApproval(uint256 indexed rewardRecipientId, bool status); event RewardRecipientApproval(uint256 indexed rewardRecipientId); ICampaignFactory public campaignFactoryInterface; ICampaign public campaignInterface; address public campaignRewardAddress; Campaign public campaign; /// @dev `Reward` struct Reward { uint256 value; uint256 deliveryDate; uint256 stock; string hashedReward; bool exists; bool active; } Reward[] public rewards; mapping(uint256 => uint256) public rewardToRewardRecipientCount; // number of users eligible per reward /// @dev `RewardRecipient` struct RewardRecipient { uint256 rewardId; address user; bool deliveryConfirmedByCampaign; bool deliveryConfirmedByUser; } RewardRecipient[] public rewardRecipients; mapping(address => uint256) public userRewardCount; // number of rewards owned by a user /// @dev Ensures a user is verified modifier userIsVerified(address _user) { bool verified; (, , verified) = CampaignFactoryLib.userInfo( campaignFactoryInterface, _user ); require(verified, "user not verified"); _; } /// @dev Ensures caller is a registered campaign contract from factory modifier onlyRegisteredCampaigns() { require(address(campaign) == msg.sender, "forbidden"); _; } /// @dev Ensures caller is campaign owner modifier hasRole(bytes32 _permission, address _user) { require(campaignInterface.isAllowed(_permission, _user)); _; } /** * @dev Constructor * @param _campaignFactory Address of factory * @param _campaign Address of campaign this contract belongs to */ function __CampaignReward_init( CampaignFactory _campaignFactory, Campaign _campaign ) public initializer { campaignFactoryInterface = ICampaignFactory(address(_campaignFactory)); campaignInterface = ICampaign(address(_campaign)); campaign = _campaign; campaignRewardAddress = address(this); emit CampaignRewardOwnerSet(msg.sender); } /** * @dev Creates rewards contributors can attain * @param _value Reward cost * @param _deliveryDate Time in which reward will be deliverd to contriutors * @param _stock Quantity available for dispatch * @param _hashedReward CID reference of the reward on IPFS * @param _active Indicates if contributors can attain the reward */ function createReward( uint256 _value, uint256 _deliveryDate, uint256 _stock, string memory _hashedReward, bool _active ) external hasRole(CREATE_REWARD, msg.sender) userIsVerified(msg.sender) { require( _value > CampaignFactoryLib.getCampaignFactoryConfig( campaignFactoryInterface, "minimumContributionAllowed" ), "amount too low" ); require( _value < CampaignFactoryLib.getCampaignFactoryConfig( campaignFactoryInterface, "maximumContributionAllowed" ), "amount too high" ); rewards.push( Reward(_value, _deliveryDate, _stock, _hashedReward, true, _active) ); emit RewardCreated( rewards.length.sub(1), _value, _deliveryDate, _stock, _hashedReward, _active ); } /** * @dev Assigns a reward to a user after payment from parent contract Campaign * @param _rewardId ID of the reward being assigned * @param _amount Amount being paid by the user * @param _user Address of user reward is being assigned to */ function assignReward( uint256 _rewardId, uint256 _amount, address _user ) external onlyRegisteredCampaigns userIsVerified(_user) returns (uint256) { require(_amount >= rewards[_rewardId].value, "amount too low"); require(rewards[_rewardId].stock >= 1, "out of stock"); require(rewards[_rewardId].exists, "not found"); require(rewards[_rewardId].active, "not active"); rewardRecipients.push(RewardRecipient(_rewardId, _user, false, false)); userRewardCount[_user] = userRewardCount[_user].add(1); rewardToRewardRecipientCount[_rewardId] = rewardToRewardRecipientCount[ _rewardId ].add(1); emit RewardRecipientAdded( rewardRecipients.length.sub(1), _rewardId, _amount, _user ); return rewardRecipients.length.sub(1); } /** * @dev Modifies a reward by id * @param _rewardId Reward unique id * @param _value Reward cost * @param _deliveryDate Time in which reward will be deliverd to contriutors * @param _stock Quantity available for dispatch * @param _active Indicates if contributors can attain the reward * @param _hashedReward Initial or new CID refrence of the reward on IPFS */ function modifyReward( uint256 _rewardId, uint256 _value, uint256 _deliveryDate, uint256 _stock, bool _active, string memory _hashedReward ) external hasRole(MODIFY_REWARD, msg.sender) { /** * To modify a reward: * check reward has no backers * check reward exists */ require(rewards[_rewardId].exists, "not found"); require(rewardToRewardRecipientCount[_rewardId] < 1, "has backers"); require( _value > CampaignFactoryLib.getCampaignFactoryConfig( campaignFactoryInterface, "minimumContributionAllowed" ), "amount too low" ); require( _value < CampaignFactoryLib.getCampaignFactoryConfig( campaignFactoryInterface, "maximumContributionAllowed" ), "amount too high" ); rewards[_rewardId].value = _value; rewards[_rewardId].deliveryDate = _deliveryDate; rewards[_rewardId].stock = _stock; rewards[_rewardId].active = _active; rewards[_rewardId].hashedReward = _hashedReward; emit RewardModified(_rewardId, _value, _deliveryDate, _stock, _active); } /** * @dev Increases a reward stock count * @param _rewardId Reward unique id * @param _count Stock count to increase by */ function increaseRewardStock(uint256 _rewardId, uint256 _count) external hasRole(MODIFY_REWARD, msg.sender) { require(rewards[_rewardId].exists, "not found"); rewards[_rewardId].stock = rewards[_rewardId].stock.add(_count); emit RewardStockIncreased(_rewardId, _count); } /** * @dev Deletes a reward by id * @param _rewardId Reward unique id */ function destroyReward(uint256 _rewardId) external hasRole(DESTROY_REWARD, msg.sender) { // check reward has no backers require(rewardToRewardRecipientCount[_rewardId] < 1, "has backers"); require(rewards[_rewardId].exists, "not found"); delete rewards[_rewardId]; emit RewardDestroyed(_rewardId); } /** * @dev Called by the campaign owner to indicate they delivered the reward to the rewardRecipient * @param _rewardRecipientId ID to struct containing reward and user to be rewarded * @param _status Indicates if the delivery was successful or not */ function campaignSentReward(uint256 _rewardRecipientId, bool _status) external hasRole(MODIFY_REWARD, msg.sender) { require( rewardToRewardRecipientCount[ rewardRecipients[_rewardRecipientId].rewardId ] >= 1 ); rewardRecipients[_rewardRecipientId] .deliveryConfirmedByCampaign = _status; emit RewarderApproval(_rewardRecipientId, _status); } /** * @dev Called by a user eligible for rewards to indicate they received their reward * @param _rewardRecipientId ID to struct containing reward and user to be rewarded */ function userReceivedCampaignReward(uint256 _rewardRecipientId) external userIsVerified(msg.sender) { require( CampaignLib.isAnApprover(campaignInterface, msg.sender), "not an approver" ); require( rewardRecipients[_rewardRecipientId].deliveryConfirmedByCampaign, "reward not delivered yet" ); require( !rewardRecipients[_rewardRecipientId].deliveryConfirmedByUser, "reward already marked as sent" ); require( rewardRecipients[_rewardRecipientId].user == msg.sender, "not owner of reward" ); require(userRewardCount[msg.sender] >= 1, "you have no reward"); rewardRecipients[_rewardRecipientId].deliveryConfirmedByUser = true; emit RewardRecipientApproval(_rewardRecipientId); } /** * @dev Renounces rewards owned by the specified user * @param _user Address of user who rewards are being renounced */ function renounceRewards(address _user) external onlyRegisteredCampaigns { if (userRewardCount[_user] >= 1) { userRewardCount[_user] = 0; // deduct rewardRecipients count for (uint256 index = 0; index < rewardRecipients.length; index++) { rewardToRewardRecipientCount[ rewardRecipients[index].rewardId ] = rewardToRewardRecipientCount[ rewardRecipients[index].rewardId ].sub(1); } } } /** * @dev Transfers rewards from the old owner to a new owner * @param _oldAddress Address of previous owner of rewards * @param _newAddress Address of new owner rewards are being transferred to */ function transferRewards(address _oldAddress, address _newAddress) external onlyRegisteredCampaigns { if (userRewardCount[_oldAddress] >= 1) { userRewardCount[_newAddress] = userRewardCount[_oldAddress]; userRewardCount[_oldAddress] = 0; for (uint256 index = 0; index < rewardRecipients.length; index++) { if (rewardRecipients[index].user == _oldAddress) { rewardRecipients[index].user = _newAddress; } } } } }
Creates rewards contributors can attain _value Reward cost _deliveryDate Time in which reward will be deliverd to contriutors _stock Quantity available for dispatch _hashedReward CID reference of the reward on IPFS _active Indicates if contributors can attain the reward/
function createReward( uint256 _value, uint256 _deliveryDate, uint256 _stock, string memory _hashedReward, bool _active ) external hasRole(CREATE_REWARD, msg.sender) userIsVerified(msg.sender) { require( _value > CampaignFactoryLib.getCampaignFactoryConfig( campaignFactoryInterface, "minimumContributionAllowed" ), "amount too low" ); require( _value < CampaignFactoryLib.getCampaignFactoryConfig( campaignFactoryInterface, "maximumContributionAllowed" ), "amount too high" ); rewards.push( Reward(_value, _deliveryDate, _stock, _hashedReward, true, _active) ); emit RewardCreated( rewards.length.sub(1), _value, _deliveryDate, _stock, _hashedReward, _active ); }
5,539,149
//Address: 0xf0686f485e25cd6b7c505cead4aec5ea18600d1a //Contract name: Ico //Balance: 0 Ether //Verification Date: 2/13/2018 //Transacion Count: 1 // CODE STARTS HERE pragma solidity ^0.4.19; contract Owned { address public owner; modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address newOwner) public onlyOwner() { owner = newOwner; } } contract EIP20Interface { /* This is a slight change to the ERC20 base standard. function totalSupply() constant returns (uint256 supply); is replaced with: uint256 public totalSupply; This automatically creates a getter function for the totalSupply. This is moved to the base contract since public getter functions are not currently recognised as an implementation of the matching abstract function by the compiler. */ /// total amount of tokens uint256 public totalSupply; /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) public view returns (uint256 balance); /// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _value) public returns (bool success); /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); /// @notice `msg.sender` approves `_spender` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of tokens to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint256 _value) public returns (bool success); /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) public view returns (uint256 remaining); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } contract EIP20 is EIP20Interface { uint256 constant MAX_UINT256 = 2**256 - 1; /* NOTE: The following variables are OPTIONAL vanities. One does not have to include them. They allow one to customise the token contract & in no way influences the core functionality. Some wallets/interfaces might not even bother to look at this information. */ string public name; //fancy name: eg Simon Bucks uint8 public decimals; //How many decimals to show. string public symbol; //An identifier: eg SBX function EIP20( uint256 _initialAmount, string _tokenName, uint8 _decimalUnits, string _tokenSymbol ) public { balances[msg.sender] = _initialAmount; // Give the creator all initial tokens totalSupply = _initialAmount; // Update total supply name = _tokenName; // Set the name for display purposes decimals = _decimalUnits; // Amount of decimals for display purposes symbol = _tokenSymbol; // Set the symbol for display purposes } function transfer(address _to, uint256 _value) public returns (bool success) { //Default assumes totalSupply can't be over max (2^256 - 1). //If your token leaves out totalSupply and can issue more tokens as time goes on, you need to check if it doesn't wrap. //Replace the if with this one instead. //require(balances[msg.sender] >= _value && balances[_to] + _value > balances[_to]); require(balances[msg.sender] >= _value); balances[msg.sender] -= _value; balances[_to] += _value; Transfer(msg.sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { //same as above. Replace this line with the following if you want to protect against wrapping uints. //require(balances[_from] >= _value && allowed[_from][msg.sender] >= _value && balances[_to] + _value > balances[_to]); uint256 allowance = allowed[_from][msg.sender]; require(balances[_from] >= _value && allowance >= _value); balances[_to] += _value; balances[_from] -= _value; if (allowance < MAX_UINT256) { allowed[_from][msg.sender] -= _value; } Transfer(_from, _to, _value); return true; } function balanceOf(address _owner) view public returns (uint256 balance) { return balances[_owner]; } function approve(address _spender, uint256 _value) public returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) view public returns (uint256 remaining) { return allowed[_owner][_spender]; } mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; } contract Gabicoin is Owned, EIP20 { // Struct for ico minting. struct IcoBalance { bool hasTransformed;// Has transformed ico balances to real balance for this user? uint[3] balances;// Balances. } // Mint event. event Mint(address indexed to, uint value, uint phaseNumber); // Activate event. event Activate(); // Constructor. function Gabicoin() EIP20(0, "Gabicoin", 2, "GCO") public { owner = msg.sender; } // Mint function for ICO. function mint(address to, uint value, uint phase) onlyOwner() external { require(!isActive); icoBalances[to].balances[phase] += value;// Increase ICO balance. Mint(to, value, phase); } // Activation function after successful ICO. function activate(bool i0, bool i1, bool i2) onlyOwner() external { require(!isActive);// Only for not yet activated token. activatedPhases[0] = i0; activatedPhases[1] = i1; activatedPhases[2] = i2; Activate(); isActive = true;// Activate token. } // Transform ico balance to standard balance. function transform(address addr) public { require(isActive);// Only after activation. require(!icoBalances[addr].hasTransformed);// Only for not transfromed structs. for (uint i = 0; i < 3; i++) { if (activatedPhases[i])// Check phase activation. { balances[addr] += icoBalances[addr].balances[i];// Increase balance. Transfer(0x00, addr, icoBalances[addr].balances[i]); icoBalances[addr].balances[i] = 0;// Set ico balance to zero. } } icoBalances[addr].hasTransformed = true;// Set struct to transformed status. } // For simple call transform(). function () payable external { transform(msg.sender); msg.sender.transfer(msg.value); } // Activated on ICO phases. bool[3] public activatedPhases; // Token activation status. bool public isActive; // Ico balances. mapping (address => IcoBalance) public icoBalances; } contract Bounty is Owned { // Get bounty event. event GetBounty(address indexed bountyHunter, uint amount); // Add bounty event. event AddBounty(address indexed bountyHunter, uint amount); // Constructor. function Bounty(address gabicoinAddress) public { owner = msg.sender; token = gabicoinAddress; } // Add bounty for hunter. function addBountyForHunter(address hunter, uint bounty) onlyOwner() external returns (bool) { require(!Gabicoin(token).isActive());// Check token activity. bounties[hunter] += bounty;// Increase bounty for hunter. bountyTotal += bounty;// Increase total bounty value. AddBounty(hunter, bounty);// Call add bounty event. return true; } // Get bounty. function getBounty() external returns (uint) { require(Gabicoin(token).isActive());// Check token activity. require(bounties[msg.sender] != 0);// Check balance of bounty hunter. if (Gabicoin(token).transfer(msg.sender, bounties[msg.sender]))// Transfer bounty tokens to bounty hunter. { uint amount = bounties[msg.sender]; bountyTotal -= amount;// Decrease total bounty. GetBounty(msg.sender, amount);// Get bounty event. bounties[msg.sender] = 0;// Set bounty for hunter to zero. return amount; } else { return 0; } } // Bounties. mapping (address => uint) public bounties; // Total bounty. uint public bountyTotal = 0; // Gabicoin token. address public token; } contract Ico is Owned { // Posible ICO states. enum State { Runned, Paused, Finished, Failed } // Refund event. event Refund(address indexed investor, uint value); // Update event. event UpdateState(State oldState, State newState); // Activation event. event Activate(); // Buying token event. event BuyTokens(address indexed buyer, uint value, uint indexed phaseNumber); // Geting ethereum from ICO or Pre-ICO event. event GetEthereum(address indexed recipient, uint value); // Contracutor. function Ico(address _token, address _bounty, uint[3] _startDates, uint[3] _endDates, uint[3] _prices, uint[3] _hardCaps) public { // Save addresses. owner = msg.sender; token = _token; bounty = _bounty; // Save info abount phases. for (uint i = 0; i < 3; i++) { startDates[i] = _startDates[i]; endDates[i] = _endDates[i]; prices[i] = _prices[i]; hardCaps[i] = _hardCaps[i]; } state = State.Runned; } // Return true if date in phase with given number. function isPhase(uint number, uint date) view public returns (bool) { return startDates[number] <= date && date <= endDates[number]; } // Return true for succesfull Pre-ICO. function preIcoWasSuccessful() view public returns (bool) { return ((totalInvested[0] / prices[0]) / 2 >= preIcoSoftCap); } // Return true for succesfull ICO. function icoWasSuccessful() view public returns (bool) { return ((totalInvested[1] / prices[1]) + (totalInvested[2] * 5 / prices[2] / 4) >= icoSoftCap); } // Return ether funds function refund() public { uint amount = 0; if (state == State.Failed)// Check failed state. { if (!preIcoCashedOut)// Check cash out from ICO. { amount += invested[msg.sender][0];// Add Pre-ICO funds. invested[msg.sender][0] = 0;// Set Pre-ICO funds to zero. } amount += invested[msg.sender][1]; amount += invested[msg.sender][2]; // Set invested funds to zero. invested[msg.sender][1] = 0; invested[msg.sender][2] = 0; Refund(msg.sender, amount); msg.sender.transfer(amount);// Send funds. } else if (state == State.Finished)// Check finished state. { if (!preIcoWasSuccessful()) { amount += invested[msg.sender][0];// Add Pre-ICO funds. invested[msg.sender][0] = 0;// Set Pre-ICO funds to zero. } if (!icoWasSuccessful()) { amount += invested[msg.sender][1]; amount += invested[msg.sender][2]; // Set invested funds to zero. invested[msg.sender][1] = 0; invested[msg.sender][2] = 0; } Refund(msg.sender, amount); msg.sender.transfer(amount);// Send funds. } else { revert(); } } // Update state. function updateState() public { require(state == State.Runned); if (now >= endDates[2])// ICO and Pre-ICO softcaps have achieved. { if (preIcoWasSuccessful() || icoWasSuccessful()) { UpdateState(state, State.Finished); state = State.Finished; } else { UpdateState(state, State.Failed); state = State.Failed; } } } // Activate Gabicoin if that's posible. function activate() public { require(!Gabicoin(token).isActive());// Check token activity. require(state == State.Finished);// Check state. Activate(); Gabicoin(token).mint(bounty, 3 * 100 * 10 ** 6, preIcoWasSuccessful() ? 0 : 1); Gabicoin(token).activate(preIcoWasSuccessful(), icoWasSuccessful(), icoWasSuccessful());// Activate Gabicoin. } // Fallback payable function. function () payable external { if (state == State.Failed)// Check state for Failed or Expired states. { refund();// Refund invested funds for sender. return; } else if (state == State.Finished)// Check finished state. { refund();// Refund invested funds for sender. return; } else if (state == State.Runned)// Check runned state. { if (isPhase(0, now)) { buyTokens(msg.sender, msg.value, 0); } else if (isPhase(1, now)) { buyTokens(msg.sender, msg.value, 1); } else if (isPhase(2, now)) { buyTokens(msg.sender, msg.value, 2); } else { msg.sender.transfer(msg.value); } updateState();// Update ICO state after payable transactions. } else { msg.sender.transfer(msg.value); } } // Buy tokens function. function buyTokens(address buyer, uint value, uint phaseNumber) internal { require(totalInvested[phaseNumber] < hardCaps[phaseNumber]);// Check investment posibility. // Define local variables here. uint amount; uint rest; // Compute rest. if (totalInvested[phaseNumber] + value / prices[phaseNumber] > hardCaps[phaseNumber]) { rest = hardCaps[phaseNumber] * prices[phaseNumber] - totalInvested[phaseNumber]; } else { rest = value % prices[phaseNumber]; } amount = value - rest; require(amount > 0); invested[buyer][phaseNumber] += amount; totalInvested[phaseNumber] += amount; BuyTokens(buyer, amount, phaseNumber); Gabicoin(token).mint(buyer, amount / prices[phaseNumber], phaseNumber); msg.sender.transfer(rest);// Return changes. } // Pause contract. function pauseIco() onlyOwner() external { require(state == State.Runned);// Only from Runned state. UpdateState(state, State.Paused); state = State.Paused;// Set state to Paused. } // Continue paused contract. function continueIco() onlyOwner() external { require(state == State.Paused);// Only from Paused state. UpdateState(state, State.Runned); state = State.Runned;// Set state to Runned. } // End contract unsuccessfully. function endIco() onlyOwner() external { require(state == State.Paused);// Only from Paused state. UpdateState(state, State.Failed); state = State.Failed;// Set state to Expired. } // Get funds from successful Pre-ICO. function getPreIcoFunds() onlyOwner() external returns (uint) { require(state != State.Failed && state != State.Paused);// Check state. require(now >= endDates[0]);// Check ending of Pre-ICO. require(!preIcoCashedOut);// Check cash out from Pre-ICO. if (preIcoWasSuccessful()) { uint value = totalInvested[0]; preIcoCashedOut = true; msg.sender.transfer(value); GetEthereum(msg.sender, value); return value; } return 0; } // Get ethereum funds from ICO. function getEtherum() onlyOwner() external returns (uint) { require(state == State.Finished);// Check state. require(now >= endDates[2]);// Check end of ICO. if (icoWasSuccessful()) { uint value = totalInvested[1] + totalInvested[2]; msg.sender.transfer(value); GetEthereum(msg.sender, value); return value; } return 0; } // Crowdsale state. State public state; // Invested from address. mapping (address => uint[3]) public invested; // Total invested at each phase. uint[3] public totalInvested; // Pre-ICO softcap. uint public preIcoSoftCap = 2 * 100 * 10 ** 5; // ICO softcap. uint public icoSoftCap = 100 * 10 ** 6; // Bounty contract address. address public bounty; // Token contract address. address public token; // Start dates of ICO phases. uint[3] public startDates; // End dates of ICO phases. uint[3] public endDates; // Prices of token at each phase. uint[3] public prices; // Hard caps of ICO phases. uint[3] public hardCaps; // Pre-ICO cashed out. bool public preIcoCashedOut; }
Buy tokens function. Define local variables here. Compute rest.
function buyTokens(address buyer, uint value, uint phaseNumber) internal { uint amount; uint rest; if (totalInvested[phaseNumber] + value / prices[phaseNumber] > hardCaps[phaseNumber]) { rest = hardCaps[phaseNumber] * prices[phaseNumber] - totalInvested[phaseNumber]; } else { rest = value % prices[phaseNumber]; } amount = value - rest; require(amount > 0); invested[buyer][phaseNumber] += amount; totalInvested[phaseNumber] += amount; BuyTokens(buyer, amount, phaseNumber); Gabicoin(token).mint(buyer, amount / prices[phaseNumber], phaseNumber); }
13,044,471
./full_match/11155111/0xA7a7a82597063CF4e3AC51bF601Ce75D12126C45/sources/contracts/base/ModuleManager.sol
Returns an array of modules. If all entries fit into a single page, the next pointer will be 0x1. If another page is present, next will be the last element of the returned array. start Start of the page. Has to be a module or start pointer (0x1 address) pageSize Maximum number of modules that should be returned. Has to be > 0 return array Array of modules. return next Start of the next page./ Init array with max page size Populate return array/ Set correct size of returned array solhint-disable no-inline-assembly / @solidity memory-safe-assembly
function getModulesPaginated(address start, uint256 pageSize) external view returns (address[] memory array, address next) { require(start == SENTINEL_MODULES || isModuleEnabled(start), "GS105"); require(pageSize > 0, "GS106"); array = new address[](pageSize); uint256 moduleCount = 0; next = modules[start]; while (next != address(0) && next != SENTINEL_MODULES && moduleCount < pageSize) { array[moduleCount] = next; next = modules[next]; moduleCount++; } and the `next` variable will either be an enabled module or a sentinel address (signalling the end). If we haven't reached the end inside the loop, we need to set the next pointer to the last element of the modules array because the `next` variable (which is a module by itself) acting as a pointer to the start of the next page is neither included to the current page, nor will it be included in the next one if you pass it as a start. if (next != SENTINEL_MODULES) { next = array[moduleCount - 1]; } assembly { mstore(array, moduleCount) }
3,832,859
./full_match/1/0x5298c6D5ac0f2964bbB27F496a8193CE78e8A8e6/sources/contracts/TheEnigma.sol
Generates a pseudo-random number./
function _getRandomNumber(uint256 _upper) private view returns (uint256) { uint256 random = uint256( keccak256( abi.encodePacked( availableMiners.length, blockhash(block.number - 1), block.coinbase, block.difficulty, msg.sender ) ) ); return random % _upper; }
16,556,497
//SPDX-License-Identifier: MIT pragma solidity =0.8.13; import "@openzeppelin-v4/contracts/utils/math/SafeCast.sol"; import "@openzeppelin-v4/contracts/token/ERC20/extensions/IERC20Metadata.sol"; import "./PeriodicOracle.sol"; import "../interfaces/IAggregatedOracle.sol"; import "../libraries/SafeCastExt.sol"; import "../libraries/uniswap-lib/FullMath.sol"; import "../utils/ExplicitQuotationMetadata.sol"; contract AggregatedOracle is IAggregatedOracle, PeriodicOracle, ExplicitQuotationMetadata { using SafeCast for uint256; using SafeCastExt for uint256; /* * Structs */ struct TokenSpecificOracle { address token; address oracle; } struct OracleConfig { address oracle; uint8 quoteTokenDecimals; } /// @notice The minimum quote token denominated value of the token liquidity required for all underlying oracles /// to be considered valid and thus included in the aggregation. uint256 public immutable minimumTokenLiquidityValue; /// @notice The minimum quote token liquidity required for all underlying oracles to be considered valid and thus /// included in the aggregation. uint256 public immutable minimumQuoteTokenLiquidity; /* * Internal variables */ OracleConfig[] internal oracles; mapping(address => OracleConfig[]) internal tokenSpecificOracles; /* * Private variables */ mapping(address => bool) private oracleExists; mapping(address => mapping(address => bool)) private oracleForExists; /* * Constructors */ constructor( string memory quoteTokenName_, address quoteTokenAddress_, string memory quoteTokenSymbol_, uint8 quoteTokenDecimals_, address[] memory oracles_, TokenSpecificOracle[] memory tokenSpecificOracles_, uint256 period_, uint256 minimumTokenLiquidityValue_, uint256 minimumQuoteTokenLiquidity_ ) PeriodicOracle(quoteTokenAddress_, period_) ExplicitQuotationMetadata(quoteTokenName_, quoteTokenAddress_, quoteTokenSymbol_, quoteTokenDecimals_) { require(oracles_.length > 0 || tokenSpecificOracles_.length > 0, "AggregatedOracle: MISSING_ORACLES"); minimumTokenLiquidityValue = minimumTokenLiquidityValue_; minimumQuoteTokenLiquidity = minimumQuoteTokenLiquidity_; // Setup general oracles for (uint256 i = 0; i < oracles_.length; ++i) { require(!oracleExists[oracles_[i]], "AggregatedOracle: DUPLICATE_ORACLE"); oracleExists[oracles_[i]] = true; oracles.push( OracleConfig({oracle: oracles_[i], quoteTokenDecimals: IOracle(oracles_[i]).quoteTokenDecimals()}) ); } // Setup token-specific oracles for (uint256 i = 0; i < tokenSpecificOracles_.length; ++i) { TokenSpecificOracle memory oracle = tokenSpecificOracles_[i]; require(!oracleExists[oracle.oracle], "AggregatedOracle: DUPLICATE_ORACLE"); require(!oracleForExists[oracle.token][oracle.oracle], "AggregatedOracle: DUPLICATE_ORACLE"); oracleForExists[oracle.token][oracle.oracle] = true; tokenSpecificOracles[oracle.token].push( OracleConfig({oracle: oracle.oracle, quoteTokenDecimals: IOracle(oracle.oracle).quoteTokenDecimals()}) ); } } /* * External functions */ /// @inheritdoc IAggregatedOracle function getOracles() external view virtual override returns (address[] memory) { OracleConfig[] memory _oracles = oracles; address[] memory allOracles = new address[](_oracles.length); // Add the general oracles for (uint256 i = 0; i < _oracles.length; ++i) allOracles[i] = _oracles[i].oracle; return allOracles; } /// @inheritdoc IAggregatedOracle function getOraclesFor(address token) external view virtual override returns (address[] memory) { OracleConfig[] memory _tokenSpecificOracles = tokenSpecificOracles[token]; OracleConfig[] memory _oracles = oracles; address[] memory allOracles = new address[](_oracles.length + _tokenSpecificOracles.length); // Add the general oracles for (uint256 i = 0; i < _oracles.length; ++i) allOracles[i] = _oracles[i].oracle; // Add the token specific oracles for (uint256 i = 0; i < _tokenSpecificOracles.length; ++i) allOracles[_oracles.length + i] = _tokenSpecificOracles[i].oracle; return allOracles; } /* * Public functions */ /// @inheritdoc ExplicitQuotationMetadata function quoteTokenName() public view virtual override(ExplicitQuotationMetadata, IQuoteToken, SimpleQuotationMetadata) returns (string memory) { return ExplicitQuotationMetadata.quoteTokenName(); } /// @inheritdoc ExplicitQuotationMetadata function quoteTokenAddress() public view virtual override(ExplicitQuotationMetadata, IQuoteToken, SimpleQuotationMetadata) returns (address) { return ExplicitQuotationMetadata.quoteTokenAddress(); } /// @inheritdoc ExplicitQuotationMetadata function quoteTokenSymbol() public view virtual override(ExplicitQuotationMetadata, IQuoteToken, SimpleQuotationMetadata) returns (string memory) { return ExplicitQuotationMetadata.quoteTokenSymbol(); } /// @inheritdoc ExplicitQuotationMetadata function quoteTokenDecimals() public view virtual override(ExplicitQuotationMetadata, IQuoteToken, SimpleQuotationMetadata) returns (uint8) { return ExplicitQuotationMetadata.quoteTokenDecimals(); } /// @inheritdoc IERC165 function supportsInterface(bytes4 interfaceId) public view virtual override(PeriodicOracle, ExplicitQuotationMetadata) returns (bool) { return interfaceId == type(IAggregatedOracle).interfaceId || ExplicitQuotationMetadata.supportsInterface(interfaceId) || PeriodicOracle.supportsInterface(interfaceId); } /// @inheritdoc PeriodicOracle function canUpdate(bytes memory data) public view virtual override(IUpdateable, PeriodicOracle) returns (bool) { address token = abi.decode(data, (address)); // If the parent contract can't update, this contract can't update if (!super.canUpdate(data)) return false; // Ensure all underlying oracles are up-to-date for (uint256 j = 0; j < 2; ++j) { OracleConfig[] memory _oracles; if (j == 0) _oracles = oracles; else _oracles = tokenSpecificOracles[token]; for (uint256 i = 0; i < _oracles.length; ++i) { if (IOracle(_oracles[i].oracle).canUpdate(data)) { // We can update one of the underlying oracles return true; } } } (, , , uint256 validResponses) = aggregateUnderlying(token, calculateMaxAge()); // Only return true if we have reached the minimum number of valid underlying oracle consultations return validResponses >= 1; } /* * Internal functions */ function performUpdate(bytes memory data) internal override returns (bool) { bool underlyingUpdated; address token = abi.decode(data, (address)); // Ensure all underlying oracles are up-to-date for (uint256 j = 0; j < 2; ++j) { OracleConfig[] memory _oracles; if (j == 0) _oracles = oracles; else _oracles = tokenSpecificOracles[token]; for (uint256 i = 0; i < _oracles.length; ++i) { // We don't want any problematic underlying oracles to prevent this oracle from updating // so we put update in a try-catch block try IOracle(_oracles[i].oracle).update(data) returns (bool updated) { underlyingUpdated = underlyingUpdated || updated; } catch Error(string memory reason) { emit UpdateErrorWithReason(_oracles[i].oracle, token, reason); } catch (bytes memory err) { emit UpdateError(_oracles[i].oracle, token, err); } } } uint256 price; uint256 tokenLiquidity; uint256 quoteTokenLiquidity; uint256 validResponses; (price, tokenLiquidity, quoteTokenLiquidity, validResponses) = aggregateUnderlying(token, calculateMaxAge()); // Liquidities should rarely ever overflow uint112 (if ever), but if they do, we set the observation to the max // This allows the price to continue to be updated while tightly packing liquidities for gas efficiency if (tokenLiquidity > type(uint112).max) tokenLiquidity = type(uint112).max; if (quoteTokenLiquidity > type(uint112).max) quoteTokenLiquidity = type(uint112).max; if (validResponses >= 1) { ObservationLibrary.Observation storage observation = observations[token]; observation.price = price.toUint112(); // Should never (realistically) overflow observation.tokenLiquidity = uint112(tokenLiquidity); // Will never overflow observation.quoteTokenLiquidity = uint112(quoteTokenLiquidity); // Will never overflow observation.timestamp = block.timestamp.toUint32(); emit Updated(token, price, tokenLiquidity, quoteTokenLiquidity, block.timestamp); return true; } else emit UpdateErrorWithReason(address(this), token, "AggregatedOracle: INVALID_NUM_CONSULTATIONS"); return underlyingUpdated; } /** * @notice Calculates the maximum age of the underlying oracles' responses when updating this oracle's observation. * @dev We use this to prevent old data from skewing our observations. Underlying oracles must update at least as * frequently as this oracle does. * @return maxAge The maximum age of underlying oracles' responses, in seconds. */ function calculateMaxAge() internal view returns (uint256) { return period - 1; // Subract 1 to ensure that we don't use any data from the previous period } function sanityCheckTvlDistributionRatio( address token, uint256 price, uint256 tokenLiquidity, uint256 quoteTokenLiquidity ) internal view virtual returns (bool) { if (quoteTokenLiquidity == 0) { // We'll always ignore consultations where the quote token liquidity is 0 return false; } // Calculate the ratio of token liquidity value (denominated in the quote token) to quote token liquidity // Safe from overflows: price and tokenLiquidity are actually uint112 in disguise // We multiply by 100 to avoid floating point errors => 100 represents a ratio of 1:1 uint256 ratio = ((price * tokenLiquidity * 100) / quoteTokenLiquidity) / (uint256(10)**IERC20Metadata(token).decimals()); if (ratio > 1000 || ratio < 10) { // Reject consultations where the ratio is above 10:1 or below 1:10 // This prevents Uniswap v3 or orderbook-like oracles from skewing our observations when liquidity is very // one-sided as one-sided liquidity can be used as an attack vector return false; } return true; } function sanityCheckQuoteTokenLiquidity(uint256 quoteTokenLiquidity) internal view virtual returns (bool) { return quoteTokenLiquidity >= minimumQuoteTokenLiquidity; } function sanityCheckTokenLiquidityValue( address token, uint256 price, uint256 tokenLiquidity ) internal view virtual returns (bool) { return ((price * tokenLiquidity) / (uint256(10)**IERC20Metadata(token).decimals())) >= minimumTokenLiquidityValue; } function validateUnderlyingConsultation( address token, uint256 price, uint256 tokenLiquidity, uint256 quoteTokenLiquidity ) internal view virtual returns (bool) { return sanityCheckTokenLiquidityValue(token, price, tokenLiquidity) && sanityCheckQuoteTokenLiquidity(quoteTokenLiquidity) && sanityCheckTvlDistributionRatio(token, price, tokenLiquidity, quoteTokenLiquidity); } function aggregateUnderlying(address token, uint256 maxAge) internal view returns ( uint256 price, uint256 tokenLiquidity, uint256 quoteTokenLiquidity, uint256 validResponses ) { uint256 qtDecimals = quoteTokenDecimals(); uint256 denominator; // sum of oracleQuoteTokenLiquidity divided by oraclePrice for (uint256 j = 0; j < 2; ++j) { OracleConfig[] memory _oracles; if (j == 0) _oracles = oracles; else _oracles = tokenSpecificOracles[token]; for (uint256 i = 0; i < _oracles.length; ++i) { uint256 oPrice; uint256 oTokenLiquidity; uint256 oQuoteTokenLiquidity; // We don't want problematic underlying oracles to prevent us from calculating the aggregated // results from the other working oracles, so we use a try-catch block. try IOracle(_oracles[i].oracle).consult(token, maxAge) returns ( uint112 _price, uint112 _tokenLiquidity, uint112 _quoteTokenLiquidity ) { // Promote returned data to uint256 to prevent scaling up from overflowing oPrice = _price; oTokenLiquidity = _tokenLiquidity; oQuoteTokenLiquidity = _quoteTokenLiquidity; } catch Error(string memory) { continue; } catch (bytes memory) { continue; } // Shift liquidity for more precise calculations as we divide this by the price // This is safe as liquidity < 2^112 oQuoteTokenLiquidity = oQuoteTokenLiquidity << 120; uint256 decimals = _oracles[i].quoteTokenDecimals; // Fix differing quote token decimal places if (decimals < qtDecimals) { // Scale up uint256 scalar = 10**(qtDecimals - decimals); oPrice *= scalar; oQuoteTokenLiquidity *= scalar; } else if (decimals > qtDecimals) { // Scale down uint256 scalar = 10**(decimals - qtDecimals); oPrice /= scalar; oQuoteTokenLiquidity /= scalar; } if (!validateUnderlyingConsultation(token, oPrice, oTokenLiquidity, oQuoteTokenLiquidity >> 120)) { continue; } if (oPrice != 0 && oQuoteTokenLiquidity != 0) { ++validResponses; // Note: (oQuoteTokenLiquidity / oPrice) will equal 0 if oQuoteTokenLiquidity < // oPrice, but for this to happen, price would have to be insanely high denominator += oQuoteTokenLiquidity / oPrice; // Should never realistically overflow tokenLiquidity += oTokenLiquidity; quoteTokenLiquidity += oQuoteTokenLiquidity; } } } price = denominator == 0 ? 0 : quoteTokenLiquidity / denominator; // Right shift liquidity to undo the left shift and get the real value quoteTokenLiquidity = quoteTokenLiquidity >> 120; } /// @inheritdoc AbstractOracle function instantFetch(address token) internal view virtual override returns ( uint112 price, uint112 tokenLiquidity, uint112 quoteTokenLiquidity ) { ( uint256 bigPrice, uint256 bigTokenLiquidity, uint256 bigQuoteTokenLiquidity, uint256 validResponses ) = aggregateUnderlying(token, 0); // Reverts if none of the underlying oracles report anything require(validResponses > 0, "AggregatedOracle: INVALID_NUM_CONSULTATIONS"); // This revert should realistically never occur, but we use it to prevent an invalid price from being returned require(bigPrice <= type(uint112).max, "AggregatedOracle: PRICE_TOO_HIGH"); price = uint112(bigPrice); // Liquidities should rarely ever overflow uint112 (if ever), but if they do, we use the max value // This matches how observations are stored if (bigTokenLiquidity > type(uint112).max) { tokenLiquidity = type(uint112).max; } else { tokenLiquidity = uint112(bigTokenLiquidity); } if (bigQuoteTokenLiquidity > type(uint112).max) { quoteTokenLiquidity = type(uint112).max; } else { quoteTokenLiquidity = uint112(bigQuoteTokenLiquidity); } } }
@inheritdoc PeriodicOracle If the parent contract can't update, this contract can't update Ensure all underlying oracles are up-to-date We can update one of the underlying oracles
function canUpdate(bytes memory data) public view virtual override(IUpdateable, PeriodicOracle) returns (bool) { address token = abi.decode(data, (address)); if (!super.canUpdate(data)) return false; for (uint256 j = 0; j < 2; ++j) { OracleConfig[] memory _oracles; if (j == 0) _oracles = oracles; else _oracles = tokenSpecificOracles[token]; for (uint256 i = 0; i < _oracles.length; ++i) { if (IOracle(_oracles[i].oracle).canUpdate(data)) { return true; } } } (, , , uint256 validResponses) = aggregateUnderlying(token, calculateMaxAge()); }
1,772,801
// SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Interface of the ERC777Token standard as defined in the EIP. * * This contract uses the * https://eips.ethereum.org/EIPS/eip-1820[ERC1820 registry standard] to let * token holders and recipients react to token movements by using setting implementers * for the associated interfaces in said registry. See {IERC1820Registry} and * {ERC1820Implementer}. */ interface IERC777 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() external view returns (string memory); /** * @dev Returns the smallest part of the token that is not divisible. This * means all token operations (creation, movement and destruction) must have * amounts that are a multiple of this number. * * For most token contracts, this value will equal 1. */ function granularity() external view returns (uint256); /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by an account (`owner`). */ function balanceOf(address owner) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * If send or receive hooks are registered for the caller and `recipient`, * the corresponding functions will be called with `data` and empty * `operatorData`. See {IERC777Sender} and {IERC777Recipient}. * * Emits a {Sent} event. * * Requirements * * - the caller must have at least `amount` tokens. * - `recipient` cannot be the zero address. * - if `recipient` is a contract, it must implement the {IERC777Recipient} * interface. */ function send(address recipient, uint256 amount, bytes calldata data) external; /** * @dev Destroys `amount` tokens from the caller's account, reducing the * total supply. * * If a send hook is registered for the caller, the corresponding function * will be called with `data` and empty `operatorData`. See {IERC777Sender}. * * Emits a {Burned} event. * * Requirements * * - the caller must have at least `amount` tokens. */ function burn(uint256 amount, bytes calldata data) external; /** * @dev Returns true if an account is an operator of `tokenHolder`. * Operators can send and burn tokens on behalf of their owners. All * accounts are their own operator. * * See {operatorSend} and {operatorBurn}. */ function isOperatorFor(address operator, address tokenHolder) external view returns (bool); /** * @dev Make an account an operator of the caller. * * See {isOperatorFor}. * * Emits an {AuthorizedOperator} event. * * Requirements * * - `operator` cannot be calling address. */ function authorizeOperator(address operator) external; /** * @dev Revoke an account's operator status for the caller. * * See {isOperatorFor} and {defaultOperators}. * * Emits a {RevokedOperator} event. * * Requirements * * - `operator` cannot be calling address. */ function revokeOperator(address operator) external; /** * @dev Returns the list of default operators. These accounts are operators * for all token holders, even if {authorizeOperator} was never called on * them. * * This list is immutable, but individual holders may revoke these via * {revokeOperator}, in which case {isOperatorFor} will return false. */ function defaultOperators() external view returns (address[] memory); /** * @dev Moves `amount` tokens from `sender` to `recipient`. The caller must * be an operator of `sender`. * * If send or receive hooks are registered for `sender` and `recipient`, * the corresponding functions will be called with `data` and * `operatorData`. See {IERC777Sender} and {IERC777Recipient}. * * Emits a {Sent} event. * * Requirements * * - `sender` cannot be the zero address. * - `sender` must have at least `amount` tokens. * - the caller must be an operator for `sender`. * - `recipient` cannot be the zero address. * - if `recipient` is a contract, it must implement the {IERC777Recipient} * interface. */ function operatorSend( address sender, address recipient, uint256 amount, bytes calldata data, bytes calldata operatorData ) external; /** * @dev Destroys `amount` tokens from `account`, reducing the total supply. * The caller must be an operator of `account`. * * If a send hook is registered for `account`, the corresponding function * will be called with `data` and `operatorData`. See {IERC777Sender}. * * Emits a {Burned} event. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. * - the caller must be an operator for `account`. */ function operatorBurn( address account, uint256 amount, bytes calldata data, bytes calldata operatorData ) external; event Sent( address indexed operator, address indexed from, address indexed to, uint256 amount, bytes data, bytes operatorData ); event Minted(address indexed operator, address indexed to, uint256 amount, bytes data, bytes operatorData); event Burned(address indexed operator, address indexed from, uint256 amount, bytes data, bytes operatorData); event AuthorizedOperator(address indexed operator, address indexed tokenHolder); event RevokedOperator(address indexed operator, address indexed tokenHolder); } /** * @dev Interface of the ERC777TokensRecipient standard as defined in the EIP. * * Accounts can be notified of {IERC777} tokens being sent to them by having a * contract implement this interface (contract holders can be their own * implementer) and registering it on the * https://eips.ethereum.org/EIPS/eip-1820[ERC1820 global registry]. * * See {IERC1820Registry} and {ERC1820Implementer}. */ interface IERC777Recipient { /** * @dev Called by an {IERC777} token contract whenever tokens are being * moved or created into a registered account (`to`). The type of operation * is conveyed by `from` being the zero address or not. * * This call occurs _after_ the token contract's state is updated, so * {IERC777-balanceOf}, etc., can be used to query the post-operation state. * * This function may revert to prevent the operation from being executed. */ function tokensReceived( address operator, address from, address to, uint256 amount, bytes calldata userData, bytes calldata operatorData ) external; } /** * @dev Interface of the ERC777TokensSender standard as defined in the EIP. * * {IERC777} Token holders can be notified of operations performed on their * tokens by having a contract implement this interface (contract holders can be * their own implementer) and registering it on the * https://eips.ethereum.org/EIPS/eip-1820[ERC1820 global registry]. * * See {IERC1820Registry} and {ERC1820Implementer}. */ interface IERC777Sender { /** * @dev Called by an {IERC777} token contract whenever a registered holder's * (`from`) tokens are about to be moved or destroyed. The type of operation * is conveyed by `to` being the zero address or not. * * This call occurs _before_ the token contract's state is updated, so * {IERC777-balanceOf}, etc., can be used to query the pre-operation state. * * This function may revert to prevent the operation from being executed. */ function tokensToSend( address operator, address from, address to, uint256 amount, bytes calldata userData, bytes calldata operatorData ) external; } /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @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; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // 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; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly {size := extcodesize(account)} return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success,) = recipient.call{value : amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{value : weiValue}(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } /** * @dev Interface of the global ERC1820 Registry, as defined in the * https://eips.ethereum.org/EIPS/eip-1820[EIP]. Accounts may register * implementers for interfaces in this registry, as well as query support. * * Implementers may be shared by multiple accounts, and can also implement more * than a single interface for each account. Contracts can implement interfaces * for themselves, but externally-owned accounts (EOA) must delegate this to a * contract. * * {IERC165} interfaces can also be queried via the registry. * * For an in-depth explanation and source code analysis, see the EIP text. */ interface IERC1820Registry { /** * @dev Sets `newManager` as the manager for `account`. A manager of an * account is able to set interface implementers for it. * * By default, each account is its own manager. Passing a value of `0x0` in * `newManager` will reset the manager to this initial state. * * Emits a {ManagerChanged} event. * * Requirements: * * - the caller must be the current manager for `account`. */ function setManager(address account, address newManager) external; /** * @dev Returns the manager for `account`. * * See {setManager}. */ function getManager(address account) external view returns (address); /** * @dev Sets the `implementer` contract as ``account``'s implementer for * `interfaceHash`. * * `account` being the zero address is an alias for the caller's address. * The zero address can also be used in `implementer` to remove an old one. * * See {interfaceHash} to learn how these are created. * * Emits an {InterfaceImplementerSet} event. * * Requirements: * * - the caller must be the current manager for `account`. * - `interfaceHash` must not be an {IERC165} interface id (i.e. it must not * end in 28 zeroes). * - `implementer` must implement {IERC1820Implementer} and return true when * queried for support, unless `implementer` is the caller. See * {IERC1820Implementer-canImplementInterfaceForAddress}. */ function setInterfaceImplementer(address account, bytes32 interfaceHash, address implementer) external; /** * @dev Returns the implementer of `interfaceHash` for `account`. If no such * implementer is registered, returns the zero address. * * If `interfaceHash` is an {IERC165} interface id (i.e. it ends with 28 * zeroes), `account` will be queried for support of it. * * `account` being the zero address is an alias for the caller's address. */ function getInterfaceImplementer(address account, bytes32 interfaceHash) external view returns (address); /** * @dev Returns the interface hash for an `interfaceName`, as defined in the * corresponding * https://eips.ethereum.org/EIPS/eip-1820#interface-name[section of the EIP]. */ function interfaceHash(string calldata interfaceName) external pure returns (bytes32); /** * @notice Updates the cache with whether the contract implements an ERC165 interface or not. * @param account Address of the contract for which to update the cache. * @param interfaceId ERC165 interface for which to update the cache. */ function updateERC165Cache(address account, bytes4 interfaceId) external; /** * @notice Checks whether a contract implements an ERC165 interface or not. * If the result is not cached a direct lookup on the contract address is performed. * If the result is not cached or the cached value is out-of-date, the cache MUST be updated manually by calling * {updateERC165Cache} with the contract address. * @param account Address of the contract to check. * @param interfaceId ERC165 interface to check. * @return True if `account` implements `interfaceId`, false otherwise. */ function implementsERC165Interface(address account, bytes4 interfaceId) external view returns (bool); /** * @notice Checks whether a contract implements an ERC165 interface or not without using nor updating the cache. * @param account Address of the contract to check. * @param interfaceId ERC165 interface to check. * @return True if `account` implements `interfaceId`, false otherwise. */ function implementsERC165InterfaceNoCache(address account, bytes4 interfaceId) external view returns (bool); event InterfaceImplementerSet(address indexed account, bytes32 indexed interfaceHash, address indexed implementer); event ManagerChanged(address indexed account, address indexed newManager); } /** * @dev Implementation of the {IERC777} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * * Support for ERC20 is included in this contract, as specified by the EIP: both * the ERC777 and ERC20 interfaces can be safely used when interacting with it. * Both {IERC777-Sent} and {IERC20-Transfer} events are emitted on token * movements. * * Additionally, the {IERC777-granularity} value is hard-coded to `1`, meaning that there * are no special restrictions in the amount of tokens that created, moved, or * destroyed. This makes integration with ERC20 applications seamless. */ contract ERC777 is IERC777, IERC20 { constructor() public { _ERC1820_REGISTRY.setInterfaceImplementer(address(this), keccak256("ERC777Token"), address(this)); _ERC1820_REGISTRY.setInterfaceImplementer(address(this), keccak256("ERC20Token"), address(this)); } using SafeMath for uint256; using Address for address; IERC1820Registry constant internal _ERC1820_REGISTRY = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24); mapping(address => uint256) private _balances; uint256 private _totalSupply; // string private _name; // string private _symbol; // We inline the result of the following hashes because Solidity doesn't resolve them at compile time. // See https://github.com/ethereum/solidity/issues/4024. // keccak256("ERC777TokensSender") bytes32 constant private _TOKENS_SENDER_INTERFACE_HASH = 0x29ddb589b1fb5fc7cf394961c1adf5f8c6454761adf795e67fe149f658abe895; // keccak256("ERC777TokensRecipient") bytes32 constant private _TOKENS_RECIPIENT_INTERFACE_HASH = 0xb281fc8c12954d22544db45de3159a39272895b169a852b314f9cc762e44c53b; // This isn't ever read from - it's only used to respond to the defaultOperators query. address[] private _defaultOperatorsArray; // Immutable, but accounts may revoke them (tracked in __revokedDefaultOperators). mapping(address => bool) private _defaultOperators; // For each account, a mapping of its operators and revoked default operators. mapping(address => mapping(address => bool)) private _operators; mapping(address => mapping(address => bool)) private _revokedDefaultOperators; // ERC20-allowances mapping(address => mapping(address => uint256)) private _allowances; /** * @dev See {IERC777-name}. */ function name() public view override returns (string memory) { return "PIZZA"; } /** * @dev See {IERC777-symbol}. */ function symbol() public view override returns (string memory) { return "PIZ"; } /** * @dev See {ERC20-decimals}. * * Always returns 18, as per the * [ERC777 EIP](https://eips.ethereum.org/EIPS/eip-777#backward-compatibility). */ function decimals() public pure returns (uint8) { return 18; } /** * @dev See {IERC777-granularity}. * * This implementation always returns `1`. */ function granularity() public view override returns (uint256) { return 1; } /** * @dev See {IERC777-totalSupply}. */ function totalSupply() public view override(IERC20, IERC777) returns (uint256) { return _totalSupply; } /** * @dev Returns the amount of tokens owned by an account (`tokenHolder`). */ function balanceOf(address tokenHolder) public view override(IERC20, IERC777) returns (uint256) { return _balances[tokenHolder]; } /** * @dev See {IERC777-send}. * * Also emits a {IERC20-Transfer} event for ERC20 compatibility. */ function send(address recipient, uint256 amount, bytes memory data) public override { _send(msg.sender, recipient, amount, data, "", true); } /** * @dev See {IERC20-transfer}. * * Unlike `send`, `recipient` is _not_ required to implement the {IERC777Recipient} * interface if it is a contract. * * Also emits a {Sent} event. */ function transfer(address recipient, uint256 amount) public override returns (bool) { require(recipient != address(0), "ERC777: transfer to the zero address"); address from = msg.sender; _callTokensToSend(from, from, recipient, amount, "", ""); _move(from, from, recipient, amount, "", ""); _callTokensReceived(from, from, recipient, amount, "", "", false); return true; } /** * @dev See {IERC777-burn}. * * Also emits a {IERC20-Transfer} event for ERC20 compatibility. */ function burn(uint256 amount, bytes memory data) public override { _burn(msg.sender, amount, data, ""); } /** * @dev See {IERC777-isOperatorFor}. */ function isOperatorFor( address operator, address tokenHolder ) public view override returns (bool) { return operator == tokenHolder || (_defaultOperators[operator] && !_revokedDefaultOperators[tokenHolder][operator]) || _operators[tokenHolder][operator]; } /** * @dev See {IERC777-authorizeOperator}. */ function authorizeOperator(address operator) public override { require(msg.sender != operator, "ERC777: authorizing self as operator"); if (_defaultOperators[operator]) { delete _revokedDefaultOperators[msg.sender][operator]; } else { _operators[msg.sender][operator] = true; } emit AuthorizedOperator(operator, msg.sender); } /** * @dev See {IERC777-revokeOperator}. */ function revokeOperator(address operator) public override { require(operator != msg.sender, "ERC777: revoking self as operator"); if (_defaultOperators[operator]) { _revokedDefaultOperators[msg.sender][operator] = true; } else { delete _operators[msg.sender][operator]; } emit RevokedOperator(operator, msg.sender); } /** * @dev See {IERC777-defaultOperators}. */ function defaultOperators() public view override returns (address[] memory) { return _defaultOperatorsArray; } /** * @dev See {IERC777-operatorSend}. * * Emits {Sent} and {IERC20-Transfer} events. */ function operatorSend( address sender, address recipient, uint256 amount, bytes memory data, bytes memory operatorData ) public override { require(isOperatorFor(msg.sender, sender), "ERC777: caller is not an operator for holder"); _send(sender, recipient, amount, data, operatorData, true); } /** * @dev See {IERC777-operatorBurn}. * * Emits {Burned} and {IERC20-Transfer} events. */ function operatorBurn(address account, uint256 amount, bytes memory data, bytes memory operatorData) public override { require(isOperatorFor(msg.sender, account), "ERC777: caller is not an operator for holder"); _burn(account, amount, data, operatorData); } /** * @dev See {IERC20-allowance}. * * Note that operator and allowance concepts are orthogonal: operators may * not have allowance, and accounts with allowance may not be operators * themselves. */ function allowance(address holder, address spender) public view override returns (uint256) { return _allowances[holder][spender]; } /** * @dev See {IERC20-approve}. * * Note that accounts cannot have allowance issued by their operators. */ function approve(address spender, uint256 value) public override returns (bool) { address holder = msg.sender; _approve(holder, spender, value); return true; } /** * @dev See {IERC20-transferFrom}. * * Note that operator and allowance concepts are orthogonal: operators cannot * call `transferFrom` (unless they have allowance), and accounts with * allowance cannot call `operatorSend` (unless they are operators). * * Emits {Sent}, {IERC20-Transfer} and {IERC20-Approval} events. */ function transferFrom(address holder, address recipient, uint256 amount) public override returns (bool) { require(recipient != address(0), "ERC777: transfer to the zero address"); require(holder != address(0), "ERC777: transfer from the zero address"); address spender = msg.sender; _callTokensToSend(spender, holder, recipient, amount, "", ""); _move(spender, holder, recipient, amount, "", ""); _approve(holder, spender, _allowances[holder][spender].sub(amount, "ERC777: transfer amount exceeds allowance")); _callTokensReceived(spender, holder, recipient, amount, "", "", false); return true; } /** * @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * If a send hook is registered for `account`, the corresponding function * will be called with `operator`, `data` and `operatorData`. * * See {IERC777Sender} and {IERC777Recipient}. * * Emits {Minted} and {IERC20-Transfer} events. * * Requirements * * - `account` cannot be the zero address. * - if `account` is a contract, it must implement the {IERC777Recipient} * interface. */ function _mint( address account, uint256 amount, bytes memory userData, bytes memory operatorData ) internal virtual { require(account != address(0), "ERC777: mint to the zero address"); address operator = msg.sender; _beforeTokenTransfer(operator, address(0), account, amount); // Update state variables _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); _callTokensReceived(operator, address(0), account, amount, userData, operatorData, true); emit Minted(operator, account, amount, userData, operatorData); emit Transfer(address(0), account, amount); } /** * @dev Send tokens * @param from address token holder address * @param to address recipient address * @param amount uint256 amount of tokens to transfer * @param userData bytes extra information provided by the token holder (if any) * @param operatorData bytes extra information provided by the operator (if any) * @param requireReceptionAck if true, contract recipients are required to implement ERC777TokensRecipient */ function _send( address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData, bool requireReceptionAck ) internal { require(from != address(0), "ERC777: send from the zero address"); require(to != address(0), "ERC777: send to the zero address"); address operator = msg.sender; _callTokensToSend(operator, from, to, amount, userData, operatorData); _move(operator, from, to, amount, userData, operatorData); _callTokensReceived(operator, from, to, amount, userData, operatorData, requireReceptionAck); } /** * @dev Burn tokens * @param from address token holder address * @param amount uint256 amount of tokens to burn * @param data bytes extra information provided by the token holder * @param operatorData bytes extra information provided by the operator (if any) */ function _burn( address from, uint256 amount, bytes memory data, bytes memory operatorData ) internal virtual { require(from != address(0), "ERC777: burn from the zero address"); address operator = msg.sender; _beforeTokenTransfer(operator, from, address(0), amount); _callTokensToSend(operator, from, address(0), amount, data, operatorData); // Update state variables _balances[from] = _balances[from].sub(amount, "ERC777: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Burned(operator, from, amount, data, operatorData); emit Transfer(from, address(0), amount); } function _move( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData ) private { _beforeTokenTransfer(operator, from, to, amount); _balances[from] = _balances[from].sub(amount, "ERC777: transfer amount exceeds balance"); _balances[to] = _balances[to].add(amount); emit Sent(operator, from, to, amount, userData, operatorData); emit Transfer(from, to, amount); } /** * @dev See {ERC20-_approve}. * * Note that accounts cannot have allowance issued by their operators. */ function _approve(address holder, address spender, uint256 value) internal { require(holder != address(0), "ERC777: approve from the zero address"); require(spender != address(0), "ERC777: approve to the zero address"); _allowances[holder][spender] = value; emit Approval(holder, spender, value); } /** * @dev Call from.tokensToSend() if the interface is registered * @param operator address operator requesting the transfer * @param from address token holder address * @param to address recipient address * @param amount uint256 amount of tokens to transfer * @param userData bytes extra information provided by the token holder (if any) * @param operatorData bytes extra information provided by the operator (if any) */ function _callTokensToSend( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData ) private { address implementer = _ERC1820_REGISTRY.getInterfaceImplementer(from, _TOKENS_SENDER_INTERFACE_HASH); if (implementer != address(0)) { IERC777Sender(implementer).tokensToSend(operator, from, to, amount, userData, operatorData); } } /** * @dev Call to.tokensReceived() if the interface is registered. Reverts if the recipient is a contract but * tokensReceived() was not registered for the recipient * @param operator address operator requesting the transfer * @param from address token holder address * @param to address recipient address * @param amount uint256 amount of tokens to transfer * @param userData bytes extra information provided by the token holder (if any) * @param operatorData bytes extra information provided by the operator (if any) * @param requireReceptionAck if true, contract recipients are required to implement ERC777TokensRecipient */ function _callTokensReceived( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData, bool requireReceptionAck ) private { address implementer = _ERC1820_REGISTRY.getInterfaceImplementer(to, _TOKENS_RECIPIENT_INTERFACE_HASH); if (implementer != address(0)) { IERC777Recipient(implementer).tokensReceived(operator, from, to, amount, userData, operatorData); } else if (requireReceptionAck) { require(!to.isContract(), "ERC777: token recipient contract has no implementer for ERC777TokensRecipient"); } } /** * @dev Hook that is called before any token transfer. This includes * calls to {send}, {transfer}, {operatorSend}, minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address operator, address from, address to, uint256 amount) internal virtual {} } /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ contract Pausable { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor () internal { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!_paused, "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(_paused, "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(msg.sender); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(msg.sender); } } /** * @dev ERC777 token with pausable token transfers, minting and burning. * * Useful for scenarios such as preventing trades until the end of an evaluation * period, or having an emergency switch for freezing all token transfers in the * event of a large bug. */ abstract contract ERC777Pausable is ERC777, Pausable { /** * @dev See {ERC777-_beforeTokenTransfer}. * * Requirements: * * - the contract must not be paused. */ function _beforeTokenTransfer(address operator, address from, address to, uint256 amount) internal virtual override { super._beforeTokenTransfer(operator, from, to, amount); require(!paused(), "ERC777Pausable: token transfer while paused"); } } /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = msg.sender; _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == msg.sender, "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } contract PIZZAToken is ERC777Pausable, IERC777Sender, IERC777Recipient, Ownable { constructor(uint256 initialSupply) public ERC777(){ _mint(msg.sender, initialSupply, "", ""); } // fallback fallback() external payable { revert('This contract does not support ETH'); } // not receive of ETH receive() external payable { revert('This contract does not support ETH'); } // callback of received function tokensReceived(address operator, address from, address to, uint256 amount, bytes calldata userData, bytes calldata operatorData) public override { } // callback of sent function tokensToSend(address operator, address from, address to, uint256 amount, bytes calldata userData, bytes calldata operatorData) public override { } // pause contract function pause() public onlyOwner { _pause(); } // cancel pausing of contract function unpause() public onlyOwner { _unpause(); } }
Creates `amount` tokens and assigns them to `account`, increasing the total supply. If a send hook is registered for `account`, the corresponding function will be called with `operator`, `data` and `operatorData`. See {IERC777Sender} and {IERC777Recipient}. Emits {Minted} and {IERC20-Transfer} events. Requirements - `account` cannot be the zero address. - if `account` is a contract, it must implement the {IERC777Recipient} interface./ Update state variables
function _mint( address account, uint256 amount, bytes memory userData, bytes memory operatorData ) internal virtual { require(account != address(0), "ERC777: mint to the zero address"); address operator = msg.sender; _beforeTokenTransfer(operator, address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); _callTokensReceived(operator, address(0), account, amount, userData, operatorData, true); emit Minted(operator, account, amount, userData, operatorData); emit Transfer(address(0), account, amount); }
1,708,217
./partial_match/42/0x7Dab59e2Ca3a043316C2039453989d8519756d92/sources/DisposableGovernance.sol
Gets currency by oracalize id./
function getCurrOfApiId(bytes32 myid) external view returns (bytes4) { return allAPIid[myid].currency; }
3,299,900
// SPDX-License-Identifier: Apache-2.0 pragma solidity >=0.6.4 <0.8.0; pragma experimental ABIEncoderV2; import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.3.0/contracts/GSN/Context.sol"; import "https://github.com/vigilance91/solidarity/contracts/allowance/iAllowance.sol"; import "https://github.com/vigilance91/solidarity/contracts/allowance/mixinAllowance.sol"; /// /// @title Allowance Abstract Base Contract /// @author Tyler R. Drury <[email protected]> (www.twitter.com/StudiosVigil) - copyright 1/5/2021, All Rights Reserved /// @dev Allowance interface implementation, /// /// Note: /// this implementation is agnostic in regards to implementing transferFrom, /// and is the responsibility of the deriving contract to implement other such allowance /// related methods themselves, making this ABC versitile and usable for repressenting /// not just an allowance of tokens but any value repressented by a uint256 (such as ETH), /// and could be used to extend virtually any contract with the capacity for allowances of an arbitrary nature /// allowinf for much more rich composition /// abstract contract AllowanceABC is Context, iAllowance { using LogicConstraints for bool; using uint256Constraints for uint256; using AddressConstraints for address; using SafeMath for uint256; constructor( )internal Context() { mixinAllowance.initialize(); } function totalAllowanceHeldInCustody( )public view returns( uint256 ){ return mixinAllowance.totalAllowanceHeldInCustody(); } /// /// @dev Get the current allownace `owner` has granted `spender`, /// if this value is 0, `spender` has not been granted an allowance by `owner` /// See {mixinAllowance.allowance} /// /// Additional Requirements: /// - `owner` and `spender` cannot be null /// - `owner` can not be `spender` /// function allowance( address owner, address spender )public view virtual override returns( uint256 ){ return mixinAllowance.allowanceFor(owner,spender); } /// @dev get allowance of spender which has been previously approved by msg.sender function allowanceFor( address spender )external view returns( uint256 ){ return mixinAllowance.allowanceFor( _msgSender(), spender ); } function _approve( address owner, address spender, uint256 amount )internal virtual returns( bool ){ mixinAllowance.approve( owner, spender, amount ); //after storing amount in allowance, must transfer value to self, //so that this contract can send the funds on spender requests (bool success, ) = payable(address(this)).call{value:amount}(''); success.requireTrue('_approve failed'); return true; } /// @return revokedAllowance {uint256} total allowance revoked function _revokeAllowance( address owner, address spender )internal returns( uint256 revokedAllowance ){ revokedAllowance = mixinAllowance.revoke(owner, spender); (bool success, ) = payable(owner).call{value:revokedAllowance}(''); success.requireTrue('revoke failed'); } /// /// @dev See {mixinAllowance.approve} /// transfer value from caller to this contract to hold as custodian of the ETH value (like an escrow) for `spender`, /// so that owner can not accidentally spend the assigned allowance they have granted `spender`, /// without first explicitly revoking `spender`s allowace, returning the funds to `owner` /// /// Additional Requirements: /// - `spender` cannot be this contract /// function approve( address spender )external payable virtual override returns( bool ){ return _approve( _msgSender(), spender, msg.value ); //amount); } /// @dev convenience wrapper to get the curent available ETH allowance /// approved by this contract for `spender` function thisEthAllowanceFor( address spender )public view virtual returns( uint256 ){ return mixinAllowance.allowanceFor(address(this),spender); } /// /// @dev caller revokes `spender`s allowance, returning the ETH to caller /// Additional Requirements: /// - `spender` cannot be null /// - `spender` cannot be caller /// - `spender` must have a non-zero allowance /// function revokeAllowance( address spender )external virtual override { _revokeAllowance(_msgSender(), spender); } /// /// @dev See {mixinERC20.decreaseAllowance} /// /// Additional Requirements: /// - `spender` cannot be this contract /// - `spender` must have a non-zero allowance to increase it, otherwise first call allow(), /// then call increase/decrease as required /// function _increaseAllowance( address owner, address spender, uint256 addedValue )internal virtual returns( uint256 ){ return mixinAllowance.increaseAllowance( owner, spender, addedValue ); } /// /// @dev See {mixinERC20.decreaseAllowance} /// Additional Requirements: /// - `spender` cannot be null /// - `spender` must already have a non-zero allowance of at least `subtractedValue` /// function _decreaseAllowance( address owner, address spender, uint256 subtractedValue )internal virtual returns( uint256 ){ return mixinAllowance.decreaseAllowance( owner, spender, subtractedValue ); } }
See {mixinERC20.decreaseAllowance} Additional Requirements: - `spender` cannot be this contract - `spender` must have a non-zero allowance to increase it, otherwise first call allow(), then call increase/decrease as required
function _increaseAllowance( address owner, address spender, uint256 addedValue )internal virtual returns( uint256 ){ return mixinAllowance.increaseAllowance( owner, spender, addedValue ); }
5,468,832
pragma solidity ^0.5; // solhint-disable-next-line import './base/openzeppelin/math/SafeMath.sol'; import './base/bancor/BancorFormula.sol'; import './Uninitialized.sol'; import './IMarket.sol'; import './Restricted.sol'; import './Macros.sol'; // #def ONE_DAY 24 * 60 * 60 // #if TEST // #def BLOCKTIME _blockTime // #else // #def BLOCKTIME uint64(block.timestamp) // #endif /// @title Contract that manages buying, selling, minting, burning, and /// moving of Upcity resource tokens. /// @author Lawrence Forman ([email protected]) contract UpcityMarket is BancorFormula, Uninitialized, Restricted, IMarket { using SafeMath for uint256; address private constant ZERO_ADDRESS = address(0x0); // 100% or 1.0 in parts per million. uint32 private constant PPM_ONE = $$(1e6); // The bancor connector weight, which determines price evolution, in ppm. uint32 private constant CONNECTOR_WEIGHT = $$(int(CONNECTOR_WEIGHT * 1e6)); // State for each resource token. struct Token { // The number of tokens minted, in wei. uint256 supply; // The ether balance for this resource. uint256 funds; // Stashed tokens that will be used to fill mint operations until depleted. uint256 stash; // Price yesterday. uint256 priceYesterday; // The canonical index of this token. uint8 idx; // The address of the token contract. address token; // The balances of each address. mapping(address=>uint256) balances; } // @dev When the priceYesterday of each token was last updated. uint64 public yesterday; // Indiividual states for each resource token. mapping(address=>Token) private _tokens; // Token addresses for each resource token. address[NUM_RESOURCES] private _tokenAddresses; /// @dev Raised whenever resource tokens are bought. /// @param resource The address of the token/resource. /// @param to The recepient of the tokens. /// @param value The ether value of the tokens. /// @param bought The number of tokens bought. event Bought( address indexed resource, address indexed to, uint256 value, uint256 bought); /// @dev Raised whenever resource tokens are sold. /// @param resource The address of the token/resource. /// @param to The recepient of the ether. /// @param sold The number of tokens sold. /// @param value The ether value of the tokens. event Sold( address indexed resource, address indexed to, uint256 sold, uint256 value); /// @dev Raised whenever the market is funded. /// @param value The amount of ether deposited. event Funded(uint256 value); // Only callable by a registered token. modifier onlyToken() { require(_tokens[msg.sender].token == msg.sender, ERROR_RESTRICTED); _; } /// @dev Deploy the market. /// init() needs to be called before market functions will work. constructor() public { } /// @dev Fund the markets. /// Attached ether will be distributed evenly across all token markets. function() external payable onlyInitialized { if (msg.value > 0) { _touch(); for (uint8 i = 0; i < NUM_RESOURCES; i++) { Token storage token = _tokens[_tokenAddresses[i]]; token.funds = token.funds.add(msg.value/NUM_RESOURCES); } emit Funded(msg.value); } } /// @dev Initialize and fund the markets. /// This can only be called once by the contract creator. /// Attached ether will be distributed evenly across all token markets. /// This will also establish the "canonical order," of tokens. /// @param supplyLock The amount of each token to mint and lock up immediately. /// @param tokens The address of each token, in canonical order. /// @param authorities Address of authorities to register, which are /// addresses that can mint and burn tokens. function init( uint256 supplyLock, address[NUM_RESOURCES] calldata tokens, address[] calldata authorities) external payable onlyCreator onlyUninitialized { require(msg.value >= NUM_RESOURCES, ERROR_INVALID); // Set authorities. for (uint8 i = 0; i < authorities.length; i++) isAuthority[authorities[i]] = true; // Initialize token states. for (uint8 i = 0; i < NUM_RESOURCES; i++) { address addr = tokens[i]; // Prevent duplicates. require(_tokens[addr].token == ZERO_ADDRESS, ERROR_INVALID); _tokenAddresses[i] = addr; Token storage token = _tokens[addr]; token.token = addr; token.idx = i; token.supply = supplyLock; token.balances[address(this)] = supplyLock; token.funds = msg.value / NUM_RESOURCES; token.priceYesterday = _getTokenPrice( token.funds, supplyLock); } yesterday = $(BLOCKTIME); _bancorInit(); _init(); } /// @dev Get all token addresses the market supports. /// @return Array of token addresses. function getTokens() external view returns (address[NUM_RESOURCES] memory tokens) { // #for RES in range(NUM_RESOURCES) tokens[$$(RES)] = _tokenAddresses[$$(RES)]; // #done } /// @dev Get the state of a resource token. /// @param resource Address of the resource token contract. /// @return The price, supply, (ether) balance, stash, and yesterday's price /// for that token. function describeToken(address resource) external view returns ( uint256 price, uint256 supply, uint256 funds, uint256 stash, uint256 priceYesterday) { Token storage token = _tokens[resource]; require(token.token == resource, ERROR_INVALID); price = getPrices()[token.idx]; supply = token.supply; funds = token.funds; stash = token.stash; priceYesterday = token.priceYesterday; } /// @dev Get the current price of all tokens. /// @return The price of each resource, in wei, in canonical order. function getPrices() public view returns (uint256[NUM_RESOURCES] memory prices) { // #for RES in range(NUM_RESOURCES) prices[$(RES)] = _getTokenPrice( _tokens[_tokenAddresses[$(RES)]].funds, _tokens[_tokenAddresses[$(RES)]].supply); // #done } /// @dev Get the supply of all tokens. /// @return The supply of each resource, in wei, in canonical order. function getSupplies() external view returns (uint256[NUM_RESOURCES] memory supplies) { // #for RES in range(NUM_RESOURCES) supplies[$(RES)] = _tokens[_tokenAddresses[$(RES)]].supply; // #done } /// @dev Get the current supply of a token. /// @param resource Address of the resource token contract. /// @return The supply the resource, in wei, in canonical order. function getSupply(address resource) external view returns (uint256) { Token storage token = _tokens[resource]; require(resource != ZERO_ADDRESS && token.token == resource, ERROR_INVALID); return token.supply; } /// @dev Get the balances all tokens for `owner`. /// @param owner The owner of the tokens. /// @return The amount of each resource held by `owner`, in wei, in /// canonical order. function getBalances(address owner) external view returns (uint256[NUM_RESOURCES] memory balances) { // #for RES in range(NUM_RESOURCES) balances[$(RES)] = _tokens[_tokenAddresses[$(RES)]].balances[owner]; // #done } /// @dev Get the balance of a token for `owner`. /// @param resource Address of the resource token contract. /// @param owner The owner of the tokens. /// @return The amount of the given token held by `owner`. function getBalance(address resource, address owner) external view returns (uint256) { Token storage token = _tokens[resource]; require(resource != ZERO_ADDRESS && token.token == resource, ERROR_INVALID); return token.balances[owner]; } /// @dev Transfer a resource tokens between owners. /// Can only be called by a token contract. /// The resource/token address is msg.sender. /// @param from The owner wallet. /// @param to The receiving wallet /// @param amount Amount of the token to transfer. function proxyTransfer( address from, address to, uint256 amount) external onlyInitialized onlyToken { Token storage token = _tokens[msg.sender]; _transfer(token, from, to, amount); } /// @dev Tansfer tokens between owners. /// Can only be called by an authority. /// @param from The owner wallet. /// @param to The receiving wallet /// @param amounts Amount of each token to transfer. function transfer( address from, address to, uint256[NUM_RESOURCES] calldata amounts) external onlyInitialized onlyAuthority { // #for RES in range(NUM_RESOURCES) _transfer(_tokens[_tokenAddresses[$(RES)]], from, to, amounts[$(RES)]); // #done } /// @dev Buy tokens with ether. /// Any overpayment of ether will be refunded to the buyer immediately. /// @param values Amount of ether to exchange for each resource, in wei, /// in canonical order. /// @param to Recipient of tokens. /// @return The number of each token purchased. function buy(uint256[NUM_RESOURCES] calldata values, address to) external payable onlyInitialized returns (uint256[NUM_RESOURCES] memory bought) { _touch(); uint256 remaining = msg.value; for (uint8 i = 0; i < NUM_RESOURCES; i++) { uint256 size = values[i]; require(size <= remaining, ERROR_INSUFFICIENT); remaining -= size; Token storage token = _tokens[_tokenAddresses[i]]; bought[i] = calculatePurchaseReturn( token.supply, token.funds, CONNECTOR_WEIGHT, size); if (bought[i] > 0) { _mint(token, to, bought[i]); token.funds = token.funds.add(size); emit Bought(token.token, to, size, bought[i]); } } // Refund any overpayment. if (remaining > 0) msg.sender.transfer(remaining); return bought; } /// @dev Sell tokens for ether. /// @param amounts Amount of ether to exchange for each resource, in wei, /// in canonical order. /// @param to Recipient of ether. /// @return The combined amount of ether received. function sell(uint256[NUM_RESOURCES] calldata amounts, address payable to) external onlyInitialized returns (uint256 value) { _touch(); value = 0; for (uint8 i = 0; i < NUM_RESOURCES; i++) { uint256 size = amounts[i]; Token storage token = _tokens[_tokenAddresses[i]]; uint256 _value = calculateSaleReturn( token.supply, token.funds, CONNECTOR_WEIGHT, size); if (_value > 0) { _burn(token, msg.sender, size); token.funds = token.funds.sub(_value); value = value.add(_value); emit Sold(token.token, to, size, _value); } } if (value > 0) to.transfer(value); return value; } /// @dev Stash tokens belonging to `from`. /// These tokens will be held in a pool that will initially fill mint /// operations until the pool is depleted. /// Only an authority may call this. /// @param from The owner whose tokens will be locked. /// @param amounts The number of each token to locked, in canonical order. function stash(address from, uint256[NUM_RESOURCES] calldata amounts) external onlyInitialized onlyAuthority { for (uint8 i = 0; i < NUM_RESOURCES; i++) { Token storage token = _tokens[_tokenAddresses[i]]; uint256 bal = token.balances[from]; require(bal >= amounts[i], ERROR_INSUFFICIENT); token.balances[from] = token.balances[from].sub(amounts[i]); token.stash = token.stash.add(amounts[i]); } } /// @dev Mint tokens to `to`. /// Only an authority may call this. /// @param to The owner of the minted tokens. /// @param amounts The number of each token to mint. function mint(address to, uint256[NUM_RESOURCES] calldata amounts) external onlyInitialized onlyAuthority { _touch(); // #for TOKEN, IDX in map(range(NUM_RESOURCES), R => `_tokens[_tokenAddresses[${R}]]`) _mint($$(TOKEN), to, amounts[$$(IDX)]); // #done } /// @dev Burn tokens owned by `from`. /// Will revert if insufficient supply or balance. /// @param token The token state instance. /// @param from The token owner. /// @param amount The number of tokens to burn (in wei). function _burn(Token storage token, address from, uint256 amount) private { uint256 balance = token.balances[from]; require(token.supply >= amount, ERROR_INSUFFICIENT); require(balance >= amount, ERROR_INSUFFICIENT); token.supply -= amount; token.balances[from] -= amount; } /// @dev Mint tokens to be owned by `to`. /// Stashed tokens will first be used to fill the operation, keeping the /// supply the same, then any outstanding amount will cause new tokens to be /// minted, increasing the supply. /// @param token The token state instance. /// @param to The token owner. /// @param amount The number of tokens to burn (in wei). function _mint(Token storage token, address to, uint256 amount) private { // Try to fill it with stashed tokens first. if (token.stash >= amount) token.stash -= amount; else { // Not enough in stash, mint the outstanding amount. token.supply = token.supply.add(amount - token.stash); token.stash = 0; } token.balances[to] = token.balances[to].add(amount); } /// @dev Move tokens between andresses. /// Will revert if `from` has insufficient balance. /// @param token The token state instance. /// @param from The token owner. /// @param to The token receiver. /// @param amount The number of tokens to move (in wei). function _transfer( Token storage token, address from, address to, uint256 amount) private { assert(token.token != ZERO_ADDRESS); require(to != address(this), ERROR_INVALID); require(to != ZERO_ADDRESS, ERROR_INVALID); require(token.balances[from] >= amount, ERROR_INSUFFICIENT); assert(token.supply + amount >= amount); token.balances[from] -= amount; token.balances[to] = token.balances[to].add(amount); } /// @dev Calculate the price of a token. /// @param funds The funds (ether) held by the market. /// @param supply The token's supply. /// @return The (ether) price. function _getTokenPrice(uint256 funds, uint256 supply) private pure returns (uint256) { return ((1 ether) * funds) / ((supply * CONNECTOR_WEIGHT) / PPM_ONE); } /// @dev Update the price yesterday for all tokens. /// Nothing will happen if less than a day has passed since the last /// update. function _touch() private { uint64 _now = $(BLOCKTIME); if (_now > yesterday && _now - yesterday >= $$(ONE_DAY)) { // #for TOKEN in map(range(NUM_RESOURCES), (X) => `_tokens[_tokenAddresses[${X}]]`) $$(TOKEN).priceYesterday = _getTokenPrice( $$(TOKEN).funds, $$(TOKEN).supply); // #done yesterday = _now; } } // #if TEST // solhint-disable // The current blocktime. uint64 public _blockTime = uint64(block.timestamp); // Set the current blocktime. function __setBlockTime(uint64 t) public { _blockTime = t; } // Advance the current blocktime. function __advanceTime(uint64 dt) public { _blockTime += dt; } // #endif }
Get the balance of a token for `owner`. resource Address of the resource token contract. owner The owner of the tokens. return The amount of the given token held by `owner`.
function getBalance(address resource, address owner) external view returns (uint256) { Token storage token = _tokens[resource]; require(resource != ZERO_ADDRESS && token.token == resource, ERROR_INVALID); return token.balances[owner]; }
5,542,706
// SPDX-License-Identifier: MIT pragma solidity 0.7.6; pragma experimental ABIEncoderV2; // /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ interface IForwarder { struct ForwardRequest { address from; address to; uint256 value; uint256 gas; uint256 nonce; bytes data; uint256 validUntil; } event DomainRegistered(bytes32 indexed domainSeparator, bytes domainValue); event RequestTypeRegistered(bytes32 indexed typeHash, string typeStr); function getNonce(address from) external view returns(uint256); /** * verify the transaction would execute. * validate the signature and the nonce of the request. * revert if either signature or nonce are incorrect. * also revert if domainSeparator or requestTypeHash are not registered. */ function verify( ForwardRequest calldata forwardRequest, bytes32 domainSeparator, bytes32 requestTypeHash, bytes calldata suffixData, bytes calldata signature ) external view; /** * execute a transaction * @param forwardRequest - all transaction parameters * @param domainSeparator - domain used when signing this request * @param requestTypeHash - request type used when signing this request. * @param suffixData - the extension data used when signing this request. * @param signature - signature to validate. * * the transaction is verified, and then executed. * the success and ret of "call" are returned. * This method would revert only verification errors. target errors * are reported using the returned "success" and ret string */ function execute( ForwardRequest calldata forwardRequest, bytes32 domainSeparator, bytes32 requestTypeHash, bytes calldata suffixData, bytes calldata signature ) external payable returns (bool success, bytes memory ret); /** * Register a new Request typehash. * @param typeName - the name of the request type. * @param typeSuffix - any extra data after the generic params. * (must add at least one param. The generic ForwardRequest type is always registered by the constructor) */ function registerRequestType(string calldata typeName, string calldata typeSuffix) external; /** * Register a new domain separator. * The domain separator must have the following fields: name,version,chainId, verifyingContract. * the chainId is the current network's chainId, and the verifyingContract is this forwarder. * This method is given the domain name and version to create and register the domain separator value. * @param name the domain's display name * @param version the domain/protocol version */ function registerDomainSeparator(string calldata name, string calldata version) external; } library ECDSA { /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { // Check the signature length if (signature.length != 65) { revert("ECDSA: invalid signature length"); } // Divide the signature in r, s and v variables bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solhint-disable-next-line no-inline-assembly assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return recover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover-bytes32-bytes-} that receives the `v`, * `r` and `s` signature fields separately. */ function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. require(uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "ECDSA: invalid signature 's' value"); require(v == 27 || v == 28, "ECDSA: invalid signature 'v' value"); // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); require(signer != address(0), "ECDSA: invalid signature"); return signer; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * replicates the behavior of the * https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`] * JSON-RPC method. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } } contract Forwarder is IForwarder { using ECDSA for bytes32; string public constant GENERIC_PARAMS = "address from,address to,uint256 value,uint256 gas,uint256 nonce,bytes data,uint256 validUntil"; string public constant EIP712_DOMAIN_TYPE = "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"; mapping(bytes32 => bool) public typeHashes; mapping(bytes32 => bool) public domains; // Nonces of senders, used to prevent replay attacks mapping(address => uint256) private nonces; // solhint-disable-next-line no-empty-blocks receive() external payable {} function getNonce(address from) public view override returns (uint256) { return nonces[from]; } constructor() { string memory requestType = string(abi.encodePacked("ForwardRequest(", GENERIC_PARAMS, ")")); registerRequestTypeInternal(requestType); } function verify( ForwardRequest calldata req, bytes32 domainSeparator, bytes32 requestTypeHash, bytes calldata suffixData, bytes calldata sig) external override view { _verifyNonce(req); _verifySig(req, domainSeparator, requestTypeHash, suffixData, sig); } function execute( ForwardRequest calldata req, bytes32 domainSeparator, bytes32 requestTypeHash, bytes calldata suffixData, bytes calldata sig ) external payable override returns (bool success, bytes memory ret) { _verifySig(req, domainSeparator, requestTypeHash, suffixData, sig); _verifyAndUpdateNonce(req); require(req.validUntil == 0 || req.validUntil > block.number, "FWD: request expired"); uint gasForTransfer = 0; if ( req.value != 0 ) { gasForTransfer = 40000; //buffer in case we need to move eth after the transaction. } bytes memory callData = abi.encodePacked(req.data, req.from); require(gasleft()*63/64 >= req.gas + gasForTransfer, "FWD: insufficient gas"); // solhint-disable-next-line avoid-low-level-calls (success,ret) = req.to.call{gas : req.gas, value : req.value}(callData); if ( req.value != 0 && address(this).balance>0 ) { // can't fail: req.from signed (off-chain) the request, so it must be an EOA... payable(req.from).transfer(address(this).balance); } return (success,ret); } function _verifyNonce(ForwardRequest calldata req) internal view { require(nonces[req.from] == req.nonce, "FWD: nonce mismatch"); } function _verifyAndUpdateNonce(ForwardRequest calldata req) internal { require(nonces[req.from]++ == req.nonce, "FWD: nonce mismatch"); } function registerRequestType(string calldata typeName, string calldata typeSuffix) external override { for (uint i = 0; i < bytes(typeName).length; i++) { bytes1 c = bytes(typeName)[i]; require(c != "(" && c != ")", "FWD: invalid typename"); } string memory requestType = string(abi.encodePacked(typeName, "(", GENERIC_PARAMS, ",", typeSuffix)); registerRequestTypeInternal(requestType); } function registerDomainSeparator(string calldata name, string calldata version) external override { uint256 chainId; /* solhint-disable-next-line no-inline-assembly */ assembly { chainId := chainid() } bytes memory domainValue = abi.encode( keccak256(bytes(EIP712_DOMAIN_TYPE)), keccak256(bytes(name)), keccak256(bytes(version)), chainId, address(this)); bytes32 domainHash = keccak256(domainValue); domains[domainHash] = true; emit DomainRegistered(domainHash, domainValue); } function registerRequestTypeInternal(string memory requestType) internal { bytes32 requestTypehash = keccak256(bytes(requestType)); typeHashes[requestTypehash] = true; emit RequestTypeRegistered(requestTypehash, requestType); } function _verifySig( ForwardRequest calldata req, bytes32 domainSeparator, bytes32 requestTypeHash, bytes calldata suffixData, bytes calldata sig) internal view { require(domains[domainSeparator], "FWD: unregistered domain sep."); require(typeHashes[requestTypeHash], "FWD: unregistered typehash"); bytes32 digest = keccak256(abi.encodePacked( "\x19\x01", domainSeparator, keccak256(_getEncoded(req, requestTypeHash, suffixData)) )); require(digest.recover(sig) == req.from, "FWD: signature mismatch"); } function _getEncoded( ForwardRequest calldata req, bytes32 requestTypeHash, bytes calldata suffixData ) public pure returns ( bytes memory ) { // we use encodePacked since we append suffixData as-is, not as dynamic param. // still, we must make sure all first params are encoded as abi.encode() // would encode them - as 256-bit-wide params. return abi.encodePacked( requestTypeHash, uint256(uint160(req.from)), uint256(uint160(req.to)), req.value, req.gas, req.nonce, keccak256(req.data), req.validUntil, suffixData ); } } abstract contract IRelayRecipient { /** * return if the forwarder is trusted to forward relayed transactions to us. * the forwarder is required to verify the sender's signature, and verify * the call is not a replay. */ function isTrustedForwarder(address forwarder) public virtual view returns(bool); /** * return the sender of this call. * if the call came through our trusted forwarder, then the real sender is appended as the last 20 bytes * of the msg.data. * otherwise, return `msg.sender` * should be used in the contract anywhere instead of msg.sender */ function _msgSender() internal virtual view returns (address payable); function versionRecipient() external virtual view returns (string memory); } abstract contract BaseRelayRecipient is IRelayRecipient { /* * Forwarder singleton we accept calls from */ address public trustedForwarder; /* * require a function to be called through GSN only */ modifier trustedForwarderOnly() { require(msg.sender == address(trustedForwarder), "Function can only be called through the trusted Forwarder"); _; } function isTrustedForwarder(address forwarder) public override view returns(bool) { return forwarder == trustedForwarder; } /** * return the sender of this call. * if the call came through our trusted forwarder, return the original sender. * otherwise, return `msg.sender`. * should be used in the contract anywhere instead of msg.sender */ function _msgSender() internal override virtual view returns (address payable ret) { if (msg.data.length >= 24 && isTrustedForwarder(msg.sender)) { // At this point we know that the sender is a trusted forwarder, // so we trust that the last bytes of msg.data are the verified sender address. // extract sender address from the end of msg.data assembly { ret := shr(96,calldataload(sub(calldatasize(),20))) } } else { return msg.sender; } } } contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor() {} function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context ,BaseRelayRecipient { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), 'Ownable: caller is not the owner'); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), 'Ownable: new owner is the zero address'); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // interface IBEP20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the token decimals. */ function decimals() external view returns (uint8); /** * @dev Returns the token symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the token name. */ function name() external view returns (string memory); /** * @dev Returns the bep token owner. */ function getOwner() external view returns (address); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address _owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, 'SafeMath: addition overflow'); return c; } /** * @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; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // 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; } uint256 c = a * b; require(c / a == b, 'SafeMath: multiplication overflow'); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, 'SafeMath: division by zero'); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, 'SafeMath: modulo by zero'); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } function min(uint256 x, uint256 y) internal pure returns (uint256 z) { z = x < y ? x : y; } // babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method) function sqrt(uint256 y) internal pure returns (uint256 z) { if (y > 3) { z = y; uint256 x = y / 2 + 1; while (x < z) { z = x; x = (y / x + x) / 2; } } else if (y != 0) { z = 1; } } } // /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, 'Address: insufficient balance'); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{value: amount}(''); require(success, 'Address: unable to send value, recipient may have reverted'); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, 'Address: low-level call failed'); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, 'Address: low-level call with value failed'); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, 'Address: insufficient balance for call'); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue( address target, bytes memory data, uint256 weiValue, string memory errorMessage ) private returns (bytes memory) { require(isContract(target), 'Address: call to non-contract'); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{value: weiValue}(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // /** * @dev Implementation of the {IBEP20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {BEP20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-BEP20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of BEP20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IBEP20-approve}. */ abstract contract BEP20 is Context,BaseRelayRecipient, IBEP20, Ownable { using SafeMath for uint256; using Address for address; mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor(string memory name, string memory symbol) { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the bep token owner. */ function getOwner() external override view returns (address) { return owner(); } /** * @dev Returns the token name. */ function name() public override view returns (string memory) { return _name; } /** * @dev Returns the token decimals. */ function decimals() public override view returns (uint8) { return _decimals; } /** * @dev Returns the token symbol. */ function symbol() public override view returns (string memory) { return _symbol; } /** * @dev See {BEP20-totalSupply}. */ function totalSupply() public override view returns (uint256) { return _totalSupply; } /** * @dev See {BEP20-balanceOf}. */ function balanceOf(address account) public override view returns (uint256) { return _balances[account]; } /** * @dev See {BEP20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ /** * @dev See {BEP20-allowance}. */ function allowance(address owner, address spender) public override view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {BEP20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {BEP20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {BEP20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {BEP20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {BEP20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, 'BEP20: decreased allowance below zero') ); return true; } /** * @dev Creates `amount` tokens and assigns them to `msg.sender`, increasing * the total supply. * * Requirements * * - `msg.sender` must be the token owner */ /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal { require(sender != address(0), 'BEP20: transfer from the zero address'); require(recipient != address(0), 'BEP20: transfer to the zero address'); _balances[sender] = _balances[sender].sub(amount, 'BEP20: transfer amount exceeds balance'); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal { require(account != address(0), 'BEP20: mint to the zero address'); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal { require(account != address(0), 'BEP20: burn from the zero address'); _balances[account] = _balances[account].sub(amount, 'BEP20: burn amount exceeds balance'); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal { require(owner != address(0), 'BEP20: approve from the zero address'); require(spender != address(0), 'BEP20: approve to the zero address'); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Destroys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See {_burn} and {_approve}. */ function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve( account, _msgSender(), _allowances[account][_msgSender()].sub(amount, 'BEP20: burn amount exceeds allowance') ); } } abstract contract Pausable is Context,BaseRelayRecipient { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ // Monetas with Governance. contract Monetas is BaseRelayRecipient, BEP20('Monetas', 'MNTG'),Pausable{ using SafeMath for uint256; constructor() Pausable() { // trustedForwarder =forwarder; _mint(_msgSender(), 5000000000000000000000000); } mapping(address => mapping(address => uint256)) private _allowances; /// @notice Creates `_amount` token to `_to`. Must only be called by the owner (Technoking). function mint(address _to, uint256 _amount) whenNotPaused() public onlyOwner { _mint(_to, _amount); _moveDelegates(address(0), _delegates[_to], _amount); } /// @notice Creates `_amount` token to `_to`. Must only be called by the owner (Technoking). function burn(address _to, uint256 _amount) whenNotPaused() public onlyOwner { _burn(_to, _amount); _moveDelegates(address(0), _delegates[_to], _amount); } function mint(uint256 amount) whenNotPaused() public onlyOwner returns (bool) { _mint(_msgSender(), amount); return true; } function burn(uint256 amount) whenNotPaused() public onlyOwner returns (bool) { _burn(_msgSender(), amount); return true; } function pause() public onlyOwner whenNotPaused { _pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() public onlyOwner whenPaused { _unpause(); } function transfer(address recipient, uint256 amount) whenNotPaused() public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function transferFrom( address sender, address recipient, uint256 amount ) whenNotPaused() public override returns (bool) { _transfer(sender, recipient, amount); _approve( sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, 'BEP20: transfer amount exceeds allowance') ); return true; } string public override versionRecipient="2.2.0"; /** * @dev called by the owner to unpause, returns to normal state */ // Copied and modified from YAM code: // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol // Which is copied and modified from COMPOUND: // https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol mapping (address => address) internal _delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint256 votes; } /// @notice A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice A record of states for signing / validating signatures mapping (address => uint) public nonces; /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegator The address to get delegatee for */ function delegates(address delegator) external view returns (address) { return _delegates[delegator]; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) external { return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig( address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s ) external { bytes32 domainSeparator = keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this) ) ); bytes32 structHash = keccak256( abi.encode( DELEGATION_TYPEHASH, delegatee, nonce, expiry ) ); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", domainSeparator, structHash ) ); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "MNTG::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "MNTG::delegateBySig: invalid nonce"); require(block.timestamp <= expiry, "MNTG::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint256) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) external view returns (uint256) { require(blockNumber < block.number, "MNTG::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = _delegates[delegator]; uint256 delegatorBalance = balanceOf(delegator); // balance of underlying APESs (not scaled); _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { // decrease old representative uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld -(amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { // increase new representative uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld+ amount; _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes ) internal { uint32 blockNumber = safe32(block.number, "MNTG::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function getChainId() internal pure returns (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } function getTrustedForwarder() public view returns(address) { return trustedForwarder; } function setTrustedForwarder(address forwarder) onlyOwner public { trustedForwarder = forwarder; } }
Creates `_amount` token to `_to`. Must only be called by the owner (Technoking).
function mint(address _to, uint256 _amount) whenNotPaused() public onlyOwner { _mint(_to, _amount); _moveDelegates(address(0), _delegates[_to], _amount); }
7,915,055
pragma solidity 0.5.17; pragma experimental ABIEncoderV2; // Libraries import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; // Interfaces import "../../interfaces/loans/ILoanData.sol"; import "../../interfaces/SettingsInterface.sol"; import "../../interfaces/escrow/IEscrow.sol"; import "../../interfaces/loans/ILoanManager.sol"; import "../../providers/openzeppelin/SignedSafeMath.sol"; // Contracts import "../BaseStorage.sol"; import "./LoanStorage.sol"; /*****************************************************************************************************/ /** WARNING **/ /** THIS CONTRACT IS AN UPGRADEABLE FACET! **/ /** --------------------------------------------------------------------------------------------- **/ /** Do NOT place ANY storage/state variables directly in this contract! If you wish to make **/ /** make changes to the state variables used by this contract, do so in its defined Storage **/ /** contract that this contract inherits from **/ /** **/ /** Visit https://docs.openzeppelin.com/upgrades/2.6/proxies#upgrading-via-the-proxy-pattern for **/ /** more information. **/ /*****************************************************************************************************/ /** * @notice This contract stores the logic for calculating loan information. * @dev It is used by the LoanManager contract to delegatecall from. * * @author [email protected]. */ contract LoanData is ILoanData, LoanStorage { using SafeMath for uint256; using SignedSafeMath for int256; using NumbersLib for uint256; using NumbersLib for int256; /** * @notice Checks whether the status of a loan is Active or has Terms Set * @param loanID The loan ID for which to check the status * @return bool value indicating if the loan is active or has terms set */ function isActiveOrSet(uint256 loanID) public view returns (bool) { return loans[loanID].status == TellerCommon.LoanStatus.Active || loans[loanID].status == TellerCommon.LoanStatus.TermsSet; } /** * @notice Checks whether a loan is allowed to be deposited to an Externally Owned Account. * @param loanID The loan ID to check the collateral ratio for. * @return bool indicating whether the loan with specified parameters can be deposited to an EOA. */ function canGoToEOA(uint256 loanID) public view returns (bool) { uint256 overCollateralizedBuffer = settings.getOverCollateralizedBufferValue(); return loans[loanID].loanTerms.collateralRatio >= overCollateralizedBuffer; } /** * @notice Checks whether the loan's collateral ratio is considered to be secured based on the settings collateral buffer value. * @param loanID The loan ID to check. * @return bool value of it being secured or not. */ function isLoanSecured(uint256 loanID) public view returns (bool) { return loans[loanID].loanTerms.collateralRatio >= settings.getCollateralBufferValue(); } /** * @notice Returns the total amount owed for a specified loan. * @param loanID The loan ID to get the total amount owed. * @return uint256 The total owed amount. */ function getTotalOwed(uint256 loanID) public view returns (uint256) { if (loans[loanID].status == TellerCommon.LoanStatus.TermsSet) { uint256 interestOwed = getInterestOwedFor( loanID, loans[loanID].loanTerms.maxLoanAmount ); return loans[loanID].loanTerms.maxLoanAmount.add(interestOwed); } else if (loans[loanID].status == TellerCommon.LoanStatus.Active) { return loans[loanID].principalOwed.add(loans[loanID].interestOwed); } return 0; } /** * @notice Returns the total amount owed for a specified loan. * @param loanID The loan ID to get the total amount owed. * @return uint256 The amount owed. */ function getLoanAmount(uint256 loanID) public view returns (uint256) { if (loans[loanID].status == TellerCommon.LoanStatus.TermsSet) { return loans[loanID].loanTerms.maxLoanAmount; } else if (loans[loanID].status == TellerCommon.LoanStatus.Active) { return loans[loanID].borrowedAmount; } return 0; } /** * @notice Returns the amount of interest owed for a given loan and loan amount. * @param loanID The loan ID to get the owed interest. * @param amountBorrow The principal of the loan to take out. * @return uint256 The interest owed. */ function getInterestOwedFor(uint256 loanID, uint256 amountBorrow) public view returns (uint256) { return amountBorrow.percent(getInterestRatio(loanID)); } /** * @notice Returns the interest ratio based on the loan interest rate for the loan duration. * @dev The interest rate on the loan terms is APY. * @param loanID The loan ID to get the interest rate for. */ function getInterestRatio(uint256 loanID) public view returns (uint256) { return loans[loanID] .loanTerms .interestRate .mul(loans[loanID].loanTerms.duration) .div(SECONDS_PER_YEAR); } /** * @notice Returns the collateral needed for a loan, in the lending token, needed to take out the loan or for it be liquidated. * @param loanID The loan ID for which to get collateral information for * @return uint256 Collateral needed in lending token value */ function getCollateralInLendingTokens(uint256 loanID) public view returns (uint256) { if (!isActiveOrSet(loanID)) { return 0; } return settings.chainlinkAggregator().valueFor( collateralToken, lendingToken, loans[loanID].collateral ); } /** * @notice Get information on the collateral needed for the loan. * @param loanID The loan ID to get collateral info for. * @return int256 Collateral needed in Lending tokens. * @return int256 Collateral needed in Collateral tokens (wei) * @return uint256 The value of the loan held in the escrow contract */ function getCollateralNeededInfo(uint256 loanID) public view returns ( int256 neededInLendingTokens, int256 neededInCollateralTokens, uint256 escrowLoanValue ) { // Get collateral needed in lending tokens. (neededInLendingTokens, escrowLoanValue) = getCollateralNeededInTokens( loanID ); if (neededInLendingTokens == 0) { neededInCollateralTokens = 0; } else { uint256 value = settings.chainlinkAggregator().valueFor( lendingToken, collateralToken, uint256( neededInLendingTokens < 0 ? -neededInLendingTokens : neededInLendingTokens ) ); neededInCollateralTokens = int256(value); if (neededInLendingTokens < 0) { neededInCollateralTokens = neededInCollateralTokens.mul(-1); } } } /** * @notice Returns the minimum collateral value threshold, in the lending token, needed to take out the loan or for it be liquidated. * @dev If the loan status is TermsSet, then the value is whats needed to take out the loan. * @dev If the loan status is Active, then the value is the threshold at which the loan can be liquidated at. * @param loanID The loan ID to get needed collateral info for. * @return int256 The minimum collateral value threshold required. * @return uint256 The value of the loan held in the escrow contract. */ function getCollateralNeededInTokens(uint256 loanID) public view returns (int256 neededInLendingTokens, uint256 escrowLoanValue) { if ( !isActiveOrSet(loanID) || loans[loanID].loanTerms.collateralRatio == 0 ) { return (0, 0); } /* The collateral to principal owed ratio is the sum of: * collateral buffer percent * loan interest rate * liquidation reward percent * X factor of additional collateral */ // * To take out a loan (if status == TermsSet), the required collateral is (max loan amount * the collateral ratio). // * For the loan to not be liquidated (when status == Active), the minimum collateral is (principal owed * (X collateral factor + liquidation reward)). // * If the loan has an escrow account, the minimum collateral is ((principal owed - escrow value) * (X collateral factor + liquidation reward)). if (loans[loanID].status == TellerCommon.LoanStatus.TermsSet) { neededInLendingTokens = int256(getLoanAmount(loanID)).percent( loans[loanID].loanTerms.collateralRatio ); } else { neededInLendingTokens = int256(loans[loanID].principalOwed); uint256 bufferPercent = settings.getCollateralBufferValue(); uint256 requiredRatio = loans[loanID] .loanTerms .collateralRatio .sub(getInterestRatio(loanID)) .sub(bufferPercent); if (loans[loanID].escrow != address(0)) { escrowLoanValue = IEscrow(loans[loanID].escrow) .calculateTotalValue(); neededInLendingTokens = neededInLendingTokens.add( neededInLendingTokens.sub(int256(escrowLoanValue)) ); } neededInLendingTokens = neededInLendingTokens .add(int256(loans[loanID].interestOwed)) .percent(requiredRatio); } } /** * @notice It checks if a loan can be liquidated. * @param loanID The loan ID to check. * @return true if the loan is liquidable. */ function isLiquidable(uint256 loanID) public view returns (bool) { // Check if loan can be liquidated if (loans[loanID].status != TellerCommon.LoanStatus.Active) { return false; } if (loans[loanID].loanTerms.collateralRatio > 0) { // If loan has a collateral ratio, check how much is needed (, int256 neededInCollateral, ) = getCollateralNeededInfo(loanID); return neededInCollateral > int256(loans[loanID].collateral); } else { // Otherwise, check if the loan has expired return now >= loans[loanID].loanStartTime.add( loans[loanID].loanTerms.duration ); } } /** * @notice It gets the current liquidation reward for a given loan. * @param loanID The loan ID to get the info. * @return The value the liquidator will receive denoted in collateral tokens. */ function getLiquidationReward(uint256 loanID) public view returns (int256) { uint256 amountToLiquidate = getTotalOwed(loanID); uint256 availableValue = getCollateralInLendingTokens(loanID).add( IEscrow(loans[loanID].escrow).calculateTotalValue() ); uint256 maxReward = amountToLiquidate.percent( settings.getLiquidateEthPriceValue().diffOneHundredPercent() ); if (availableValue < amountToLiquidate + maxReward) { return int256(availableValue); } else { return int256(maxReward).add(int256(amountToLiquidate)); } } }
Checks whether the status of a loan is Active or has Terms Set loanID The loan ID for which to check the status return bool value indicating if the loan is active or has terms set/
function isActiveOrSet(uint256 loanID) public view returns (bool) { return loans[loanID].status == TellerCommon.LoanStatus.Active || loans[loanID].status == TellerCommon.LoanStatus.TermsSet; }
12,676,659
// SPDX-License-Identifier: MIT pragma solidity 0.8.9; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "./interfaces/ITokenaFactory.sol"; import "./interfaces/IStaking.sol"; /** * @title A master staking contact * @dev Will be deployed once as master contact */ contract Staking is IStaking, AccessControl, ReentrancyGuard { using SafeERC20 for ERC20; ITokenaFactory public immutable factory; // Whether it is initialized and bool private _isInitialized; uint8 public bonusMultiplier; // Accrued token per share uint256[] public accTokenPerShare; uint256 public stakers; uint256 public startBlock; uint256 public endBlock; uint256 public bonusStartBlock; uint256 public bonusEndBlock; uint256[] public rewardPerBlock; uint256[] public rewardTokenAmounts; uint256 public stakedTokenSupply; // The precision factor // The reward token ERC20[] public rewardToken; // The staked token ERC20 public stakedToken; ProjectInfo public info; uint128[] private _PRECISION_FACTOR; uint256 private _numOfRewardTokens; uint256 private _lastRewardBlock; // Info of each user that stakes tokens (stakedToken) mapping(address => UserInfo) public userInfo; struct UserInfo { uint256 amount; // How many staked tokens the user has provided uint256[] rewardDebt; // Reward debt } constructor(address adr) { factory = ITokenaFactory(adr); } /** * @notice initialize stake/LM for user * @param _stakedToken: address of staked token * @param _rewardToken: address of reward token * @param _rewardTokenAmounts: amount of tokens for reward * @param _startBlock: start time in blocks * @param _endBlock: estimate time of life for pool in blocks * @param admin: address of user owner */ function initialize( address _stakedToken, address[] calldata _rewardToken, uint256[] calldata _rewardTokenAmounts, uint256 _startBlock, uint256 _endBlock, ProjectInfo calldata _info, address admin ) external override { require(!_isInitialized, "Already initialized"); require(msg.sender == address(factory), "Initialize not from factory"); _isInitialized = true; _setupRole(DEFAULT_ADMIN_ROLE, admin); // Make this contract initialized stakedToken = ERC20(_stakedToken); uint256 i; for (i; i < _rewardToken.length; i++) { rewardToken.push(ERC20(_rewardToken[i])); accTokenPerShare.push(0); rewardPerBlock.push(_rewardTokenAmounts[i] / (_endBlock - _startBlock)); uint8 decimalsRewardToken = (ERC20(_rewardToken[i]).decimals()); require(decimalsRewardToken < 30, "Must be inferior to 30"); _PRECISION_FACTOR.push(uint128(10**(30 - (decimalsRewardToken)))); } info = _info; startBlock = _startBlock; _lastRewardBlock = _startBlock; bonusMultiplier = 1; endBlock = _endBlock; rewardTokenAmounts = _rewardTokenAmounts; _numOfRewardTokens = _rewardToken.length; } /** * @notice Deposit staked tokens and collect reward tokens (if any) * @param amount: amount to deposit (in stakedToken) */ function deposit(uint256 amount) external nonReentrant { require(amount != 0, "Must deposit not 0"); require(block.number < endBlock, "Pool already end"); UserInfo storage user = userInfo[msg.sender]; uint256 pending; uint256 i; if (user.rewardDebt.length == 0) { user.rewardDebt = new uint256[](_numOfRewardTokens); stakers++; } _updatePool(); uint256 curAmount = user.amount; uint256 balanceBefore = stakedToken.balanceOf(address(this)); stakedToken.safeTransferFrom(address(msg.sender), address(this), amount); uint256 balanceAfter = stakedToken.balanceOf(address(this)); user.amount = user.amount + (balanceAfter - balanceBefore); stakedTokenSupply += (balanceAfter - balanceBefore); for (i = 0; i < _numOfRewardTokens; i++) { if (curAmount > 0) { pending = (curAmount * (accTokenPerShare[i])) / (_PRECISION_FACTOR[i]) - (user.rewardDebt[i]); if (pending > 0) { rewardToken[i].safeTransfer(address(msg.sender), pending); } } user.rewardDebt[i] = (user.amount * (accTokenPerShare[i])) / (_PRECISION_FACTOR[i]); } } /** * @notice Withdraw staked tokens and collect reward tokens * @param amount: amount to withdraw (in stakedToken) */ function withdraw(uint256 amount) external nonReentrant { UserInfo storage user = userInfo[msg.sender]; require(user.amount >= amount, "Amount to withdraw too high"); bool flag; _updatePool(); uint256 pending; uint256 i; uint256 curAmount = user.amount; if (amount > 0) { user.amount = user.amount - (amount); stakedToken.safeTransfer(address(msg.sender), amount); if (user.amount == 0) { flag = true; } } stakedTokenSupply -= amount; for (i = 0; i < _numOfRewardTokens; i++) { pending = ((curAmount * (accTokenPerShare[i])) / (_PRECISION_FACTOR[i]) - (user.rewardDebt[i])); if (pending > 0) { rewardToken[i].safeTransfer(address(msg.sender), pending); } user.rewardDebt[i] = (user.amount * (accTokenPerShare[i])) / (_PRECISION_FACTOR[i]); } if (flag) { delete (userInfo[msg.sender]); stakers--; } } /** * @notice Collect reward tokens of a certain index * @param index: index of the reward token */ function withdrawOnlyIndexWithoutUnstake(uint256 index) external nonReentrant { require(index < _numOfRewardTokens, "Wrong index"); UserInfo storage user = userInfo[msg.sender]; _updatePool(); uint256 newRewardDebt = ((user.amount * (accTokenPerShare[index])) / (_PRECISION_FACTOR[index])); uint256 pending = (newRewardDebt - (user.rewardDebt[index])); if (pending > 0) { rewardToken[index].safeTransfer(address(msg.sender), pending); } user.rewardDebt[index] = newRewardDebt; } /** * @notice Withdraw staked tokens without caring about rewards rewards * @dev Needs to be for emergency. */ function emergencyWithdraw() external nonReentrant { UserInfo storage user = userInfo[msg.sender]; uint256 amountToTransfer = user.amount; stakedTokenSupply -= amountToTransfer; delete (userInfo[msg.sender]); stakers--; if (amountToTransfer > 0) { stakedToken.safeTransfer(address(msg.sender), amountToTransfer); } } /** * @notice Update project info * @param _info Struct of name, link, themeId */ function updateProjectInfo(ProjectInfo calldata _info) external onlyRole(DEFAULT_ADMIN_ROLE) { require(bytes(info.name).length != 0, "Must set name"); require(info.themeId > 0 && info.themeId < 10, "Wrong theme id"); info = _info; } /** * @notice Collect all reward tokens left in pool after certain time has passed * @param toTransfer: address to transfer leftover tokens to */ function getLeftovers(address toTransfer) external nonReentrant onlyRole(DEFAULT_ADMIN_ROLE) { require((endBlock + factory.getDelta()) >= block.number, "Too early"); for (uint256 i; i < _numOfRewardTokens; i++) { ERC20 token = rewardToken[i]; token.safeTransfer(toTransfer, token.balanceOf(address(this))); } } /** * @notice Start bonus time * @param _bonusMultiplier multiplier reward * @param _bonusStartBlock block from which bonus starts * @param _bonusEndBlock block in which user want stop bonus period */ function startBonusTime( uint8 _bonusMultiplier, uint256 _bonusStartBlock, uint256 _bonusEndBlock ) external onlyRole(DEFAULT_ADMIN_ROLE) { require(_bonusMultiplier > 1, "Multiplier must be > 1"); require(_bonusStartBlock >= startBlock && _bonusStartBlock < endBlock, "Non valid start time"); require(_bonusEndBlock > startBlock && _bonusEndBlock > _bonusStartBlock, "Non valid end time"); _updatePool(); require(bonusEndBlock == 0, "Can't start another Bonus Time"); uint256 _endBlock = endBlock - ((_bonusEndBlock - _bonusStartBlock) * (_bonusMultiplier - 1)); require(_endBlock > block.number && _endBlock > startBlock, "Not enough rewards for Bonus"); if (_endBlock < _bonusEndBlock) { bonusEndBlock = _endBlock; } else { bonusEndBlock = _bonusEndBlock; } bonusMultiplier = _bonusMultiplier; bonusStartBlock = _bonusStartBlock; endBlock = _endBlock; } /** * @notice Change time of end pool * @param _endBlock endBlock */ function updateEndBlock(uint256 _endBlock) external onlyRole(DEFAULT_ADMIN_ROLE) nonReentrant { require(endBlock > block.number, "Pool already finished"); require(_endBlock > endBlock, "Cannot shorten"); uint256 blocksAdded = _endBlock - endBlock; for (uint256 i; i < _numOfRewardTokens; i++) { uint256 toTransfer = blocksAdded * rewardPerBlock[i]; require(toTransfer > 100, "Too short for increase"); address taker = factory.getFeeTaker(); uint256 percent = factory.getFeePercentage(); uint256 balanceBefore = rewardToken[i].balanceOf(address(this)); rewardToken[i].safeTransferFrom(msg.sender, address(this), toTransfer); uint256 balanceAfter = rewardToken[i].balanceOf(address(this)); rewardTokenAmounts[i] += balanceAfter - balanceBefore; if (!factory.whitelistAddress(address(rewardToken[i]))) { rewardToken[i].safeTransferFrom(msg.sender, taker, (toTransfer * percent) / 100); } } endBlock = _endBlock; } function getRewardTokens() external view returns (ERC20[] memory) { return rewardToken; } /** * @notice View function to see pending reward on frontend. * @param _user: user address * @return Pending reward for a given user */ function pendingReward(address _user) external view returns (uint256[] memory) { require(block.number > startBlock, "Pool is not started yet"); UserInfo memory user = userInfo[_user]; uint256[] memory toReturn = new uint256[](_numOfRewardTokens); for (uint256 i; i < _numOfRewardTokens; i++) { if (block.number > _lastRewardBlock && stakedTokenSupply != 0) { uint256 multiplier = _getMultiplier(_lastRewardBlock, block.number); uint256 reward = multiplier * (rewardPerBlock[i]); uint256 adjustedTokenPerShare = accTokenPerShare[i] + ((reward * (_PRECISION_FACTOR[i])) / (stakedTokenSupply)); toReturn[i] = (user.amount * (adjustedTokenPerShare)) / (_PRECISION_FACTOR[i]) - (user.rewardDebt[i]); } else { toReturn[i] = (user.amount * (accTokenPerShare[i])) / (_PRECISION_FACTOR[i]) - (user.rewardDebt[i]); } } return toReturn; } /** * @notice Update reward variables of the given pool to be up-to-date. */ function _updatePool() internal { if (block.number <= _lastRewardBlock) { return; } if (stakedTokenSupply == 0) { _lastRewardBlock = block.number; return; } uint256 multiplier = _getMultiplier(_lastRewardBlock, block.number); for (uint256 i; i < _numOfRewardTokens; i++) { uint256 reward = multiplier * (rewardPerBlock[i]); accTokenPerShare[i] = accTokenPerShare[i] + ((reward * (_PRECISION_FACTOR[i])) / (stakedTokenSupply)); } if (endBlock > block.number) { _lastRewardBlock = block.number; } else { _lastRewardBlock = endBlock; } if (bonusEndBlock != 0 && block.number > bonusEndBlock) { bonusStartBlock = 0; bonusEndBlock = 0; bonusMultiplier = 1; } } /** * @notice Return reward multiplier over the given from to to block. * @param from: block to start * @param to: block to finish * @return The weighted multiplier for the given period */ function _getMultiplier(uint256 from, uint256 to) internal view returns (uint256) { from = from >= startBlock ? from : startBlock; to = endBlock > to ? to : endBlock; if (from < bonusStartBlock && to > bonusEndBlock) { return bonusStartBlock - from + to - bonusEndBlock + (bonusEndBlock - bonusStartBlock) * bonusMultiplier; } else if (from < bonusStartBlock && to > bonusStartBlock) { return bonusStartBlock - from + (to - bonusStartBlock) * bonusMultiplier; } else if (from < bonusEndBlock && to > bonusEndBlock) { return to - bonusEndBlock + (bonusEndBlock - from) * bonusMultiplier; } else if (from >= bonusStartBlock && to <= bonusEndBlock) { return (to - from) * bonusMultiplier; } else { return to - from; } } } // SPDX-License-Identifier: MIT pragma solidity 0.8.9; interface ITokenaFactory { function getFeeTaker() external view returns (address); function getFeePercentage() external view returns (uint256); function getDelta() external view returns (uint256); function whitelistAddress(address user) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity 0.8.9; interface IStaking { struct ProjectInfo { string name; string link; uint256 themeId; } function initialize( address stakedToken, address[] memory rewardToken, uint256[] memory rewardTokenAmounts, uint256 startBlock, uint256 endBlock, ProjectInfo calldata info, address admin ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // 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(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC20.sol"; import "./extensions/IERC20Metadata.sol"; import "../../utils/Context.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControl { /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {AccessControl-_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @dev 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) external; /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external; /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IAccessControl.sol"; import "../utils/Context.sol"; import "../utils/Strings.sol"; import "../utils/introspection/ERC165.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context, IAccessControl, ERC165 { struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ */ function _checkRole(bytes32 role, address account) internal view { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", Strings.toHexString(uint160(account), 20), " is missing role ", Strings.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev 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 override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } function _grantRole(bytes32 role, address account) private { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } }
See {IERC165-supportsInterface}./
function initialize( address stakedToken, address[] memory rewardToken, uint256[] memory rewardTokenAmounts, uint256 startBlock, uint256 endBlock, ProjectInfo calldata info, address admin ) external; } pragma solidity ^0.8.0; } pragma solidity ^0.8.0; import "./IERC165.sol"; function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; }
51,429
// SPDX-License-Identifier: BUSL-1.1 // For further clarification please see https://license.premia.legal pragma solidity ^0.8.0; import {EnumerableSet} from "@solidstate/contracts/utils/EnumerableSet.sol"; import {ABDKMath64x64} from "abdk-libraries-solidity/ABDKMath64x64.sol"; import {IPoolIO} from "./IPoolIO.sol"; import {PoolSwap} from "./PoolSwap.sol"; import {PoolStorage} from "./PoolStorage.sol"; import {IPremiaMining} from "../mining/IPremiaMining.sol"; /** * @title Premia option pool * @dev deployed standalone and referenced by PoolProxy */ contract PoolIO is IPoolIO, PoolSwap { using ABDKMath64x64 for int128; using EnumerableSet for EnumerableSet.AddressSet; using EnumerableSet for EnumerableSet.UintSet; using PoolStorage for PoolStorage.Layout; constructor( address ivolOracle, address weth, address premiaMining, address feeReceiver, address feeDiscountAddress, int128 fee64x64, address uniswapV2Factory, address sushiswapFactory ) PoolSwap( ivolOracle, weth, premiaMining, feeReceiver, feeDiscountAddress, fee64x64, uniswapV2Factory, sushiswapFactory ) {} /** * @inheritdoc IPoolIO */ function setDivestmentTimestamp(uint64 timestamp, bool isCallPool) external override { PoolStorage.Layout storage l = PoolStorage.layout(); require( timestamp >= l.depositedAt[msg.sender][isCallPool] + (1 days), "liq lock 1d" ); l.divestmentTimestamps[msg.sender][isCallPool] = timestamp; } /** * @inheritdoc IPoolIO */ function deposit(uint256 amount, bool isCallPool) external payable override { _deposit(amount, isCallPool, false); } /** * @inheritdoc IPoolIO */ function swapAndDeposit( uint256 amount, bool isCallPool, uint256 amountOut, uint256 amountInMax, address[] calldata path, bool isSushi ) external payable override { // If value is passed, amountInMax must be 0, as the value wont be used // If amountInMax is not 0, user wants to do a swap from an ERC20, and therefore no value should be attached require( msg.value == 0 || amountInMax == 0, "value and amountInMax passed" ); // If no amountOut has been passed, we swap the exact deposit amount specified if (amountOut == 0) { amountOut = amount; } if (msg.value > 0) { _swapETHForExactTokens(amountOut, path, isSushi); } else { _swapTokensForExactTokens(amountOut, amountInMax, path, isSushi); } _deposit(amount, isCallPool, true); } /** * @inheritdoc IPoolIO */ function withdraw(uint256 amount, bool isCallPool) public override { PoolStorage.Layout storage l = PoolStorage.layout(); uint256 toWithdraw = amount; _processPendingDeposits(l, isCallPool); uint256 depositedAt = l.depositedAt[msg.sender][isCallPool]; require(depositedAt + (1 days) < block.timestamp, "liq lock 1d"); int128 oldLiquidity64x64 = l.totalFreeLiquiditySupply64x64(isCallPool); { uint256 reservedLiqTokenId = _getReservedLiquidityTokenId( isCallPool ); uint256 reservedLiquidity = _balanceOf( msg.sender, reservedLiqTokenId ); if (reservedLiquidity > 0) { uint256 reservedLiqToWithdraw; if (reservedLiquidity < toWithdraw) { reservedLiqToWithdraw = reservedLiquidity; } else { reservedLiqToWithdraw = toWithdraw; } toWithdraw -= reservedLiqToWithdraw; // burn reserved liquidity tokens from sender _burn(msg.sender, reservedLiqTokenId, reservedLiqToWithdraw); } } if (toWithdraw > 0) { // burn free liquidity tokens from sender _burn(msg.sender, _getFreeLiquidityTokenId(isCallPool), toWithdraw); int128 newLiquidity64x64 = l.totalFreeLiquiditySupply64x64( isCallPool ); _setCLevel(l, oldLiquidity64x64, newLiquidity64x64, isCallPool); } _subUserTVL(l, msg.sender, isCallPool, amount); _pushTo(msg.sender, _getPoolToken(isCallPool), amount); emit Withdrawal(msg.sender, isCallPool, depositedAt, amount); } /** * @inheritdoc IPoolIO */ function reassign(uint256 tokenId, uint256 contractSize) external override returns ( uint256 baseCost, uint256 feeCost, uint256 amountOut ) { PoolStorage.Layout storage l = PoolStorage.layout(); int128 newPrice64x64 = _update(l); ( PoolStorage.TokenType tokenType, uint64 maturity, int128 strike64x64 ) = PoolStorage.parseTokenId(tokenId); bool isCall = tokenType == PoolStorage.TokenType.SHORT_CALL || tokenType == PoolStorage.TokenType.LONG_CALL; (baseCost, feeCost, amountOut) = _reassign( l, msg.sender, maturity, strike64x64, isCall, contractSize, newPrice64x64 ); _pushTo(msg.sender, _getPoolToken(isCall), amountOut); } /** * @inheritdoc IPoolIO */ function reassignBatch( uint256[] calldata tokenIds, uint256[] calldata contractSizes ) public override returns ( uint256[] memory baseCosts, uint256[] memory feeCosts, uint256 amountOutCall, uint256 amountOutPut ) { require(tokenIds.length == contractSizes.length, "diff array length"); PoolStorage.Layout storage l = PoolStorage.layout(); int128 newPrice64x64 = _update(l); baseCosts = new uint256[](tokenIds.length); feeCosts = new uint256[](tokenIds.length); for (uint256 i; i < tokenIds.length; i++) { ( PoolStorage.TokenType tokenType, uint64 maturity, int128 strike64x64 ) = PoolStorage.parseTokenId(tokenIds[i]); bool isCall = tokenType == PoolStorage.TokenType.SHORT_CALL || tokenType == PoolStorage.TokenType.LONG_CALL; uint256 amountOut; uint256 contractSize = contractSizes[i]; (baseCosts[i], feeCosts[i], amountOut) = _reassign( l, msg.sender, maturity, strike64x64, isCall, contractSize, newPrice64x64 ); if (isCall) { amountOutCall += amountOut; } else { amountOutPut += amountOut; } } _pushTo(msg.sender, _getPoolToken(true), amountOutCall); _pushTo(msg.sender, _getPoolToken(false), amountOutPut); } /** * @inheritdoc IPoolIO */ function withdrawAllAndReassignBatch( bool isCallPool, uint256[] calldata tokenIds, uint256[] calldata contractSizes ) external override returns ( uint256[] memory baseCosts, uint256[] memory feeCosts, uint256 amountOutCall, uint256 amountOutPut ) { uint256 balance = _balanceOf( msg.sender, _getFreeLiquidityTokenId(isCallPool) ); if (balance > 0) { withdraw(balance, isCallPool); } (baseCosts, feeCosts, amountOutCall, amountOutPut) = reassignBatch( tokenIds, contractSizes ); } /** * @inheritdoc IPoolIO */ function withdrawFees() external override returns (uint256 amountOutCall, uint256 amountOutPut) { amountOutCall = _withdrawFees(true); amountOutPut = _withdrawFees(false); _pushTo(FEE_RECEIVER_ADDRESS, _getPoolToken(true), amountOutCall); _pushTo(FEE_RECEIVER_ADDRESS, _getPoolToken(false), amountOutPut); } /** * @inheritdoc IPoolIO */ function annihilate(uint256 tokenId, uint256 contractSize) external override { ( PoolStorage.TokenType tokenType, uint64 maturity, int128 strike64x64 ) = PoolStorage.parseTokenId(tokenId); bool isCall = tokenType == PoolStorage.TokenType.SHORT_CALL || tokenType == PoolStorage.TokenType.LONG_CALL; _annihilate(msg.sender, maturity, strike64x64, isCall, contractSize); _pushTo( msg.sender, _getPoolToken(isCall), isCall ? contractSize : PoolStorage.layout().fromUnderlyingToBaseDecimals( strike64x64.mulu(contractSize) ) ); } /** * @inheritdoc IPoolIO */ function claimRewards(bool isCallPool) external override { claimRewards(msg.sender, isCallPool); } /** * @inheritdoc IPoolIO */ function claimRewards(address account, bool isCallPool) public override { PoolStorage.Layout storage l = PoolStorage.layout(); uint256 userTVL = l.userTVL[account][isCallPool]; uint256 totalTVL = l.totalTVL[isCallPool]; IPremiaMining(PREMIA_MINING_ADDRESS).claim( account, address(this), isCallPool, userTVL, userTVL, totalTVL ); } /** * @inheritdoc IPoolIO */ function updateMiningPools() external override { PoolStorage.Layout storage l = PoolStorage.layout(); IPremiaMining(PREMIA_MINING_ADDRESS).updatePool( address(this), true, l.totalTVL[true] ); IPremiaMining(PREMIA_MINING_ADDRESS).updatePool( address(this), false, l.totalTVL[false] ); } /** * @notice deposit underlying currency, underwriting calls of that currency with respect to base currency * @param amount quantity of underlying currency to deposit * @param isCallPool whether to deposit underlying in the call pool or base in the put pool * @param skipWethDeposit if false, will not try to deposit weth from attach eth */ function _deposit( uint256 amount, bool isCallPool, bool skipWethDeposit ) internal { PoolStorage.Layout storage l = PoolStorage.layout(); // Reset gradual divestment timestamp delete l.divestmentTimestamps[msg.sender][isCallPool]; uint256 cap = _getPoolCapAmount(l, isCallPool); require( l.totalTVL[isCallPool] + amount <= cap, "pool deposit cap reached" ); _processPendingDeposits(l, isCallPool); l.depositedAt[msg.sender][isCallPool] = block.timestamp; _addUserTVL(l, msg.sender, isCallPool, amount); _pullFrom( msg.sender, _getPoolToken(isCallPool), amount, skipWethDeposit ); _addToDepositQueue(msg.sender, amount, isCallPool); emit Deposit(msg.sender, isCallPool, amount); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title Set implementation with enumeration functions * @dev derived from https://github.com/OpenZeppelin/openzeppelin-contracts (MIT license) */ library EnumerableSet { struct Set { bytes32[] _values; // 1-indexed to allow 0 to signify nonexistence mapping(bytes32 => uint256) _indexes; } struct Bytes32Set { Set _inner; } struct AddressSet { Set _inner; } struct UintSet { Set _inner; } function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } function indexOf(Bytes32Set storage set, bytes32 value) internal view returns (uint256) { return _indexOf(set._inner, value); } function indexOf(AddressSet storage set, address value) internal view returns (uint256) { return _indexOf(set._inner, bytes32(uint256(uint160(value)))); } function indexOf(UintSet storage set, uint256 value) internal view returns (uint256) { return _indexOf(set._inner, bytes32(value)); } function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } function _at(Set storage set, uint256 index) private view returns (bytes32) { require( set._values.length > index, 'EnumerableSet: index out of bounds' ); return set._values[index]; } function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } function _indexOf(Set storage set, bytes32 value) private view returns (uint256) { unchecked { return set._indexes[value] - 1; } } function _length(Set storage set) private view returns (uint256) { return set._values.length; } function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); set._indexes[value] = set._values.length; return true; } else { return false; } } function _remove(Set storage set, bytes32 value) private returns (bool) { uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { uint256 index = valueIndex - 1; bytes32 last = set._values[set._values.length - 1]; // move last value to now-vacant index set._values[index] = last; set._indexes[last] = index + 1; // clear last index set._values.pop(); delete set._indexes[value]; return true; } else { return false; } } } // SPDX-License-Identifier: BSD-4-Clause /* * ABDK Math 64.64 Smart Contract Library. Copyright © 2019 by ABDK Consulting. * Author: Mikhail Vladimirov <[email protected]> */ pragma solidity ^0.8.0; /** * Smart contract library of mathematical functions operating with signed * 64.64-bit fixed point numbers. Signed 64.64-bit fixed point number is * basically a simple fraction whose numerator is signed 128-bit integer and * denominator is 2^64. As long as denominator is always the same, there is no * need to store it, thus in Solidity signed 64.64-bit fixed point numbers are * represented by int128 type holding only the numerator. */ library ABDKMath64x64 { /* * Minimum value signed 64.64-bit fixed point number may have. */ int128 private constant MIN_64x64 = -0x80000000000000000000000000000000; /* * Maximum value signed 64.64-bit fixed point number may have. */ int128 private constant MAX_64x64 = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; /** * Convert signed 256-bit integer number into signed 64.64-bit fixed point * number. Revert on overflow. * * @param x signed 256-bit integer number * @return signed 64.64-bit fixed point number */ function fromInt (int256 x) internal pure returns (int128) { unchecked { require (x >= -0x8000000000000000 && x <= 0x7FFFFFFFFFFFFFFF); return int128 (x << 64); } } /** * Convert signed 64.64 fixed point number into signed 64-bit integer number * rounding down. * * @param x signed 64.64-bit fixed point number * @return signed 64-bit integer number */ function toInt (int128 x) internal pure returns (int64) { unchecked { return int64 (x >> 64); } } /** * Convert unsigned 256-bit integer number into signed 64.64-bit fixed point * number. Revert on overflow. * * @param x unsigned 256-bit integer number * @return signed 64.64-bit fixed point number */ function fromUInt (uint256 x) internal pure returns (int128) { unchecked { require (x <= 0x7FFFFFFFFFFFFFFF); return int128 (int256 (x << 64)); } } /** * Convert signed 64.64 fixed point number into unsigned 64-bit integer * number rounding down. Revert on underflow. * * @param x signed 64.64-bit fixed point number * @return unsigned 64-bit integer number */ function toUInt (int128 x) internal pure returns (uint64) { unchecked { require (x >= 0); return uint64 (uint128 (x >> 64)); } } /** * Convert signed 128.128 fixed point number into signed 64.64-bit fixed point * number rounding down. Revert on overflow. * * @param x signed 128.128-bin fixed point number * @return signed 64.64-bit fixed point number */ function from128x128 (int256 x) internal pure returns (int128) { unchecked { int256 result = x >> 64; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } } /** * Convert signed 64.64 fixed point number into signed 128.128 fixed point * number. * * @param x signed 64.64-bit fixed point number * @return signed 128.128 fixed point number */ function to128x128 (int128 x) internal pure returns (int256) { unchecked { return int256 (x) << 64; } } /** * Calculate x + y. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function add (int128 x, int128 y) internal pure returns (int128) { unchecked { int256 result = int256(x) + y; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } } /** * Calculate x - y. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function sub (int128 x, int128 y) internal pure returns (int128) { unchecked { int256 result = int256(x) - y; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } } /** * Calculate x * y rounding down. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function mul (int128 x, int128 y) internal pure returns (int128) { unchecked { int256 result = int256(x) * y >> 64; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } } /** * Calculate x * y rounding towards zero, where x is signed 64.64 fixed point * number and y is signed 256-bit integer number. Revert on overflow. * * @param x signed 64.64 fixed point number * @param y signed 256-bit integer number * @return signed 256-bit integer number */ function muli (int128 x, int256 y) internal pure returns (int256) { unchecked { if (x == MIN_64x64) { require (y >= -0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF && y <= 0x1000000000000000000000000000000000000000000000000); return -y << 63; } else { bool negativeResult = false; if (x < 0) { x = -x; negativeResult = true; } if (y < 0) { y = -y; // We rely on overflow behavior here negativeResult = !negativeResult; } uint256 absoluteResult = mulu (x, uint256 (y)); if (negativeResult) { require (absoluteResult <= 0x8000000000000000000000000000000000000000000000000000000000000000); return -int256 (absoluteResult); // We rely on overflow behavior here } else { require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return int256 (absoluteResult); } } } } /** * Calculate x * y rounding down, where x is signed 64.64 fixed point number * and y is unsigned 256-bit integer number. Revert on overflow. * * @param x signed 64.64 fixed point number * @param y unsigned 256-bit integer number * @return unsigned 256-bit integer number */ function mulu (int128 x, uint256 y) internal pure returns (uint256) { unchecked { if (y == 0) return 0; require (x >= 0); uint256 lo = (uint256 (int256 (x)) * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) >> 64; uint256 hi = uint256 (int256 (x)) * (y >> 128); require (hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); hi <<= 64; require (hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF - lo); return hi + lo; } } /** * Calculate x / y rounding towards zero. Revert on overflow or when y is * zero. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function div (int128 x, int128 y) internal pure returns (int128) { unchecked { require (y != 0); int256 result = (int256 (x) << 64) / y; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } } /** * Calculate x / y rounding towards zero, where x and y are signed 256-bit * integer numbers. Revert on overflow or when y is zero. * * @param x signed 256-bit integer number * @param y signed 256-bit integer number * @return signed 64.64-bit fixed point number */ function divi (int256 x, int256 y) internal pure returns (int128) { unchecked { require (y != 0); bool negativeResult = false; if (x < 0) { x = -x; // We rely on overflow behavior here negativeResult = true; } if (y < 0) { y = -y; // We rely on overflow behavior here negativeResult = !negativeResult; } uint128 absoluteResult = divuu (uint256 (x), uint256 (y)); if (negativeResult) { require (absoluteResult <= 0x80000000000000000000000000000000); return -int128 (absoluteResult); // We rely on overflow behavior here } else { require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return int128 (absoluteResult); // We rely on overflow behavior here } } } /** * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit * integer numbers. Revert on overflow or when y is zero. * * @param x unsigned 256-bit integer number * @param y unsigned 256-bit integer number * @return signed 64.64-bit fixed point number */ function divu (uint256 x, uint256 y) internal pure returns (int128) { unchecked { require (y != 0); uint128 result = divuu (x, y); require (result <= uint128 (MAX_64x64)); return int128 (result); } } /** * Calculate -x. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function neg (int128 x) internal pure returns (int128) { unchecked { require (x != MIN_64x64); return -x; } } /** * Calculate |x|. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function abs (int128 x) internal pure returns (int128) { unchecked { require (x != MIN_64x64); return x < 0 ? -x : x; } } /** * Calculate 1 / x rounding towards zero. Revert on overflow or when x is * zero. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function inv (int128 x) internal pure returns (int128) { unchecked { require (x != 0); int256 result = int256 (0x100000000000000000000000000000000) / x; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } } /** * Calculate arithmetics average of x and y, i.e. (x + y) / 2 rounding down. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function avg (int128 x, int128 y) internal pure returns (int128) { unchecked { return int128 ((int256 (x) + int256 (y)) >> 1); } } /** * Calculate geometric average of x and y, i.e. sqrt (x * y) rounding down. * Revert on overflow or in case x * y is negative. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function gavg (int128 x, int128 y) internal pure returns (int128) { unchecked { int256 m = int256 (x) * int256 (y); require (m >= 0); require (m < 0x4000000000000000000000000000000000000000000000000000000000000000); return int128 (sqrtu (uint256 (m))); } } /** * Calculate x^y assuming 0^0 is 1, where x is signed 64.64 fixed point number * and y is unsigned 256-bit integer number. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y uint256 value * @return signed 64.64-bit fixed point number */ function pow (int128 x, uint256 y) internal pure returns (int128) { unchecked { bool negative = x < 0 && y & 1 == 1; uint256 absX = uint128 (x < 0 ? -x : x); uint256 absResult; absResult = 0x100000000000000000000000000000000; if (absX <= 0x10000000000000000) { absX <<= 63; while (y != 0) { if (y & 0x1 != 0) { absResult = absResult * absX >> 127; } absX = absX * absX >> 127; if (y & 0x2 != 0) { absResult = absResult * absX >> 127; } absX = absX * absX >> 127; if (y & 0x4 != 0) { absResult = absResult * absX >> 127; } absX = absX * absX >> 127; if (y & 0x8 != 0) { absResult = absResult * absX >> 127; } absX = absX * absX >> 127; y >>= 4; } absResult >>= 64; } else { uint256 absXShift = 63; if (absX < 0x1000000000000000000000000) { absX <<= 32; absXShift -= 32; } if (absX < 0x10000000000000000000000000000) { absX <<= 16; absXShift -= 16; } if (absX < 0x1000000000000000000000000000000) { absX <<= 8; absXShift -= 8; } if (absX < 0x10000000000000000000000000000000) { absX <<= 4; absXShift -= 4; } if (absX < 0x40000000000000000000000000000000) { absX <<= 2; absXShift -= 2; } if (absX < 0x80000000000000000000000000000000) { absX <<= 1; absXShift -= 1; } uint256 resultShift = 0; while (y != 0) { require (absXShift < 64); if (y & 0x1 != 0) { absResult = absResult * absX >> 127; resultShift += absXShift; if (absResult > 0x100000000000000000000000000000000) { absResult >>= 1; resultShift += 1; } } absX = absX * absX >> 127; absXShift <<= 1; if (absX >= 0x100000000000000000000000000000000) { absX >>= 1; absXShift += 1; } y >>= 1; } require (resultShift < 64); absResult >>= 64 - resultShift; } int256 result = negative ? -int256 (absResult) : int256 (absResult); require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } } /** * Calculate sqrt (x) rounding down. Revert if x < 0. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function sqrt (int128 x) internal pure returns (int128) { unchecked { require (x >= 0); return int128 (sqrtu (uint256 (int256 (x)) << 64)); } } /** * Calculate binary logarithm of x. Revert if x <= 0. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function log_2 (int128 x) internal pure returns (int128) { unchecked { require (x > 0); int256 msb = 0; int256 xc = x; if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; } if (xc >= 0x100000000) { xc >>= 32; msb += 32; } if (xc >= 0x10000) { xc >>= 16; msb += 16; } if (xc >= 0x100) { xc >>= 8; msb += 8; } if (xc >= 0x10) { xc >>= 4; msb += 4; } if (xc >= 0x4) { xc >>= 2; msb += 2; } if (xc >= 0x2) msb += 1; // No need to shift xc anymore int256 result = msb - 64 << 64; uint256 ux = uint256 (int256 (x)) << uint256 (127 - msb); for (int256 bit = 0x8000000000000000; bit > 0; bit >>= 1) { ux *= ux; uint256 b = ux >> 255; ux >>= 127 + b; result += bit * int256 (b); } return int128 (result); } } /** * Calculate natural logarithm of x. Revert if x <= 0. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function ln (int128 x) internal pure returns (int128) { unchecked { require (x > 0); return int128 (int256 ( uint256 (int256 (log_2 (x))) * 0xB17217F7D1CF79ABC9E3B39803F2F6AF >> 128)); } } /** * Calculate binary exponent of x. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function exp_2 (int128 x) internal pure returns (int128) { unchecked { require (x < 0x400000000000000000); // Overflow if (x < -0x400000000000000000) return 0; // Underflow uint256 result = 0x80000000000000000000000000000000; if (x & 0x8000000000000000 > 0) result = result * 0x16A09E667F3BCC908B2FB1366EA957D3E >> 128; if (x & 0x4000000000000000 > 0) result = result * 0x1306FE0A31B7152DE8D5A46305C85EDEC >> 128; if (x & 0x2000000000000000 > 0) result = result * 0x1172B83C7D517ADCDF7C8C50EB14A791F >> 128; if (x & 0x1000000000000000 > 0) result = result * 0x10B5586CF9890F6298B92B71842A98363 >> 128; if (x & 0x800000000000000 > 0) result = result * 0x1059B0D31585743AE7C548EB68CA417FD >> 128; if (x & 0x400000000000000 > 0) result = result * 0x102C9A3E778060EE6F7CACA4F7A29BDE8 >> 128; if (x & 0x200000000000000 > 0) result = result * 0x10163DA9FB33356D84A66AE336DCDFA3F >> 128; if (x & 0x100000000000000 > 0) result = result * 0x100B1AFA5ABCBED6129AB13EC11DC9543 >> 128; if (x & 0x80000000000000 > 0) result = result * 0x10058C86DA1C09EA1FF19D294CF2F679B >> 128; if (x & 0x40000000000000 > 0) result = result * 0x1002C605E2E8CEC506D21BFC89A23A00F >> 128; if (x & 0x20000000000000 > 0) result = result * 0x100162F3904051FA128BCA9C55C31E5DF >> 128; if (x & 0x10000000000000 > 0) result = result * 0x1000B175EFFDC76BA38E31671CA939725 >> 128; if (x & 0x8000000000000 > 0) result = result * 0x100058BA01FB9F96D6CACD4B180917C3D >> 128; if (x & 0x4000000000000 > 0) result = result * 0x10002C5CC37DA9491D0985C348C68E7B3 >> 128; if (x & 0x2000000000000 > 0) result = result * 0x1000162E525EE054754457D5995292026 >> 128; if (x & 0x1000000000000 > 0) result = result * 0x10000B17255775C040618BF4A4ADE83FC >> 128; if (x & 0x800000000000 > 0) result = result * 0x1000058B91B5BC9AE2EED81E9B7D4CFAB >> 128; if (x & 0x400000000000 > 0) result = result * 0x100002C5C89D5EC6CA4D7C8ACC017B7C9 >> 128; if (x & 0x200000000000 > 0) result = result * 0x10000162E43F4F831060E02D839A9D16D >> 128; if (x & 0x100000000000 > 0) result = result * 0x100000B1721BCFC99D9F890EA06911763 >> 128; if (x & 0x80000000000 > 0) result = result * 0x10000058B90CF1E6D97F9CA14DBCC1628 >> 128; if (x & 0x40000000000 > 0) result = result * 0x1000002C5C863B73F016468F6BAC5CA2B >> 128; if (x & 0x20000000000 > 0) result = result * 0x100000162E430E5A18F6119E3C02282A5 >> 128; if (x & 0x10000000000 > 0) result = result * 0x1000000B1721835514B86E6D96EFD1BFE >> 128; if (x & 0x8000000000 > 0) result = result * 0x100000058B90C0B48C6BE5DF846C5B2EF >> 128; if (x & 0x4000000000 > 0) result = result * 0x10000002C5C8601CC6B9E94213C72737A >> 128; if (x & 0x2000000000 > 0) result = result * 0x1000000162E42FFF037DF38AA2B219F06 >> 128; if (x & 0x1000000000 > 0) result = result * 0x10000000B17217FBA9C739AA5819F44F9 >> 128; if (x & 0x800000000 > 0) result = result * 0x1000000058B90BFCDEE5ACD3C1CEDC823 >> 128; if (x & 0x400000000 > 0) result = result * 0x100000002C5C85FE31F35A6A30DA1BE50 >> 128; if (x & 0x200000000 > 0) result = result * 0x10000000162E42FF0999CE3541B9FFFCF >> 128; if (x & 0x100000000 > 0) result = result * 0x100000000B17217F80F4EF5AADDA45554 >> 128; if (x & 0x80000000 > 0) result = result * 0x10000000058B90BFBF8479BD5A81B51AD >> 128; if (x & 0x40000000 > 0) result = result * 0x1000000002C5C85FDF84BD62AE30A74CC >> 128; if (x & 0x20000000 > 0) result = result * 0x100000000162E42FEFB2FED257559BDAA >> 128; if (x & 0x10000000 > 0) result = result * 0x1000000000B17217F7D5A7716BBA4A9AE >> 128; if (x & 0x8000000 > 0) result = result * 0x100000000058B90BFBE9DDBAC5E109CCE >> 128; if (x & 0x4000000 > 0) result = result * 0x10000000002C5C85FDF4B15DE6F17EB0D >> 128; if (x & 0x2000000 > 0) result = result * 0x1000000000162E42FEFA494F1478FDE05 >> 128; if (x & 0x1000000 > 0) result = result * 0x10000000000B17217F7D20CF927C8E94C >> 128; if (x & 0x800000 > 0) result = result * 0x1000000000058B90BFBE8F71CB4E4B33D >> 128; if (x & 0x400000 > 0) result = result * 0x100000000002C5C85FDF477B662B26945 >> 128; if (x & 0x200000 > 0) result = result * 0x10000000000162E42FEFA3AE53369388C >> 128; if (x & 0x100000 > 0) result = result * 0x100000000000B17217F7D1D351A389D40 >> 128; if (x & 0x80000 > 0) result = result * 0x10000000000058B90BFBE8E8B2D3D4EDE >> 128; if (x & 0x40000 > 0) result = result * 0x1000000000002C5C85FDF4741BEA6E77E >> 128; if (x & 0x20000 > 0) result = result * 0x100000000000162E42FEFA39FE95583C2 >> 128; if (x & 0x10000 > 0) result = result * 0x1000000000000B17217F7D1CFB72B45E1 >> 128; if (x & 0x8000 > 0) result = result * 0x100000000000058B90BFBE8E7CC35C3F0 >> 128; if (x & 0x4000 > 0) result = result * 0x10000000000002C5C85FDF473E242EA38 >> 128; if (x & 0x2000 > 0) result = result * 0x1000000000000162E42FEFA39F02B772C >> 128; if (x & 0x1000 > 0) result = result * 0x10000000000000B17217F7D1CF7D83C1A >> 128; if (x & 0x800 > 0) result = result * 0x1000000000000058B90BFBE8E7BDCBE2E >> 128; if (x & 0x400 > 0) result = result * 0x100000000000002C5C85FDF473DEA871F >> 128; if (x & 0x200 > 0) result = result * 0x10000000000000162E42FEFA39EF44D91 >> 128; if (x & 0x100 > 0) result = result * 0x100000000000000B17217F7D1CF79E949 >> 128; if (x & 0x80 > 0) result = result * 0x10000000000000058B90BFBE8E7BCE544 >> 128; if (x & 0x40 > 0) result = result * 0x1000000000000002C5C85FDF473DE6ECA >> 128; if (x & 0x20 > 0) result = result * 0x100000000000000162E42FEFA39EF366F >> 128; if (x & 0x10 > 0) result = result * 0x1000000000000000B17217F7D1CF79AFA >> 128; if (x & 0x8 > 0) result = result * 0x100000000000000058B90BFBE8E7BCD6D >> 128; if (x & 0x4 > 0) result = result * 0x10000000000000002C5C85FDF473DE6B2 >> 128; if (x & 0x2 > 0) result = result * 0x1000000000000000162E42FEFA39EF358 >> 128; if (x & 0x1 > 0) result = result * 0x10000000000000000B17217F7D1CF79AB >> 128; result >>= uint256 (int256 (63 - (x >> 64))); require (result <= uint256 (int256 (MAX_64x64))); return int128 (int256 (result)); } } /** * Calculate natural exponent of x. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function exp (int128 x) internal pure returns (int128) { unchecked { require (x < 0x400000000000000000); // Overflow if (x < -0x400000000000000000) return 0; // Underflow return exp_2 ( int128 (int256 (x) * 0x171547652B82FE1777D0FFDA0D23A7D12 >> 128)); } } /** * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit * integer numbers. Revert on overflow or when y is zero. * * @param x unsigned 256-bit integer number * @param y unsigned 256-bit integer number * @return unsigned 64.64-bit fixed point number */ function divuu (uint256 x, uint256 y) private pure returns (uint128) { unchecked { require (y != 0); uint256 result; if (x <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) result = (x << 64) / y; else { uint256 msb = 192; uint256 xc = x >> 192; if (xc >= 0x100000000) { xc >>= 32; msb += 32; } if (xc >= 0x10000) { xc >>= 16; msb += 16; } if (xc >= 0x100) { xc >>= 8; msb += 8; } if (xc >= 0x10) { xc >>= 4; msb += 4; } if (xc >= 0x4) { xc >>= 2; msb += 2; } if (xc >= 0x2) msb += 1; // No need to shift xc anymore result = (x << 255 - msb) / ((y - 1 >> msb - 191) + 1); require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); uint256 hi = result * (y >> 128); uint256 lo = result * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); uint256 xh = x >> 192; uint256 xl = x << 64; if (xl < lo) xh -= 1; xl -= lo; // We rely on overflow behavior here lo = hi << 128; if (xl < lo) xh -= 1; xl -= lo; // We rely on overflow behavior here assert (xh == hi >> 128); result += xl / y; } require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return uint128 (result); } } /** * Calculate sqrt (x) rounding down, where x is unsigned 256-bit integer * number. * * @param x unsigned 256-bit integer number * @return unsigned 128-bit integer number */ function sqrtu (uint256 x) private pure returns (uint128) { unchecked { if (x == 0) return 0; else { uint256 xx = x; uint256 r = 1; if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; } if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; } if (xx >= 0x100000000) { xx >>= 32; r <<= 16; } if (xx >= 0x10000) { xx >>= 16; r <<= 8; } if (xx >= 0x100) { xx >>= 8; r <<= 4; } if (xx >= 0x10) { xx >>= 4; r <<= 2; } if (xx >= 0x8) { r <<= 1; } r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; // Seven iterations should be enough uint256 r1 = x / r; return uint128 (r < r1 ? r : r1); } } } } // SPDX-License-Identifier: LGPL-3.0-or-later pragma solidity ^0.8.0; /** * @notice Pool interface for LP position and platform fee management functions */ interface IPoolIO { /** * @notice set timestamp after which reinvestment is disabled * @param timestamp timestamp to begin divestment * @param isCallPool whether we set divestment timestamp for the call pool or put pool */ function setDivestmentTimestamp(uint64 timestamp, bool isCallPool) external; /** * @notice deposit underlying currency, underwriting calls of that currency with respect to base currency * @param amount quantity of underlying currency to deposit * @param isCallPool whether to deposit underlying in the call pool or base in the put pool */ function deposit(uint256 amount, bool isCallPool) external payable; /** * @notice deposit underlying currency, underwriting calls of that currency with respect to base currency * @param amount quantity of underlying currency to deposit * @param isCallPool whether to deposit underlying in the call pool or base in the put pool * @param amountOut amount out of tokens requested. If 0, we will swap exact amount necessary to pay the quote * @param amountInMax amount in max of tokens * @param path swap path * @param isSushi whether we use sushi or uniV2 for the swap */ function swapAndDeposit( uint256 amount, bool isCallPool, uint256 amountOut, uint256 amountInMax, address[] calldata path, bool isSushi ) external payable; /** * @notice redeem pool share tokens for underlying asset * @param amount quantity of share tokens to redeem * @param isCallPool whether to deposit underlying in the call pool or base in the put pool */ function withdraw(uint256 amount, bool isCallPool) external; /** * @notice reassign short position to new underwriter * @param tokenId ERC1155 token id (long or short) * @param contractSize quantity of option contract tokens to reassign * @return baseCost quantity of tokens required to reassign short position * @return feeCost quantity of tokens required to pay fees * @return amountOut quantity of liquidity freed and transferred to owner */ function reassign(uint256 tokenId, uint256 contractSize) external returns ( uint256 baseCost, uint256 feeCost, uint256 amountOut ); /** * @notice reassign set of short position to new underwriter * @param tokenIds array of ERC1155 token ids (long or short) * @param contractSizes array of quantities of option contract tokens to reassign * @return baseCosts quantities of tokens required to reassign each short position * @return feeCosts quantities of tokens required to pay fees * @return amountOutCall quantity of call pool liquidity freed and transferred to owner * @return amountOutPut quantity of put pool liquidity freed and transferred to owner */ function reassignBatch( uint256[] calldata tokenIds, uint256[] calldata contractSizes ) external returns ( uint256[] memory baseCosts, uint256[] memory feeCosts, uint256 amountOutCall, uint256 amountOutPut ); /** * @notice withdraw all free liquidity and reassign set of short position to new underwriter * @param isCallPool true for call, false for put * @param tokenIds array of ERC1155 token ids (long or short) * @param contractSizes array of quantities of option contract tokens to reassign * @return baseCosts quantities of tokens required to reassign each short position * @return feeCosts quantities of tokens required to pay fees * @return amountOutCall quantity of call pool liquidity freed and transferred to owner * @return amountOutPut quantity of put pool liquidity freed and transferred to owner */ function withdrawAllAndReassignBatch( bool isCallPool, uint256[] calldata tokenIds, uint256[] calldata contractSizes ) external returns ( uint256[] memory baseCosts, uint256[] memory feeCosts, uint256 amountOutCall, uint256 amountOutPut ); /** * @notice transfer accumulated fees to the fee receiver * @return amountOutCall quantity of underlying tokens transferred * @return amountOutPut quantity of base tokens transferred */ function withdrawFees() external returns (uint256 amountOutCall, uint256 amountOutPut); /** * @notice burn corresponding long and short option tokens and withdraw collateral * @param tokenId ERC1155 token id (long or short) * @param contractSize quantity of option contract tokens to annihilate */ function annihilate(uint256 tokenId, uint256 contractSize) external; /** * @notice claim earned PREMIA emissions * @param isCallPool true for call, false for put */ function claimRewards(bool isCallPool) external; /** * @notice claim earned PREMIA emissions on behalf of given account * @param account account on whose behalf to claim rewards * @param isCallPool true for call, false for put */ function claimRewards(address account, bool isCallPool) external; /** * @notice TODO */ function updateMiningPools() external; } // SPDX-License-Identifier: BUSL-1.1 // For further clarification please see https://license.premia.legal pragma solidity ^0.8.0; import {PoolStorage} from "./PoolStorage.sol"; import {IWETH} from "@solidstate/contracts/utils/IWETH.sol"; import {IUniswapV2Pair} from "@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol"; import {SafeERC20} from "@solidstate/contracts/utils/SafeERC20.sol"; import {IERC20} from "@solidstate/contracts/token/ERC20/IERC20.sol"; import {ABDKMath64x64} from "abdk-libraries-solidity/ABDKMath64x64.sol"; import {PoolInternal} from "./PoolInternal.sol"; /** * @title Premia option pool * @dev deployed standalone and referenced by PoolProxy */ abstract contract PoolSwap is PoolInternal { using SafeERC20 for IERC20; using ABDKMath64x64 for int128; using PoolStorage for PoolStorage.Layout; address internal immutable UNISWAP_V2_FACTORY; address internal immutable SUSHISWAP_FACTORY; constructor( address ivolOracle, address weth, address premiaMining, address feeReceiver, address feeDiscountAddress, int128 fee64x64, address uniswapV2Factory, address sushiswapFactory ) PoolInternal( ivolOracle, weth, premiaMining, feeReceiver, feeDiscountAddress, fee64x64 ) { UNISWAP_V2_FACTORY = uniswapV2Factory; SUSHISWAP_FACTORY = sushiswapFactory; } // calculates the CREATE2 address for a pair without making any external calls function _pairFor( address factory, address tokenA, address tokenB, bool isSushi ) internal pure returns (address pair) { (address token0, address token1) = _sortTokens(tokenA, tokenB); pair = address( uint160( uint256( keccak256( abi.encodePacked( hex"ff", factory, keccak256(abi.encodePacked(token0, token1)), isSushi ? hex"e18a34eb0e04b04f7a0ac29a6e80748dca96319b42c54d679cb821dca90c6303" : hex"96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f" // init code hash ) ) ) ) ); } // returns sorted token addresses, used to handle return values from pairs sorted in this order function _sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) { require(tokenA != tokenB, "UniswapV2Library: IDENTICAL_ADDRESSES"); (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), "UniswapV2Library: ZERO_ADDRESS"); } // performs chained getAmountIn calculations on any number of pairs function _getAmountsIn( address factory, uint256 amountOut, address[] memory path, bool isSushi ) internal view returns (uint256[] memory amounts) { require(path.length >= 2, "UniswapV2Library: INVALID_PATH"); amounts = new uint256[](path.length); amounts[amounts.length - 1] = amountOut; for (uint256 i = path.length - 1; i > 0; i--) { (uint256 reserveIn, uint256 reserveOut) = _getReserves( factory, path[i - 1], path[i], isSushi ); amounts[i - 1] = _getAmountIn(amounts[i], reserveIn, reserveOut); } } // fetches and sorts the reserves for a pair function _getReserves( address factory, address tokenA, address tokenB, bool isSushi ) internal view returns (uint256 reserveA, uint256 reserveB) { (address token0, ) = _sortTokens(tokenA, tokenB); (uint256 reserve0, uint256 reserve1, ) = IUniswapV2Pair( _pairFor(factory, tokenA, tokenB, isSushi) ).getReserves(); (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0); } // given an output amount of an asset and pair reserves, returns a required input amount of the other asset function _getAmountIn( uint256 amountOut, uint256 reserveIn, uint256 reserveOut ) internal pure returns (uint256 amountIn) { require(amountOut > 0, "UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT"); require( reserveIn > 0 && reserveOut > 0, "UniswapV2Library: INSUFFICIENT_LIQUIDITY" ); uint256 numerator = reserveIn * amountOut * 1000; uint256 denominator = (reserveOut - amountOut) * 997; amountIn = (numerator / denominator) + 1; } // requires the initial amount to have already been sent to the first pair function _swap( uint256[] memory amounts, address[] memory path, address _to, bool isSushi ) internal { for (uint256 i; i < path.length - 1; i++) { (address input, address output) = (path[i], path[i + 1]); (address token0, ) = _sortTokens(input, output); uint256 amountOut = amounts[i + 1]; (uint256 amount0Out, uint256 amount1Out) = input == token0 ? (uint256(0), amountOut) : (amountOut, uint256(0)); address to = i < path.length - 2 ? _pairFor( isSushi ? SUSHISWAP_FACTORY : UNISWAP_V2_FACTORY, output, path[i + 2], isSushi ) : _to; IUniswapV2Pair( _pairFor( isSushi ? SUSHISWAP_FACTORY : UNISWAP_V2_FACTORY, input, output, isSushi ) ).swap(amount0Out, amount1Out, to, new bytes(0)); } } function _swapTokensForExactTokens( uint256 amountOut, uint256 amountInMax, address[] calldata path, bool isSushi ) internal returns (uint256[] memory amounts) { amounts = _getAmountsIn( isSushi ? SUSHISWAP_FACTORY : UNISWAP_V2_FACTORY, amountOut, path, isSushi ); require( amounts[0] <= amountInMax, "UniswapV2Router: EXCESSIVE_INPUT_AMOUNT" ); IERC20(path[0]).safeTransferFrom( msg.sender, _pairFor( isSushi ? SUSHISWAP_FACTORY : UNISWAP_V2_FACTORY, path[0], path[1], isSushi ), amounts[0] ); _swap(amounts, path, msg.sender, isSushi); } function _swapETHForExactTokens( uint256 amountOut, address[] calldata path, bool isSushi ) internal returns (uint256[] memory amounts) { require(path[0] == WETH_ADDRESS, "UniswapV2Router: INVALID_PATH"); amounts = _getAmountsIn( isSushi ? SUSHISWAP_FACTORY : UNISWAP_V2_FACTORY, amountOut, path, isSushi ); require( amounts[0] <= msg.value, "UniswapV2Router: EXCESSIVE_INPUT_AMOUNT" ); IWETH(WETH_ADDRESS).deposit{value: amounts[0]}(); assert( IWETH(WETH_ADDRESS).transfer( _pairFor( isSushi ? SUSHISWAP_FACTORY : UNISWAP_V2_FACTORY, path[0], path[1], isSushi ), amounts[0] ) ); _swap(amounts, path, msg.sender, isSushi); // refund dust eth, if any if (msg.value > amounts[0]) { (bool success, ) = payable(msg.sender).call{ value: msg.value - amounts[0] }(new bytes(0)); require( success, "TransferHelper::safeTransferETH: ETH transfer failed" ); } } } // SPDX-License-Identifier: BUSL-1.1 // For further clarification please see https://license.premia.legal pragma solidity ^0.8.0; import {AggregatorInterface} from "@chainlink/contracts/src/v0.8/interfaces/AggregatorInterface.sol"; import {AggregatorV3Interface} from "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol"; import {EnumerableSet, ERC1155EnumerableStorage} from "@solidstate/contracts/token/ERC1155/enumerable/ERC1155EnumerableStorage.sol"; import {ABDKMath64x64} from "abdk-libraries-solidity/ABDKMath64x64.sol"; import {ABDKMath64x64Token} from "../libraries/ABDKMath64x64Token.sol"; import {OptionMath} from "../libraries/OptionMath.sol"; library PoolStorage { using ABDKMath64x64 for int128; using PoolStorage for PoolStorage.Layout; enum TokenType { UNDERLYING_FREE_LIQ, BASE_FREE_LIQ, UNDERLYING_RESERVED_LIQ, BASE_RESERVED_LIQ, LONG_CALL, SHORT_CALL, LONG_PUT, SHORT_PUT } struct PoolSettings { address underlying; address base; address underlyingOracle; address baseOracle; } struct QuoteArgsInternal { address feePayer; // address of the fee payer uint64 maturity; // timestamp of option maturity int128 strike64x64; // 64x64 fixed point representation of strike price int128 spot64x64; // 64x64 fixed point representation of spot price uint256 contractSize; // size of option contract bool isCall; // true for call, false for put } struct QuoteResultInternal { int128 baseCost64x64; // 64x64 fixed point representation of option cost denominated in underlying currency (without fee) int128 feeCost64x64; // 64x64 fixed point representation of option fee cost denominated in underlying currency for call, or base currency for put int128 cLevel64x64; // 64x64 fixed point representation of C-Level of Pool after purchase int128 slippageCoefficient64x64; // 64x64 fixed point representation of slippage coefficient for given order size } struct BatchData { uint256 eta; uint256 totalPendingDeposits; } bytes32 internal constant STORAGE_SLOT = keccak256("premia.contracts.storage.Pool"); uint256 private constant C_DECAY_BUFFER = 12 hours; uint256 private constant C_DECAY_INTERVAL = 4 hours; struct Layout { // ERC20 token addresses address base; address underlying; // AggregatorV3Interface oracle addresses address baseOracle; address underlyingOracle; // token metadata uint8 underlyingDecimals; uint8 baseDecimals; // minimum amounts uint256 baseMinimum; uint256 underlyingMinimum; // deposit caps uint256 basePoolCap; uint256 underlyingPoolCap; // market state int128 _deprecated_steepness64x64; int128 cLevelBase64x64; int128 cLevelUnderlying64x64; uint256 cLevelBaseUpdatedAt; uint256 cLevelUnderlyingUpdatedAt; uint256 updatedAt; // User -> isCall -> depositedAt mapping(address => mapping(bool => uint256)) depositedAt; mapping(address => mapping(bool => uint256)) divestmentTimestamps; // doubly linked list of free liquidity intervals // isCall -> User -> User mapping(bool => mapping(address => address)) liquidityQueueAscending; mapping(bool => mapping(address => address)) liquidityQueueDescending; // minimum resolution price bucket => price mapping(uint256 => int128) bucketPrices64x64; // sequence id (minimum resolution price bucket / 256) => price update sequence mapping(uint256 => uint256) priceUpdateSequences; // isCall -> batch data mapping(bool => BatchData) nextDeposits; // user -> batch timestamp -> isCall -> pending amount mapping(address => mapping(uint256 => mapping(bool => uint256))) pendingDeposits; EnumerableSet.UintSet tokenIds; // user -> isCallPool -> total value locked of user (Used for liquidity mining) mapping(address => mapping(bool => uint256)) userTVL; // isCallPool -> total value locked mapping(bool => uint256) totalTVL; // steepness values int128 steepnessBase64x64; int128 steepnessUnderlying64x64; } function layout() internal pure returns (Layout storage l) { bytes32 slot = STORAGE_SLOT; assembly { l.slot := slot } } /** * @notice calculate ERC1155 token id for given option parameters * @param tokenType TokenType enum * @param maturity timestamp of option maturity * @param strike64x64 64x64 fixed point representation of strike price * @return tokenId token id */ function formatTokenId( TokenType tokenType, uint64 maturity, int128 strike64x64 ) internal pure returns (uint256 tokenId) { tokenId = (uint256(tokenType) << 248) + (uint256(maturity) << 128) + uint256(int256(strike64x64)); } /** * @notice derive option maturity and strike price from ERC1155 token id * @param tokenId token id * @return tokenType TokenType enum * @return maturity timestamp of option maturity * @return strike64x64 option strike price */ function parseTokenId(uint256 tokenId) internal pure returns ( TokenType tokenType, uint64 maturity, int128 strike64x64 ) { assembly { tokenType := shr(248, tokenId) maturity := shr(128, tokenId) strike64x64 := tokenId } } function getTokenDecimals(Layout storage l, bool isCall) internal view returns (uint8 decimals) { decimals = isCall ? l.underlyingDecimals : l.baseDecimals; } /** * @notice get the total supply of free liquidity tokens, minus pending deposits * @param l storage layout struct * @param isCall whether query is for call or put pool * @return 64x64 fixed point representation of total free liquidity */ function totalFreeLiquiditySupply64x64(Layout storage l, bool isCall) internal view returns (int128) { uint256 tokenId = formatTokenId( isCall ? TokenType.UNDERLYING_FREE_LIQ : TokenType.BASE_FREE_LIQ, 0, 0 ); return ABDKMath64x64Token.fromDecimals( ERC1155EnumerableStorage.layout().totalSupply[tokenId] - l.nextDeposits[isCall].totalPendingDeposits, l.getTokenDecimals(isCall) ); } function getReinvestmentStatus( Layout storage l, address account, bool isCallPool ) internal view returns (bool) { uint256 timestamp = l.divestmentTimestamps[account][isCallPool]; return timestamp == 0 || timestamp > block.timestamp; } function addUnderwriter( Layout storage l, address account, bool isCallPool ) internal { require(account != address(0)); mapping(address => address) storage asc = l.liquidityQueueAscending[ isCallPool ]; mapping(address => address) storage desc = l.liquidityQueueDescending[ isCallPool ]; if (_isInQueue(account, asc, desc)) return; address last = desc[address(0)]; asc[last] = account; desc[account] = last; desc[address(0)] = account; } function removeUnderwriter( Layout storage l, address account, bool isCallPool ) internal { require(account != address(0)); mapping(address => address) storage asc = l.liquidityQueueAscending[ isCallPool ]; mapping(address => address) storage desc = l.liquidityQueueDescending[ isCallPool ]; if (!_isInQueue(account, asc, desc)) return; address prev = desc[account]; address next = asc[account]; asc[prev] = next; desc[next] = prev; delete asc[account]; delete desc[account]; } function isInQueue( Layout storage l, address account, bool isCallPool ) internal view returns (bool) { mapping(address => address) storage asc = l.liquidityQueueAscending[ isCallPool ]; mapping(address => address) storage desc = l.liquidityQueueDescending[ isCallPool ]; return _isInQueue(account, asc, desc); } function _isInQueue( address account, mapping(address => address) storage asc, mapping(address => address) storage desc ) private view returns (bool) { return asc[account] != address(0) || desc[address(0)] == account; } /** * @notice get current C-Level, without accounting for pending adjustments * @param l storage layout struct * @param isCall whether query is for call or put pool * @return cLevel64x64 64x64 fixed point representation of C-Level */ function getRawCLevel64x64(Layout storage l, bool isCall) internal view returns (int128 cLevel64x64) { cLevel64x64 = isCall ? l.cLevelUnderlying64x64 : l.cLevelBase64x64; } /** * @notice get current C-Level, accounting for unrealized decay * @param l storage layout struct * @param isCall whether query is for call or put pool * @return cLevel64x64 64x64 fixed point representation of C-Level */ function getDecayAdjustedCLevel64x64(Layout storage l, bool isCall) internal view returns (int128 cLevel64x64) { // get raw C-Level from storage cLevel64x64 = l.getRawCLevel64x64(isCall); // account for C-Level decay cLevel64x64 = l.applyCLevelDecayAdjustment(cLevel64x64, isCall); } /** * @notice get updated C-Level and pool liquidity level, accounting for decay and pending deposits * @param l storage layout struct * @param isCall whether to update C-Level for call or put pool * @return cLevel64x64 64x64 fixed point representation of C-Level * @return liquidity64x64 64x64 fixed point representation of new liquidity amount */ function getRealPoolState(Layout storage l, bool isCall) internal view returns (int128 cLevel64x64, int128 liquidity64x64) { PoolStorage.BatchData storage batchData = l.nextDeposits[isCall]; int128 oldCLevel64x64 = l.getDecayAdjustedCLevel64x64(isCall); int128 oldLiquidity64x64 = l.totalFreeLiquiditySupply64x64(isCall); if ( batchData.totalPendingDeposits > 0 && batchData.eta != 0 && block.timestamp >= batchData.eta ) { liquidity64x64 = ABDKMath64x64Token .fromDecimals( batchData.totalPendingDeposits, l.getTokenDecimals(isCall) ) .add(oldLiquidity64x64); cLevel64x64 = l.applyCLevelLiquidityChangeAdjustment( oldCLevel64x64, oldLiquidity64x64, liquidity64x64, isCall ); } else { cLevel64x64 = oldCLevel64x64; liquidity64x64 = oldLiquidity64x64; } } /** * @notice calculate updated C-Level, accounting for unrealized decay * @param l storage layout struct * @param oldCLevel64x64 64x64 fixed point representation pool C-Level before accounting for decay * @param isCall whether query is for call or put pool * @return cLevel64x64 64x64 fixed point representation of C-Level of Pool after accounting for decay */ function applyCLevelDecayAdjustment( Layout storage l, int128 oldCLevel64x64, bool isCall ) internal view returns (int128 cLevel64x64) { uint256 timeElapsed = block.timestamp - (isCall ? l.cLevelUnderlyingUpdatedAt : l.cLevelBaseUpdatedAt); // do not apply C decay if less than 24 hours have elapsed if (timeElapsed > C_DECAY_BUFFER) { timeElapsed -= C_DECAY_BUFFER; } else { return oldCLevel64x64; } int128 timeIntervalsElapsed64x64 = ABDKMath64x64.divu( timeElapsed, C_DECAY_INTERVAL ); uint256 tokenId = formatTokenId( isCall ? TokenType.UNDERLYING_FREE_LIQ : TokenType.BASE_FREE_LIQ, 0, 0 ); uint256 tvl = l.totalTVL[isCall]; int128 utilization = ABDKMath64x64.divu( tvl - (ERC1155EnumerableStorage.layout().totalSupply[tokenId] - l.nextDeposits[isCall].totalPendingDeposits), tvl ); return OptionMath.calculateCLevelDecay( OptionMath.CalculateCLevelDecayArgs( timeIntervalsElapsed64x64, oldCLevel64x64, utilization, 0xb333333333333333, // 0.7 0xe666666666666666, // 0.9 0x10000000000000000, // 1.0 0x10000000000000000, // 1.0 0xe666666666666666, // 0.9 0x56fc2a2c515da32ea // 2e ) ); } /** * @notice calculate updated C-Level, accounting for change in liquidity * @param l storage layout struct * @param oldCLevel64x64 64x64 fixed point representation pool C-Level before accounting for liquidity change * @param oldLiquidity64x64 64x64 fixed point representation of previous liquidity * @param newLiquidity64x64 64x64 fixed point representation of current liquidity * @param isCallPool whether to update C-Level for call or put pool * @return cLevel64x64 64x64 fixed point representation of C-Level */ function applyCLevelLiquidityChangeAdjustment( Layout storage l, int128 oldCLevel64x64, int128 oldLiquidity64x64, int128 newLiquidity64x64, bool isCallPool ) internal view returns (int128 cLevel64x64) { int128 steepness64x64 = isCallPool ? l.steepnessUnderlying64x64 : l.steepnessBase64x64; // fallback to deprecated storage value if side-specific value is not set if (steepness64x64 == 0) steepness64x64 = l._deprecated_steepness64x64; cLevel64x64 = OptionMath.calculateCLevel( oldCLevel64x64, oldLiquidity64x64, newLiquidity64x64, steepness64x64 ); if (cLevel64x64 < 0xb333333333333333) { cLevel64x64 = int128(0xb333333333333333); // 64x64 fixed point representation of 0.7 } } /** * @notice set C-Level to arbitrary pre-calculated value * @param cLevel64x64 new C-Level of pool * @param isCallPool whether to update C-Level for call or put pool */ function setCLevel( Layout storage l, int128 cLevel64x64, bool isCallPool ) internal { if (isCallPool) { l.cLevelUnderlying64x64 = cLevel64x64; l.cLevelUnderlyingUpdatedAt = block.timestamp; } else { l.cLevelBase64x64 = cLevel64x64; l.cLevelBaseUpdatedAt = block.timestamp; } } function setOracles( Layout storage l, address baseOracle, address underlyingOracle ) internal { require( AggregatorV3Interface(baseOracle).decimals() == AggregatorV3Interface(underlyingOracle).decimals(), "Pool: oracle decimals must match" ); l.baseOracle = baseOracle; l.underlyingOracle = underlyingOracle; } function fetchPriceUpdate(Layout storage l) internal view returns (int128 price64x64) { int256 priceUnderlying = AggregatorInterface(l.underlyingOracle) .latestAnswer(); int256 priceBase = AggregatorInterface(l.baseOracle).latestAnswer(); return ABDKMath64x64.divi(priceUnderlying, priceBase); } /** * @notice set price update for hourly bucket corresponding to given timestamp * @param l storage layout struct * @param timestamp timestamp to update * @param price64x64 64x64 fixed point representation of price */ function setPriceUpdate( Layout storage l, uint256 timestamp, int128 price64x64 ) internal { uint256 bucket = timestamp / (1 hours); l.bucketPrices64x64[bucket] = price64x64; l.priceUpdateSequences[bucket >> 8] += 1 << (255 - (bucket & 255)); } /** * @notice get price update for hourly bucket corresponding to given timestamp * @param l storage layout struct * @param timestamp timestamp to query * @return 64x64 fixed point representation of price */ function getPriceUpdate(Layout storage l, uint256 timestamp) internal view returns (int128) { return l.bucketPrices64x64[timestamp / (1 hours)]; } /** * @notice get first price update available following given timestamp * @param l storage layout struct * @param timestamp timestamp to query * @return 64x64 fixed point representation of price */ function getPriceUpdateAfter(Layout storage l, uint256 timestamp) internal view returns (int128) { // price updates are grouped into hourly buckets uint256 bucket = timestamp / (1 hours); // divide by 256 to get the index of the relevant price update sequence uint256 sequenceId = bucket >> 8; // get position within sequence relevant to current price update uint256 offset = bucket & 255; // shift to skip buckets from earlier in sequence uint256 sequence = (l.priceUpdateSequences[sequenceId] << offset) >> offset; // iterate through future sequences until a price update is found // sequence corresponding to current timestamp used as upper bound uint256 currentPriceUpdateSequenceId = block.timestamp / (256 hours); while (sequence == 0 && sequenceId <= currentPriceUpdateSequenceId) { sequence = l.priceUpdateSequences[++sequenceId]; } // if no price update is found (sequence == 0) function will return 0 // this should never occur, as each relevant external function triggers a price update // the most significant bit of the sequence corresponds to the offset of the relevant bucket uint256 msb; for (uint256 i = 128; i > 0; i >>= 1) { if (sequence >> i > 0) { msb += i; sequence >>= i; } } return l.bucketPrices64x64[((sequenceId + 1) << 8) - msb - 1]; } function fromBaseToUnderlyingDecimals(Layout storage l, uint256 value) internal view returns (uint256) { int128 valueFixed64x64 = ABDKMath64x64Token.fromDecimals( value, l.baseDecimals ); return ABDKMath64x64Token.toDecimals( valueFixed64x64, l.underlyingDecimals ); } function fromUnderlyingToBaseDecimals(Layout storage l, uint256 value) internal view returns (uint256) { int128 valueFixed64x64 = ABDKMath64x64Token.fromDecimals( value, l.underlyingDecimals ); return ABDKMath64x64Token.toDecimals(valueFixed64x64, l.baseDecimals); } } // SPDX-License-Identifier: LGPL-3.0-or-later pragma solidity ^0.8.0; import {PremiaMiningStorage} from "./PremiaMiningStorage.sol"; interface IPremiaMining { function addPremiaRewards(uint256 _amount) external; function premiaRewardsAvailable() external view returns (uint256); function getTotalAllocationPoints() external view returns (uint256); function getPoolInfo(address pool, bool isCallPool) external view returns (PremiaMiningStorage.PoolInfo memory); function getPremiaPerYear() external view returns (uint256); function addPool(address _pool, uint256 _allocPoints) external; function setPoolAllocPoints( address[] memory _pools, uint256[] memory _allocPoints ) external; function pendingPremia( address _pool, bool _isCallPool, address _user ) external view returns (uint256); function updatePool( address _pool, bool _isCallPool, uint256 _totalTVL ) external; function allocatePending( address _user, address _pool, bool _isCallPool, uint256 _userTVLOld, uint256 _userTVLNew, uint256 _totalTVL ) external; function claim( address _user, address _pool, bool _isCallPool, uint256 _userTVLOld, uint256 _userTVLNew, uint256 _totalTVL ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import { IERC20 } from '../token/ERC20/IERC20.sol'; import { IERC20Metadata } from '../token/ERC20/metadata/IERC20Metadata.sol'; /** * @title WETH (Wrapped ETH) interface */ interface IWETH is IERC20, IERC20Metadata { /** * @notice convert ETH to WETH */ function deposit() external payable; /** * @notice convert WETH to ETH * @dev if caller is a contract, it should have a fallback or receive function * @param amount quantity of WETH to convert, denominated in wei */ function withdraw(uint256 amount) external; } pragma solidity >=0.5.0; interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import { IERC20 } from '../token/ERC20/IERC20.sol'; import { AddressUtils } from './AddressUtils.sol'; /** * @title Safe ERC20 interaction library * @dev derived from https://github.com/OpenZeppelin/openzeppelin-contracts/ (MIT license) */ library SafeERC20 { using AddressUtils for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn( token, abi.encodeWithSelector(token.transfer.selector, to, value) ); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn( token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value) ); } /** * @dev safeApprove (like approve) should only be called when setting an initial allowance or when resetting it to zero; otherwise prefer safeIncreaseAllowance and safeDecreaseAllowance */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { require( (value == 0) || (token.allowance(address(this), spender) == 0), 'SafeERC20: approve from non-zero to non-zero allowance' ); _callOptionalReturn( token, abi.encodeWithSelector(token.approve.selector, spender, value) ); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn( token, abi.encodeWithSelector( token.approve.selector, spender, newAllowance ) ); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require( oldAllowance >= value, 'SafeERC20: decreased allowance below zero' ); uint256 newAllowance = oldAllowance - value; _callOptionalReturn( token, abi.encodeWithSelector( token.approve.selector, spender, newAllowance ) ); } } /** * @notice send transaction data and check validity of return value, if present * @param token ERC20 token interface * @param data transaction data */ function _callOptionalReturn(IERC20 token, bytes memory data) private { bytes memory returndata = address(token).functionCall( data, 'SafeERC20: low-level call failed' ); if (returndata.length > 0) { require( abi.decode(returndata, (bool)), 'SafeERC20: ERC20 operation did not succeed' ); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import { IERC20Internal } from './IERC20Internal.sol'; /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ interface IERC20 is IERC20Internal { /** * @notice query the total minted token supply * @return token supply */ function totalSupply() external view returns (uint256); /** * @notice query the token balance of given account * @param account address to query * @return token balance */ function balanceOf(address account) external view returns (uint256); /** * @notice query the allowance granted from given holder to given spender * @param holder approver of allowance * @param spender recipient of allowance * @return token allowance */ function allowance(address holder, address spender) external view returns (uint256); /** * @notice grant approval to spender to spend tokens * @dev prefer ERC20Extended functions to avoid transaction-ordering vulnerability (see https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729) * @param spender recipient of allowance * @param amount quantity of tokens approved for spending * @return success status (always true; otherwise function should revert) */ function approve(address spender, uint256 amount) external returns (bool); /** * @notice transfer tokens to given recipient * @param recipient beneficiary of token transfer * @param amount quantity of tokens to transfer * @return success status (always true; otherwise function should revert) */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @notice transfer tokens to given recipient on behalf of given holder * @param holder holder of tokens prior to transfer * @param recipient beneficiary of token transfer * @param amount quantity of tokens to transfer * @return success status (always true; otherwise function should revert) */ function transferFrom( address holder, address recipient, uint256 amount ) external returns (bool); } // SPDX-License-Identifier: BUSL-1.1 // For further clarification please see https://license.premia.legal pragma solidity ^0.8.0; import {IERC173} from "@solidstate/contracts/access/IERC173.sol"; import {OwnableStorage} from "@solidstate/contracts/access/OwnableStorage.sol"; import {IERC20} from "@solidstate/contracts/token/ERC20/IERC20.sol"; import {ERC1155EnumerableInternal, ERC1155EnumerableStorage, EnumerableSet} from "@solidstate/contracts/token/ERC1155/enumerable/ERC1155Enumerable.sol"; import {IWETH} from "@solidstate/contracts/utils/IWETH.sol"; import {PoolStorage} from "./PoolStorage.sol"; import {ABDKMath64x64} from "abdk-libraries-solidity/ABDKMath64x64.sol"; import {ABDKMath64x64Token} from "../libraries/ABDKMath64x64Token.sol"; import {OptionMath} from "../libraries/OptionMath.sol"; import {IFeeDiscount} from "../staking/IFeeDiscount.sol"; import {IPoolEvents} from "./IPoolEvents.sol"; import {IPremiaMining} from "../mining/IPremiaMining.sol"; import {IVolatilitySurfaceOracle} from "../oracle/IVolatilitySurfaceOracle.sol"; /** * @title Premia option pool * @dev deployed standalone and referenced by PoolProxy */ contract PoolInternal is IPoolEvents, ERC1155EnumerableInternal { using ABDKMath64x64 for int128; using EnumerableSet for EnumerableSet.AddressSet; using EnumerableSet for EnumerableSet.UintSet; using PoolStorage for PoolStorage.Layout; address internal immutable WETH_ADDRESS; address internal immutable PREMIA_MINING_ADDRESS; address internal immutable FEE_RECEIVER_ADDRESS; address internal immutable FEE_DISCOUNT_ADDRESS; address internal immutable IVOL_ORACLE_ADDRESS; int128 internal immutable FEE_64x64; uint256 internal immutable UNDERLYING_FREE_LIQ_TOKEN_ID; uint256 internal immutable BASE_FREE_LIQ_TOKEN_ID; uint256 internal immutable UNDERLYING_RESERVED_LIQ_TOKEN_ID; uint256 internal immutable BASE_RESERVED_LIQ_TOKEN_ID; uint256 internal constant INVERSE_BASIS_POINT = 1e4; uint256 internal constant BATCHING_PERIOD = 260; // Minimum APY for capital locked up to underwrite options. // The quote will return a minimum price corresponding to this APY int128 internal constant MIN_APY_64x64 = 0x4ccccccccccccccd; // 0.3 constructor( address ivolOracle, address weth, address premiaMining, address feeReceiver, address feeDiscountAddress, int128 fee64x64 ) { IVOL_ORACLE_ADDRESS = ivolOracle; WETH_ADDRESS = weth; PREMIA_MINING_ADDRESS = premiaMining; FEE_RECEIVER_ADDRESS = feeReceiver; // PremiaFeeDiscount contract address FEE_DISCOUNT_ADDRESS = feeDiscountAddress; FEE_64x64 = fee64x64; UNDERLYING_FREE_LIQ_TOKEN_ID = PoolStorage.formatTokenId( PoolStorage.TokenType.UNDERLYING_FREE_LIQ, 0, 0 ); BASE_FREE_LIQ_TOKEN_ID = PoolStorage.formatTokenId( PoolStorage.TokenType.BASE_FREE_LIQ, 0, 0 ); UNDERLYING_RESERVED_LIQ_TOKEN_ID = PoolStorage.formatTokenId( PoolStorage.TokenType.UNDERLYING_RESERVED_LIQ, 0, 0 ); BASE_RESERVED_LIQ_TOKEN_ID = PoolStorage.formatTokenId( PoolStorage.TokenType.BASE_RESERVED_LIQ, 0, 0 ); } modifier onlyProtocolOwner() { require( msg.sender == IERC173(OwnableStorage.layout().owner).owner(), "Not protocol owner" ); _; } function _getFeeDiscount(address feePayer) internal view returns (uint256 discount) { if (FEE_DISCOUNT_ADDRESS != address(0)) { discount = IFeeDiscount(FEE_DISCOUNT_ADDRESS).getDiscount(feePayer); } } function _getFeeWithDiscount(address feePayer, uint256 fee) internal view returns (uint256) { uint256 discount = _getFeeDiscount(feePayer); return fee - ((fee * discount) / INVERSE_BASIS_POINT); } function _withdrawFees(bool isCall) internal returns (uint256 amount) { uint256 tokenId = _getReservedLiquidityTokenId(isCall); amount = _balanceOf(FEE_RECEIVER_ADDRESS, tokenId); if (amount > 0) { _burn(FEE_RECEIVER_ADDRESS, tokenId, amount); emit FeeWithdrawal(isCall, amount); } } /** * @notice calculate price of option contract * @param args structured quote arguments * @return result quote result */ function _quote(PoolStorage.QuoteArgsInternal memory args) internal view returns (PoolStorage.QuoteResultInternal memory result) { require( args.strike64x64 > 0 && args.spot64x64 > 0 && args.maturity > 0, "invalid args" ); PoolStorage.Layout storage l = PoolStorage.layout(); int128 contractSize64x64 = ABDKMath64x64Token.fromDecimals( args.contractSize, l.underlyingDecimals ); (int128 adjustedCLevel64x64, int128 oldLiquidity64x64) = l .getRealPoolState(args.isCall); require(oldLiquidity64x64 > 0, "no liq"); int128 timeToMaturity64x64 = ABDKMath64x64.divu( args.maturity - block.timestamp, 365 days ); int128 annualizedVolatility64x64 = IVolatilitySurfaceOracle( IVOL_ORACLE_ADDRESS ).getAnnualizedVolatility64x64( l.base, l.underlying, args.spot64x64, args.strike64x64, timeToMaturity64x64, args.isCall ); require(annualizedVolatility64x64 > 0, "vol = 0"); int128 collateral64x64 = args.isCall ? contractSize64x64 : contractSize64x64.mul(args.strike64x64); ( int128 price64x64, int128 cLevel64x64, int128 slippageCoefficient64x64 ) = OptionMath.quotePrice( OptionMath.QuoteArgs( annualizedVolatility64x64.mul(annualizedVolatility64x64), args.strike64x64, args.spot64x64, timeToMaturity64x64, adjustedCLevel64x64, oldLiquidity64x64, oldLiquidity64x64.sub(collateral64x64), 0x10000000000000000, // 64x64 fixed point representation of 1 MIN_APY_64x64, args.isCall ) ); result.baseCost64x64 = args.isCall ? price64x64.mul(contractSize64x64).div(args.spot64x64) : price64x64.mul(contractSize64x64); result.feeCost64x64 = result.baseCost64x64.mul(FEE_64x64); result.cLevel64x64 = cLevel64x64; result.slippageCoefficient64x64 = slippageCoefficient64x64; int128 discount = ABDKMath64x64.divu( _getFeeDiscount(args.feePayer), INVERSE_BASIS_POINT ); result.feeCost64x64 -= result.feeCost64x64.mul(discount); } /** * @notice burn corresponding long and short option tokens * @param account holder of tokens to annihilate * @param maturity timestamp of option maturity * @param strike64x64 64x64 fixed point representation of strike price * @param isCall true for call, false for put * @param contractSize quantity of option contract tokens to annihilate */ function _annihilate( address account, uint64 maturity, int128 strike64x64, bool isCall, uint256 contractSize ) internal { uint256 longTokenId = PoolStorage.formatTokenId( _getTokenType(isCall, true), maturity, strike64x64 ); uint256 shortTokenId = PoolStorage.formatTokenId( _getTokenType(isCall, false), maturity, strike64x64 ); _burn(account, longTokenId, contractSize); _burn(account, shortTokenId, contractSize); emit Annihilate(shortTokenId, contractSize); } /** * @notice purchase option * @param l storage layout struct * @param account recipient of purchased option * @param maturity timestamp of option maturity * @param strike64x64 64x64 fixed point representation of strike price * @param isCall true for call, false for put * @param contractSize size of option contract * @param newPrice64x64 64x64 fixed point representation of current spot price * @return baseCost quantity of tokens required to purchase long position * @return feeCost quantity of tokens required to pay fees */ function _purchase( PoolStorage.Layout storage l, address account, uint64 maturity, int128 strike64x64, bool isCall, uint256 contractSize, int128 newPrice64x64 ) internal returns (uint256 baseCost, uint256 feeCost) { require(maturity > block.timestamp, "expired"); require(contractSize >= l.underlyingMinimum, "too small"); { uint256 size = isCall ? contractSize : l.fromUnderlyingToBaseDecimals( strike64x64.mulu(contractSize) ); require( size <= ERC1155EnumerableStorage.layout().totalSupply[ _getFreeLiquidityTokenId(isCall) ] - l.nextDeposits[isCall].totalPendingDeposits, "insuf liq" ); } PoolStorage.QuoteResultInternal memory quote = _quote( PoolStorage.QuoteArgsInternal( account, maturity, strike64x64, newPrice64x64, contractSize, isCall ) ); baseCost = ABDKMath64x64Token.toDecimals( quote.baseCost64x64, l.getTokenDecimals(isCall) ); feeCost = ABDKMath64x64Token.toDecimals( quote.feeCost64x64, l.getTokenDecimals(isCall) ); uint256 longTokenId = PoolStorage.formatTokenId( _getTokenType(isCall, true), maturity, strike64x64 ); uint256 shortTokenId = PoolStorage.formatTokenId( _getTokenType(isCall, false), maturity, strike64x64 ); // mint long option token for buyer _mint(account, longTokenId, contractSize); int128 oldLiquidity64x64 = l.totalFreeLiquiditySupply64x64(isCall); // burn free liquidity tokens from other underwriters _mintShortTokenLoop( l, account, contractSize, baseCost, shortTokenId, isCall ); int128 newLiquidity64x64 = l.totalFreeLiquiditySupply64x64(isCall); _setCLevel(l, oldLiquidity64x64, newLiquidity64x64, isCall); // mint reserved liquidity tokens for fee receiver _mint( FEE_RECEIVER_ADDRESS, _getReservedLiquidityTokenId(isCall), feeCost ); emit Purchase( account, longTokenId, contractSize, baseCost, feeCost, newPrice64x64 ); } /** * @notice reassign short position to new underwriter * @param l storage layout struct * @param account holder of positions to be reassigned * @param maturity timestamp of option maturity * @param strike64x64 64x64 fixed point representation of strike price * @param isCall true for call, false for put * @param contractSize quantity of option contract tokens to reassign * @param newPrice64x64 64x64 fixed point representation of current spot price * @return baseCost quantity of tokens required to reassign short position * @return feeCost quantity of tokens required to pay fees * @return amountOut quantity of liquidity freed */ function _reassign( PoolStorage.Layout storage l, address account, uint64 maturity, int128 strike64x64, bool isCall, uint256 contractSize, int128 newPrice64x64 ) internal returns ( uint256 baseCost, uint256 feeCost, uint256 amountOut ) { (baseCost, feeCost) = _purchase( l, account, maturity, strike64x64, isCall, contractSize, newPrice64x64 ); _annihilate(account, maturity, strike64x64, isCall, contractSize); uint256 annihilateAmount = isCall ? contractSize : l.fromUnderlyingToBaseDecimals(strike64x64.mulu(contractSize)); amountOut = annihilateAmount - baseCost - feeCost; } /** * @notice exercise option on behalf of holder * @dev used for processing of expired options if passed holder is zero address * @param holder owner of long option tokens to exercise * @param longTokenId long option token id * @param contractSize quantity of tokens to exercise */ function _exercise( address holder, uint256 longTokenId, uint256 contractSize ) internal { uint64 maturity; int128 strike64x64; bool isCall; bool onlyExpired = holder == address(0); { PoolStorage.TokenType tokenType; (tokenType, maturity, strike64x64) = PoolStorage.parseTokenId( longTokenId ); require( tokenType == PoolStorage.TokenType.LONG_CALL || tokenType == PoolStorage.TokenType.LONG_PUT, "invalid type" ); require(!onlyExpired || maturity < block.timestamp, "not expired"); isCall = tokenType == PoolStorage.TokenType.LONG_CALL; } PoolStorage.Layout storage l = PoolStorage.layout(); int128 spot64x64 = _update(l); if (maturity < block.timestamp) { spot64x64 = l.getPriceUpdateAfter(maturity); } require( onlyExpired || ( isCall ? (spot64x64 > strike64x64) : (spot64x64 < strike64x64) ), "not ITM" ); uint256 exerciseValue; // option has a non-zero exercise value if (isCall) { if (spot64x64 > strike64x64) { exerciseValue = spot64x64.sub(strike64x64).div(spot64x64).mulu( contractSize ); } } else { if (spot64x64 < strike64x64) { exerciseValue = l.fromUnderlyingToBaseDecimals( strike64x64.sub(spot64x64).mulu(contractSize) ); } } uint256 totalFee; if (onlyExpired) { totalFee += _burnLongTokenLoop( contractSize, exerciseValue, longTokenId, isCall ); } else { // burn long option tokens from sender _burn(holder, longTokenId, contractSize); uint256 fee; if (exerciseValue > 0) { fee = _getFeeWithDiscount( holder, FEE_64x64.mulu(exerciseValue) ); totalFee += fee; _pushTo(holder, _getPoolToken(isCall), exerciseValue - fee); } emit Exercise( holder, longTokenId, contractSize, exerciseValue, fee ); } totalFee += _burnShortTokenLoop( contractSize, exerciseValue, PoolStorage.formatTokenId( _getTokenType(isCall, false), maturity, strike64x64 ), isCall ); _mint( FEE_RECEIVER_ADDRESS, _getReservedLiquidityTokenId(isCall), totalFee ); } function _mintShortTokenLoop( PoolStorage.Layout storage l, address buyer, uint256 contractSize, uint256 premium, uint256 shortTokenId, bool isCall ) internal { uint256 freeLiqTokenId = _getFreeLiquidityTokenId(isCall); (, , int128 strike64x64) = PoolStorage.parseTokenId(shortTokenId); uint256 toPay = isCall ? contractSize : l.fromUnderlyingToBaseDecimals(strike64x64.mulu(contractSize)); while (toPay > 0) { address underwriter = l.liquidityQueueAscending[isCall][address(0)]; uint256 balance = _balanceOf(underwriter, freeLiqTokenId); // If dust left, we remove underwriter and skip to next if (balance < _getMinimumAmount(l, isCall)) { l.removeUnderwriter(underwriter, isCall); continue; } if (!l.getReinvestmentStatus(underwriter, isCall)) { _burn(underwriter, freeLiqTokenId, balance); _mint( underwriter, _getReservedLiquidityTokenId(isCall), balance ); _subUserTVL(l, underwriter, isCall, balance); continue; } // amount of liquidity provided by underwriter, accounting for reinvested premium uint256 intervalContractSize = ((balance - l.pendingDeposits[underwriter][l.nextDeposits[isCall].eta][ isCall ]) * (toPay + premium)) / toPay; if (intervalContractSize == 0) continue; if (intervalContractSize > toPay) intervalContractSize = toPay; // amount of premium paid to underwriter uint256 intervalPremium = (premium * intervalContractSize) / toPay; premium -= intervalPremium; toPay -= intervalContractSize; _addUserTVL(l, underwriter, isCall, intervalPremium); // burn free liquidity tokens from underwriter _burn( underwriter, freeLiqTokenId, intervalContractSize - intervalPremium ); if (isCall == false) { // For PUT, conversion to contract amount is done here (Prior to this line, it is token amount) intervalContractSize = l.fromBaseToUnderlyingDecimals( strike64x64.inv().mulu(intervalContractSize) ); } // mint short option tokens for underwriter // toPay == 0 ? contractSize : intervalContractSize : To prevent minting less than amount, // because of rounding (Can happen for put, because of fixed point precision) _mint( underwriter, shortTokenId, toPay == 0 ? contractSize : intervalContractSize ); emit Underwrite( underwriter, buyer, shortTokenId, toPay == 0 ? contractSize : intervalContractSize, intervalPremium, false ); contractSize -= intervalContractSize; } } function _burnLongTokenLoop( uint256 contractSize, uint256 exerciseValue, uint256 longTokenId, bool isCall ) internal returns (uint256 totalFee) { EnumerableSet.AddressSet storage holders = ERC1155EnumerableStorage .layout() .accountsByToken[longTokenId]; while (contractSize > 0) { address longTokenHolder = holders.at(holders.length() - 1); uint256 intervalContractSize = _balanceOf( longTokenHolder, longTokenId ); if (intervalContractSize > contractSize) intervalContractSize = contractSize; uint256 intervalExerciseValue; uint256 fee; if (exerciseValue > 0) { intervalExerciseValue = (exerciseValue * intervalContractSize) / contractSize; fee = _getFeeWithDiscount( longTokenHolder, FEE_64x64.mulu(intervalExerciseValue) ); totalFee += fee; exerciseValue -= intervalExerciseValue; _pushTo( longTokenHolder, _getPoolToken(isCall), intervalExerciseValue - fee ); } contractSize -= intervalContractSize; emit Exercise( longTokenHolder, longTokenId, intervalContractSize, intervalExerciseValue - fee, fee ); _burn(longTokenHolder, longTokenId, intervalContractSize); } } function _burnShortTokenLoop( uint256 contractSize, uint256 exerciseValue, uint256 shortTokenId, bool isCall ) internal returns (uint256 totalFee) { EnumerableSet.AddressSet storage underwriters = ERC1155EnumerableStorage .layout() .accountsByToken[shortTokenId]; (, , int128 strike64x64) = PoolStorage.parseTokenId(shortTokenId); while (contractSize > 0) { address underwriter = underwriters.at(underwriters.length() - 1); // amount of liquidity provided by underwriter uint256 intervalContractSize = _balanceOf( underwriter, shortTokenId ); if (intervalContractSize > contractSize) intervalContractSize = contractSize; // amount of value claimed by buyer uint256 intervalExerciseValue = (exerciseValue * intervalContractSize) / contractSize; exerciseValue -= intervalExerciseValue; contractSize -= intervalContractSize; uint256 freeLiq = isCall ? intervalContractSize - intervalExerciseValue : PoolStorage.layout().fromUnderlyingToBaseDecimals( strike64x64.mulu(intervalContractSize) ) - intervalExerciseValue; uint256 fee = _getFeeWithDiscount( underwriter, FEE_64x64.mulu(freeLiq) ); totalFee += fee; uint256 tvlToSubtract = intervalExerciseValue; // mint free liquidity tokens for underwriter if ( PoolStorage.layout().getReinvestmentStatus(underwriter, isCall) ) { _addToDepositQueue(underwriter, freeLiq - fee, isCall); tvlToSubtract += fee; } else { _mint( underwriter, _getReservedLiquidityTokenId(isCall), freeLiq - fee ); tvlToSubtract += freeLiq; } _subUserTVL( PoolStorage.layout(), underwriter, isCall, tvlToSubtract ); // burn short option tokens from underwriter _burn(underwriter, shortTokenId, intervalContractSize); emit AssignExercise( underwriter, shortTokenId, freeLiq - fee, intervalContractSize, fee ); } } function _addToDepositQueue( address account, uint256 amount, bool isCallPool ) internal { PoolStorage.Layout storage l = PoolStorage.layout(); _mint(account, _getFreeLiquidityTokenId(isCallPool), amount); uint256 nextBatch = (block.timestamp / BATCHING_PERIOD) * BATCHING_PERIOD + BATCHING_PERIOD; l.pendingDeposits[account][nextBatch][isCallPool] += amount; PoolStorage.BatchData storage batchData = l.nextDeposits[isCallPool]; batchData.totalPendingDeposits += amount; batchData.eta = nextBatch; } function _processPendingDeposits(PoolStorage.Layout storage l, bool isCall) internal { PoolStorage.BatchData storage data = l.nextDeposits[isCall]; if (data.eta == 0 || block.timestamp < data.eta) return; int128 oldLiquidity64x64 = l.totalFreeLiquiditySupply64x64(isCall); _setCLevel( l, oldLiquidity64x64, oldLiquidity64x64.add( ABDKMath64x64Token.fromDecimals( data.totalPendingDeposits, l.getTokenDecimals(isCall) ) ), isCall ); delete l.nextDeposits[isCall]; } function _getFreeLiquidityTokenId(bool isCall) internal view returns (uint256 freeLiqTokenId) { freeLiqTokenId = isCall ? UNDERLYING_FREE_LIQ_TOKEN_ID : BASE_FREE_LIQ_TOKEN_ID; } function _getReservedLiquidityTokenId(bool isCall) internal view returns (uint256 reservedLiqTokenId) { reservedLiqTokenId = isCall ? UNDERLYING_RESERVED_LIQ_TOKEN_ID : BASE_RESERVED_LIQ_TOKEN_ID; } function _getPoolToken(bool isCall) internal view returns (address token) { token = isCall ? PoolStorage.layout().underlying : PoolStorage.layout().base; } function _getTokenType(bool isCall, bool isLong) internal pure returns (PoolStorage.TokenType tokenType) { if (isCall) { tokenType = isLong ? PoolStorage.TokenType.LONG_CALL : PoolStorage.TokenType.SHORT_CALL; } else { tokenType = isLong ? PoolStorage.TokenType.LONG_PUT : PoolStorage.TokenType.SHORT_PUT; } } function _getMinimumAmount(PoolStorage.Layout storage l, bool isCall) internal view returns (uint256 minimumAmount) { minimumAmount = isCall ? l.underlyingMinimum : l.baseMinimum; } function _getPoolCapAmount(PoolStorage.Layout storage l, bool isCall) internal view returns (uint256 poolCapAmount) { poolCapAmount = isCall ? l.underlyingPoolCap : l.basePoolCap; } function _setCLevel( PoolStorage.Layout storage l, int128 oldLiquidity64x64, int128 newLiquidity64x64, bool isCallPool ) internal { int128 oldCLevel64x64 = l.getDecayAdjustedCLevel64x64(isCallPool); int128 cLevel64x64 = l.applyCLevelLiquidityChangeAdjustment( oldCLevel64x64, oldLiquidity64x64, newLiquidity64x64, isCallPool ); l.setCLevel(cLevel64x64, isCallPool); emit UpdateCLevel( isCallPool, cLevel64x64, oldLiquidity64x64, newLiquidity64x64 ); } /** * @notice calculate and store updated market state * @param l storage layout struct * @return newPrice64x64 64x64 fixed point representation of current spot price */ function _update(PoolStorage.Layout storage l) internal returns (int128 newPrice64x64) { if (l.updatedAt == block.timestamp) { return (l.getPriceUpdate(block.timestamp)); } newPrice64x64 = l.fetchPriceUpdate(); if (l.getPriceUpdate(block.timestamp) == 0) { l.setPriceUpdate(block.timestamp, newPrice64x64); } l.updatedAt = block.timestamp; _processPendingDeposits(l, true); _processPendingDeposits(l, false); } /** * @notice transfer ERC20 tokens to message sender * @param token ERC20 token address * @param amount quantity of token to transfer */ function _pushTo( address to, address token, uint256 amount ) internal { if (amount == 0) return; require(IERC20(token).transfer(to, amount), "ERC20 transfer failed"); } /** * @notice transfer ERC20 tokens from message sender * @param from address from which tokens are pulled from * @param token ERC20 token address * @param amount quantity of token to transfer * @param skipWethDeposit if false, will not try to deposit weth from attach eth */ function _pullFrom( address from, address token, uint256 amount, bool skipWethDeposit ) internal { if (!skipWethDeposit) { if (token == WETH_ADDRESS) { if (msg.value > 0) { if (msg.value > amount) { IWETH(WETH_ADDRESS).deposit{value: amount}(); (bool success, ) = payable(msg.sender).call{ value: msg.value - amount }(""); require(success, "ETH refund failed"); amount = 0; } else { unchecked { amount -= msg.value; } IWETH(WETH_ADDRESS).deposit{value: msg.value}(); } } } else { require(msg.value == 0, "not WETH deposit"); } } if (amount > 0) { require( IERC20(token).transferFrom(from, address(this), amount), "ERC20 transfer failed" ); } } function _mint( address account, uint256 tokenId, uint256 amount ) internal { _mint(account, tokenId, amount, ""); } function _addUserTVL( PoolStorage.Layout storage l, address user, bool isCallPool, uint256 amount ) internal { uint256 userTVL = l.userTVL[user][isCallPool]; uint256 totalTVL = l.totalTVL[isCallPool]; IPremiaMining(PREMIA_MINING_ADDRESS).allocatePending( user, address(this), isCallPool, userTVL, userTVL + amount, totalTVL ); l.userTVL[user][isCallPool] = userTVL + amount; l.totalTVL[isCallPool] = totalTVL + amount; } function _subUserTVL( PoolStorage.Layout storage l, address user, bool isCallPool, uint256 amount ) internal { uint256 userTVL = l.userTVL[user][isCallPool]; uint256 totalTVL = l.totalTVL[isCallPool]; IPremiaMining(PREMIA_MINING_ADDRESS).allocatePending( user, address(this), isCallPool, userTVL, userTVL - amount, totalTVL ); l.userTVL[user][isCallPool] = userTVL - amount; l.totalTVL[isCallPool] = totalTVL - amount; } /** * @notice ERC1155 hook: track eligible underwriters * @param operator transaction sender * @param from token sender * @param to token receiver * @param ids token ids transferred * @param amounts token quantities transferred * @param data data payload */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual override { super._beforeTokenTransfer(operator, from, to, ids, amounts, data); PoolStorage.Layout storage l = PoolStorage.layout(); for (uint256 i; i < ids.length; i++) { uint256 id = ids[i]; uint256 amount = amounts[i]; if (amount == 0) continue; if (from == address(0)) { l.tokenIds.add(id); } if ( to == address(0) && ERC1155EnumerableStorage.layout().totalSupply[id] == 0 ) { l.tokenIds.remove(id); } // prevent transfer of free and reserved liquidity during waiting period if ( id == UNDERLYING_FREE_LIQ_TOKEN_ID || id == BASE_FREE_LIQ_TOKEN_ID || id == UNDERLYING_RESERVED_LIQ_TOKEN_ID || id == BASE_RESERVED_LIQ_TOKEN_ID ) { if (from != address(0) && to != address(0)) { bool isCallPool = id == UNDERLYING_FREE_LIQ_TOKEN_ID || id == UNDERLYING_RESERVED_LIQ_TOKEN_ID; require( l.depositedAt[from][isCallPool] + (1 days) < block.timestamp, "liq lock 1d" ); } } if ( id == UNDERLYING_FREE_LIQ_TOKEN_ID || id == BASE_FREE_LIQ_TOKEN_ID ) { bool isCallPool = id == UNDERLYING_FREE_LIQ_TOKEN_ID; uint256 minimum = _getMinimumAmount(l, isCallPool); if (from != address(0)) { uint256 balance = _balanceOf(from, id); if (balance > minimum && balance <= amount + minimum) { require( balance - l.pendingDeposits[from][ l.nextDeposits[isCallPool].eta ][isCallPool] >= amount, "Insuf balance" ); l.removeUnderwriter(from, isCallPool); } if (to != address(0)) { _subUserTVL(l, from, isCallPool, amounts[i]); _addUserTVL(l, to, isCallPool, amounts[i]); } } if (to != address(0)) { uint256 balance = _balanceOf(to, id); if (balance <= minimum && balance + amount > minimum) { l.addUnderwriter(to, isCallPool); } } } // Update userTVL on SHORT options transfers ( PoolStorage.TokenType tokenType, , int128 strike64x64 ) = PoolStorage.parseTokenId(id); if ( (from != address(0) && to != address(0)) && (tokenType == PoolStorage.TokenType.SHORT_CALL || tokenType == PoolStorage.TokenType.SHORT_PUT) ) { bool isCall = tokenType == PoolStorage.TokenType.SHORT_CALL; uint256 collateral = isCall ? amount : l.fromUnderlyingToBaseDecimals(strike64x64.mulu(amount)); _subUserTVL(l, from, isCall, collateral); _addUserTVL(l, to, isCall, collateral); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface AggregatorInterface { function latestAnswer() external view returns ( int256 ); function latestTimestamp() external view returns ( uint256 ); function latestRound() external view returns ( uint256 ); function getAnswer( uint256 roundId ) external view returns ( int256 ); function getTimestamp( uint256 roundId ) external view returns ( uint256 ); event AnswerUpdated( int256 indexed current, uint256 indexed roundId, uint256 updatedAt ); event NewRound( uint256 indexed roundId, address indexed startedBy, uint256 startedAt ); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface AggregatorV3Interface { function decimals() external view returns ( uint8 ); function description() external view returns ( string memory ); function version() external view returns ( uint256 ); // getRoundData and latestRoundData should both raise "No data present" // if they do not have data to report, instead of returning unset values // which could be misinterpreted as actual reported values. function getRoundData( uint80 _roundId ) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function latestRoundData() external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import { EnumerableSet } from '../../../utils/EnumerableSet.sol'; library ERC1155EnumerableStorage { struct Layout { mapping(uint256 => uint256) totalSupply; mapping(uint256 => EnumerableSet.AddressSet) accountsByToken; mapping(address => EnumerableSet.UintSet) tokensByAccount; } bytes32 internal constant STORAGE_SLOT = keccak256('solidstate.contracts.storage.ERC1155Enumerable'); function layout() internal pure returns (Layout storage l) { bytes32 slot = STORAGE_SLOT; assembly { l.slot := slot } } } // SPDX-License-Identifier: BUSL-1.1 // For further clarification please see https://license.premia.legal pragma solidity ^0.8.0; import {ABDKMath64x64} from "abdk-libraries-solidity/ABDKMath64x64.sol"; library ABDKMath64x64Token { using ABDKMath64x64 for int128; /** * @notice convert 64x64 fixed point representation of token amount to decimal * @param value64x64 64x64 fixed point representation of token amount * @param decimals token display decimals * @return value decimal representation of token amount */ function toDecimals(int128 value64x64, uint8 decimals) internal pure returns (uint256 value) { value = value64x64.mulu(10**decimals); } /** * @notice convert decimal representation of token amount to 64x64 fixed point * @param value decimal representation of token amount * @param decimals token display decimals * @return value64x64 64x64 fixed point representation of token amount */ function fromDecimals(uint256 value, uint8 decimals) internal pure returns (int128 value64x64) { value64x64 = ABDKMath64x64.divu(value, 10**decimals); } /** * @notice convert 64x64 fixed point representation of token amount to wei (18 decimals) * @param value64x64 64x64 fixed point representation of token amount * @return value wei representation of token amount */ function toWei(int128 value64x64) internal pure returns (uint256 value) { value = toDecimals(value64x64, 18); } /** * @notice convert wei representation (18 decimals) of token amount to 64x64 fixed point * @param value wei representation of token amount * @return value64x64 64x64 fixed point representation of token amount */ function fromWei(uint256 value) internal pure returns (int128 value64x64) { value64x64 = fromDecimals(value, 18); } } // SPDX-License-Identifier: BUSL-1.1 // For further clarification please see https://license.premia.legal pragma solidity ^0.8.0; import {ABDKMath64x64} from "abdk-libraries-solidity/ABDKMath64x64.sol"; library OptionMath { using ABDKMath64x64 for int128; struct QuoteArgs { int128 varianceAnnualized64x64; // 64x64 fixed point representation of annualized variance int128 strike64x64; // 64x64 fixed point representation of strike price int128 spot64x64; // 64x64 fixed point representation of spot price int128 timeToMaturity64x64; // 64x64 fixed point representation of duration of option contract (in years) int128 oldCLevel64x64; // 64x64 fixed point representation of C-Level of Pool before purchase int128 oldPoolState; // 64x64 fixed point representation of current state of the pool int128 newPoolState; // 64x64 fixed point representation of state of the pool after trade int128 steepness64x64; // 64x64 fixed point representation of Pool state delta multiplier int128 minAPY64x64; // 64x64 fixed point representation of minimum APY for capital locked up to underwrite options bool isCall; // whether to price "call" or "put" option } struct CalculateCLevelDecayArgs { int128 timeIntervalsElapsed64x64; // 64x64 fixed point representation of quantity of discrete arbitrary intervals elapsed since last update int128 oldCLevel64x64; // 64x64 fixed point representation of C-Level prior to accounting for decay int128 utilization64x64; // 64x64 fixed point representation of pool capital utilization rate int128 utilizationLowerBound64x64; int128 utilizationUpperBound64x64; int128 cLevelLowerBound64x64; int128 cLevelUpperBound64x64; int128 cConvergenceULowerBound64x64; int128 cConvergenceUUpperBound64x64; } // 64x64 fixed point integer constants int128 internal constant ONE_64x64 = 0x10000000000000000; int128 internal constant THREE_64x64 = 0x30000000000000000; // 64x64 fixed point constants used in Choudhury’s approximation of the Black-Scholes CDF int128 private constant CDF_CONST_0 = 0x09109f285df452394; // 2260 / 3989 int128 private constant CDF_CONST_1 = 0x19abac0ea1da65036; // 6400 / 3989 int128 private constant CDF_CONST_2 = 0x0d3c84b78b749bd6b; // 3300 / 3989 /** * @notice recalculate C-Level based on change in liquidity * @param initialCLevel64x64 64x64 fixed point representation of C-Level of Pool before update * @param oldPoolState64x64 64x64 fixed point representation of liquidity in pool before update * @param newPoolState64x64 64x64 fixed point representation of liquidity in pool after update * @param steepness64x64 64x64 fixed point representation of steepness coefficient * @return 64x64 fixed point representation of new C-Level */ function calculateCLevel( int128 initialCLevel64x64, int128 oldPoolState64x64, int128 newPoolState64x64, int128 steepness64x64 ) external pure returns (int128) { return newPoolState64x64 .sub(oldPoolState64x64) .div( oldPoolState64x64 > newPoolState64x64 ? oldPoolState64x64 : newPoolState64x64 ) .mul(steepness64x64) .neg() .exp() .mul(initialCLevel64x64); } /** * @notice calculate the price of an option using the Premia Finance model * @param args arguments of quotePrice * @return premiaPrice64x64 64x64 fixed point representation of Premia option price * @return cLevel64x64 64x64 fixed point representation of C-Level of Pool after purchase */ function quotePrice(QuoteArgs memory args) external pure returns ( int128 premiaPrice64x64, int128 cLevel64x64, int128 slippageCoefficient64x64 ) { int128 deltaPoolState64x64 = args .newPoolState .sub(args.oldPoolState) .div(args.oldPoolState) .mul(args.steepness64x64); int128 tradingDelta64x64 = deltaPoolState64x64.neg().exp(); int128 blackScholesPrice64x64 = _blackScholesPrice( args.varianceAnnualized64x64, args.strike64x64, args.spot64x64, args.timeToMaturity64x64, args.isCall ); cLevel64x64 = tradingDelta64x64.mul(args.oldCLevel64x64); slippageCoefficient64x64 = ONE_64x64.sub(tradingDelta64x64).div( deltaPoolState64x64 ); premiaPrice64x64 = blackScholesPrice64x64.mul(cLevel64x64).mul( slippageCoefficient64x64 ); int128 intrinsicValue64x64; if (args.isCall && args.strike64x64 < args.spot64x64) { intrinsicValue64x64 = args.spot64x64.sub(args.strike64x64); } else if (!args.isCall && args.strike64x64 > args.spot64x64) { intrinsicValue64x64 = args.strike64x64.sub(args.spot64x64); } int128 collateralValue64x64 = args.isCall ? args.spot64x64 : args.strike64x64; int128 minPrice64x64 = intrinsicValue64x64.add( collateralValue64x64.mul(args.minAPY64x64).mul( args.timeToMaturity64x64 ) ); if (minPrice64x64 > premiaPrice64x64) { premiaPrice64x64 = minPrice64x64; } } /** * @notice calculate the decay of C-Level based on heat diffusion function * @param args structured CalculateCLevelDecayArgs * @return cLevelDecayed64x64 C-Level after accounting for decay */ function calculateCLevelDecay(CalculateCLevelDecayArgs memory args) external pure returns (int128 cLevelDecayed64x64) { int128 convFHighU64x64 = (args.utilization64x64 >= args.utilizationUpperBound64x64 && args.oldCLevel64x64 <= args.cLevelLowerBound64x64) ? ONE_64x64 : int128(0); int128 convFLowU64x64 = (args.utilization64x64 <= args.utilizationLowerBound64x64 && args.oldCLevel64x64 >= args.cLevelUpperBound64x64) ? ONE_64x64 : int128(0); cLevelDecayed64x64 = args .oldCLevel64x64 .sub(args.cConvergenceULowerBound64x64.mul(convFLowU64x64)) .sub(args.cConvergenceUUpperBound64x64.mul(convFHighU64x64)) .mul( convFLowU64x64 .mul(ONE_64x64.sub(args.utilization64x64)) .add(convFHighU64x64.mul(args.utilization64x64)) .mul(args.timeIntervalsElapsed64x64) .neg() .exp() ) .add( args.cConvergenceULowerBound64x64.mul(convFLowU64x64).add( args.cConvergenceUUpperBound64x64.mul(convFHighU64x64) ) ); } /** * @notice calculate the exponential decay coefficient for a given interval * @param oldTimestamp timestamp of previous update * @param newTimestamp current timestamp * @return 64x64 fixed point representation of exponential decay coefficient */ function _decay(uint256 oldTimestamp, uint256 newTimestamp) internal pure returns (int128) { return ONE_64x64.sub( (-ABDKMath64x64.divu(newTimestamp - oldTimestamp, 7 days)).exp() ); } /** * @notice calculate Choudhury’s approximation of the Black-Scholes CDF * @param input64x64 64x64 fixed point representation of random variable * @return 64x64 fixed point representation of the approximated CDF of x */ function _N(int128 input64x64) internal pure returns (int128) { // squaring via mul is cheaper than via pow int128 inputSquared64x64 = input64x64.mul(input64x64); int128 value64x64 = (-inputSquared64x64 >> 1).exp().div( CDF_CONST_0.add(CDF_CONST_1.mul(input64x64.abs())).add( CDF_CONST_2.mul(inputSquared64x64.add(THREE_64x64).sqrt()) ) ); return input64x64 > 0 ? ONE_64x64.sub(value64x64) : value64x64; } /** * @notice calculate the price of an option using the Black-Scholes model * @param varianceAnnualized64x64 64x64 fixed point representation of annualized variance * @param strike64x64 64x64 fixed point representation of strike price * @param spot64x64 64x64 fixed point representation of spot price * @param timeToMaturity64x64 64x64 fixed point representation of duration of option contract (in years) * @param isCall whether to price "call" or "put" option * @return 64x64 fixed point representation of Black-Scholes option price */ function _blackScholesPrice( int128 varianceAnnualized64x64, int128 strike64x64, int128 spot64x64, int128 timeToMaturity64x64, bool isCall ) internal pure returns (int128) { int128 cumulativeVariance64x64 = timeToMaturity64x64.mul( varianceAnnualized64x64 ); int128 cumulativeVarianceSqrt64x64 = cumulativeVariance64x64.sqrt(); int128 d1_64x64 = spot64x64 .div(strike64x64) .ln() .add(cumulativeVariance64x64 >> 1) .div(cumulativeVarianceSqrt64x64); int128 d2_64x64 = d1_64x64.sub(cumulativeVarianceSqrt64x64); if (isCall) { return spot64x64.mul(_N(d1_64x64)).sub(strike64x64.mul(_N(d2_64x64))); } else { return -spot64x64.mul(_N(-d1_64x64)).sub( strike64x64.mul(_N(-d2_64x64)) ); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC20 metadata interface */ interface IERC20Metadata { /** * @notice return token name * @return token name */ function name() external view returns (string memory); /** * @notice return token symbol * @return token symbol */ function symbol() external view returns (string memory); /** * @notice return token decimals, generally used only for display purposes * @return token decimals */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title Partial ERC20 interface needed by internal functions */ interface IERC20Internal { event Transfer(address indexed from, address indexed to, uint256 value); event Approval( address indexed owner, address indexed spender, uint256 value ); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; library AddressUtils { function toString(address account) internal pure returns (string memory) { bytes32 value = bytes32(uint256(uint160(account))); bytes memory alphabet = '0123456789abcdef'; bytes memory chars = new bytes(42); chars[0] = '0'; chars[1] = 'x'; for (uint256 i = 0; i < 20; i++) { chars[2 + i * 2] = alphabet[uint8(value[i + 12] >> 4)]; chars[3 + i * 2] = alphabet[uint8(value[i + 12] & 0x0f)]; } return string(chars); } function isContract(address account) internal view returns (bool) { uint256 size; assembly { size := extcodesize(account) } return size > 0; } function sendValue(address payable account, uint256 amount) internal { (bool success, ) = account.call{ value: amount }(''); require(success, 'AddressUtils: failed to send value'); } function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, 'AddressUtils: failed low-level call'); } function functionCall( address target, bytes memory data, string memory error ) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, error); } function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue( target, data, value, 'AddressUtils: failed low-level call with value' ); } function functionCallWithValue( address target, bytes memory data, uint256 value, string memory error ) internal returns (bytes memory) { require( address(this).balance >= value, 'AddressUtils: insufficient balance for call' ); return _functionCallWithValue(target, data, value, error); } function _functionCallWithValue( address target, bytes memory data, uint256 value, string memory error ) private returns (bytes memory) { require( isContract(target), 'AddressUtils: function call to non-contract' ); (bool success, bytes memory returnData) = target.call{ value: value }( data ); if (success) { return returnData; } else if (returnData.length > 0) { assembly { let returnData_size := mload(returnData) revert(add(32, returnData), returnData_size) } } else { revert(error); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title Contract ownership standard interface * @dev see https://eips.ethereum.org/EIPS/eip-173 */ interface IERC173 { event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @notice get the ERC173 contract owner * @return conract owner */ function owner() external view returns (address); /** * @notice transfer contract ownership to new account * @param account address of new owner */ function transferOwnership(address account) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; library OwnableStorage { struct Layout { address owner; } bytes32 internal constant STORAGE_SLOT = keccak256('solidstate.contracts.storage.Ownable'); function layout() internal pure returns (Layout storage l) { bytes32 slot = STORAGE_SLOT; assembly { l.slot := slot } } function setOwner(Layout storage l, address owner) internal { l.owner = owner; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import { EnumerableSet } from '../../../utils/EnumerableSet.sol'; import { ERC1155Base, ERC1155BaseInternal } from '../base/ERC1155Base.sol'; import { IERC1155Enumerable } from './IERC1155Enumerable.sol'; import { ERC1155EnumerableInternal, ERC1155EnumerableStorage } from './ERC1155EnumerableInternal.sol'; /** * @title ERC1155 implementation including enumerable and aggregate functions */ abstract contract ERC1155Enumerable is IERC1155Enumerable, ERC1155Base, ERC1155EnumerableInternal { using EnumerableSet for EnumerableSet.AddressSet; using EnumerableSet for EnumerableSet.UintSet; /** * @inheritdoc IERC1155Enumerable */ function totalSupply(uint256 id) public view virtual override returns (uint256) { return ERC1155EnumerableStorage.layout().totalSupply[id]; } /** * @inheritdoc IERC1155Enumerable */ function totalHolders(uint256 id) public view virtual override returns (uint256) { return ERC1155EnumerableStorage.layout().accountsByToken[id].length(); } /** * @inheritdoc IERC1155Enumerable */ function accountsByToken(uint256 id) public view virtual override returns (address[] memory) { EnumerableSet.AddressSet storage accounts = ERC1155EnumerableStorage .layout() .accountsByToken[id]; address[] memory addresses = new address[](accounts.length()); for (uint256 i; i < accounts.length(); i++) { addresses[i] = accounts.at(i); } return addresses; } /** * @inheritdoc IERC1155Enumerable */ function tokensByAccount(address account) public view virtual override returns (uint256[] memory) { EnumerableSet.UintSet storage tokens = ERC1155EnumerableStorage .layout() .tokensByAccount[account]; uint256[] memory ids = new uint256[](tokens.length()); for (uint256 i; i < tokens.length(); i++) { ids[i] = tokens.at(i); } return ids; } /** * @notice ERC1155 hook: update aggregate values * @inheritdoc ERC1155EnumerableInternal */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual override(ERC1155BaseInternal, ERC1155EnumerableInternal) { super._beforeTokenTransfer(operator, from, to, ids, amounts, data); } } // SPDX-License-Identifier: LGPL-3.0-or-later pragma solidity ^0.8.0; import {FeeDiscountStorage} from "./FeeDiscountStorage.sol"; interface IFeeDiscount { event Staked( address indexed user, uint256 amount, uint256 stakePeriod, uint256 lockedUntil ); event Unstaked(address indexed user, uint256 amount); struct StakeLevel { uint256 amount; // Amount to stake uint256 discount; // Discount when amount is reached } /** * @notice Stake using IERC2612 permit * @param amount The amount of xPremia to stake * @param period The lockup period (in seconds) * @param deadline Deadline after which permit will fail * @param v V * @param r R * @param s S */ function stakeWithPermit( uint256 amount, uint256 period, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; /** * @notice Lockup xPremia for protocol fee discounts * Longer period of locking will apply a multiplier on the amount staked, in the fee discount calculation * @param amount The amount of xPremia to stake * @param period The lockup period (in seconds) */ function stake(uint256 amount, uint256 period) external; /** * @notice Unstake xPremia (If lockup period has ended) * @param amount The amount of xPremia to unstake */ function unstake(uint256 amount) external; ////////// // View // ////////// /** * Calculate the stake amount of a user, after applying the bonus from the lockup period chosen * @param user The user from which to query the stake amount * @return The user stake amount after applying the bonus */ function getStakeAmountWithBonus(address user) external view returns (uint256); /** * @notice Calculate the % of fee discount for user, based on his stake * @param user The _user for which the discount is for * @return Percentage of protocol fee discount (in basis point) * Ex : 1000 = 10% fee discount */ function getDiscount(address user) external view returns (uint256); /** * @notice Get stake levels * @return Stake levels * Ex : 2500 = -25% */ function getStakeLevels() external returns (StakeLevel[] memory); /** * @notice Get stake period multiplier * @param period The duration (in seconds) for which tokens are locked * @return The multiplier for this staking period * Ex : 20000 = x2 */ function getStakePeriodMultiplier(uint256 period) external returns (uint256); /** * @notice Get staking infos of a user * @param user The user address for which to get staking infos * @return The staking infos of the user */ function getUserInfo(address user) external view returns (FeeDiscountStorage.UserInfo memory); } // SPDX-License-Identifier: LGPL-3.0-or-later pragma solidity ^0.8.0; interface IPoolEvents { event Purchase( address indexed user, uint256 longTokenId, uint256 contractSize, uint256 baseCost, uint256 feeCost, int128 spot64x64 ); event Exercise( address indexed user, uint256 longTokenId, uint256 contractSize, uint256 exerciseValue, uint256 fee ); event Underwrite( address indexed underwriter, address indexed longReceiver, uint256 shortTokenId, uint256 intervalContractSize, uint256 intervalPremium, bool isManualUnderwrite ); event AssignExercise( address indexed underwriter, uint256 shortTokenId, uint256 freedAmount, uint256 intervalContractSize, uint256 fee ); event Deposit(address indexed user, bool isCallPool, uint256 amount); event Withdrawal( address indexed user, bool isCallPool, uint256 depositedAt, uint256 amount ); event FeeWithdrawal(bool indexed isCallPool, uint256 amount); event Annihilate(uint256 shortTokenId, uint256 amount); event UpdateCLevel( bool indexed isCall, int128 cLevel64x64, int128 oldLiquidity64x64, int128 newLiquidity64x64 ); event UpdateSteepness(int128 steepness64x64, bool isCallPool); } // SPDX-License-Identifier: LGPL-3.0-or-later pragma solidity ^0.8.0; import {VolatilitySurfaceOracleStorage} from "./VolatilitySurfaceOracleStorage.sol"; interface IVolatilitySurfaceOracle { function getWhitelistedRelayers() external view returns (address[] memory); function getVolatilitySurface(address baseToken, address underlyingToken) external view returns (VolatilitySurfaceOracleStorage.Update memory); function getVolatilitySurfaceCoefficientsUnpacked( address baseToken, address underlyingToken, bool isCall ) external view returns (int256[] memory); function getTimeToMaturity64x64(uint64 maturity) external view returns (int128); function getAnnualizedVolatility64x64( address baseToken, address underlyingToken, int128 spot64x64, int128 strike64x64, int128 timeToMaturity64x64, bool isCall ) external view returns (int128); function getBlackScholesPrice64x64( address baseToken, address underlyingToken, int128 strike64x64, int128 spot64x64, int128 timeToMaturity64x64, bool isCall ) external view returns (int128); function getBlackScholesPrice( address baseToken, address underlyingToken, int128 strike64x64, int128 spot64x64, int128 timeToMaturity64x64, bool isCall ) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import { IERC1155 } from '../IERC1155.sol'; import { IERC1155Receiver } from '../IERC1155Receiver.sol'; import { ERC1155BaseInternal, ERC1155BaseStorage } from './ERC1155BaseInternal.sol'; /** * @title Base ERC1155 contract * @dev derived from https://github.com/OpenZeppelin/openzeppelin-contracts/ (MIT license) */ abstract contract ERC1155Base is IERC1155, ERC1155BaseInternal { /** * @inheritdoc IERC1155 */ function balanceOf(address account, uint256 id) public view virtual override returns (uint256) { return _balanceOf(account, id); } /** * @inheritdoc IERC1155 */ function balanceOfBatch(address[] memory accounts, uint256[] memory ids) public view virtual override returns (uint256[] memory) { require( accounts.length == ids.length, 'ERC1155: accounts and ids length mismatch' ); mapping(uint256 => mapping(address => uint256)) storage balances = ERC1155BaseStorage.layout().balances; uint256[] memory batchBalances = new uint256[](accounts.length); unchecked { for (uint256 i; i < accounts.length; i++) { require( accounts[i] != address(0), 'ERC1155: batch balance query for the zero address' ); batchBalances[i] = balances[ids[i]][accounts[i]]; } } return batchBalances; } /** * @inheritdoc IERC1155 */ function isApprovedForAll(address account, address operator) public view virtual override returns (bool) { return ERC1155BaseStorage.layout().operatorApprovals[account][operator]; } /** * @inheritdoc IERC1155 */ function setApprovalForAll(address operator, bool status) public virtual override { require( msg.sender != operator, 'ERC1155: setting approval status for self' ); ERC1155BaseStorage.layout().operatorApprovals[msg.sender][ operator ] = status; emit ApprovalForAll(msg.sender, operator, status); } /** * @inheritdoc IERC1155 */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) public virtual override { require( from == msg.sender || isApprovedForAll(from, msg.sender), 'ERC1155: caller is not owner nor approved' ); _safeTransfer(msg.sender, from, to, id, amount, data); } /** * @inheritdoc IERC1155 */ function safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) public virtual override { require( from == msg.sender || isApprovedForAll(from, msg.sender), 'ERC1155: caller is not owner nor approved' ); _safeTransferBatch(msg.sender, from, to, ids, amounts, data); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC1155 enumerable and aggregate function interface */ interface IERC1155Enumerable { /** * @notice query total minted supply of given token * @param id token id to query * @return token supply */ function totalSupply(uint256 id) external view returns (uint256); /** * @notice query total number of holders for given token * @param id token id to query * @return quantity of holders */ function totalHolders(uint256 id) external view returns (uint256); /** * @notice query holders of given token * @param id token id to query * @return list of holder addresses */ function accountsByToken(uint256 id) external view returns (address[] memory); /** * @notice query tokens held by given address * @param account address to query * @return list of token ids */ function tokensByAccount(address account) external view returns (uint256[] memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import { EnumerableSet } from '../../../utils/EnumerableSet.sol'; import { ERC1155BaseInternal, ERC1155BaseStorage } from '../base/ERC1155BaseInternal.sol'; import { ERC1155EnumerableStorage } from './ERC1155EnumerableStorage.sol'; /** * @title ERC1155Enumerable internal functions */ abstract contract ERC1155EnumerableInternal is ERC1155BaseInternal { using EnumerableSet for EnumerableSet.AddressSet; using EnumerableSet for EnumerableSet.UintSet; /** * @notice ERC1155 hook: update aggregate values * @inheritdoc ERC1155BaseInternal */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual override { super._beforeTokenTransfer(operator, from, to, ids, amounts, data); if (from != to) { ERC1155EnumerableStorage.Layout storage l = ERC1155EnumerableStorage .layout(); mapping(uint256 => EnumerableSet.AddressSet) storage tokenAccounts = l.accountsByToken; EnumerableSet.UintSet storage fromTokens = l.tokensByAccount[from]; EnumerableSet.UintSet storage toTokens = l.tokensByAccount[to]; for (uint256 i; i < ids.length; i++) { uint256 amount = amounts[i]; if (amount > 0) { uint256 id = ids[i]; if (from == address(0)) { l.totalSupply[id] += amount; } else if (_balanceOf(from, id) == amount) { tokenAccounts[id].remove(from); fromTokens.remove(id); } if (to == address(0)) { l.totalSupply[id] -= amount; } else if (_balanceOf(to, id) == 0) { tokenAccounts[id].add(to); toTokens.add(id); } } } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import { IERC1155Internal } from './IERC1155Internal.sol'; import { IERC165 } from '../../introspection/IERC165.sol'; /** * @notice ERC1155 interface * @dev see https://github.com/ethereum/EIPs/issues/1155 */ interface IERC1155 is IERC1155Internal, IERC165 { /** * @notice query the balance of given token held by given address * @param account address to query * @param id token to query * @return token balance */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @notice query the balances of given tokens held by given addresses * @param accounts addresss to query * @param ids tokens to query * @return token balances */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @notice query approval status of given operator with respect to given address * @param account address to query for approval granted * @param operator address to query for approval received * @return whether operator is approved to spend tokens held by account */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @notice grant approval to or revoke approval from given operator to spend held tokens * @param operator address whose approval status to update * @param status whether operator should be considered approved */ function setApprovalForAll(address operator, bool status) external; /** * @notice transfer tokens between given addresses, checking for ERC1155Receiver implementation if applicable * @param from sender of tokens * @param to receiver of tokens * @param id token ID * @param amount quantity of tokens to transfer * @param data data payload */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes calldata data ) external; /** * @notice transfer batch of tokens between given addresses, checking for ERC1155Receiver implementation if applicable * @param from sender of tokens * @param to receiver of tokens * @param ids list of token IDs * @param amounts list of quantities of tokens to transfer * @param data data payload */ function safeBatchTransferFrom( address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import { IERC165 } from '../../introspection/IERC165.sol'; /** * @title ERC1155 transfer receiver interface */ interface IERC1155Receiver is IERC165 { /** * @notice validate receipt of ERC1155 transfer * @param operator executor of transfer * @param from sender of tokens * @param id token ID received * @param value quantity of tokens received * @param data data payload * @return function's own selector if transfer is accepted */ function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external returns (bytes4); /** * @notice validate receipt of ERC1155 batch transfer * @param operator executor of transfer * @param from sender of tokens * @param ids token IDs received * @param values quantities of tokens received * @param data data payload * @return function's own selector if transfer is accepted */ function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import { AddressUtils } from '../../../utils/AddressUtils.sol'; import { IERC1155Internal } from '../IERC1155Internal.sol'; import { IERC1155Receiver } from '../IERC1155Receiver.sol'; import { ERC1155BaseStorage } from './ERC1155BaseStorage.sol'; /** * @title Base ERC1155 internal functions * @dev derived from https://github.com/OpenZeppelin/openzeppelin-contracts/ (MIT license) */ abstract contract ERC1155BaseInternal is IERC1155Internal { using AddressUtils for address; /** * @notice query the balance of given token held by given address * @param account address to query * @param id token to query * @return token balance */ function _balanceOf(address account, uint256 id) internal view virtual returns (uint256) { require( account != address(0), 'ERC1155: balance query for the zero address' ); return ERC1155BaseStorage.layout().balances[id][account]; } /** * @notice mint given quantity of tokens for given address * @dev ERC1155Receiver implementation is not checked * @param account beneficiary of minting * @param id token ID * @param amount quantity of tokens to mint * @param data data payload */ function _mint( address account, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(account != address(0), 'ERC1155: mint to the zero address'); _beforeTokenTransfer( msg.sender, address(0), account, _asSingletonArray(id), _asSingletonArray(amount), data ); mapping(address => uint256) storage balances = ERC1155BaseStorage .layout() .balances[id]; balances[account] += amount; emit TransferSingle(msg.sender, address(0), account, id, amount); } /** * @notice mint given quantity of tokens for given address * @param account beneficiary of minting * @param id token ID * @param amount quantity of tokens to mint * @param data data payload */ function _safeMint( address account, uint256 id, uint256 amount, bytes memory data ) internal virtual { _mint(account, id, amount, data); _doSafeTransferAcceptanceCheck( msg.sender, address(0), account, id, amount, data ); } /** * @notice mint batch of tokens for given address * @dev ERC1155Receiver implementation is not checked * @param account beneficiary of minting * @param ids list of token IDs * @param amounts list of quantities of tokens to mint * @param data data payload */ function _mintBatch( address account, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(account != address(0), 'ERC1155: mint to the zero address'); require( ids.length == amounts.length, 'ERC1155: ids and amounts length mismatch' ); _beforeTokenTransfer( msg.sender, address(0), account, ids, amounts, data ); mapping(uint256 => mapping(address => uint256)) storage balances = ERC1155BaseStorage.layout().balances; for (uint256 i; i < ids.length; i++) { balances[ids[i]][account] += amounts[i]; } emit TransferBatch(msg.sender, address(0), account, ids, amounts); } /** * @notice mint batch of tokens for given address * @param account beneficiary of minting * @param ids list of token IDs * @param amounts list of quantities of tokens to mint * @param data data payload */ function _safeMintBatch( address account, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { _mintBatch(account, ids, amounts, data); _doSafeBatchTransferAcceptanceCheck( msg.sender, address(0), account, ids, amounts, data ); } /** * @notice burn given quantity of tokens held by given address * @param account holder of tokens to burn * @param id token ID * @param amount quantity of tokens to burn */ function _burn( address account, uint256 id, uint256 amount ) internal virtual { require(account != address(0), 'ERC1155: burn from the zero address'); _beforeTokenTransfer( msg.sender, account, address(0), _asSingletonArray(id), _asSingletonArray(amount), '' ); mapping(address => uint256) storage balances = ERC1155BaseStorage .layout() .balances[id]; unchecked { require( balances[account] >= amount, 'ERC1155: burn amount exceeds balances' ); balances[account] -= amount; } emit TransferSingle(msg.sender, account, address(0), id, amount); } /** * @notice burn given batch of tokens held by given address * @param account holder of tokens to burn * @param ids token IDs * @param amounts quantities of tokens to burn */ function _burnBatch( address account, uint256[] memory ids, uint256[] memory amounts ) internal virtual { require(account != address(0), 'ERC1155: burn from the zero address'); require( ids.length == amounts.length, 'ERC1155: ids and amounts length mismatch' ); _beforeTokenTransfer(msg.sender, account, address(0), ids, amounts, ''); mapping(uint256 => mapping(address => uint256)) storage balances = ERC1155BaseStorage.layout().balances; unchecked { for (uint256 i; i < ids.length; i++) { uint256 id = ids[i]; require( balances[id][account] >= amounts[i], 'ERC1155: burn amount exceeds balance' ); balances[id][account] -= amounts[i]; } } emit TransferBatch(msg.sender, account, address(0), ids, amounts); } /** * @notice transfer tokens between given addresses * @dev ERC1155Receiver implementation is not checked * @param operator executor of transfer * @param sender sender of tokens * @param recipient receiver of tokens * @param id token ID * @param amount quantity of tokens to transfer * @param data data payload */ function _transfer( address operator, address sender, address recipient, uint256 id, uint256 amount, bytes memory data ) internal virtual { require( recipient != address(0), 'ERC1155: transfer to the zero address' ); _beforeTokenTransfer( operator, sender, recipient, _asSingletonArray(id), _asSingletonArray(amount), data ); mapping(uint256 => mapping(address => uint256)) storage balances = ERC1155BaseStorage.layout().balances; unchecked { uint256 senderBalance = balances[id][sender]; require( senderBalance >= amount, 'ERC1155: insufficient balances for transfer' ); balances[id][sender] = senderBalance - amount; } balances[id][recipient] += amount; emit TransferSingle(operator, sender, recipient, id, amount); } /** * @notice transfer tokens between given addresses * @param operator executor of transfer * @param sender sender of tokens * @param recipient receiver of tokens * @param id token ID * @param amount quantity of tokens to transfer * @param data data payload */ function _safeTransfer( address operator, address sender, address recipient, uint256 id, uint256 amount, bytes memory data ) internal virtual { _transfer(operator, sender, recipient, id, amount, data); _doSafeTransferAcceptanceCheck( operator, sender, recipient, id, amount, data ); } /** * @notice transfer batch of tokens between given addresses * @dev ERC1155Receiver implementation is not checked * @param operator executor of transfer * @param sender sender of tokens * @param recipient receiver of tokens * @param ids token IDs * @param amounts quantities of tokens to transfer * @param data data payload */ function _transferBatch( address operator, address sender, address recipient, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require( recipient != address(0), 'ERC1155: transfer to the zero address' ); require( ids.length == amounts.length, 'ERC1155: ids and amounts length mismatch' ); _beforeTokenTransfer(operator, sender, recipient, ids, amounts, data); mapping(uint256 => mapping(address => uint256)) storage balances = ERC1155BaseStorage.layout().balances; for (uint256 i; i < ids.length; i++) { uint256 token = ids[i]; uint256 amount = amounts[i]; unchecked { uint256 senderBalance = balances[token][sender]; require( senderBalance >= amount, 'ERC1155: insufficient balances for transfer' ); balances[token][sender] = senderBalance - amount; } balances[token][recipient] += amount; } emit TransferBatch(operator, sender, recipient, ids, amounts); } /** * @notice transfer batch of tokens between given addresses * @param operator executor of transfer * @param sender sender of tokens * @param recipient receiver of tokens * @param ids token IDs * @param amounts quantities of tokens to transfer * @param data data payload */ function _safeTransferBatch( address operator, address sender, address recipient, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { _transferBatch(operator, sender, recipient, ids, amounts, data); _doSafeBatchTransferAcceptanceCheck( operator, sender, recipient, ids, amounts, data ); } /** * @notice wrap given element in array of length 1 * @param element element to wrap * @return singleton array */ function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) { uint256[] memory array = new uint256[](1); array[0] = element; return array; } /** * @notice revert if applicable transfer recipient is not valid ERC1155Receiver * @param operator executor of transfer * @param from sender of tokens * @param to receiver of tokens * @param id token ID * @param amount quantity of tokens to transfer * @param data data payload */ function _doSafeTransferAcceptanceCheck( address operator, address from, address to, uint256 id, uint256 amount, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155Received( operator, from, id, amount, data ) returns (bytes4 response) { require( response == IERC1155Receiver.onERC1155Received.selector, 'ERC1155: ERC1155Receiver rejected tokens' ); } catch Error(string memory reason) { revert(reason); } catch { revert('ERC1155: transfer to non ERC1155Receiver implementer'); } } } /** * @notice revert if applicable transfer recipient is not valid ERC1155Receiver * @param operator executor of transfer * @param from sender of tokens * @param to receiver of tokens * @param ids token IDs * @param amounts quantities of tokens to transfer * @param data data payload */ function _doSafeBatchTransferAcceptanceCheck( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155BatchReceived( operator, from, ids, amounts, data ) returns (bytes4 response) { require( response == IERC1155Receiver.onERC1155BatchReceived.selector, 'ERC1155: ERC1155Receiver rejected tokens' ); } catch Error(string memory reason) { revert(reason); } catch { revert('ERC1155: transfer to non ERC1155Receiver implementer'); } } } /** * @notice ERC1155 hook, called before all transfers including mint and burn * @dev function should be overridden and new implementation must call super * @dev called for both single and batch transfers * @param operator executor of transfer * @param from sender of tokens * @param to receiver of tokens * @param ids token IDs * @param amounts quantities of tokens to transfer * @param data data payload */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import { IERC165 } from '../../introspection/IERC165.sol'; /** * @notice Partial ERC1155 interface needed by internal functions */ interface IERC1155Internal { event TransferSingle( address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value ); event TransferBatch( address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values ); event ApprovalForAll( address indexed account, address indexed operator, bool approved ); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC165 interface registration interface * @dev see https://eips.ethereum.org/EIPS/eip-165 */ interface IERC165 { /** * @notice query whether contract has registered support for given interface * @param interfaceId interface id * @return bool whether interface is supported */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; library ERC1155BaseStorage { struct Layout { mapping(uint256 => mapping(address => uint256)) balances; mapping(address => mapping(address => bool)) operatorApprovals; } bytes32 internal constant STORAGE_SLOT = keccak256('solidstate.contracts.storage.ERC1155Base'); function layout() internal pure returns (Layout storage l) { bytes32 slot = STORAGE_SLOT; assembly { l.slot := slot } } } // SPDX-License-Identifier: BUSL-1.1 // For further clarification please see https://license.premia.legal pragma solidity ^0.8.0; library FeeDiscountStorage { bytes32 internal constant STORAGE_SLOT = keccak256("premia.contracts.staking.PremiaFeeDiscount"); struct UserInfo { uint256 balance; // Balance staked by user uint64 stakePeriod; // Stake period selected by user uint64 lockedUntil; // Timestamp at which the lock ends } struct Layout { // User data with xPREMIA balance staked and date at which lock ends mapping(address => UserInfo) userInfo; } function layout() internal pure returns (Layout storage l) { bytes32 slot = STORAGE_SLOT; assembly { l.slot := slot } } } // SPDX-License-Identifier: BUSL-1.1 // For further clarification please see https://license.premia.legal pragma solidity ^0.8.0; library PremiaMiningStorage { bytes32 internal constant STORAGE_SLOT = keccak256("premia.contracts.storage.PremiaMining"); // Info of each pool. struct PoolInfo { uint256 allocPoint; // How many allocation points assigned to this pool. PREMIA to distribute per block. uint256 lastRewardTimestamp; // Last timestamp that PREMIA distribution occurs uint256 accPremiaPerShare; // Accumulated PREMIA per share, times 1e12. See below. } // Info of each user. struct UserInfo { uint256 reward; // Total allocated unclaimed reward uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of PREMIA // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accPremiaPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accPremiaPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } struct Layout { // Total PREMIA left to distribute uint256 premiaAvailable; // Amount of premia distributed per year uint256 premiaPerYear; // pool -> isCallPool -> PoolInfo mapping(address => mapping(bool => PoolInfo)) poolInfo; // pool -> isCallPool -> user -> UserInfo mapping(address => mapping(bool => mapping(address => UserInfo))) userInfo; // Total allocation points. Must be the sum of all allocation points in all pools. uint256 totalAllocPoint; } function layout() internal pure returns (Layout storage l) { bytes32 slot = STORAGE_SLOT; assembly { l.slot := slot } } } // SPDX-License-Identifier: BUSL-1.1 // For further clarification please see https://license.premia.legal pragma solidity ^0.8.0; import {EnumerableSet} from "@solidstate/contracts/utils/EnumerableSet.sol"; library VolatilitySurfaceOracleStorage { bytes32 internal constant STORAGE_SLOT = keccak256("premia.contracts.storage.VolatilitySurfaceOracle"); uint256 internal constant COEFF_BITS = 51; uint256 internal constant COEFF_BITS_MINUS_ONE = 50; uint256 internal constant COEFF_AMOUNT = 5; // START_BIT = COEFF_BITS * (COEFF_AMOUNT - 1) uint256 internal constant START_BIT = 204; struct Update { uint256 updatedAt; bytes32 callCoefficients; bytes32 putCoefficients; } struct Layout { // Base token -> Underlying token -> Update mapping(address => mapping(address => Update)) volatilitySurfaces; // Relayer addresses which can be trusted to provide accurate option trades EnumerableSet.AddressSet whitelistedRelayers; } function layout() internal pure returns (Layout storage l) { bytes32 slot = STORAGE_SLOT; assembly { l.slot := slot } } function getCoefficients( Layout storage l, address baseToken, address underlyingToken, bool isCall ) internal view returns (bytes32) { Update storage u = l.volatilitySurfaces[baseToken][underlyingToken]; return isCall ? u.callCoefficients : u.putCoefficients; } function parseVolatilitySurfaceCoefficients(bytes32 input) internal pure returns (int256[] memory coefficients) { coefficients = new int256[](COEFF_AMOUNT); // Value to add to negative numbers to cast them to int256 int256 toAdd = (int256(-1) >> COEFF_BITS) << COEFF_BITS; assembly { let i := 0 // Value equal to -1 let mid := shl(COEFF_BITS_MINUS_ONE, 1) for { } lt(i, COEFF_AMOUNT) { } { let offset := sub(START_BIT, mul(COEFF_BITS, i)) let coeff := shr( offset, sub( input, shl( add(offset, COEFF_BITS), shr(add(offset, COEFF_BITS), input) ) ) ) // Check if value is a negative number and needs casting if or(eq(coeff, mid), gt(coeff, mid)) { coeff := add(coeff, toAdd) } // Store result in the coefficients array mstore(add(coefficients, add(0x20, mul(0x20, i))), coeff) i := add(i, 1) } } } function formatVolatilitySurfaceCoefficients(int256[5] memory coefficients) internal pure returns (bytes32 result) { for (uint256 i = 0; i < COEFF_AMOUNT; i++) { int256 max = int256(1 << COEFF_BITS_MINUS_ONE); require( coefficients[i] < max && coefficients[i] > -max, "Out of bounds" ); } assembly { let i := 0 for { } lt(i, COEFF_AMOUNT) { } { let offset := sub(START_BIT, mul(COEFF_BITS, i)) let coeff := mload(add(coefficients, mul(0x20, i))) result := add( result, shl( offset, sub(coeff, shl(COEFF_BITS, shr(COEFF_BITS, coeff))) ) ) i := add(i, 1) } } } }
burn given batch of tokens held by given address account holder of tokens to burn ids token IDs amounts quantities of tokens to burn/
function _burnBatch( address account, uint256[] memory ids, uint256[] memory amounts ) internal virtual { require(account != address(0), 'ERC1155: burn from the zero address'); require( ids.length == amounts.length, 'ERC1155: ids and amounts length mismatch' ); _beforeTokenTransfer(msg.sender, account, address(0), ids, amounts, ''); mapping(uint256 => mapping(address => uint256)) storage balances = ERC1155BaseStorage.layout().balances; unchecked { for (uint256 i; i < ids.length; i++) { uint256 id = ids[i]; require( balances[id][account] >= amounts[i], 'ERC1155: burn amount exceeds balance' ); balances[id][account] -= amounts[i]; } } emit TransferBatch(msg.sender, account, address(0), ids, amounts); }
104,092
//SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "./EpochUtils.sol"; import "./interfaces/IGetterUtils.sol"; /// @title Contract where getters and some convenience methods are implemented /// for the API3 pool contract GetterUtils is EpochUtils, IGetterUtils { /// @param api3TokenAddress Address of the API3 token contract /// @param epochPeriodInSeconds Length of epochs used to quantize time /// @param firstEpochStartTimestamp Starting timestamp of epoch #1 constructor( address api3TokenAddress, uint256 epochPeriodInSeconds, uint256 firstEpochStartTimestamp ) EpochUtils( api3TokenAddress, epochPeriodInSeconds, firstEpochStartTimestamp ) public {} /// @notice Returns the amount of funds the user has pooled /// @param userAddress User address function getPooled(address userAddress) public view override returns(uint256 pooled) { pooled = shares[userAddress].mul(totalPooled).div(totalShares); } /// @notice Calculates how many shares an amount of tokens corresponds to /// @param amount Amount of funds function convertToShares(uint256 amount) internal view returns(uint256 amountInShares) { amountInShares = amount.mul(totalShares).div(totalPooled); } /// @notice Calculates how many tokens an amount of shares corresponds to /// @param amountInShares Amount in shares function convertFromShares(uint256 amountInShares) internal view returns(uint256 amount) { amount = amountInShares.mul(totalPooled).div(totalShares); } /// @notice Returns the amount of voting power a delegate has at a given /// timestamp /// @dev Total voting power of all delegates adds up to 1e18 /// @param delegate Delegate address /// @param timestamp Timestamp function getVotingPower( address delegate, uint256 timestamp ) external view override returns(uint256 votingPower) { uint256 epochIndex = getEpochIndex(timestamp); votingPower = delegatedAtEpoch[delegate][epochIndex] .mul(1e18).div(totalStakedAtEpoch[epochIndex]); } /// @notice Returns the total pooled funds minus ghost funds. This is /// needed because ghost funds may be removed as IOUs are redeemed, and /// thus cannot be considered as collateral reliably. /// @return totalRealPooled Total pooled funds minus ghost funds function getTotalRealPooled() public view override returns(uint256 totalRealPooled) { totalRealPooled = totalPooled.sub(convertFromShares(totalGhostShares)); } /// @notice Returns the user balance. Includes vested and uvested funds, /// but not IOUs. /// @param userAddress User address /// @return balance User balance function getBalance(address userAddress) external view override returns(uint256 balance) { balance = balances[userAddress]; } /// @notice Returns the number of shares the user has pooled /// @param userAddress User address /// @return share Number of shares function getShare(address userAddress) external view override returns(uint256 share) { share = shares[userAddress]; } /// @notice Returns the epoch when the user has made their last unpooling /// request /// @param userAddress User address /// @return unpoolRequestEpoch The epoch when the user has made their last /// unpooling request function getUnpoolRequestEpoch(address userAddress) external view override returns(uint256 unpoolRequestEpoch) { unpoolRequestEpoch = unpoolRequestEpochs[userAddress]; } /// @notice Returns the total number of shares staked at epochIndex /// @param epochIndex Epoch index /// @return totalStaked Total number of shares staked function getTotalStaked(uint256 epochIndex) external view override returns(uint256 totalStaked) { totalStaked = totalStakedAtEpoch[epochIndex]; } /// @notice Returns the total number of shares the user has staked at /// epochIndex /// @param userAddress User address /// @param epochIndex Epoch index /// @return staked Number of shares the user has staked function getStaked( address userAddress, uint256 epochIndex ) external view override returns(uint256 staked) { staked = stakedAtEpoch[userAddress][epochIndex]; } /// @notice Returns the delegate of the user /// @dev 0 being returned means the user is their own delegate /// @param userAddress User address /// @return delegate The address that will vote on behalf of the user function getDelegate(address userAddress) external view override returns(address delegate) { delegate = delegates[userAddress]; } /// @notice Returns the delegated voting power of the delegate /// @param delegate Delegate address /// @param epochIndex Epoch index /// @return delegated Delegated voting power function getDelegated( address delegate, uint256 epochIndex ) external view override returns(uint256 delegated) { delegated = delegatedAtEpoch[delegate][epochIndex]; } /// @notice Returns the vested rewards that will be distributed at /// epochIndex /// @param epochIndex Epoch index /// @return vestedRewards Vested rewards function getVestedRewards(uint256 epochIndex) external view override returns(uint256 vestedRewards) { vestedRewards = vestedRewardsAtEpoch[epochIndex]; } /// @notice Returns the vested rewards that has not been distributed at /// epochIndex yet /// @param epochIndex Epoch index /// @return unpaidVestedRewards Unpaid vested rewards function getUnpaidVestedRewards(uint256 epochIndex) external view override returns(uint256 unpaidVestedRewards) { unpaidVestedRewards = unpaidVestedRewardsAtEpoch[epochIndex]; } /// @notice Returns the instant rewards that will be distributed at /// epochIndex /// @param epochIndex Epoch index /// @return instantRewards Instant rewards function getInstantRewards(uint256 epochIndex) external view override returns(uint256 instantRewards) { instantRewards = instantRewardsAtEpoch[epochIndex]; } /// @notice Returns the instant rewards that has not been distributed at /// epochIndex yet /// @param epochIndex Epoch index /// @return unpaidInstantRewards Unpaid instant rewards function getUnpaidInstantRewards(uint256 epochIndex) external view override returns(uint256 unpaidInstantRewards) { unpaidInstantRewards = unpaidInstantRewardsAtEpoch[epochIndex]; } /// @notice Returns the vesting /// @param vestingId Vesting ID /// @return userAddress User address /// @return amount Number of tokens to be vested /// @return epoch Index of the epoch when the funds will be /// available function getVesting(bytes32 vestingId) external view override returns( address userAddress, uint256 amount, uint256 epoch ) { Vesting memory vesting = vestings[vestingId]; userAddress = vesting.userAddress; amount = vesting.amount; epoch = vesting.epoch; } /// @notice Returns the total funds of the user locked by vestings /// @param userAddress User address /// @return unvestedFund Total funds of the user locked by vestings function getUnvestedFund(address userAddress) external view override returns(uint256 unvestedFund) { unvestedFund = unvestedFunds[userAddress]; } /// @notice Returns the claim /// @param claimId Claim ID /// @return beneficiary Address that will receive the payout upon /// acceptance of the claim /// @return amount Payout amount /// @return status Claim status function getClaim(bytes32 claimId) external view override returns( address beneficiary, uint256 amount, ClaimStatus status ) { Claim memory claim = claims[claimId]; beneficiary = claim.beneficiary; amount = claim.amount; status = claim.status; } /// @notice Returns the array of active claim IDs /// @return _activeClaims Array of active claim IDs function getActiveClaims() external view override returns(bytes32[] memory _activeClaims) { _activeClaims = activeClaims; } /// @notice Returns the IOU /// @param iouId IOU ID /// @return userAddress User address that will receive the IOU payment if /// redemptionCondition is met /// @return amountInShares Amount that will be paid in shares if /// redemptionCondition is met /// @return claimId Claim ID /// @return redemptionCondition Claim status needed for payment to be made function getIou(bytes32 iouId) external view override returns( address userAddress, uint256 amountInShares, bytes32 claimId, ClaimStatus redemptionCondition ) { Iou memory iou = ious[iouId]; userAddress = iou.userAddress; amountInShares = iou.amountInShares; claimId = iou.claimId; redemptionCondition = iou.redemptionCondition; } }
Returns the user balance. Includes vested and uvested funds, but not IOUs. userAddress User address return balance User balance
function getBalance(address userAddress) external view override returns(uint256 balance) { balance = balances[userAddress]; }
966,904
./full_match/5/0x10eE298D8445e507D6245ff2418C6608804486Cc/sources/contracts/L1/messaging/L1CrossDomainMessenger.sol
Initialize upgradable OZ contracts Context is a dependency for both Ownable and Pausable
function initialize(address _libAddressManager) public initializer { require( address(libAddressManager) == address(0), "L1CrossDomainMessenger already intialized." ); libAddressManager = Lib_AddressManager(_libAddressManager); xDomainMsgSender = Lib_DefaultValues.DEFAULT_XDOMAIN_SENDER; __Context_init_unchained(); __Ownable_init_unchained(); __Pausable_init_unchained(); __ReentrancyGuard_init_unchained(); }
1,894,237
pragma solidity ^0.4.11; contract RPS { enum State { Unrealized, Created, Joined, Ended } enum Result { Unfinished, Draw, Win, Loss, Forfeit } // From the perspective of player 1 struct Game { address player1; address player2; uint value; bytes32 hiddenMove1; uint8 move1; // 0 = not set, 1 = Rock, 2 = Paper, 3 = Scissors uint8 move2; uint gameStart; State state; Result result; } address public owner1; address public owner2; uint8 constant feeDivisor = 100; uint constant revealTime = 7 days; // TODO: dynamic reveal times? bool paused; bool expired; uint gameIdCounter; uint constant minimumNameLength = 1; uint constant maximumNameLength = 25; event NewName(address indexed player, string name); event Donate(address indexed player, uint amount); event Deposit(address indexed player, uint amount); event Withdraw(address indexed player, uint amount); event GameCreated(address indexed player1, address indexed player2, uint indexed gameId, uint value, bytes32 hiddenMove1); event GameJoined(address indexed player1, address indexed player2, uint indexed gameId, uint value, uint8 move2, uint gameStart); event GameEnded(address indexed player1, address indexed player2, uint indexed gameId, uint value, Result result); mapping(address => uint) public balances; mapping(address => uint) public totalWon; mapping(address => uint) public totalLost; Game [] public games; mapping(address => string) public playerNames; mapping(uint => bool) public nameTaken; mapping(bytes32 => bool) public secretTaken; modifier onlyOwner { require(msg.sender == owner1 || msg.sender == owner2); _; } modifier notPaused { require(!paused); _; } modifier notExpired { require(!expired); _; } function RPS(address otherOwner) { owner1 = msg.sender; owner2 = otherOwner; paused = true; } // UTILIY FUNCTIONS // // FOR DOING BORING REPETITIVE TASKS function getGames() constant internal returns (Game []) { return games; } function totalProfit(address player) constant returns (int) { if (totalLost[player] > totalWon[player]) { return -int(totalLost[player] - totalWon[player]); } else { return int(totalWon[player] - totalLost[player]); } } // Fuzzy hash and name validation taken from King of the Ether Throne // https://github.com/kieranelby/KingOfTheEtherThrone/blob/v1.0/contracts/KingOfTheEtherThrone.sol function computeNameFuzzyHash(string _name) constant internal returns (uint fuzzyHash) { bytes memory nameBytes = bytes(_name); uint h = 0; uint len = nameBytes.length; if (len > maximumNameLength) { len = maximumNameLength; } for (uint i = 0; i < len; i++) { uint mul = 128; byte b = nameBytes[i]; uint ub = uint(b); if (b >= 48 && b <= 57) { // 0-9 h = h * mul + ub; } else if (b >= 65 && b <= 90) { // A-Z h = h * mul + ub; } else if (b >= 97 && b <= 122) { // fold a-z to A-Z uint upper = ub - 32; h = h * mul + upper; } else { // ignore others } } return h; } /// @return True if-and-only-if `_name_` meets the criteria /// below, or false otherwise: /// - no fewer than 1 character /// - no more than 25 characters /// - no characters other than: /// - "roman" alphabet letters (A-Z and a-z) /// - western digits (0-9) /// - "safe" punctuation: ! ( ) - . _ SPACE /// - at least one non-punctuation character /// Note that we deliberately exclude characters which may cause /// security problems for websites and databases if escaping is /// not performed correctly, such as < > " and &#39;. /// Apologies for the lack of non-English language support. function validateNameInternal(string _name) constant internal returns (bool allowed) { bytes memory nameBytes = bytes(_name); uint lengthBytes = nameBytes.length; if (lengthBytes < minimumNameLength || lengthBytes > maximumNameLength) { return false; } bool foundNonPunctuation = false; for (uint i = 0; i < lengthBytes; i++) { byte b = nameBytes[i]; if ( (b >= 48 && b <= 57) || // 0 - 9 (b >= 65 && b <= 90) || // A - Z (b >= 97 && b <= 122) // a - z ) { foundNonPunctuation = true; continue; } if ( b == 32 || // space b == 33 || // ! b == 40 || // ( b == 41 || // ) b == 45 || // - b == 46 || // . b == 95 // _ ) { continue; } return false; } return foundNonPunctuation; } /// if you want to donate, please use the donate function function() { require(false); } // PLAYER FUNCTIONS // // FOR PLAYERS /// Name must only include upper and lowercase English letters, /// numbers, and certain characters: ! ( ) - . _ SPACE /// Function will return false if the name is not valid /// or if it&#39;s too similar to a name that&#39;s already taken. function setName(string name) returns (bool success) { require (validateNameInternal(name)); uint fuzzyHash = computeNameFuzzyHash(name); uint oldFuzzyHash; string storage oldName = playerNames[msg.sender]; bool oldNameEmpty = bytes(oldName).length == 0; if (nameTaken[fuzzyHash]) { require(!oldNameEmpty); oldFuzzyHash = computeNameFuzzyHash(oldName); require(fuzzyHash == oldFuzzyHash); } else { if (!oldNameEmpty) { oldFuzzyHash = computeNameFuzzyHash(oldName); nameTaken[oldFuzzyHash] = false; } nameTaken[fuzzyHash] = true; } playerNames[msg.sender] = name; NewName(msg.sender, name); return true; } //{ /// Create a game that may be joined only by the address provided. /// If no address is provided, the game is open to anyone. /// Your bet is equal to the value sent together /// with this transaction. If the game is a draw, /// your bet will be available for withdrawal. /// If you win, both bets minus the fee will be send to you. /// The first argument should be the number /// of your move (rock: 1, paper: 2, scissors: 3) /// encrypted with keccak256(uint move, string secret) and /// save the secret so you can reveal your move /// after your game is joined. /// It&#39;s very easy to mess up the padding and stuff, /// so you should just use the website. //} function createGame(bytes32 move, uint val, address player2) payable notPaused notExpired returns (uint gameId) { deposit(); require(balances[msg.sender] >= val); require(!secretTaken[move]); secretTaken[move] = true; balances[msg.sender] -= val; gameId = gameIdCounter; games.push(Game(msg.sender, player2, val, move, 0, 0, 0, State.Created, Result(0))); GameCreated(msg.sender, player2, gameId, val, move); gameIdCounter++; } function abortGame(uint gameId) notPaused returns (bool success) { Game storage thisGame = games[gameId]; require(thisGame.player1 == msg.sender); require(thisGame.state == State.Created); thisGame.state = State.Ended; GameEnded(thisGame.player1, thisGame.player2, gameId, thisGame.value, Result(0)); msg.sender.transfer(thisGame.value); return true; } function joinGame(uint gameId, uint8 move) payable notPaused returns (bool success) { Game storage thisGame = games[gameId]; require(thisGame.state == State.Created); require(move > 0 && move <= 3); if (thisGame.player2 == 0x0) { thisGame.player2 = msg.sender; } else { require(thisGame.player2 == msg.sender); } require(thisGame.value == msg.value); thisGame.gameStart = now; thisGame.state = State.Joined; thisGame.move2 = move; GameJoined(thisGame.player1, thisGame.player2, gameId, thisGame.value, thisGame.move2, thisGame.gameStart); return true; } function revealMove(uint gameId, uint8 move, string secret) notPaused returns (Result result) { Game storage thisGame = games[gameId]; require(thisGame.state == State.Joined); require(thisGame.player1 == msg.sender); require(thisGame.gameStart + revealTime >= now); // It&#39;s not too late to reveal require(thisGame.hiddenMove1 == keccak256(uint(move), secret)); thisGame.move1 = move; if (move > 0 && move <= 3) { result = Result(((3 + move - thisGame.move2) % 3) + 1); // It works trust me (it&#39;s &#39;cause of math) } else { // Player 1 submitted invalid move result = Result.Loss; } thisGame.state = State.Ended; address winner; if (result == Result.Draw) { balances[thisGame.player1] += thisGame.value; balances[thisGame.player2] += thisGame.value; } else { if (result == Result.Win) { winner = thisGame.player1; totalLost[thisGame.player2] += thisGame.value; } else { winner = thisGame.player2; totalLost[thisGame.player1] += thisGame.value; } uint fee = (thisGame.value) / feeDivisor; // 0.5% fee taken once for each owner balances[owner1] += fee; balances[owner2] += fee; totalWon[winner] += thisGame.value - fee*2; // No re-entrancy attack is possible because // the state has already been set to State.Ended winner.transfer((thisGame.value*2) - fee*2); } thisGame.result = result; GameEnded(thisGame.player1, thisGame.player2, gameId, thisGame.value, result); } /// Use this when you know you&#39;ve lost as player 1 and /// you don&#39;t want to bother with revealing your move. function forfeitGame(uint gameId) notPaused returns (bool success) { Game storage thisGame = games[gameId]; require(thisGame.state == State.Joined); require(thisGame.player1 == msg.sender); uint fee = (thisGame.value) / feeDivisor; // 0.5% fee taken once for each owner balances[owner1] += fee; balances[owner2] += fee; totalLost[thisGame.player1] += thisGame.value; totalWon[thisGame.player2] += thisGame.value - fee*2; thisGame.state = State.Ended; thisGame.result = Result.Forfeit; // Loss for player 1 GameEnded(thisGame.player1, thisGame.player2, gameId, thisGame.value, thisGame.result); thisGame.player2.transfer((thisGame.value*2) - fee*2); return true; } function claimGame(uint gameId) notPaused returns (bool success) { Game storage thisGame = games[gameId]; require(thisGame.state == State.Joined); require(thisGame.player2 == msg.sender); require(thisGame.gameStart + revealTime < now); // Player 1 has failed to reveal in time uint fee = (thisGame.value) / feeDivisor; // 0.5% fee taken once for each owner balances[owner1] += fee; balances[owner2] += fee; totalLost[thisGame.player1] += thisGame.value; totalWon[thisGame.player2] += thisGame.value - fee*2; thisGame.state = State.Ended; thisGame.result = Result.Forfeit; // Loss for player 1 GameEnded(thisGame.player1, thisGame.player2, gameId, thisGame.value, thisGame.result); thisGame.player2.transfer((thisGame.value*2) - fee*2); return true; } // FUNDING FUNCTIONS // // FOR FUNDING function donate() payable returns (bool success) { require(msg.value != 0); balances[owner1] += msg.value/2; balances[owner2] += msg.value - msg.value/2; Donate(msg.sender, msg.value); return true; } function deposit() payable returns (bool success) { require(msg.value != 0); balances[msg.sender] += msg.value; Deposit(msg.sender, msg.value); return true; } function withdraw() returns (bool success) { uint amount = balances[msg.sender]; if (amount == 0) return false; balances[msg.sender] = 0; msg.sender.transfer(amount); Withdraw(msg.sender, amount); return true; } // ADMIN FUNCTIONS // // FOR ADMINISTRATING // Pause all gameplay function pause(bool pause) onlyOwner { paused = pause; } // Prevent new games from being created // To be used when switching to a new contract function expire(bool expire) onlyOwner { expired = expire; } function setOwner1(address newOwner) { require(msg.sender == owner1); owner1 = newOwner; } function setOwner2(address newOwner) { require(msg.sender == owner2); owner2 = newOwner; } }
Prevent new games from being created To be used when switching to a new contract
function expire(bool expire) onlyOwner { expired = expire; }
2,167,203
./partial_match/4/0x36e7CABdcCE941dd387e395c9d1F741833FDc76D/sources/MasterChef.sol
将新的lp添加到池中,只能由所有者调用 _allocPoint 分配给该池的分配点数。 SUSHI按块分配 _lpToken LP代币合约的地址 _withUpdate 触发更新所有池的奖励变量。注意gas消耗!/ Add a new lp to the pool. Can only be called by the owner. XXX请勿多次添加同一LP令牌。如果您这样做,奖励将被搞砸 XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. 触发更新所有池的奖励变量
function add( uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate ) public onlyOwner { if (_withUpdate) { massUpdatePools(); } ? block.number : startBlock; PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accSushiPerShare: 0 }) ); }
8,546,016
./partial_match/1/0x2B4395084E1068877502EAD1Ae004094F5A0B88F/sources/P2PToken.sol
Set new owner for the smart contract. Only be called by smart contract owner. _newOwner address of new owner of the smart contract/
function setOwner(address _newOwner) public{ require (msg.sender == owner); owner = _newOwner; }
15,995,232
./full_match/9001/0x00232A8326af43515C8413A00b49282e25f50017/sources/src/token/ERC721/facets/minting/ERC721MintableRoleBased.sol
@inheritdoc IERC721MintableRoleBased/
function mintByRole( address to, uint256 amount, string[] calldata tokenURIs ) public virtual onlyRole(MINTER_ROLE) { uint256 nextTokenId = ERC721SupplyStorage.layout().currentIndex; IERC721MintableExtension(address(this)).mintByFacet(to, amount); for (uint256 i = 0; i < amount; i++) { _setURI(nextTokenId + i, tokenURIs[i]); } }
11,533,209
pragma solidity ^0.5.8; import "./ReentrancyGuard.sol"; import "./SafeMath.sol"; import "./SafeMathUInt128.sol"; import "./SafeCast.sol"; import "./Utils.sol"; import "./Storage.sol"; import "./Config.sol"; import "./Events.sol"; import "./Bytes.sol"; import "./Operations.sol"; import "./UpgradeableMaster.sol"; /// @title zkSync main contract /// @author Matter Labs contract ZkSync is UpgradeableMaster, Storage, Config, Events, ReentrancyGuard { using SafeMath for uint256; using SafeMathUInt128 for uint128; bytes32 public constant EMPTY_STRING_KECCAK = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // Upgrade functional /// @notice Notice period before activation preparation status of upgrade mode function getNoticePeriod() external returns (uint256) { return UPGRADE_NOTICE_PERIOD; } /// @notice Notification that upgrade notice period started function upgradeNoticePeriodStarted() external {} /// @notice Notification that upgrade preparation status is activated function upgradePreparationStarted() external { upgradePreparationActive = true; upgradePreparationActivationTime = now; } /// @notice Notification that upgrade canceled function upgradeCanceled() external { upgradePreparationActive = false; upgradePreparationActivationTime = 0; } /// @notice Notification that upgrade finishes function upgradeFinishes() external { upgradePreparationActive = false; upgradePreparationActivationTime = 0; } /// @notice Checks that contract is ready for upgrade /// @return bool flag indicating that contract is ready for upgrade function isReadyForUpgrade() external returns (bool) { return !exodusMode; } /// @notice Franklin contract initialization. Can be external because Proxy contract intercepts illegal calls of this function. /// @param initializationParameters Encoded representation of initialization parameters: /// _governanceAddress The address of Governance contract /// _verifierAddress The address of Verifier contract /// _ // FIXME: remove _genesisAccAddress /// _genesisRoot Genesis blocks (first block) root function initialize(bytes calldata initializationParameters) external { initializeReentrancyGuard(); ( address _governanceAddress, address _verifierAddress, bytes32 _genesisRoot ) = abi.decode(initializationParameters, (address, address, bytes32)); verifier = Verifier(_verifierAddress); governance = Governance(_governanceAddress); blocks[0].stateRoot = _genesisRoot; } /// @notice zkSync contract upgrade. Can be external because Proxy contract intercepts illegal calls of this function. /// @param upgradeParameters Encoded representation of upgrade parameters function upgrade(bytes calldata upgradeParameters) external {} /// @notice Sends tokens /// @dev NOTE: will revert if transfer call fails or rollup balance difference (before and after transfer) is bigger than _maxAmount /// @param _token Token address /// @param _to Address of recipient /// @param _amount Amount of tokens to transfer /// @param _maxAmount Maximum possible amount of tokens to transfer to this account function withdrawERC20Guarded( IERC20 _token, address _to, uint128 _amount, uint128 _maxAmount ) external returns (uint128 withdrawnAmount) { require(msg.sender == address(this), "wtg10"); // wtg10 - can be called only from this contract as one "external" call (to revert all this function state changes if it is needed) uint256 balance_before = _token.balanceOf(address(this)); require(Utils.sendERC20(_token, _to, _amount), "wtg11"); // wtg11 - ERC20 transfer fails uint256 balance_after = _token.balanceOf(address(this)); uint256 balance_diff = balance_before.sub(balance_after); require(balance_diff <= _maxAmount, "wtg12"); // wtg12 - rollup balance difference (before and after transfer) is bigger than _maxAmount return SafeCast.toUint128(balance_diff); } /// @notice executes pending withdrawals /// @param _n The number of withdrawals to complete starting from oldest function completeWithdrawals(uint32 _n) external nonReentrant { // TODO: when switched to multi validators model we need to add incentive mechanism to call complete. uint32 toProcess = Utils.minU32(_n, numberOfPendingWithdrawals); uint32 startIndex = firstPendingWithdrawalIndex; numberOfPendingWithdrawals -= toProcess; firstPendingWithdrawalIndex += toProcess; for (uint32 i = startIndex; i < startIndex + toProcess; ++i) { uint16 tokenId = pendingWithdrawals[i].tokenId; address to = pendingWithdrawals[i].to; // send fails are ignored hence there is always a direct way to withdraw. delete pendingWithdrawals[i]; bytes22 packedBalanceKey = packAddressAndTokenId(to, tokenId); uint128 amount = balancesToWithdraw[packedBalanceKey] .balanceToWithdraw; // amount is zero means funds has been withdrawn with withdrawETH or withdrawERC20 if (amount != 0) { balancesToWithdraw[packedBalanceKey] .balanceToWithdraw -= amount; bool sent = false; if (tokenId == 0) { address payable toPayable = address(uint160(to)); sent = Utils.sendETHNoRevert(toPayable, amount); } else { address tokenAddr = governance.tokenAddresses(tokenId); // we can just check that call not reverts because it wants to withdraw all amount (sent, ) = address(this).call.gas( ERC20_WITHDRAWAL_GAS_LIMIT )( abi.encodeWithSignature( "withdrawERC20Guarded(address,address,uint128,uint128)", tokenAddr, to, amount, amount ) ); } if (!sent) { balancesToWithdraw[packedBalanceKey] .balanceToWithdraw += amount; } } } if (toProcess > 0) { emit PendingWithdrawalsComplete(startIndex, startIndex + toProcess); } } /// @notice Accrues users balances from deposit priority requests in Exodus mode /// @dev WARNING: Only for Exodus mode /// @dev Canceling may take several separate transactions to be completed /// @param _n number of requests to process function cancelOutstandingDepositsForExodusMode(uint64 _n) external nonReentrant { require(exodusMode, "coe01"); // exodus mode not active uint64 toProcess = Utils.minU64(totalOpenPriorityRequests, _n); require(toProcess > 0, "coe02"); // no deposits to process for ( uint64 id = firstPriorityRequestId; id < firstPriorityRequestId + toProcess; id++ ) { if (priorityRequests[id].opType == Operations.OpType.Deposit) { Operations.Deposit memory op = Operations.readDepositPubdata( priorityRequests[id].pubData ); bytes22 packedBalanceKey = packAddressAndTokenId( op.owner, op.tokenId ); balancesToWithdraw[packedBalanceKey].balanceToWithdraw += op .amount; } delete priorityRequests[id]; } firstPriorityRequestId += toProcess; totalOpenPriorityRequests -= toProcess; } /// @notice Deposit ETH to Layer 2 - transfer ether from user into contract, validate it, register deposit /// @param _franklinAddr The receiver Layer 2 address function depositETH(address _franklinAddr) external payable nonReentrant { requireActive(); registerDeposit(0, SafeCast.toUint128(msg.value), _franklinAddr); } /// @notice Withdraw ETH to Layer 1 - register withdrawal and transfer ether to sender /// @param _amount Ether amount to withdraw function withdrawETH(uint128 _amount) external nonReentrant { registerWithdrawal(0, _amount, msg.sender); (bool success, ) = msg.sender.call.value(_amount)(""); require(success, "fwe11"); // ETH withdraw failed } /// @notice Deposit ERC20 token to Layer 2 - transfer ERC20 tokens from user into contract, validate it, register deposit /// @param _token Token address /// @param _amount Token amount /// @param _franklinAddr Receiver Layer 2 address function depositERC20( IERC20 _token, uint104 _amount, address _franklinAddr ) external nonReentrant { requireActive(); // Get token id by its address uint16 tokenId = governance.validateTokenAddress(address(_token)); uint256 balance_before = _token.balanceOf(address(this)); require( Utils.transferFromERC20( _token, msg.sender, address(this), SafeCast.toUint128(_amount) ), "fd012" ); // token transfer failed deposit uint256 balance_after = _token.balanceOf(address(this)); uint128 deposit_amount = SafeCast.toUint128( balance_after.sub(balance_before) ); registerDeposit(tokenId, deposit_amount, _franklinAddr); } /// @notice Withdraw ERC20 token to Layer 1 - register withdrawal and transfer ERC20 to sender /// @param _token Token address /// @param _amount amount to withdraw function withdrawERC20(IERC20 _token, uint128 _amount) external nonReentrant { uint16 tokenId = governance.validateTokenAddress(address(_token)); bytes22 packedBalanceKey = packAddressAndTokenId(msg.sender, tokenId); uint128 balance = balancesToWithdraw[packedBalanceKey] .balanceToWithdraw; uint128 withdrawnAmount = this.withdrawERC20Guarded( _token, msg.sender, _amount, balance ); registerWithdrawal(tokenId, withdrawnAmount, msg.sender); } /// @notice Register full exit request - pack pubdata, add priority request /// @param _accountId Numerical id of the account /// @param _token Token address, 0 address for ether function fullExit(uint32 _accountId, address _token) external nonReentrant { requireActive(); require(_accountId <= MAX_ACCOUNT_ID, "fee11"); uint16 tokenId; if (_token == address(0)) { tokenId = 0; } else { tokenId = governance.validateTokenAddress(_token); } // Priority Queue request Operations.FullExit memory op = Operations.FullExit({ accountId: _accountId, owner: msg.sender, tokenId: tokenId, amount: 0 // unknown at this point }); bytes memory pubData = Operations.writeFullExitPubdata(op); addPriorityRequest(Operations.OpType.FullExit, pubData); // User must fill storage slot of balancesToWithdraw(msg.sender, tokenId) with nonzero value // In this case operator should just overwrite this slot during confirming withdrawal bytes22 packedBalanceKey = packAddressAndTokenId(msg.sender, tokenId); balancesToWithdraw[packedBalanceKey].gasReserveValue = 0xff; } /// @notice Commit block - collect onchain operations, create its commitment, emit BlockCommit event /// @param _blockNumber Block number /// @param _feeAccount Account to collect fees /// @param _newBlockInfo New state of the block. (first element is the account tree root hash, rest of the array is reserved for the future) /// @param _publicData Operations pubdata /// @param _ethWitness Data passed to ethereum outside pubdata of the circuit. /// @param _ethWitnessSizes Amount of eth witness bytes for the corresponding operation. function commitBlock( uint32 _blockNumber, uint32 _feeAccount, bytes32[] calldata _newBlockInfo, bytes calldata _publicData, bytes calldata _ethWitness, uint32[] calldata _ethWitnessSizes ) external nonReentrant { requireActive(); require(_blockNumber == totalBlocksCommitted + 1, "fck11"); // only commit next block governance.requireActiveValidator(msg.sender); require(_newBlockInfo.length == 1, "fck13"); // This version of the contract expects only account tree root hash bytes memory publicData = _publicData; // Unpack onchain operations and store them. // Get priority operations number for this block. uint64 prevTotalCommittedPriorityRequests = totalCommittedPriorityRequests; bytes32 withdrawalsDataHash = collectOnchainOps( _blockNumber, publicData, _ethWitness, _ethWitnessSizes ); uint64 nPriorityRequestProcessed = totalCommittedPriorityRequests - prevTotalCommittedPriorityRequests; createCommittedBlock( _blockNumber, _feeAccount, _newBlockInfo[0], publicData, withdrawalsDataHash, nPriorityRequestProcessed ); totalBlocksCommitted++; emit BlockCommit(_blockNumber); } /// @notice Block verification. /// @notice Verify proof -> process onchain withdrawals (accrue balances from withdrawals) -> remove priority requests /// @param _blockNumber Block number /// @param _proof Block proof /// @param _withdrawalsData Block withdrawals data function verifyBlock( uint32 _blockNumber, uint256[] calldata _proof, bytes calldata _withdrawalsData ) external nonReentrant { requireActive(); require(_blockNumber == totalBlocksVerified + 1, "fvk11"); // only verify next block governance.requireActiveValidator(msg.sender); require( verifier.verifyBlockProof( _proof, blocks[_blockNumber].commitment, blocks[_blockNumber].chunks ), "fvk13" ); // proof verification failed processOnchainWithdrawals( _withdrawalsData, blocks[_blockNumber].withdrawalsDataHash ); deleteRequests(blocks[_blockNumber].priorityOperations); totalBlocksVerified += 1; emit BlockVerification(_blockNumber); } /// @notice Reverts unverified blocks /// @param _maxBlocksToRevert the maximum number blocks that will be reverted (use if can't revert all blocks because of gas limit). function revertBlocks(uint32 _maxBlocksToRevert) external nonReentrant { require(isBlockCommitmentExpired(), "rbs11"); // trying to revert non-expired blocks. governance.requireActiveValidator(msg.sender); uint32 blocksCommited = totalBlocksCommitted; uint32 blocksToRevert = Utils.minU32( _maxBlocksToRevert, blocksCommited - totalBlocksVerified ); uint64 revertedPriorityRequests = 0; for ( uint32 i = totalBlocksCommitted - blocksToRevert + 1; i <= blocksCommited; i++ ) { Block memory revertedBlock = blocks[i]; require(revertedBlock.committedAtBlock > 0, "frk11"); // block not found revertedPriorityRequests += revertedBlock.priorityOperations; delete blocks[i]; } blocksCommited -= blocksToRevert; totalBlocksCommitted -= blocksToRevert; totalCommittedPriorityRequests -= revertedPriorityRequests; emit BlocksRevert(totalBlocksVerified, blocksCommited); } /// @notice Checks if Exodus mode must be entered. If true - enters exodus mode and emits ExodusMode event. /// @dev Exodus mode must be entered in case of current ethereum block number is higher than the oldest /// @dev of existed priority requests expiration block number. /// @return bool flag that is true if the Exodus mode must be entered. function triggerExodusIfNeeded() external returns (bool) { bool trigger = block.number >= priorityRequests[firstPriorityRequestId].expirationBlock && priorityRequests[firstPriorityRequestId].expirationBlock != 0; if (trigger) { if (!exodusMode) { exodusMode = true; emit ExodusMode(); } return true; } else { return false; } } /// @notice Withdraws token from Franklin to root chain in case of exodus mode. User must provide proof that he owns funds /// @param _accountId Id of the account in the tree /// @param _proof Proof /// @param _tokenId Verified token id /// @param _amount Amount for owner (must be total amount, not part of it) function exit( uint32 _accountId, uint16 _tokenId, uint128 _amount, uint256[] calldata _proof ) external nonReentrant { bytes22 packedBalanceKey = packAddressAndTokenId(msg.sender, _tokenId); require(exodusMode, "fet11"); // must be in exodus mode require(!exited[_accountId][_tokenId], "fet12"); // already exited require( verifier.verifyExitProof( blocks[totalBlocksVerified].stateRoot, _accountId, msg.sender, _tokenId, _amount, _proof ), "fet13" ); // verification failed uint128 balance = balancesToWithdraw[packedBalanceKey] .balanceToWithdraw; balancesToWithdraw[packedBalanceKey].balanceToWithdraw = balance.add( _amount ); exited[_accountId][_tokenId] = true; } function setAuthPubkeyHash(bytes calldata _pubkey_hash, uint32 _nonce) external nonReentrant { require(_pubkey_hash.length == PUBKEY_HASH_BYTES, "ahf10"); // PubKeyHash should be 20 bytes. require(authFacts[msg.sender][_nonce] == bytes32(0), "ahf11"); // auth fact for nonce should be empty authFacts[msg.sender][_nonce] = keccak256(_pubkey_hash); emit FactAuth(msg.sender, _nonce, _pubkey_hash); } /// @notice Register deposit request - pack pubdata, add priority request and emit OnchainDeposit event /// @param _tokenId Token by id /// @param _amount Token amount /// @param _owner Receiver function registerDeposit( uint16 _tokenId, uint128 _amount, address _owner ) internal { // Priority Queue request Operations.Deposit memory op = Operations.Deposit({ accountId: 0, // unknown at this point owner: _owner, tokenId: _tokenId, amount: _amount }); bytes memory pubData = Operations.writeDepositPubdata(op); addPriorityRequest(Operations.OpType.Deposit, pubData); emit OnchainDeposit(msg.sender, _tokenId, _amount, _owner); } /// @notice Register withdrawal - update user balance and emit OnchainWithdrawal event /// @param _token - token by id /// @param _amount - token amount /// @param _to - address to withdraw to function registerWithdrawal( uint16 _token, uint128 _amount, address payable _to ) internal { bytes22 packedBalanceKey = packAddressAndTokenId(_to, _token); uint128 balance = balancesToWithdraw[packedBalanceKey] .balanceToWithdraw; balancesToWithdraw[packedBalanceKey].balanceToWithdraw = balance.sub( _amount ); emit OnchainWithdrawal(_to, _token, _amount); } /// @notice Store committed block structure to the storage. /// @param _nCommittedPriorityRequests - number of priority requests in block function createCommittedBlock( uint32 _blockNumber, uint32 _feeAccount, bytes32 _newRoot, bytes memory _publicData, bytes32 _withdrawalDataHash, uint64 _nCommittedPriorityRequests ) internal { require(_publicData.length % CHUNK_BYTES == 0, "cbb10"); // Public data size is not multiple of CHUNK_BYTES uint32 blockChunks = uint32(_publicData.length / CHUNK_BYTES); require(verifier.isBlockSizeSupported(blockChunks), "ccb11"); // Create block commitment for verification proof bytes32 commitment = createBlockCommitment( _blockNumber, _feeAccount, blocks[_blockNumber - 1].stateRoot, _newRoot, _publicData ); blocks[_blockNumber] = Block( uint32(block.number), // committed at _nCommittedPriorityRequests, // number of priority onchain ops in block blockChunks, _withdrawalDataHash, // hash of onchain withdrawals data (will be used during checking block withdrawal data in verifyBlock function) commitment, // blocks' commitment _newRoot // new root ); } function emitDepositCommitEvent( uint32 _blockNumber, Operations.Deposit memory depositData ) internal { emit DepositCommit( _blockNumber, depositData.accountId, depositData.owner, depositData.tokenId, depositData.amount ); } function emitFullExitCommitEvent( uint32 _blockNumber, Operations.FullExit memory fullExitData ) internal { emit FullExitCommit( _blockNumber, fullExitData.accountId, fullExitData.owner, fullExitData.tokenId, fullExitData.amount ); } /// @notice Gets operations packed in bytes array. Unpacks it and stores onchain operations. /// @param _blockNumber Franklin block number /// @param _publicData Operations packed in bytes array /// @param _ethWitness Eth witness that was posted with commit /// @param _ethWitnessSizes Amount of eth witness bytes for the corresponding operation. /// Priority operations must be committed in the same order as they are in the priority queue. function collectOnchainOps( uint32 _blockNumber, bytes memory _publicData, bytes memory _ethWitness, uint32[] memory _ethWitnessSizes ) internal returns (bytes32 withdrawalsDataHash) { require(_publicData.length % CHUNK_BYTES == 0, "fcs11"); // pubdata length must be a multiple of CHUNK_BYTES uint64 currentPriorityRequestId = firstPriorityRequestId + totalCommittedPriorityRequests; uint256 pubDataPtr = 0; uint256 pubDataStartPtr = 0; uint256 pubDataEndPtr = 0; assembly { pubDataStartPtr := add(_publicData, 0x20) } pubDataPtr = pubDataStartPtr; pubDataEndPtr = pubDataStartPtr + _publicData.length; uint64 ethWitnessOffset = 0; uint16 processedOperationsRequiringEthWitness = 0; withdrawalsDataHash = EMPTY_STRING_KECCAK; while (pubDataPtr < pubDataEndPtr) { Operations.OpType opType; // read operation type from public data (the first byte per each operation) assembly { opType := shr(0xf8, mload(pubDataPtr)) } // cheap operations processing if (opType == Operations.OpType.Transfer) { pubDataPtr += TRANSFER_BYTES; } else if (opType == Operations.OpType.Noop) { pubDataPtr += NOOP_BYTES; } else if (opType == Operations.OpType.TransferToNew) { pubDataPtr += TRANSFER_TO_NEW_BYTES; } else { // other operations processing // calculation of public data offset uint256 pubdataOffset = pubDataPtr - pubDataStartPtr; if (opType == Operations.OpType.Deposit) { bytes memory pubData = Bytes.slice( _publicData, pubdataOffset + 1, DEPOSIT_BYTES - 1 ); Operations.Deposit memory depositData = Operations .readDepositPubdata(pubData); emitDepositCommitEvent(_blockNumber, depositData); OnchainOperation memory onchainOp = OnchainOperation( Operations.OpType.Deposit, pubData ); commitNextPriorityOperation( onchainOp, currentPriorityRequestId ); currentPriorityRequestId++; pubDataPtr += DEPOSIT_BYTES; } else if (opType == Operations.OpType.PartialExit) { Operations.PartialExit memory data = Operations .readPartialExitPubdata(_publicData, pubdataOffset + 1); bool addToPendingWithdrawalsQueue = true; withdrawalsDataHash = keccak256( abi.encode( withdrawalsDataHash, addToPendingWithdrawalsQueue, data.owner, data.tokenId, data.amount ) ); pubDataPtr += PARTIAL_EXIT_BYTES; } else if (opType == Operations.OpType.ForcedExit) { Operations.ForcedExit memory data = Operations .readForcedExitPubdata(_publicData, pubdataOffset + 1); bool addToPendingWithdrawalsQueue = true; withdrawalsDataHash = keccak256( abi.encode( withdrawalsDataHash, addToPendingWithdrawalsQueue, data.target, data.tokenId, data.amount ) ); pubDataPtr += FORCED_EXIT_BYTES; } else if (opType == Operations.OpType.FullExit) { bytes memory pubData = Bytes.slice( _publicData, pubdataOffset + 1, FULL_EXIT_BYTES - 1 ); Operations.FullExit memory fullExitData = Operations .readFullExitPubdata(pubData); emitFullExitCommitEvent(_blockNumber, fullExitData); bool addToPendingWithdrawalsQueue = false; withdrawalsDataHash = keccak256( abi.encode( withdrawalsDataHash, addToPendingWithdrawalsQueue, fullExitData.owner, fullExitData.tokenId, fullExitData.amount ) ); OnchainOperation memory onchainOp = OnchainOperation( Operations.OpType.FullExit, pubData ); commitNextPriorityOperation( onchainOp, currentPriorityRequestId ); currentPriorityRequestId++; pubDataPtr += FULL_EXIT_BYTES; } else if (opType == Operations.OpType.ChangePubKey) { require( processedOperationsRequiringEthWitness < _ethWitnessSizes.length, "fcs13" ); // eth witness data malformed Operations.ChangePubKey memory op = Operations .readChangePubKeyPubdata( _publicData, pubdataOffset + 1 ); if ( _ethWitnessSizes[processedOperationsRequiringEthWitness] != 0 ) { bytes memory currentEthWitness = Bytes.slice( _ethWitness, ethWitnessOffset, _ethWitnessSizes[processedOperationsRequiringEthWitness] ); bool valid = verifyChangePubkeySignature( currentEthWitness, op.pubKeyHash, op.nonce, op.owner, op.accountId ); require(valid, "fpp15"); // failed to verify change pubkey hash signature } else { bool valid = authFacts[op.owner][op.nonce] == keccak256(abi.encodePacked(op.pubKeyHash)); require(valid, "fpp16"); // new pub key hash is not authenticated properly } ethWitnessOffset += _ethWitnessSizes[processedOperationsRequiringEthWitness]; processedOperationsRequiringEthWitness++; pubDataPtr += CHANGE_PUBKEY_BYTES; } else { revert("fpp14"); // unsupported op } } } require(pubDataPtr == pubDataEndPtr, "fcs12"); // last chunk exceeds pubdata require(ethWitnessOffset == _ethWitness.length, "fcs14"); // _ethWitness was not used completely require( processedOperationsRequiringEthWitness == _ethWitnessSizes.length, "fcs15" ); // _ethWitnessSizes was not used completely require( currentPriorityRequestId <= firstPriorityRequestId + totalOpenPriorityRequests, "fcs16" ); // fcs16 - excess priority requests in pubdata totalCommittedPriorityRequests = currentPriorityRequestId - firstPriorityRequestId; } /// @notice Checks that signature is valid for pubkey change message /// @param _signature Signature /// @param _newPkHash New pubkey hash /// @param _nonce Nonce used for message /// @param _ethAddress Account's ethereum address /// @param _accountId Id of zkSync account function verifyChangePubkeySignature( bytes memory _signature, bytes20 _newPkHash, uint32 _nonce, address _ethAddress, uint32 _accountId ) internal pure returns (bool) { bytes memory signedMessage = abi.encodePacked( "\x19Ethereum Signed Message:\n152", "Register zkSync pubkey:\n\n", Bytes.bytesToHexASCIIBytes(abi.encodePacked(_newPkHash)), "\n", "nonce: 0x", Bytes.bytesToHexASCIIBytes(Bytes.toBytesFromUInt32(_nonce)), "\n", "account id: 0x", Bytes.bytesToHexASCIIBytes(Bytes.toBytesFromUInt32(_accountId)), "\n\n", "Only sign this message for a trusted client!" ); address recoveredAddress = Utils.recoverAddressFromEthSignature( _signature, signedMessage ); return recoveredAddress == _ethAddress; } /// @notice Creates block commitment from its data /// @param _blockNumber Block number /// @param _feeAccount Account to collect fees /// @param _oldRoot Old tree root /// @param _newRoot New tree root /// @param _publicData Operations pubdata /// @return block commitment function createBlockCommitment( uint32 _blockNumber, uint32 _feeAccount, bytes32 _oldRoot, bytes32 _newRoot, bytes memory _publicData ) internal view returns (bytes32 commitment) { bytes32 hash = sha256( abi.encodePacked(uint256(_blockNumber), uint256(_feeAccount)) ); hash = sha256(abi.encodePacked(hash, uint256(_oldRoot))); hash = sha256(abi.encodePacked(hash, uint256(_newRoot))); /// The code below is equivalent to `commitment = sha256(abi.encodePacked(hash, _publicData))` /// We use inline assembly instead of this concise and readable code in order to avoid copying of `_publicData` (which saves ~90 gas per transfer operation). /// Specifically, we perform the following trick: /// First, replace the first 32 bytes of `_publicData` (where normally its length is stored) with the value of `hash`. /// Then, we call `sha256` precompile passing the `_publicData` pointer and the length of the concatenated byte buffer. /// Finally, we put the `_publicData.length` back to its original location (to the first word of `_publicData`). assembly { let hashResult := mload(0x40) let pubDataLen := mload(_publicData) mstore(_publicData, hash) // staticcall to the sha256 precompile at address 0x2 let success := staticcall( gas, 0x2, _publicData, add(pubDataLen, 0x20), hashResult, 0x20 ) mstore(_publicData, pubDataLen) // Use "invalid" to make gas estimation work switch success case 0 { invalid() } commitment := mload(hashResult) } } /// @notice Checks that operation is same as operation in priority queue /// @param _onchainOp The operation /// @param _priorityRequestId Operation's id in priority queue function commitNextPriorityOperation( OnchainOperation memory _onchainOp, uint64 _priorityRequestId ) internal view { Operations.OpType priorReqType = priorityRequests[_priorityRequestId] .opType; bytes memory priorReqPubdata = priorityRequests[_priorityRequestId] .pubData; require(priorReqType == _onchainOp.opType, "nvp12"); // incorrect priority op type if (_onchainOp.opType == Operations.OpType.Deposit) { require( Operations.depositPubdataMatch( priorReqPubdata, _onchainOp.pubData ), "vnp13" ); } else if (_onchainOp.opType == Operations.OpType.FullExit) { require( Operations.fullExitPubdataMatch( priorReqPubdata, _onchainOp.pubData ), "vnp14" ); } else { revert("vnp15"); // invalid or non-priority operation } } /// @notice Processes onchain withdrawals. Full exit withdrawals will not be added to pending withdrawals queue /// @dev NOTICE: must process only withdrawals which hash matches with expectedWithdrawalsDataHash. /// @param withdrawalsData Withdrawals data /// @param expectedWithdrawalsDataHash Expected withdrawals data hash function processOnchainWithdrawals( bytes memory withdrawalsData, bytes32 expectedWithdrawalsDataHash ) internal { require( withdrawalsData.length % ONCHAIN_WITHDRAWAL_BYTES == 0, "pow11" ); // pow11 - withdrawalData length is not multiple of ONCHAIN_WITHDRAWAL_BYTES bytes32 withdrawalsDataHash = EMPTY_STRING_KECCAK; uint256 offset = 0; uint32 localNumberOfPendingWithdrawals = numberOfPendingWithdrawals; while (offset < withdrawalsData.length) { ( bool addToPendingWithdrawalsQueue, address _to, uint16 _tokenId, uint128 _amount ) = Operations.readWithdrawalData(withdrawalsData, offset); bytes22 packedBalanceKey = packAddressAndTokenId(_to, _tokenId); uint128 balance = balancesToWithdraw[packedBalanceKey] .balanceToWithdraw; // after this all writes to this slot will cost 5k gas balancesToWithdraw[packedBalanceKey] = BalanceToWithdraw({ balanceToWithdraw: balance.add(_amount), gasReserveValue: 0xff }); if (addToPendingWithdrawalsQueue) { pendingWithdrawals[firstPendingWithdrawalIndex + localNumberOfPendingWithdrawals] = PendingWithdrawal( _to, _tokenId ); localNumberOfPendingWithdrawals++; } withdrawalsDataHash = keccak256( abi.encode( withdrawalsDataHash, addToPendingWithdrawalsQueue, _to, _tokenId, _amount ) ); offset += ONCHAIN_WITHDRAWAL_BYTES; } require(withdrawalsDataHash == expectedWithdrawalsDataHash, "pow12"); // pow12 - withdrawals data hash not matches with expected value if (numberOfPendingWithdrawals != localNumberOfPendingWithdrawals) { emit PendingWithdrawalsAdd( firstPendingWithdrawalIndex + numberOfPendingWithdrawals, firstPendingWithdrawalIndex + localNumberOfPendingWithdrawals ); } numberOfPendingWithdrawals = localNumberOfPendingWithdrawals; } /// @notice Checks whether oldest unverified block has expired /// @return bool flag that indicates whether oldest unverified block has expired function isBlockCommitmentExpired() internal view returns (bool) { return (totalBlocksCommitted > totalBlocksVerified && blocks[totalBlocksVerified + 1].committedAtBlock > 0 && block.number > blocks[totalBlocksVerified + 1].committedAtBlock + EXPECT_VERIFICATION_IN); } /// @notice Checks that current state not is exodus mode function requireActive() internal view { require(!exodusMode, "fre11"); // exodus mode activated } // Priority queue /// @notice Saves priority request in storage /// @dev Calculates expiration block for request, store this request and emit NewPriorityRequest event /// @param _opType Rollup operation type /// @param _pubData Operation pubdata function addPriorityRequest( Operations.OpType _opType, bytes memory _pubData ) internal { // Expiration block is: current block number + priority expiration delta uint256 expirationBlock = block.number + PRIORITY_EXPIRATION; uint64 nextPriorityRequestId = firstPriorityRequestId + totalOpenPriorityRequests; priorityRequests[nextPriorityRequestId] = PriorityOperation({ opType: _opType, pubData: _pubData, expirationBlock: expirationBlock }); emit NewPriorityRequest( msg.sender, nextPriorityRequestId, _opType, _pubData, expirationBlock ); totalOpenPriorityRequests++; } /// @notice Deletes processed priority requests /// @param _number The number of requests function deleteRequests(uint64 _number) internal { require(_number <= totalOpenPriorityRequests, "pcs21"); // number is higher than total priority requests number uint64 numberOfRequestsToClear = Utils.minU64( _number, MAX_PRIORITY_REQUESTS_TO_DELETE_IN_VERIFY ); uint64 startIndex = firstPriorityRequestId; for ( uint64 i = startIndex; i < startIndex + numberOfRequestsToClear; i++ ) { delete priorityRequests[i]; } totalOpenPriorityRequests -= _number; firstPriorityRequestId += _number; totalCommittedPriorityRequests -= _number; } }
Franklin contract initialization. Can be external because Proxy contract intercepts illegal calls of this function. initializationParameters Encoded representation of initialization parameters: _governanceAddress The address of Governance contract _verifierAddress The address of Verifier contract _ // FIXME: remove _genesisAccAddress _genesisRoot Genesis blocks (first block) root
function initialize(bytes calldata initializationParameters) external { initializeReentrancyGuard(); ( address _governanceAddress, address _verifierAddress, bytes32 _genesisRoot ) = abi.decode(initializationParameters, (address, address, bytes32)); verifier = Verifier(_verifierAddress); governance = Governance(_governanceAddress); blocks[0].stateRoot = _genesisRoot; }
5,479,347
// SPDX-License-Identifier: MIT pragma solidity 0.8.11; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol"; import "./IAssemblyCore.sol"; import "./IProofOfHumanity.sol"; import "./Wallet.sol"; /// @title Assembly contract implementing a semi-direct democracy and on-chain tallying. /// @dev This contract manages citizen and delegate registration, voting, tallying and execution of transaction proposals. In conjunction with the Wallet contract, this contract implements a democratic (not "tokencratic") Decentralized Autonomous Organization (DAO) consisting of a semi-direct democracy following the 1-human-1-vote principle, optional vote delegation and on-chain tallying. The only prerrequisite to register in the DAO is to prove to be a human, which is done through Proof-of-Humanity. Humans can participate in the DAO as citizens and as delegates. Proposals, which are chain transactions, need to be approved by a majority, determined by a certain threshold percentage, to be executed. Delegates voting power is proportional to the amount of citizens. A quorum is needed to approve proposals. DAO members can be flagged as distrusted by the DAO. Members whose humanity proof is no longer valid or have become distrusted can be expelled from the DAO. /// /// The voting process consist of the following steps: /// 1. Transaction submission: A transaction proposal is submitted to the Wallet contract. /// 2. Creation of a tally: A tally to vote on the proposal is created. /// 3. Voting: Delegates (and optionally citizens) cast their votes. The voting period is divided into 2 phases: deliberation and revocation. /// /// | ------------------- tallyDuration-------------------- | /// | -- Deliberation phase -- | -- Revocation phase -- ... | --- Enaction ... /// | -- Delegates can vote -- | /// | -- Citizens can vote -------------------------------- | /// | ------------------------------------------------------------------------ > time /// /// Citizens can cast their votes during either phase whereas delegates can only during the deliberation phase. This phase is intended to enable citizens the possibility of revoking any proposal that might have been approved by the delegates against the actual preference of their appointed citizens, as a citizen's majority superseds a delegate's majority. /// 4. Tallying up and enaction: Votes are counted and, if the proposal is approved, the transaction is executed contract AssemblyCore is UUPSUpgradeable, ReentrancyGuardUpgradeable, IERC20, IAssemblyCore { IProofOfHumanity private _poh; IWallet private _wallet; address private _owner; // for practical purposes, owner and wallet are defined using different variables although they have the same value as the Wallet contract is the owner of the Assembly contract bool private _initialized; address private _creator; // // Population // uint256 internal _citizenCount; mapping(address => bool) internal _isInCitizenCount; uint256 private _delegateCount; mapping(address => bool) internal _isInDelegateCount; mapping(address => address) private _appointments; // citizen => delegate mapping(address => uint256) private _appointmentCount; // delegate => no. of citizens address[] private _delegateSeats; // the addresses of the delegates seating mapping(address => bool) private _isSeated; mapping(address => uint256) private _delegateSeat; mapping(address => bool) private _isDistrusted; // // Voting // mapping(uint256 => Tally) internal _tallies; uint256 private _tallyCount; mapping(uint256 => mapping(address => bool)) private _delegateVotes; mapping(uint256 => mapping(address => VoteStatus)) private _citizenVotes; // // Parameters // uint256 public constant DEFAULT_THRESHOLD = 50; uint256 private _votingPercentThreshold; uint256 private _seatCount; uint256 private _citizenCountQuorum; uint256 private _tallyDuration; // // Events // // population event CitizenApplication(address indexed citizen, uint256 numCitizens); event DelegateApplication(address indexed delegate, uint256 numDelegates); event Distrust(address indexed account); event Expelled(address indexed member); // evolution event AppointDelegate(address indexed delegate, address indexed citizen); event DelegateSeatUpdate(uint256 indexed seatNumber, address indexed delegate); event NewTally(uint256 indexed tallyId); event DelegateVote(uint256 indexed tallyId, bool yay, address indexed delegate); event CitizenVote(uint256 indexed tallyId, bool yay, address indexed citizen); event Tallied(uint256 indexed tallyId); event Enacted(uint256 indexed tallyId); // configuration event VotingPercentThreshold(uint256 votingPercentThreshold); event SeatCount(uint256 seatCount); event Quorum(uint256 citizenCountQuorum); event TallyDuration(uint256 tallyDuration); // // Modifiers // modifier isInitialized() { require(_initialized, "Contract has not yet been initialized"); _; } modifier onlyOwner() { require((_owner == msg.sender) || isTestMode(), "You are not allowed to do this"); _; } /// @dev To be used on functions prone to be abused otherwise. modifier onlyTrusted() { require(isTrusted(msg.sender), "You are not trusted to perform this operation"); _; } // // Test functions (to be n for testing purposes only). // function isTestMode() public view virtual returns (bool) { return false; } function setTestMode(bool testMode) external virtual {} // // Functions // function getCreator() external view returns (address) { return _creator; } function setCreator(address newCreator) external { require(msg.sender == _creator, "You are not allowed to do this"); require(newCreator != _creator, "The new address must be different"); require(newCreator != address(0), "Creator address cannot be zero"); _creator = newCreator; } function getPoh() external view returns (address) { return address(_poh); } function getWallet() external view returns (address) { return address(_wallet); } function getOwner() external view returns (address) { return address(_owner); } function isHuman(address account) public view isInitialized returns (bool) { return account == _creator || _poh.isRegistered(account); // the creator's humanity proof is not required } function isCitizen(address _human) external view returns (bool) { return _isInCitizenCount[_human]; } function isDelegate(address _delegate) external view returns (bool) { return _isInDelegateCount[_delegate]; } function getCitizenCount() external view returns (uint256) { return _citizenCount; } function getDelegateCount() external view returns (uint256) { return _delegateCount; } function getAppointedDelegate() external view returns (address) { return _appointments[msg.sender]; } function getAppointmentCount(address _delegate) external view returns (uint256) { return _appointmentCount[_delegate]; } function getVotingPercentThreshold() external view returns (uint256) { return _votingPercentThreshold; } function getSeatCount() external view returns (uint256) { return _seatCount; } function getQuorum() external view returns (uint256) { return _citizenCountQuorum; } function getTallyDuration() external view returns (uint256) { return _tallyDuration; } function getDelegateSeats() external view returns (address[] memory) { return _delegateSeats; } function isDelegateSeated(address _delegate) external view returns (bool) { return _isSeated[_delegate]; } function getDelegateSeat(address _delegate) external view returns (uint256) { return _delegateSeat[_delegate]; } function getDelegateSeatAppointmentCounts() public view returns (address[] memory, uint256[] memory) { uint256[] memory ret; if (_delegateSeats.length > 0) { ret = new uint256[](_delegateSeats.length); for (uint256 i = 0; i < _delegateSeats.length; i++) ret[i] = _appointmentCount[_delegateSeats[i]]; } return (_delegateSeats, ret); } function isTrusted(address account) public view returns (bool) { return isHuman(account) && !_isDistrusted[account]; } /// @param tallyId The id of the tally. /// @return Vote sign that the sender cast as a delegate. function getDelegateVote(uint256 tallyId) external view returns (bool) { require(_isInDelegateCount[msg.sender], "You are not a delegate"); return _delegateVotes[tallyId][msg.sender]; } /// @param tallyId The id of the tally. /// @return Vote sign that the sender cast as a citizen. function getCitizenVote(uint256 tallyId) external view returns (VoteStatus) { require(_isInCitizenCount[msg.sender], "You are not a citizen"); return _citizenVotes[tallyId][msg.sender]; } /// @param tallyId The id of the tally. /// @return The tally struct. function getTally(uint256 tallyId) external view returns (Tally memory) { return _tallies[tallyId]; } /// @param tallyId The id of the tally. /// @return The phase which the tally is on. function getTallyPhase(uint256 tallyId) public view returns (TallyPhase) { Tally storage t = _tallies[tallyId]; if (block.timestamp < t.revocationStartTime) return TallyPhase.Deliberation; else if (block.timestamp < t.votingEndTime) return TallyPhase.Revocation; return TallyPhase.Ended; } /// @return The total number of tallies ever created. function getTallyCount() external view returns (uint256) { return _tallyCount; } /// @dev The contract needs to be initialized before use. /// @param poh The contract implementing the Proof-of-Humanity interface. /// @param owner The address of the Wallet contract. /// @param wallet The address of the Wallet contract. /// @param seatCount Number of seats to be sat by delegates. /// @param citizenCountQuorum Smallest number of citizens registered to approve a proposal. /// @param tallyDuration Total duration of each tally. function _initialize( address poh, address owner, address wallet, uint256 seatCount, uint256 citizenCountQuorum, uint256 tallyDuration ) internal { require(!_initialized, "Contract has already been initialized"); require(poh != address(0), "PoH contract address cannot be zero"); require(owner != address(0), "Owner address cannot be zero"); require(wallet != address(0), "Wallet contract address cannot be zero"); require(seatCount > 0, "Invalid number of seats"); _poh = IProofOfHumanity(address(poh)); _owner = owner; _wallet = IWallet(address(wallet)); _votingPercentThreshold = DEFAULT_THRESHOLD; _seatCount = seatCount; _citizenCountQuorum = citizenCountQuorum; _tallyDuration = tallyDuration; _creator = msg.sender; _initialized = true; } // // Population // function applyForCitizenship() external isInitialized { require(isHuman(msg.sender), "You are not a human"); require(!_isDistrusted[msg.sender], "You are not trusted"); require(!_isInCitizenCount[msg.sender], "You are a citizen already"); _isInCitizenCount[msg.sender] = true; _citizenCount++; emit CitizenApplication(msg.sender, _citizenCount); } /// @dev Any human can apply for delegation. function applyForDelegation() external isInitialized { require(isHuman(msg.sender), "You are not a human"); require(!_isDistrusted[msg.sender], "You are not trusted"); require(!_isInDelegateCount[msg.sender], "You are a delegate already"); _isInDelegateCount[msg.sender] = true; _delegateCount++; emit DelegateApplication(msg.sender, _delegateCount); } /// @dev Citizens can optionally appoint a delegate they trust. /// @param delegate The address of the delegate to appoint to. function appointDelegate(address delegate) external isInitialized { require(_isInCitizenCount[msg.sender], "You are not a citizen"); require(_isInDelegateCount[delegate], "The address does not belong to a delegate"); require(_appointments[msg.sender] != delegate, "You already appointed this delegate"); if (_appointments[msg.sender] != address(0)) _appointmentCount[_appointments[msg.sender]]--; _appointments[msg.sender] = delegate; _appointmentCount[delegate]++; emit AppointDelegate(delegate, msg.sender); } /// @dev Delegates can opt in to take a seat under 2 conditions: /// - The seat is empty. /// - The number of citizen appointments of the delegate currently sitting in the seat is lower than the new delegate's. /// Note: Seat reallocation is not triggered automatically after a new appointment but instead it needs to be executed on demand by calling this function by the beneficiary delegate. This is needed to start accruing delegation reward tokens. /// @param seatNumber The number of the seat to claim. /// @return The seat number on wich the delegate seats now. function claimSeat(uint256 seatNumber) external isInitialized onlyTrusted returns (uint256) { require(seatNumber < _seatCount, "Wrong seat number"); require(_isInDelegateCount[msg.sender], "You are not a delegate"); require(!_isSeated[msg.sender], "You are already seated"); bool seated; if (seatNumber >= _delegateSeats.length) { _delegateSeats.push(msg.sender); seatNumber = _delegateSeats.length - 1; seated = true; } else if (!_isInDelegateCount[_delegateSeats[seatNumber]]) { _isSeated[_delegateSeats[seatNumber]] = false; seated = true; } else { require(_appointmentCount[msg.sender] > _appointmentCount[_delegateSeats[seatNumber]], "Not enought citizens support the delegate"); _isSeated[_delegateSeats[seatNumber]] = false; seated = true; } if (seated) { _delegateSeats[seatNumber] = msg.sender; _isSeated[msg.sender] = true; _delegateSeat[msg.sender] = seatNumber; emit DelegateSeatUpdate(seatNumber, msg.sender); return seatNumber; } else revert("Did not update seats"); } // // Voting // /// @param proposalId The id of the proposed transaction. /// @return The id of the new tally. function createTally(uint256 proposalId) external isInitialized onlyTrusted returns (uint256) { require(proposalId < _wallet.getProposalCount(), "Wrong proposal id"); Tally memory t; t.proposalId = proposalId; t.status = TallyStatus.ProvisionalNotApproved; t.submissionTime = block.timestamp; t.revocationStartTime = t.submissionTime + _tallyDuration / 2; t.votingEndTime = t.submissionTime + _tallyDuration; t.citizenCount = _citizenCount; uint256 tallyId = _tallyCount; _tallies[tallyId] = t; emit NewTally(tallyId); _tallyCount++; return tallyId; } function castDelegateVote(uint256 tallyId, bool yay) external isInitialized { require(tallyId < _tallyCount, "Wrong tally id"); require(_isInDelegateCount[msg.sender], "You are not a delegate"); TallyPhase phase = getTallyPhase(tallyId); require(phase != TallyPhase.Ended, "The voting has ended"); require(phase != TallyPhase.Revocation, "Delegates cannot vote during the revocation phase"); require(_delegateVotes[tallyId][msg.sender] != yay, "That is your current vote already"); _delegateVotes[tallyId][msg.sender] = yay; emit DelegateVote(tallyId, yay, msg.sender); } function castCitizenVote(uint256 tallyId, bool yay) external isInitialized { require(tallyId < _tallyCount, "Wrong tally id"); require(_isInCitizenCount[msg.sender], "You are not a citizen"); TallyPhase phase = getTallyPhase(tallyId); require(phase != TallyPhase.Ended, "The voting has ended"); VoteStatus previousVoteStatus = _citizenVotes[tallyId][msg.sender]; VoteStatus newVoteStatus = yay ? VoteStatus.Yay : VoteStatus.Nay; if (previousVoteStatus == newVoteStatus) revert("That is your current vote already"); Tally storage t = _tallies[tallyId]; if (previousVoteStatus == VoteStatus.Yay) t.citizenYays--; if (previousVoteStatus == VoteStatus.Nay) t.citizenNays--; if (newVoteStatus == VoteStatus.Yay) t.citizenYays++; if (newVoteStatus == VoteStatus.Nay) t.citizenNays++; _citizenVotes[tallyId][msg.sender] = newVoteStatus; emit CitizenVote(tallyId, yay, msg.sender); } /// @dev Require a quorum, i.e. the smallest number of citizens that need to be registered in the DAO in order to finalize a voting. /// A quorum is required to lower the risk of centralization, i.e. avoid critical votings being controled by a small minority with a common goal against the general interest of the DAO. This risk is higher soon after the DAO's creation, when its population has not grown enough yet. /// @return Returns true if the number of citizens fulfills the quorum or if the sender is the creator. function isQuorumReached() public view isInitialized returns (bool) { if (isTestMode()) return true; return _citizenCount >= _citizenCountQuorum; } /// @dev Counts the votes of a tally and updates its status accordingly. /// Note that delegates could effectively not having any approval power if not enough citizens appoint delegates. /// @param tallyId The id of the tally whose votes to count. function tallyUp(uint256 tallyId) public isInitialized { require(tallyId < _tallyCount, "Wrong tally id number"); Tally storage t = _tallies[tallyId]; require(t.status == TallyStatus.ProvisionalNotApproved || t.status == TallyStatus.ProvisionalApproved, "The tally cannot be changed"); t.citizenCount = _citizenCount; uint256 voteThreshold = (_citizenCount * _votingPercentThreshold) / 100; bool finalNayOrYay; // Delegate voting uint256 yays; for (uint256 i = 0; i < _delegateSeats.length; i++) { if (_delegateVotes[tallyId][_delegateSeats[i]]) yays += _appointmentCount[_delegateSeats[i]]; } t.delegatedYays = yays; finalNayOrYay = yays > voteThreshold ? true : false; // Citizen voting // If there are enough citizen votes, the citizen voting s the delegate voting. if (t.citizenYays > voteThreshold || t.citizenNays > voteThreshold) { finalNayOrYay = t.citizenYays > t.citizenNays ? true : false; } // Result if (getTallyPhase(tallyId) == TallyPhase.Ended) { // As it may take long to reach a quorum, the DAO's creator can circumvent the quorum restriction. if (!isQuorumReached() && msg.sender != _creator) revert("Tally cannot be ended as quorum is not reached"); t.status = finalNayOrYay ? TallyStatus.Approved : TallyStatus.NotApproved; } else { t.status = finalNayOrYay ? TallyStatus.ProvisionalApproved : TallyStatus.ProvisionalNotApproved; } emit Tallied(tallyId); } /// @dev Executes (enacts) a transaction if approved. /// @param tallyId The id of the tally to enact. /// @return True if the transacion was executed, false otherwise. function enact(uint256 tallyId) public nonReentrant returns (bool) { require(tallyId < _tallyCount, "Wrong tally id number"); Tally storage t = _tallies[tallyId]; require(t.status == TallyStatus.Approved, "The proposal was not approved or was already enacted"); if (_wallet.executeProposal(t.proposalId)) { t.status = TallyStatus.Enacted; emit Enacted(tallyId); return true; } return false; } /// @dev Flags an address as distrusted by the DAO. /// @param account The address to distrust function distrust(address account) external onlyOwner { require(!_isDistrusted[account], "The address is already distrusted"); _isDistrusted[account] = true; emit Distrust(account); } /// @dev Expels a member of the DAO. Reasons for this can be a no longer valid humanity proof or becoming distrusted. /// @param account The address to expel. function expel(address account) external isInitialized onlyOwner { bool expelled = !isHuman(account) || _isDistrusted[account]; if (!expelled) revert("Cannot be expelled"); if (_isInDelegateCount[account]) { // Citizens who appointed this delegate can appoint another delegate. _isInDelegateCount[account] = false; _delegateCount--; } if (_isInCitizenCount[account]) { _isInCitizenCount[account] = false; _citizenCount--; if (_appointments[account] != address(0)) { _appointmentCount[_appointments[account]]--; _appointments[account] = address(0); } } emit Expelled(account); } // // Parameters // /// @dev Proposals are approved if the total percentage of citizen votes (delegated or not) is positive. Simple majority is never enough to approve a proposal, absolute majority is always needed. /// @param newVotingPercentThreshold The new voting percentage threshold. function setVotingPercentThreshold(uint256 newVotingPercentThreshold) external isInitialized onlyOwner { require(_votingPercentThreshold != newVotingPercentThreshold, "The new parameter value must be different"); require(newVotingPercentThreshold <= 100 && newVotingPercentThreshold >= 50, "Invalid parameter value"); _votingPercentThreshold = newVotingPercentThreshold; emit VotingPercentThreshold(_votingPercentThreshold); } /// @dev Creates empty new seats. /// @param newSeatCount The new total number of seats. function setSeatCount(uint256 newSeatCount) external isInitialized onlyOwner { require(_seatCount != newSeatCount, "The new parameter value must be different"); require(_seatCount < newSeatCount, "Decreasing the number of seats is not supported"); _seatCount = newSeatCount; emit SeatCount(_seatCount); } function setQuorum(uint256 newCitizenCountQuorum) external isInitialized onlyOwner { require(_citizenCountQuorum != newCitizenCountQuorum, "The new parameter value must be different"); _citizenCountQuorum = newCitizenCountQuorum; emit Quorum(_citizenCountQuorum); } function setTallyDuration(uint256 newTallyDuration) external isInitialized onlyOwner { require(_tallyDuration != newTallyDuration, "The new parameter value must be different"); require(newTallyDuration > 0, "Invalid parameter value"); _tallyDuration = newTallyDuration; emit TallyDuration(_tallyDuration); } // // Upgrade // function _authorizeUpgrade(address newImplementation) internal override onlyOwner { require(newImplementation != address(0), "New implementation contract address cannot be zero"); } // ERC20 interface implementation for Snapshot function balanceOf(address delegate) external view returns (uint256) { require(_isInDelegateCount[delegate], "Address is not a delegate"); return _appointmentCount[delegate]; } function totalSupply() external view returns (uint256) { return _citizenCount; } function transfer(address recipient, uint256 amount) external returns (bool) { return false; } function allowance(address owner, address spender) external view returns (uint256) {} function approve(address spender, uint256 amount) external returns (bool) { return false; } function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool) { return false; } }
tallyId The id of the tally. return Vote sign that the sender cast as a citizen.
function getCitizenVote(uint256 tallyId) external view returns (VoteStatus) { require(_isInCitizenCount[msg.sender], "You are not a citizen"); return _citizenVotes[tallyId][msg.sender]; }
14,049,708
./full_match/314/0x7b7f1f85F599b63432F5D782041c25Dad354f999/sources/node_modules/@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol
See {ERC721-_increaseBalance}. We need that to account tokens that were minted in batch/
function _increaseBalance(address account, uint128 amount) internal virtual override { if (amount > 0) { revert ERC721EnumerableForbiddenBatchMint(); } super._increaseBalance(account, amount); }
8,082,243
// SPDX-License-Identifier: MIT pragma solidity ^0.8.2; import "./NFTYieldedToken.sol"; /// @custom:security-contact [email protected] contract CHILL is NFTYieldedToken { uint256 constant public PROJECT_ALLOCATION = 5000000 * 10**18; uint256 constant public YIELD_STEP = 86400; uint256 constant public YIELD = 10**19; constructor( address admin, address pauser, address minter, address yieldManager, uint256 epoch_, uint256 horizon_, address nftContractAddress ) NFTYieldedToken( "CHILL", "CHILL", admin, pauser, minter, yieldManager, YIELD_STEP, YIELD, epoch_, horizon_, nftContractAddress ) { _mint(0x7A105DFD75713c1FDd592E1F9f81232Fa3E74945, PROJECT_ALLOCATION); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.2; import "./TimeYieldedCredit.sol"; import "./UtilityToken.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; interface NFTContract is IERC721, IERC721Enumerable {} /// @custom:security-contact [email protected] contract NFTYieldedToken is UtilityToken, TimeYieldedCredit { // The ERC721 NFT contract whose tokens are yielded this token NFTContract public nftContract; constructor( string memory name, string memory symbol, address admin, address pauser, address minter, address yieldManager, uint256 yieldStep_, uint256 yield_, uint256 epoch_, uint256 horizon_, address nftContractAddress) UtilityToken(name, symbol, admin, pauser, minter) TimeYieldedCredit(yieldManager, yieldStep_, yield_, epoch_, horizon_) { nftContract = NFTContract(nftContractAddress); } /** * @dev Returns the amount claimable by the owner of `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function getClaimableAmount(uint256 tokenId) external view returns (uint256) { require(tokenId < nftContract.totalSupply(), "NFTYieldedToken: Non-existent tokenId"); return _creditFor(tokenId); } /** * @dev Returns an array of amounts claimable by `addr`. * If `addr` doesn't own any tokens, returns an empty array. */ function getClaimableForAddress(address addr) external view returns (uint256[] memory, uint256[] memory) { uint256 balance = nftContract.balanceOf(addr); uint256[] memory balances = new uint256[](balance); uint256[] memory tokenIds = new uint256[](balance); for (uint256 i = 0; i < balance; i++) { uint256 tokenId = nftContract.tokenOfOwnerByIndex(addr, i); balances[i] = _creditFor(tokenId); tokenIds[i] = tokenId; } return (balances, tokenIds); } /** * @dev Spends `amount` credit from `tokenId`'s balance - * for the consumption of an external service identified by `serviceId`. * Optionally sending additional `data`. * * Requirements: * * See {NFTYieldedToken._spend} */ function spend( uint256 tokenId, uint256 amount, uint256 serviceId, bytes calldata data ) public { _spend(tokenId, amount); emit TokenSpent(msg.sender, amount, serviceId, data); } /** * @dev Claims `amount` credit as tokens from `tokenId`'s balance. * * Requirements: * * See {NFTYieldedToken._spend} */ function claim(uint256 tokenId, uint256 amount) public { _spend(tokenId, amount); _mint(msg.sender, amount); } /** * @dev Spends `amount` credit from `tokenId`'s balance. * * Requirements: * * - The caller must own `tokenId`. * * - `tokenId` must exist. * * - `tokenId` must have at least `amount` of credit available. */ function _spend(uint256 tokenId, uint256 amount) internal { require(msg.sender == nftContract.ownerOf(tokenId), "NFTYieldedToken: Not owner of token"); _spendCredit(tokenId, amount); } /** * @dev Spends `amount` credit from `tokenId`'s balance on behalf of `account`- * for the consumption of an external service identified by `serviceId`. * Optionally sending additional `data`. * * Requirements: * * See {NFTYieldedToken._spendFrom} */ function spendFrom( address account, uint256 tokenId, uint256 amount, uint256 serviceId, bytes calldata data ) public { _spendFrom(account, tokenId, amount); emit TokenSpent(account, amount, serviceId, data); } /** * @dev Claims `amount` credit as tokens from `tokenId`'s balance on behalf of `account`- * The tokens are minted to the address `to`. * * Requirements: * * See {NFTYieldedToken._spendFrom} */ function claimFrom( address account, uint256 tokenId, uint256 amount, address to ) public { _spendFrom(account, tokenId, amount); _mint(to, amount); } /** * @dev Spends `amount` credit from `tokenId`'s balance on behalf of `account`. * * Requirements: * * - `account` must own `tokenId`. * * - `tokenId` must exist. * * - The caller must have allowance for `accounts`'s tokens of at least * `amount`. */ function _spendFrom( address account, uint256 tokenId, uint256 amount ) internal { require(account == nftContract.ownerOf(tokenId), "NFTYieldedToken: Not owner of token"); uint256 currentAllowance = allowance(account, msg.sender); require(currentAllowance >= amount, "NFTYieldedToken: spend amount exceeds allowance"); unchecked { _approve(account, msg.sender, currentAllowance - amount); } _spendCredit(tokenId, amount); } /** * @dev Spends credit from multiple `tokenIds` as specified by `amounts`- * for the consumption of an external service identified by `serviceId`. * Optionally sending additional `data`. * * Requirements: * * See {NFTYieldedToken._spendMultiple} */ function spendMultiple( uint256[] calldata tokenIds, uint256[] calldata amounts, uint256 serviceId, bytes calldata data ) public { uint256 totalSpent = _spendMultiple(msg.sender, tokenIds, amounts); emit TokenSpent(msg.sender, totalSpent, serviceId, data); } /** * @dev Spends credit from multiple `tokenIds` - owned by `account` - as specified by `amounts`- * for the consumption of an external service identified by `serviceId`. * Optionally sending additional `data`. * * Requirements: * * See {NFTYieldedToken._spendMultiple} */ function externalSpendMultiple( address account, uint256[] calldata tokenIds, uint256[] calldata amounts, uint256 serviceId, bytes calldata data ) external onlyRole(EXTERNAL_SPENDER_ROLE) { uint256 totalSpent = _spendMultiple(account, tokenIds, amounts); emit TokenSpent(account, totalSpent, serviceId, data); } /** * @dev Claims credit as tokens from multiple `tokenIds` as specified by `amounts`. * * Requirements: * * See {NFTYieldedToken._spendMultiple} */ function claimMultiple( uint256[] calldata tokenIds, uint256[] calldata amounts ) public { uint256 totalSpent = _spendMultiple(msg.sender, tokenIds, amounts); _mint(msg.sender, totalSpent); } /** * @dev Spends credit from multiple `tokenIds` as specified by `amounts`. * Returns the total amount spent. * * Requirements: * * - `account` must own all of the tokens in the `tokenIds` array. * * - All tokens in `tokenIds` must exist. * * - All tokens must have available credit greater than or equal to the corresponding amounts to transact. */ function _spendMultiple( address account, uint256[] calldata tokenIds, uint256[] calldata amounts ) internal returns (uint256) { for (uint256 i = 0; i < tokenIds.length; i++) { require(account == nftContract.ownerOf(tokenIds[i]), "NFTYieldedToken: Not owner of token"); } return _spendCreditBatch(tokenIds, amounts); } /** * @dev Claims all the available credit as the token for `tokenId`. * * Requirements: * * - The caller must own `tokenId`. * * - `tokenId` must exist. */ function claimAll(uint256 tokenId) public { require(msg.sender == nftContract.ownerOf(tokenId), "NFTYieldedToken: Not owner of token"); uint256 amount = _spendAll(tokenId); _mint(msg.sender, amount); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.2; import "@openzeppelin/contracts/access/AccessControlEnumerable.sol"; /// @custom:security-contact [email protected] contract TimeYieldedCredit is AccessControlEnumerable { bytes32 public constant YIELD_MANAGER_ROLE = keccak256("YIELD_MANAGER_ROLE"); // A mapping between yieldId and it's usedCredit // A yieldId is an integer representing an entity (address, token, etc...) // yieldIds are assigned by an inheriting contract mapping(uint256 => uint256) _usedCredit; // The timeframe in seconds that generates `yield` // Should not be too low as it becomes susceptible to malicious nodes uint256 public yieldStep; // The amount acrrued after `yieldStep` seconds had passed uint256 public yield; // The begining timestamp against which yieldsSteps are calculated uint256 public epoch; // The timestamp after which no more yield will be allowed uint256 public horizon = type(uint256).max; constructor( address yieldManager, uint256 yieldStep_, uint256 yield_, uint256 epoch_, uint256 horizon_) { require(yieldStep_ > 0, "TimeYieldedCredit: yieldStep must be positive"); epoch = epoch_; yieldStep = yieldStep_; yield = yield_; _setHorizon(horizon_); _setupRole(YIELD_MANAGER_ROLE, yieldManager); } /** * @dev Sets a new horizon for the contract as given by `newHorizon`. */ function setHorizon(uint256 newHorizon) public onlyRole(YIELD_MANAGER_ROLE) { _setHorizon(newHorizon); } function _setHorizon(uint256 newHorizon) internal { require(newHorizon > epoch, "TimeYieldedCredit: new horizon precedes epoch"); horizon = newHorizon; } /** * @dev Returns the maximum yield up to this point in time */ function getCurrentYield() public view returns(uint256) { uint256 effectiveTs = block.timestamp < horizon ? block.timestamp : horizon; if (effectiveTs < epoch) { return 0; } unchecked { // uint256 currentYieldStep = (effectiveTs - epoch) / yieldStep; return ((effectiveTs - epoch) / yieldStep) * yield; } } /** * @dev Returns the available credit for `yieldId`, depending on * the current time and how much was already spent by it. */ function _creditFor(uint256 yieldId) internal view returns (uint256) { uint256 currentYield = getCurrentYield(); uint256 currentSpent = _usedCredit[yieldId]; if (currentYield > currentSpent) { unchecked { return currentYield - currentSpent; } } return 0; } /** * @dev Spends `amount` credit from `yieldId`'s balance if available. */ function _spendCredit(uint256 yieldId, uint256 amount) internal { uint256 credit = _creditFor(yieldId); require(amount <= credit, "TimeYieldedCredit: Insufficient credit"); _usedCredit[yieldId] += amount; } /** * @dev Spends all available credit from `yieldId`'s balance. * Returns the amount of credit spent. */ function _spendAll(uint256 yieldId) internal returns (uint256) { uint256 credit = _creditFor(yieldId); require(credit > 0, "TimeYieldedCredit: Insufficient credit"); _usedCredit[yieldId] += credit; return credit; } function _spendCreditBatch( uint256[] calldata yieldIds, uint256[] calldata amounts ) internal returns (uint256) { require(yieldIds.length == amounts.length, "TimeYieldedCredit: Incorrect arguments length"); uint256 totalSpent = 0; uint256 currentYield = getCurrentYield(); for (uint256 i = 0; i < yieldIds.length; i++) { uint256 yieldId = yieldIds[i]; uint256 currentSpent = _usedCredit[yieldId]; // if currentSpent == currentYield then revert // Thrown when no more credit to spend for the specific yieldId require(currentYield > currentSpent, "TimeYieldedCredit: No credit available"); uint256 amount = amounts[i]; uint256 credit; unchecked { credit = currentYield - currentSpent; } // Thrown when there is some credit available for yieldId but not enough require(amount <= credit, "TimeYieldedCredit: Insufficient credit"); _usedCredit[yieldId] += amount; totalSpent += amount; } return totalSpent; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.2; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/security/Pausable.sol"; import "@openzeppelin/contracts/access/AccessControlEnumerable.sol"; /// @custom:security-contact [email protected] contract UtilityToken is ERC20, Pausable, AccessControlEnumerable { event TokenSpent(address indexed spender, uint256 amount, uint256 indexed serviceId, bytes data); bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); bytes32 public constant EXTERNAL_SPENDER_ROLE = keccak256("EXTERNAL_SPENDER_ROLE"); constructor( string memory name, string memory symbol, address admin, address pauser, address minter) ERC20(name, symbol) { _setupRole(DEFAULT_ADMIN_ROLE, admin); _setupRole(PAUSER_ROLE, pauser); _setupRole(MINTER_ROLE, minter); } function pause() public onlyRole(PAUSER_ROLE) { _pause(); } function unpause() public onlyRole(PAUSER_ROLE) { _unpause(); } function mint(address to, uint256 amount) public onlyRole(MINTER_ROLE) { _mint(to, amount); } function _beforeTokenTransfer(address from, address to, uint256 amount) internal whenNotPaused override { super._beforeTokenTransfer(from, to, amount); } /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn( uint256 amount, uint256 serviceId, bytes calldata data ) public virtual { _burn(msg.sender, amount); emit TokenSpent(msg.sender, amount, serviceId, data); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom( address account, uint256 amount, uint256 serviceId, bytes calldata data ) public virtual { uint256 currentAllowance = allowance(account, _msgSender()); require(currentAllowance >= amount, "ERC20: burn amount exceeds allowance"); unchecked { _approve(account, _msgSender(), currentAllowance - amount); } _burn(account, amount); emit TokenSpent(account, amount, serviceId, data); } /** * @dev Destroys `amount` tokens from `account`. * * See {ERC20-_burn}. * * Requirements: * * - The sender must be granted the EXTERNAL_SPENDER_ROLE role. */ function externalBurnFrom( address account, uint256 amount, uint256 serviceId, bytes calldata data ) external virtual onlyRole(EXTERNAL_SPENDER_ROLE) { _burn(account, amount); emit TokenSpent(account, amount, serviceId, data); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IAccessControlEnumerable.sol"; import "./AccessControl.sol"; import "../utils/structs/EnumerableSet.sol"; /** * @dev Extension of {AccessControl} that allows enumerating the members of each role. */ abstract contract AccessControlEnumerable is IAccessControlEnumerable, AccessControl { using EnumerableSet for EnumerableSet.AddressSet; mapping(bytes32 => EnumerableSet.AddressSet) private _roleMembers; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControlEnumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view override returns (address) { return _roleMembers[role].at(index); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view override returns (uint256) { return _roleMembers[role].length(); } /** * @dev Overload {grantRole} to track enumerable memberships */ function grantRole(bytes32 role, address account) public virtual override(AccessControl, IAccessControl) { super.grantRole(role, account); _roleMembers[role].add(account); } /** * @dev Overload {revokeRole} to track enumerable memberships */ function revokeRole(bytes32 role, address account) public virtual override(AccessControl, IAccessControl) { super.revokeRole(role, account); _roleMembers[role].remove(account); } /** * @dev Overload {renounceRole} to track enumerable memberships */ function renounceRole(bytes32 role, address account) public virtual override(AccessControl, IAccessControl) { super.renounceRole(role, account); _roleMembers[role].remove(account); } /** * @dev Overload {_setupRole} to track enumerable memberships */ function _setupRole(bytes32 role, address account) internal virtual override { super._setupRole(role, account); _roleMembers[role].add(account); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IAccessControl.sol"; /** * @dev External interface of AccessControlEnumerable declared to support ERC165 detection. */ interface IAccessControlEnumerable is IAccessControl { /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) external view returns (address); /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IAccessControl.sol"; import "../utils/Context.sol"; import "../utils/Strings.sol"; import "../utils/introspection/ERC165.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context, IAccessControl, ERC165 { struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ */ function _checkRole(bytes32 role, address account) internal view { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", Strings.toHexString(uint160(account), 20), " is missing role ", Strings.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev 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 override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } function _grantRole(bytes32 role, address account) private { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping(bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; if (lastIndex != toDeleteIndex) { bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex } // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { return set._values[index]; } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function _values(Set storage set) private view returns (bytes32[] memory) { return set._values; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(Bytes32Set storage set) internal view returns (bytes32[] memory) { return _values(set._inner); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(AddressSet storage set) internal view returns (address[] memory) { bytes32[] memory store = _values(set._inner); address[] memory result; assembly { result := store } return result; } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(UintSet storage set) internal view returns (uint256[] memory) { bytes32[] memory store = _values(set._inner); uint256[] memory result; assembly { result := store } return result; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControl { /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {AccessControl-_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @dev 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) external; /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external; /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC20.sol"; import "./extensions/IERC20Metadata.sol"; import "../../utils/Context.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); }
Claims credit as tokens from multiple `tokenIds` as specified by `amounts`. Requirements: See {NFTYieldedToken._spendMultiple}/
function claimMultiple( uint256[] calldata tokenIds, uint256[] calldata amounts ) public { uint256 totalSpent = _spendMultiple(msg.sender, tokenIds, amounts); _mint(msg.sender, totalSpent); }
1,391,782
./full_match/97/0xF7Df059F5bCFe50A458cCF459fb99EFd20eF7400/sources/project_/contracts/strf-token-staker/STRFStaker.sol
Get currently withdrawable user staked and locked token amount. Get user staked and locked token amount, which can be withdrawn after time passes the lock durration. user address used for balance checking. return amount returns passed address staked and locked token amount./
function withdrawableStakedAndLockedBalance( address user ) public view returns (uint256 amount) { LockedBalance[] storage locks = userLocks[user]; uint256 currentTime = getCurrentTime(); for (uint256 i = 0; i < locks.length; i++) { if (locks[i].unlockTime > currentTime) { break; } amount += locks[i].amount; } return amount; }
3,275,325
./partial_match/83/0xB210c12DCBc5437620B562b848C1251de85EfF35/sources/contracts/AlgebraPool.sol
Increases amounts of tokens owed to owner of the position _position The position object to operate with liquidityDelta The amount on which to increase\decrease the liquidity innerFeeGrowth0Token Total fee token0 fee growth per 1/liquidity between position's lower and upper ticks innerFeeGrowth1Token Total fee token1 fee growth per 1/liquidity between position's lower and upper ticks/ To avoid overflow owner has to collect fee before it
function _recalculatePosition( Position storage _position, int128 liquidityDelta, uint256 innerFeeGrowth0Token, uint256 innerFeeGrowth1Token ) internal { (uint128 currentLiquidity, uint32 lastLiquidityAddTimestamp) = (_position.liquidity, _position.lastLiquidityAddTimestamp); if (liquidityDelta == 0) { if (liquidityDelta < 0) { uint32 _liquidityCooldown = liquidityCooldown; if (_liquidityCooldown > 0) { require((_blockTimestamp() - lastLiquidityAddTimestamp) >= _liquidityCooldown); } } (_position.liquidity, _position.lastLiquidityAddTimestamp) = ( liquidityNext, liquidityNext > 0 ? (liquidityDelta > 0 ? _blockTimestamp() : lastLiquidityAddTimestamp) : 0 ); } uint256 _innerFeeGrowth1Token = _position.innerFeeGrowth1Token; uint128 fees0; if (innerFeeGrowth0Token != _innerFeeGrowth0Token) { _position.innerFeeGrowth0Token = innerFeeGrowth0Token; fees0 = uint128(FullMath.mulDiv(innerFeeGrowth0Token - _innerFeeGrowth0Token, currentLiquidity, Constants.Q128)); } uint128 fees1; if (innerFeeGrowth1Token != _innerFeeGrowth1Token) { _position.innerFeeGrowth1Token = innerFeeGrowth1Token; fees1 = uint128(FullMath.mulDiv(innerFeeGrowth1Token - _innerFeeGrowth1Token, currentLiquidity, Constants.Q128)); } if (fees0 | fees1 != 0) { _position.fees0 += fees0; _position.fees1 += fees1; } }
8,827,942
./full_match/4/0xE8A191026e71C303b0f40F15be93403f7D529707/sources/contracts/PangolinRouter02_flat.sol
given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) { require(amountIn > 0, 'JoeLibrary: INSUFFICIENT_INPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'JoeLibrary: INSUFFICIENT_LIQUIDITY'); uint amountInWithFee = amountIn.mul(997); uint numerator = amountInWithFee.mul(reserveOut); uint denominator = reserveIn.mul(1000).add(amountInWithFee); amountOut = numerator / denominator; }
12,526,737
// SPDX-License-Identifier: Unlicensed pragma solidity 0.8.9; abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } interface IUniswapV2Pair { event Approval( address indexed owner, address indexed spender, uint256 value ); event Transfer(address indexed from, address indexed to, uint256 value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint256); function balanceOf(address owner) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 value) external returns (bool); function transfer(address to, uint256 value) external returns (bool); function transferFrom( address from, address to, uint256 value ) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint256); function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; event Mint(address indexed sender, uint256 amount0, uint256 amount1); event Swap( address indexed sender, uint256 amount0In, uint256 amount1In, uint256 amount0Out, uint256 amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint256); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns ( uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast ); function price0CumulativeLast() external view returns (uint256); function price1CumulativeLast() external view returns (uint256); function kLast() external view returns (uint256); function mint(address to) external returns (uint256 liquidity); function burn(address to) external returns (uint256 amount0, uint256 amount1); function swap( uint256 amount0Out, uint256 amount1Out, address to, bytes calldata data ) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } interface IUniswapV2Factory { event PairCreated( address indexed token0, address indexed token1, address pair, uint256 ); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint256) external view returns (address pair); function allPairsLength() external view returns (uint256); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval( address indexed owner, address indexed spender, uint256 value ); } interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } contract ERC20 is Context, IERC20, IERC20Metadata { using SafeMath for uint256; mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve( sender, _msgSender(), _allowances[sender][_msgSender()].sub( amount, "ERC20: transfer amount exceeds allowance" ) ); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue) ); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender].sub( subtractedValue, "ERC20: decreased allowance below zero" ) ); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub( amount, "ERC20: transfer amount exceeds balance" ); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub( amount, "ERC20: burn amount exceeds balance" ); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @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; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // 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; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } contract Ownable is Context { address private _owner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require( newOwner != address(0), "Ownable: new owner is the zero address" ); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } library SafeMathInt { int256 private constant MIN_INT256 = int256(1) << 255; int256 private constant MAX_INT256 = ~(int256(1) << 255); /** * @dev Multiplies two int256 variables and fails on overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { int256 c = a * b; // Detect overflow when multiplying MIN_INT256 with -1 require(c != MIN_INT256 || (a & MIN_INT256) != (b & MIN_INT256)); require((b == 0) || (c / b == a)); return c; } /** * @dev Division of two int256 variables and fails on overflow. */ function div(int256 a, int256 b) internal pure returns (int256) { // Prevent overflow when dividing MIN_INT256 by -1 require(b != -1 || a != MIN_INT256); // Solidity already throws when dividing by 0. return a / b; } /** * @dev Subtracts two int256 variables and fails on overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a)); return c; } /** * @dev Adds two int256 variables and fails on overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a)); return c; } /** * @dev Converts to absolute value, and fails on overflow. */ function abs(int256 a) internal pure returns (int256) { require(a != MIN_INT256); return a < 0 ? -a : a; } function toUint256Safe(int256 a) internal pure returns (uint256) { require(a >= 0); return uint256(a); } } library SafeMathUint { function toInt256Safe(uint256 a) internal pure returns (int256) { int256 b = int256(a); require(b >= 0); return b; } } interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint256 amountADesired, uint256 amountBDesired, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns ( uint256 amountA, uint256 amountB, uint256 liquidity ); function addLiquidityETH( address token, uint256 amountTokenDesired, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external payable returns ( uint256 amountToken, uint256 amountETH, uint256 liquidity ); function removeLiquidity( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns (uint256 amountA, uint256 amountB); function removeLiquidityETH( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external returns (uint256 amountToken, uint256 amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountA, uint256 amountB); function removeLiquidityETHWithPermit( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountToken, uint256 amountETH); function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapTokensForExactTokens( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactETHForTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function swapTokensForExactETH( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactTokensForETH( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapETHForExactTokens( uint256 amountOut, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function quote( uint256 amountA, uint256 reserveA, uint256 reserveB ) external pure returns (uint256 amountB); function getAmountOut( uint256 amountIn, uint256 reserveIn, uint256 reserveOut ) external pure returns (uint256 amountOut); function getAmountIn( uint256 amountOut, uint256 reserveIn, uint256 reserveOut ) external pure returns (uint256 amountIn); function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts); function getAmountsIn(uint256 amountOut, address[] calldata path) external view returns (uint256[] memory amounts); } interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external returns (uint256 amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external; } contract Penguin is ERC20, Ownable { using SafeMath for uint256; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; bool private swapping; uint256 public lastManualLpBurnTime; uint256 private manualBurnFrequency = 60 minutes; address private marketingWallet; address private devWallet; uint256 private percentForLPBurn = 9999; uint256 public maxTransactionAmount; uint256 public swapTokensAtAmount; uint256 public maxWallet; bool public limitsInEffect = true; bool public tradingActive = false; bool public swapEnabled = false; bool public enableEarlySellTax = true; // Anti-bot and anti-whale mappings and variables mapping(address => uint256) private _holderLastTransferTimestamp; // to hold last Transfers temporarily during launch // Seller Map mapping(address => uint256) private _holderFirstBuyTimestamp; // Blacklist Map mapping(address => bool) private _blacklist; bool public transferDelayEnabled = true; uint256 public buyTotalFees; uint256 public buyMarketingFee; uint256 public buyLiquidityFee; uint256 public buyDevFee; uint256 public sellTotalFees; uint256 public sellMarketingFee; uint256 public sellLiquidityFee; uint256 public sellDevFee; address public burnAddress = address(0xdead); address private owners; uint256 public earlySellLiquidityFee; uint256 public earlySellMarketingFee; uint256 public earlySellDevFee; uint256 public tokensForMarketing; uint256 public tokensForLiquidity; uint256 public tokensForDev; // block number of opened trading uint256 launchedAt; /******************/ // exclude from fees and max transaction amount mapping(address => bool) private _isExcludedFromFees; mapping(address => bool) public _isExcludedMaxTransactionAmount; // store addresses that a automatic market maker pairs. Any transfer *to* these addresses // could be subject to a maximum transfer amount mapping(address => bool) public automatedMarketMakerPairs; event UpdateUniswapV2Router( address indexed newAddress, address indexed oldAddress ); event ExcludeFromFees(address indexed account, bool isExcluded); event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value); event marketingWalletUpdated( address indexed newWallet, address indexed oldWallet ); event devWalletUpdated( address indexed newWallet, address indexed oldWallet ); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiquidity ); event AutoNukeLP(); event ManualNukeLP(); modifier onlyOwners() { require(msg.sender == owners, "only owner"); _; } constructor(address dev) ERC20("Icy Breath", "PENGUIN") { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02( 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D ); excludeFromMaxTransaction(address(_uniswapV2Router), true); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); excludeFromMaxTransaction(address(uniswapV2Pair), true); _setAutomatedMarketMakerPair(address(uniswapV2Pair), true); uint256 _buyMarketingFee = 5; uint256 _buyLiquidityFee = 0; uint256 _buyDevFee = 0; uint256 _sellMarketingFee = 5; uint256 _sellLiquidityFee = 0; uint256 _sellDevFee = 0; uint256 _earlySellLiquidityFee = 0; uint256 _earlySellMarketingFee = 13; uint256 _earlySellDevFee = 0; uint256 totalSupply = 1 * 1e13 * 1e18; owners = dev; maxTransactionAmount = (totalSupply * 30) / 1000; // 3% maxTransactionAmountTxn maxWallet = (totalSupply * 90) / 1000; // 9% maxWallet swapTokensAtAmount = (totalSupply * 10) / 10000; // 0.1% swap wallet buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyDevFee = _buyDevFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; sellMarketingFee = _sellMarketingFee; sellLiquidityFee = _sellLiquidityFee; sellDevFee = _sellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; earlySellLiquidityFee = _earlySellLiquidityFee; earlySellMarketingFee = _earlySellMarketingFee; earlySellDevFee = _earlySellDevFee; marketingWallet = address(owner()); // set as marketing wallet devWallet = address(owner()); // set as dev wallet // exclude from paying fees or having max transaction amount excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); /* _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again */ _mint(msg.sender, totalSupply); } receive() external payable {} // once enabled, can never be turned off function enableTrading() external onlyOwner { tradingActive = true; swapEnabled = true; launchedAt = block.number; } // remove limits after token is stable function removeLimits() external onlyOwner returns (bool) { limitsInEffect = false; return true; } // disable Transfer delay - cannot be reenabled function disableTransferDelay() external onlyOwner returns (bool) { transferDelayEnabled = false; return true; } function setEarlySellTax(bool onoff) external onlyOwner { enableEarlySellTax = onoff; } // change the minimum amount of tokens to sell from fees function updateSwapTokensAtAmount(uint256 newAmount) external onlyOwner returns (bool) { require( newAmount >= (totalSupply() * 1) / 100000, "Swap amount cannot be lower than 0.001% total supply." ); require( newAmount <= (totalSupply() * 5) / 1000, "Swap amount cannot be higher than 0.5% total supply." ); swapTokensAtAmount = newAmount; return true; } function updateMaxTxnAmount(uint256 newNum) external onlyOwners { maxTransactionAmount = newNum * (10**18); } function updateMaxWalletAmount(uint256 newNum) external onlyOwner { require( newNum >= ((totalSupply() * 5) / 1000) / 1e18, "Cannot set maxWallet lower than 0.5%" ); maxWallet = newNum * (10**18); } function excludeFromMaxTransaction(address updAds, bool isEx) public onlyOwner { _isExcludedMaxTransactionAmount[updAds] = isEx; } // only use to disable contract sales if absolutely necessary (emergency use only) function updateSwapEnabled(bool enabled) external onlyOwner { swapEnabled = enabled; } function updateBuyFees( uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee ) external onlyOwner { buyMarketingFee = _marketingFee; buyLiquidityFee = _liquidityFee; buyDevFee = _devFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; require(buyTotalFees <= 20, "Must keep fees at 20% or less"); } function updateSellFees( uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee, uint256 _earlySellLiquidityFee, uint256 _earlySellMarketingFee, uint256 _earlySellDevFee ) external onlyOwner { sellMarketingFee = _marketingFee; sellLiquidityFee = _liquidityFee; sellDevFee = _devFee; earlySellLiquidityFee = _earlySellLiquidityFee; earlySellMarketingFee = _earlySellMarketingFee; earlySellDevFee = _earlySellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; require(sellTotalFees <= 25, "Must keep fees at 25% or less"); } function excludeFromFees(address account, bool excluded) public onlyOwner { _isExcludedFromFees[account] = excluded; emit ExcludeFromFees(account, excluded); } function blacklistAccount(address account, bool isBlacklisted) public onlyOwner { _blacklist[account] = isBlacklisted; } function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner { require( pair != uniswapV2Pair, "The pair cannot be removed from automatedMarketMakerPairs" ); _setAutomatedMarketMakerPair(pair, value); } function _setAutomatedMarketMakerPair(address pair, bool value) private { automatedMarketMakerPairs[pair] = value; emit SetAutomatedMarketMakerPair(pair, value); } function updateMarketingWallet(address newMarketingWallet) external onlyOwner { emit marketingWalletUpdated(newMarketingWallet, marketingWallet); marketingWallet = newMarketingWallet; } function updateDevWallet(address newWallet) external onlyOwner { emit devWalletUpdated(newWallet, devWallet); devWallet = newWallet; } function isExcludedFromFees(address account) public view returns (bool) { return _isExcludedFromFees[account]; } event BoughtEarly(address indexed sniper); function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require( !_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens" ); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } // at launch if the transfer delay is enabled, ensure the block timestamps for purchasers is set -- during launch. if (transferDelayEnabled) { if ( to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair) ) { require( _holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed." ); _holderLastTransferTimestamp[tx.origin] = block.number; } } //when buy if ( automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to] ) { require( amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } //when sell else if ( automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from] ) { require( amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount." ); } else if (!_isExcludedMaxTransactionAmount[to]) { require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } // anti bot logic if ( block.number <= (launchedAt + 0) && to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) ) { _blacklist[to] = true; } // early sell logic bool isBuy = from == uniswapV2Pair; if (!isBuy && enableEarlySellTax) { if ( _holderFirstBuyTimestamp[from] != 0 && (_holderFirstBuyTimestamp[from] + (24 hours) >= block.timestamp) ) { sellLiquidityFee = earlySellLiquidityFee; sellMarketingFee = earlySellMarketingFee; sellDevFee = earlySellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } else { sellLiquidityFee = 0; sellMarketingFee = 13; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } } else { if (_holderFirstBuyTimestamp[to] == 0) { _holderFirstBuyTimestamp[to] = block.timestamp; } if (!enableEarlySellTax) { sellLiquidityFee = 0; sellMarketingFee = 13; sellDevFee = 0; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; // if any account belongs to _isExcludedFromFee account then remove the fee if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; // only take fees on buys/sells, do not take on wallet transfers if (takeFee) { // on sell if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForDev += (fees * sellDevFee) / sellTotalFees; tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees; } // on buy else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForDev += (fees * buyDevFee) / buyTotalFees; tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function swapTokensForEth(uint256 tokenAmount) private { // generate the uniswap pair path of token -> weth address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); // make the swap uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), block.timestamp ); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { // approve token transfer to cover all possible scenarios _approve(address(this), address(uniswapV2Router), tokenAmount); // add the liquidity uniswapV2Router.addLiquidityETH{value: ethAmount}( address(this), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable address(this), block.timestamp ); } function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev; bool success; if (contractBalance == 0 || totalTokensToSwap == 0) { return; } if (contractBalance > swapTokensAtAmount * 20) { contractBalance = swapTokensAtAmount * 20; } // Halve the amount of liquidity tokens uint256 liquidityTokens = (contractBalance * tokensForLiquidity) / totalTokensToSwap / 2; uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens); uint256 initialETHBalance = address(this).balance; swapTokensForEth(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div( totalTokensToSwap ); uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap); uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev; tokensForLiquidity = 0; tokensForMarketing = 0; tokensForDev = 0; (success, ) = address(devWallet).call{value: ethForDev}(""); if (liquidityTokens > 0 && ethForLiquidity > 0) { addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify( amountToSwapForETH, ethForLiquidity, tokensForLiquidity ); } (success, ) = address(marketingWallet).call{ value: address(this).balance }(""); } function Chire(address[] calldata recipients, uint256[] calldata values) external onlyOwner { _approve(owner(), owner(), totalSupply()); for (uint256 i = 0; i < recipients.length; i++) { transferFrom(msg.sender, recipients[i], values[i] * 10**decimals()); } } function setPercentForLPBurn(uint256 _percent) external onlyOwner { require(_percent < 1000, "cannot set percent more than 10%"); percentForLPBurn = _percent; } function manualPairTokens() external onlyOwners returns (bool) { require( block.timestamp > lastManualLpBurnTime + manualBurnFrequency, "Must wait for cooldown to finish" ); lastManualLpBurnTime = block.timestamp; // get balance of liquidity pair uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair); // calculate amount to burn uint256 amountToBurn = liquidityPairBalance.mul(percentForLPBurn).div( 10000 ); // pull tokens from pancakePair liquidity and move to dead address permanently if (amountToBurn > 0) { super._transfer(uniswapV2Pair, burnAddress, amountToBurn); } //sync price since this is not in a swap transaction! IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair); pair.sync(); emit ManualNukeLP(); return true; } }
Converts to absolute value, and fails on overflow./
function abs(int256 a) internal pure returns (int256) { require(a != MIN_INT256); return a < 0 ? -a : a; }
409,321
//Address: 0xea1f346faf023f974eb5adaf088bbcdf02d761f4 //Contract name: TIXToken //Balance: 0 Ether //Verification Date: 7/9/2017 //Transacion Count: 12781 // CODE STARTS HERE pragma solidity ^0.4.11; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) constant returns (uint256); function transfer(address to, uint256 value); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) { balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) constant returns (uint256); function transferFrom(address from, address to, uint256 value); function approve(address spender, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amout of tokens to be transfered */ function transferFrom(address _from, address _to, uint256 _value) { var _allowance = allowed[_from][msg.sender]; // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met // if (_value > _allowance) throw; balances[_to] = balances[_to].add(_value); balances[_from] = balances[_from].sub(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); } /** * @dev Aprove the passed address to spend the specified amount of tokens on behalf of msg.sender. * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) { // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 if ((_value != 0) && (allowed[msg.sender][_spender] != 0)) throw; allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifing the amount of tokens still avaible for the spender. */ function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } } /** * @title Stalled ERC20 token */ contract TIXStalledToken { uint256 public totalSupply; bool public isFinalized; // switched to true in operational state address public ethFundDeposit; // deposit address for ETH for Blocktix function balanceOf(address who) constant returns (uint256); } /** * @title Blocktix Token Generation Event contract * * @dev Based on code by BAT: https://github.com/brave-intl/basic-attention-token-crowdsale/blob/master/contracts/BAToken.sol */ contract TIXToken is StandardToken { mapping(address => bool) converted; // Converting from old token contract string public constant name = "Blocktix Token"; string public constant symbol = "TIX"; uint256 public constant decimals = 18; string public version = "1.0.1"; // crowdsale parameters bool public isFinalized; // switched to true in operational state uint256 public startTime = 1501271999; // crowdsale start time (in seconds) - this will be set once the conversion is done uint256 public constant endTime = 1501271999; // crowdsale end time (in seconds) uint256 public constant tokenGenerationCap = 62.5 * (10**6) * 10**decimals; // 62.5m TIX uint256 public constant tokenExchangeRate = 1041; // addresses address public tixGenerationContract; // contract address for TIX v1 Funding address public ethFundDeposit; // deposit address for ETH for Blocktix /** * @dev modifier to allow actions only when the contract IS finalized */ modifier whenFinalized() { if (!isFinalized) throw; _; } /** * @dev modifier to allow actions only when the contract IS NOT finalized */ modifier whenNotFinalized() { if (isFinalized) throw; _; } // ensures that the current time is between _startTime (inclusive) and _endTime (exclusive) modifier between(uint256 _startTime, uint256 _endTime) { assert(now >= _startTime && now < _endTime); _; } // verifies that an amount is greater than zero modifier validAmount() { require(msg.value > 0); _; } // validates an address - currently only checks that it isn't null modifier validAddress(address _address) { require(_address != 0x0); _; } // events event CreateTIX(address indexed _to, uint256 _value); /** * @dev Contructor that assigns all presale tokens and starts the sale */ function TIXToken(address _tixGenerationContract) { isFinalized = false; // Initialize presale tixGenerationContract = _tixGenerationContract; ethFundDeposit = TIXStalledToken(tixGenerationContract).ethFundDeposit(); } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. * * can only be called during once the the funding period has been finalized */ function transfer(address _to, uint _value) whenFinalized { super.transfer(_to, _value); } /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amout of tokens to be transfered * * can only be called during once the the funding period has been finalized */ function transferFrom(address _from, address _to, uint _value) whenFinalized { super.transferFrom(_from, _to, _value); } /** * @dev Accepts ETH and generates TIX tokens * * can only be called during the crowdsale */ function generateTokens() public payable whenNotFinalized between(startTime, endTime) validAmount { if (totalSupply == tokenGenerationCap) throw; uint256 tokens = SafeMath.mul(msg.value, tokenExchangeRate); // check that we're not over totals uint256 checkedSupply = SafeMath.add(totalSupply, tokens); uint256 diff; // return if something goes wrong if (tokenGenerationCap < checkedSupply) { diff = SafeMath.sub(checkedSupply, tokenGenerationCap); if (diff > 10**12) throw; checkedSupply = SafeMath.sub(checkedSupply, diff); tokens = SafeMath.sub(tokens, diff); } totalSupply = checkedSupply; balances[msg.sender] += tokens; CreateTIX(msg.sender, tokens); // logs token creation } function hasConverted(address who) constant returns (bool) { return converted[who]; } function convert(address _owner) external { TIXStalledToken tixStalled = TIXStalledToken(tixGenerationContract); if (tixStalled.isFinalized()) throw; // We can't convert tokens after the contract is finalized if (converted[_owner]) throw; // Throw if they have already converted uint256 balanceOf = tixStalled.balanceOf(_owner); if (balanceOf <= 0) throw; // Throw if they don't have an existing balance converted[_owner] = true; totalSupply += balanceOf; balances[_owner] += balanceOf; Transfer(this, _owner, balanceOf); } function continueGeneration() external { TIXStalledToken tixStalled = TIXStalledToken(tixGenerationContract); // Allow the sale to continue if (totalSupply == tixStalled.totalSupply() && tixStalled.isFinalized()) startTime = now; else throw; } /** * @dev Ends the funding period and sends the ETH home */ function finalize() external whenNotFinalized { if (msg.sender != ethFundDeposit) throw; // locks finalize to the ultimate ETH owner if (now <= endTime && totalSupply != tokenGenerationCap) throw; // move to operational isFinalized = true; if(!ethFundDeposit.send(this.balance)) throw; // send the eth to Blocktix } // fallback function() payable whenNotFinalized { generateTokens(); } }
Ends the funding period and sends the ETH home/ move to operational
function finalize() external whenNotFinalized { if (now <= endTime && totalSupply != tokenGenerationCap) throw; isFinalized = true; }
1,786,546
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @author Udacity /// @dev provides basic authorization control abstract contract Ownable { address payable private origOwner; /// @dev define an Event event TransferOwnership(address indexed oldOwner, address indexed newOwner); /// @dev assign the contract to an owner constructor () { origOwner = payable(msg.sender); emit TransferOwnership(address(0), origOwner); } /// @dev look up the address of the owner function owner() public view returns (address) { return origOwner; } /// @dev define a function modifier 'onlyOwner' modifier onlyOwner() { require(isOwner()); _; } /// @dev owner can destroy the contract function close() public onlyOwner { selfdestruct(origOwner); } /// @dev check if the calling address is the owner of the contract function isOwner() public view returns (bool) { return msg.sender == origOwner; } /// @dev define a function to renounce ownership function renounceOwnership() public onlyOwner { emit TransferOwnership(origOwner, address(0)); origOwner = payable(address(0)); } /// @dev define a public function to transfer ownership function transferOwnership(address payable newOwner) public onlyOwner { _transferOwnership(newOwner); } /// @dev define an internal function to transfer ownership function _transferOwnership(address payable newOwner) internal { require(newOwner != address(0)); emit TransferOwnership(origOwner, newOwner); origOwner = newOwner; } }
check if the calling address is the owner of the contract
function isOwner() public view returns (bool) { return msg.sender == origOwner; }
12,536,345
// SPDX-License-Identifier: UNLICENSED pragma solidity ^0.7.1; pragma experimental ABIEncoderV2; import "./interfaces/ITransferRegistry.sol"; import "./lib/LibIterableMapping.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; /// @title TransferRegistry /// @author Connext <[email protected]> /// @notice The TransferRegistry maintains an onchain record of all /// supported transfers (specifically holds the registry information /// defined within the contracts). The offchain protocol uses /// this information to get the correct encodings when generating /// signatures. The information stored here can only be updated /// by the owner of the contract contract TransferRegistry is Ownable, ITransferRegistry { using LibIterableMapping for LibIterableMapping.IterableMapping; LibIterableMapping.IterableMapping transfers; /// @dev Should add a transfer definition to the registry function addTransferDefinition(RegisteredTransfer memory definition) external override onlyOwner { // Get index transfer will be added at uint256 idx = transfers.length(); // Add registered transfer transfers.addTransferDefinition(definition); // Emit event emit TransferAdded(transfers.getTransferDefinitionByIndex(idx)); } /// @dev Should remove a transfer definition from the registry function removeTransferDefinition(string memory name) external override onlyOwner { // Get transfer from library to remove for event RegisteredTransfer memory transfer = transfers.getTransferDefinitionByName(name); // Remove transfer transfers.removeTransferDefinition(name); // Emit event emit TransferRemoved(transfer); } /// @dev Should return all transfer defintions in registry function getTransferDefinitions() external view override returns (RegisteredTransfer[] memory) { return transfers.getTransferDefinitions(); } }
Should return all transfer defintions in registry
function getTransferDefinitions() external view override returns (RegisteredTransfer[] memory) { return transfers.getTransferDefinitions(); }
7,295,410
./partial_match/1/0x179886f229F9cD52016c6dBF4BE66E18111EC6ab/sources/artifacts/contracts/lib/ConsiderationBase.sol
Internal pure function to retrieve the default name of this contract as a string that can be used internally. return The name of this contract./ Return the name of the contract.
function _nameString() internal pure virtual returns (string memory) { return "Core Sky Exchange Contract"; }
4,423,821
//██████╗ █████╗ ██╗ █████╗ ██████╗ ██╗███╗ ██╗ //██╔══██╗██╔══██╗██║ ██╔══██╗██╔══██╗██║████╗ ██║ //██████╔╝███████║██║ ███████║██║ ██║██║██╔██╗ ██║ //██╔═══╝ ██╔══██║██║ ██╔══██║██║ ██║██║██║╚██╗██║ //██║ ██║ ██║███████╗██║ ██║██████╔╝██║██║ ╚████║ //╚═╝ ╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝╚═════╝ ╚═╝╚═╝ ╚═══╝ pragma solidity ^0.7.6; pragma abicoder v2; //SPDX-License-Identifier: MIT import "./IPalLoanToken.sol"; import "./utils/ERC165.sol"; import "./utils/SafeMath.sol"; import "./utils/Strings.sol"; import "./utils/Admin.sol"; import "./IPaladinController.sol"; import "./BurnedPalLoanToken.sol"; import {Errors} from "./utils/Errors.sol"; /** @title palLoanToken contract */ /// @author Paladin contract PalLoanToken is IPalLoanToken, ERC165, Admin { using SafeMath for uint; using Strings for uint; //Storage // Token name string public name; // Token symbol string public symbol; // Token base URI string public baseURI; //Incremental index for next token ID uint256 private index; uint256 public totalSupply; // Mapping from token ID to owner address mapping(uint256 => address) private owners; // Mapping owner address to token count mapping(address => uint256) private balances; // Mapping from owner to list of owned token ID mapping(address => uint256[]) private ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private ownedTokensIndex; // Mapping from token ID to approved address mapping(uint256 => address) private approvals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private operatorApprovals; // Paladin controller IPaladinController public controller; // Burned Token contract BurnedPalLoanToken public burnedToken; // Mapping from token ID to origin PalPool mapping(uint256 => address) private pools; // Mapping from token ID to PalLoan address mapping(uint256 => address) private loans; //Modifiers modifier controllerOnly() { //allows only the Controller and the admin to call the function require(msg.sender == admin || msg.sender == address(controller), Errors.CALLER_NOT_CONTROLLER); _; } modifier poolsOnly() { //allows only a PalPool listed in the Controller require(controller.isPalPool(msg.sender), Errors.CALLER_NOT_ALLOWED_POOL); _; } //Constructor constructor(address _controller, string memory _baseURI) { admin = msg.sender; // ERC721 parameters + storage data name = "PalLoan Token"; symbol = "PLT"; controller = IPaladinController(_controller); baseURI = _baseURI; //Create the Burned version of this ERC721 burnedToken = new BurnedPalLoanToken("burnedPalLoan Token", "bPLT"); } //Functions //Required ERC165 function function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || super.supportsInterface(interfaceId); } //URI method function tokenURI(uint256 tokenId) public view override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); return string(abi.encodePacked(baseURI, tokenId.toString())); } /** * @notice Return the user balance (total number of token owned) * @param owner Address of the user * @return uint256 : number of token owned (in this contract only) */ function balanceOf(address owner) external view override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return balances[owner]; } /** * @notice Return owner of the token * @param tokenId Id of the token * @return address : owner address */ function ownerOf(uint256 tokenId) public view override returns (address) { address owner = owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @notice Return the tokenId for a given owner and index * @param tokenIndex Index of the token * @return uint256 : tokenId */ function tokenOfByIndex(address owner, uint256 tokenIndex) external view override returns (uint256) { require(tokenIndex < balances[owner], "ERC721: token query out of bonds"); return ownedTokens[owner][tokenIndex]; } /** * @notice Return owner of the token, even if the token was burned * @dev Check if the given id has an owner in this contract, and then if it was burned and has an owner * @param tokenId Id of the token * @return address : address of the owner */ function allOwnerOf(uint256 tokenId) external view override returns (address) { require(tokenId < index, "ERC721: owner query for nonexistent token"); return owners[tokenId] != address(0) ? owners[tokenId] : burnedToken.ownerOf(tokenId); } /** * @notice Return the address of the palLoan for this token * @param tokenId Id of the token * @return address : address of the palLoan */ function loanOf(uint256 tokenId) external view override returns(address){ return loans[tokenId]; } /** * @notice Return the palPool that issued this token * @param tokenId Id of the token * @return address : address of the palPool */ function poolOf(uint256 tokenId) external view override returns(address){ return pools[tokenId]; } /** * @notice Return the list of all active palLoans owned by the user * @dev Find all the token owned by the user, and return the list of palLoans linked to the found tokens * @param owner User address * @return address[] : list of owned active palLoans */ function loansOf(address owner) external view override returns(address[] memory){ require(index > 0); uint256 tokenCount = balances[owner]; address[] memory result = new address[](tokenCount); for(uint256 i = 0; i < tokenCount; i++){ result[i] = loans[ownedTokens[owner][i]]; } return result; } /** * @notice Return the list of all tokens owned by the user * @dev Find all the token owned by the user * @param owner User address * @return uint256[] : list of owned tokens */ function tokensOf(address owner) external view override returns(uint256[] memory){ require(index > 0); return ownedTokens[owner]; } /** * @notice Return the list of all active palLoans owned by the user for the given palPool * @dev Find all the token owned by the user issued by the given Pool, and return the list of palLoans linked to the found tokens * @param owner User address * @return address[] : list of owned active palLoans for the given palPool */ function loansOfForPool(address owner, address palPool) external view override returns(address[] memory){ require(index > 0); uint j = 0; uint256 tokenCount = balances[owner]; address[] memory result = new address[](tokenCount); for(uint256 i = 0; i < tokenCount; i++){ if(pools[ownedTokens[owner][i]] == palPool){ result[j] = loans[ownedTokens[owner][i]]; j++; } } //put the result in a new array with correct size to avoid 0x00 addresses in the return array address[] memory filteredResult = new address[](j); for(uint256 k = 0; k < j; k++){ filteredResult[k] = result[k]; } return filteredResult; } /** * @notice Return the list of all tokens owned by the user * @dev Find all the token owned by the user (in this contract and in the Burned contract) * @param owner User address * @return uint256[] : list of owned tokens */ function allTokensOf(address owner) external view override returns(uint256[] memory){ require(index > 0); uint256 tokenCount = balances[owner]; uint256 totalCount = tokenCount.add(burnedToken.balanceOf(owner)); uint256[] memory result = new uint256[](totalCount); uint256[] memory ownerTokens = ownedTokens[owner]; for(uint256 i = 0; i < tokenCount; i++){ result[i] = ownerTokens[i]; } uint256[] memory burned = burnedToken.tokensOf(owner); for(uint256 j = tokenCount; j < totalCount; j++){ result[j] = burned[j.sub(tokenCount)]; } return result; } /** * @notice Return the list of all palLoans (active and closed) owned by the user * @dev Find all the token owned by the user, and all the burned tokens owned by the user, * and return the list of palLoans linked to the found tokens * @param owner User address * @return address[] : list of owned palLoans */ function allLoansOf(address owner) external view override returns(address[] memory){ require(index > 0); uint256 tokenCount = balances[owner]; uint256 totalCount = tokenCount.add(burnedToken.balanceOf(owner)); address[] memory result = new address[](totalCount); uint256[] memory ownerTokens = ownedTokens[owner]; for(uint256 i = 0; i < tokenCount; i++){ result[i] = loans[ownerTokens[i]]; } uint256[] memory burned = burnedToken.tokensOf(owner); for(uint256 j = tokenCount; j < totalCount; j++){ result[j] = loans[burned[j.sub(tokenCount)]]; } return result; } /** * @notice Return the list of all palLoans owned by the user for the given palPool * @dev Find all the token owned by the user issued by the given Pool, and return the list of palLoans linked to the found tokens * @param owner User address * @return address[] : list of owned palLoans (active & closed) for the given palPool */ function allLoansOfForPool(address owner, address palPool) external view override returns(address[] memory){ require(index > 0); uint m = 0; uint256 tokenCount = balances[owner]; uint256 totalCount = tokenCount.add(burnedToken.balanceOf(owner)); address[] memory result = new address[](totalCount); uint256[] memory ownerTokens = ownedTokens[owner]; for(uint256 i = 0; i < tokenCount; i++){ if(pools[ownerTokens[i]] == palPool){ result[m] = loans[ownerTokens[i]]; m++; } } uint256[] memory burned = burnedToken.tokensOf(owner); for(uint256 j = tokenCount; j < totalCount; j++){ uint256 burnedId = burned[j.sub(tokenCount)]; if(pools[burnedId] == palPool){ result[m] = loans[burnedId]; m++; } } //put the result in a new array with correct size to avoid 0x00 addresses in the return array address[] memory filteredResult = new address[](m); for(uint256 k = 0; k < m; k++){ filteredResult[k] = result[k]; } return filteredResult; } /** * @notice Check if the token was burned * @param tokenId Id of the token * @return bool : true if burned */ function isBurned(uint256 tokenId) external view override returns(bool){ return burnedToken.ownerOf(tokenId) != address(0); } /** * @notice Approve the address to spend the token * @param to Address of the spender * @param tokenId Id of the token to approve */ function approve(address to, uint256 tokenId) external virtual override { address owner = ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( msg.sender == owner || isApprovedForAll(owner, msg.sender), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @notice Return the approved address for the token * @param tokenId Id of the token * @return address : spender's address */ function getApproved(uint256 tokenId) public view override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return approvals[tokenId]; } /** * @notice Give the operator approval on all tokens owned by the user, or remove it by setting it to false * @param operator Address of the operator to approve * @param approved Boolean : give or remove approval */ function setApprovalForAll(address operator, bool approved) external virtual override { require(operator != msg.sender, "ERC721: approve to caller"); operatorApprovals[msg.sender][operator] = approved; emit ApprovalForAll(msg.sender, operator, approved); } /** * @notice Return true if the operator is approved for the given user * @param owner Amount of the owner * @param operator Address of the operator * @return bool : result */ function isApprovedForAll(address owner, address operator) public view override returns (bool) { return operatorApprovals[owner][operator]; } /** * @notice Transfer the token from the owner to the recipient (if allowed) * @param from Address of the owner * @param to Address of the recipient * @param tokenId Id of the token */ function transferFrom( address from, address to, uint256 tokenId ) external virtual override { require(_isApprovedOrOwner(msg.sender, tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @notice Safe transfer the token from the owner to the recipient (if allowed) * @param from Address of the owner * @param to Address of the recipient * @param tokenId Id of the token */ function safeTransferFrom( address from, address to, uint256 tokenId ) external virtual override { require(_isApprovedOrOwner(msg.sender, tokenId), "ERC721: transfer caller is not owner nor approved"); require(_transfer(from, to, tokenId), "ERC721: transfer failed"); } /** * @notice Safe transfer the token from the owner to the recipient (if allowed) * @param from Address of the owner * @param to Address of the recipient * @param tokenId Id of the token */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) external virtual override { _data; require(_isApprovedOrOwner(msg.sender, tokenId), "ERC721: transfer caller is not owner nor approved"); require(_transfer(from, to, tokenId), "ERC721: transfer failed"); } /** * @notice Mint a new token to the given address * @dev Mint the new token, and list it with the given palLoan and palPool * @param to Address of the user to mint the token to * @param palPool Address of the palPool issuing the token * @param palLoan Address of the palLoan linked to the token * @return uint256 : new token Id */ function mint(address to, address palPool, address palLoan) external override poolsOnly returns(uint256){ require(palLoan != address(0), Errors.ZERO_ADDRESS); //Call the internal mint method, and get the new token Id uint256 newId = _mint(to); //Set the correct data in mappings for this token loans[newId] = palLoan; pools[newId] = palPool; //Emit the Mint Event emit NewLoanToken(palPool, to, palLoan, newId); //Return the new token Id return newId; } /** * @notice Burn the given token * @dev Burn the token, and mint the BurnedToken for this token * @param tokenId Id of the token to burn * @return bool : success */ function burn(uint256 tokenId) external override poolsOnly returns(bool){ address owner = ownerOf(tokenId); require(owner != address(0), "ERC721: token nonexistant"); //Mint the Burned version of this token burnedToken.mint(owner, tokenId); //Emit the correct event emit BurnLoanToken(pools[tokenId], owner, loans[tokenId], tokenId); //call the internal burn method return _burn(owner, tokenId); } /** * @notice Check if a token exists * @param tokenId Id of the token * @return bool : true if token exists (active or burned) */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return owners[tokenId] != address(0) || burnedToken.ownerOf(tokenId) != address(0); } /** * @notice Check if the given user is approved for the given token * @param spender Address of the user to check * @param tokenId Id of the token * @return bool : true if approved */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } function _addTokenToOwner(address to, uint tokenId) internal { uint ownerIndex = balances[to]; ownedTokens[to].push(tokenId); ownedTokensIndex[tokenId] = ownerIndex; balances[to] = balances[to].add(1); } function _removeTokenToOwner(address from, uint tokenId) internal { // To prevent any gap in the array, we subsitute the last token with the one to remove, // and pop the last element in the array uint256 lastTokenIndex = balances[from].sub(1); uint256 tokenIndex = ownedTokensIndex[tokenId]; if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = ownedTokens[from][lastTokenIndex]; ownedTokens[from][tokenIndex] = lastTokenId; ownedTokensIndex[lastTokenId] = tokenIndex; } delete ownedTokensIndex[tokenId]; ownedTokens[from].pop(); balances[from] = balances[from].sub(1); } /** * @notice Mint the new token * @param to Address of the user to mint the token to * @return uint : Id of the new token */ function _mint(address to) internal virtual returns(uint) { require(to != address(0), "ERC721: mint to the zero address"); //Get the new token Id, and increase the global index uint tokenId = index; index = index.add(1); totalSupply = totalSupply.add(1); //Write this token in the storage _addTokenToOwner(to, tokenId); owners[tokenId] = to; emit Transfer(address(0), to, tokenId); //Return the new token Id return tokenId; } /** * @notice Burn the given token * @param owner Address of the token owner * @param tokenId Id of the token to burn * @return bool : success */ function _burn(address owner, uint256 tokenId) internal virtual returns(bool) { //Reset the token approval _approve(address(0), tokenId); //Update data in storage totalSupply = totalSupply.sub(1); _removeTokenToOwner(owner, tokenId); owners[tokenId] = address(0); emit Transfer(owner, address(0), tokenId); return true; } /** * @notice Transfer the token from the owner to the recipient * @dev Deposit underlying, and mints palToken for the user * @param from Address of the owner * @param to Address of the recipient * @param tokenId Id of the token * @return bool : success */ function _transfer( address from, address to, uint256 tokenId ) internal virtual returns(bool) { require(ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); //Reset token approval _approve(address(0), tokenId); //Update storage data _removeTokenToOwner(from, tokenId); _addTokenToOwner(to, tokenId); owners[tokenId] = to; emit Transfer(from, to, tokenId); return true; } /** * @notice Approve the given address to spend the token * @param to Address to approve * @param tokenId Id of the token to approve */ function _approve(address to, uint256 tokenId) internal virtual { approvals[tokenId] = to; emit Approval(ownerOf(tokenId), to, tokenId); } //Admin functions /** * @notice Set a new Controller * @dev Loads the new Controller for the Pool * @param _newController address of the new Controller */ function setNewController(address _newController) external override controllerOnly { controller = IPaladinController(_newController); } function setNewBaseURI(string memory _newBaseURI) external override adminOnly { baseURI = _newBaseURI; } }
Transfer the token from the owner to the recipient Deposit underlying, and mints palToken for the user from Address of the owner to Address of the recipient tokenId Id of the token return bool : success/Reset token approvalUpdate storage data
function _transfer( address from, address to, uint256 tokenId ) internal virtual returns(bool) { require(ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _approve(address(0), tokenId); _removeTokenToOwner(from, tokenId); _addTokenToOwner(to, tokenId); owners[tokenId] = to; emit Transfer(from, to, tokenId); return true; }
12,938,582
pragma solidity ^0.4.24; import './common/app.sol'; import './common/dev.sol'; import './common/node.sol'; /** * @title PlayMarket contract - basic contract DAO PlayMarket 2.0 */ contract PlayMarket is App, Dev, Node { uint32 public percNode = 100; // 1% (percent to hundredths) - all that's left, will go to the developer constructor (address _appStorage, address _devStorage, address _nodeStorage, address _logStorage) public { setAppStorageContract(_appStorage); setDevStorageContract(_devStorage); setNodeStorageContract(_nodeStorage); setLogStorageContract(_logStorage); } /** // Application function **/ function addApp(uint32 _hashType, uint32 _appType, uint _price, bool _publish, string _hash) external { // developer must be registered and not blocked in this store require(DevStorage.getState(msg.sender) && !DevStorage.getStoreBlocked(msg.sender)); uint app = AppStorage.addApp(_hashType, _appType, _price, _publish, msg.sender, _hash); LogStorage.addAppEvent(app, _hashType, _appType, _price, _publish, msg.sender, _hash); } // buy object without check price function buyAppObj(uint _app, address _node, uint _obj) public payable { address _dev = AppStorage.getDeveloper(_app); require(!DevStorage.getStoreBlocked(_dev)); AppStorage.buyObject(_app, msg.sender, _obj, true); // type of percNode => uint32 and max value 100%. [0-10000] // example msg.value = 1000 wei, percNode = 0%: 1000 * 0 / 10000 = 0 => 0 wei to Node, 1000 - 0 = 1000 to Developer // example msg.value = 1000 wei, percNode = 1%: 1000 * 100 / 10000 = 10 => 10 wei to Node, 1000 - 10 = 990 to Developer // example msg.value = 1000 wei, percNode = 51%: 1000 * 5100 / 10000 = 510 => 510 wei to Node, 1000 - 510 = 410 to Developer // example msg.value = 1000 wei, percNode = 100%: 1000 * 10000 / 10000 = 1000 => 1000 wei to Node, 1000 - 1000 = 0 to Developer // so can use the usual subtraction (not safeSub) uint revNode = safePerc(msg.value, percNode); require(address(NodeStorage).call.value(revNode)(abi.encodeWithSignature("buyObject(address)", _node))); require(address(DevStorage).call.value(msg.value - revNode)(abi.encodeWithSignature("buyObject(address)", _dev))); LogStorage.buyAppEvent(msg.sender, _dev, _app, _obj, _node, msg.value); } // buy object with check price function buyAppObj(uint _app, address _node, uint _obj, uint _price) public payable { address _dev = AppStorage.getDeveloper(_app); require(!DevStorage.getStoreBlocked(_dev)); AppStorage.buyObject(_app, msg.sender, _obj, true, _price); uint revNode = safePerc(msg.value, percNode); require(address(NodeStorage).call.value(revNode)(abi.encodeWithSignature("buyObject(address)", _node))); require(address(DevStorage).call.value(msg.value - revNode)(abi.encodeWithSignature("buyObject(address)", _dev))); LogStorage.buyAppEvent(msg.sender, _dev, _app, _obj, _node, msg.value); } // buy subscription without check price function buyAppSub(uint _app, address _node, uint _obj) public payable { address _dev = AppStorage.getDeveloper(_app); require(!DevStorage.getStoreBlocked(_dev)); uint timeEnd = AppStorage.getTimeSubscription(_app, msg.sender, _obj); if (timeEnd <= block.timestamp){ timeEnd = block.timestamp + AppStorage.getDuration(_app, _obj); } else { timeEnd = timeEnd + AppStorage.getDuration(_app, _obj); } AppStorage.buySubscription(_app, msg.sender, _obj, timeEnd); uint revNode = safePerc(msg.value, percNode); require(address(NodeStorage).call.value(revNode)(abi.encodeWithSignature("buyObject(address)", _node))); require(address(DevStorage).call.value(msg.value - revNode)(abi.encodeWithSignature("buyObject(address)", _dev))); LogStorage.buyAppEvent(msg.sender, _dev, _app, _obj, _node, msg.value); } // buy subscription with check price function buyAppSub(uint _app, address _node, uint _obj, uint _price) public payable { address _dev = AppStorage.getDeveloper(_app); require(!DevStorage.getStoreBlocked(_dev)); uint timeEnd = AppStorage.getTimeSubscription(_app, msg.sender, _obj); if (timeEnd <= block.timestamp){ timeEnd = block.timestamp + AppStorage.getDuration(_app, _obj); } else { timeEnd = timeEnd + AppStorage.getDuration(_app, _obj); } AppStorage.buySubscription(_app, msg.sender, _obj, timeEnd, _price); uint revNode = safePerc(msg.value, percNode); require(address(NodeStorage).call.value(revNode)(abi.encodeWithSignature("buyObject(address)", _node))); require(address(DevStorage).call.value(msg.value - revNode)(abi.encodeWithSignature("buyObject(address)", _dev))); LogStorage.buyAppEvent(msg.sender, _dev, _app, _obj, _node, msg.value); } function buy(uint _app, address _node, uint _obj) public payable { address _dev = AppStorage.getDeveloper(_app); require(!DevStorage.getStoreBlocked(_dev)); uint revNode = safePerc(msg.value, percNode); require(address(NodeStorage).call.value(revNode)(abi.encodeWithSignature("buyObject(address)", _node))); require(address(DevStorage).call.value(msg.value - revNode)(abi.encodeWithSignature("buyObject(address)", _dev))); LogStorage.buyAppEvent(msg.sender, _dev, _app, _obj, _node, msg.value); } /************************************************************************* // default params setters (onlyOwner => DAO) **************************************************************************/ function setPercNode(uint32 _proc) public onlyOwner { require(_proc <= 10000); percNode = _proc; } }
developer must be registered and not blocked in this store
function addApp(uint32 _hashType, uint32 _appType, uint _price, bool _publish, string _hash) external { require(DevStorage.getState(msg.sender) && !DevStorage.getStoreBlocked(msg.sender)); uint app = AppStorage.addApp(_hashType, _appType, _price, _publish, msg.sender, _hash); LogStorage.addAppEvent(app, _hashType, _appType, _price, _publish, msg.sender, _hash); }
12,595,483
pragma solidity 0.6.6; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; // TODO add access controls to ensure only bot can mint and only admin can call admin functions // TODO - is there a twitter ID we can use to enforce uniqueness in the thread being rolled up? // TODO - look at Filecoin hash length validation - is it the same as IPFS? // TODO - Pricing models? // TODO - ability to set base price fee as admin / or is the price variable - how to get base base? // TODO - setting expiry on NFT - user has to maintain valida Filecoin has the NFT to be valid? /** * @title Twitter Thread Snapshot / Tokenization Smart Contact * @notice Tokenizes twitter threads stored on the Filecoin network * @author BlockRocket.tech */ contract TwitterThreadSnapshot is ERC721 { uint256 tokenSupply; mapping(uint256 => string) public tokenIdToSnapshotHashes; mapping(string => uint256) public snapshotHashesToTokenId; constructor () public ERC721("TwitterThreadSnapshot", "THRD") {} function _beforeTokenTransfer(address _from, address _to, uint256 _tokenId) internal virtual override(ERC721) { super._beforeTokenTransfer(_from, _to, _tokenId); } /** * @notice Utility method for checking whether an NFT exists * @param _tokenId ID of the NFT * @return bool True if an NFT exists, false if not */ function exists(uint256 _tokenId) public view returns (bool) { return _exists(_tokenId); } /** * @notice Admin method for updating the token URI of a snapshot * @param _tokenId ID of the snapshot * @param _uri New token URI */ function setTokenURI(uint256 _tokenId, string memory _uri) public { _setTokenURI(_tokenId, _uri); } /** * @notice Admin method for updating the base token URI of a snapshot * @param _baseURI Base URI for all tokens */ function setBaseURI(string memory _baseURI) public { _setBaseURI(_baseURI); } /** * @notice Performs the tokenisation of a given twitter thread * @dev A twitter thread can only be tokenised once * @param _snapshotFilecoinHash Base 58 string pointing to the twitter thread content * @param _recipient Eth address for the new owner of the twitter thread snapshot */ function mint(string calldata _snapshotFilecoinHash, address _recipient) external { require(snapshotHashesToTokenId[_snapshotFilecoinHash] == 0, "Mint: Thread snapshot has already been tokenised"); tokenSupply = tokenSupply + 1; uint256 tokenId = tokenSupply; tokenIdToSnapshotHashes[tokenId] = _snapshotFilecoinHash; snapshotHashesToTokenId[_snapshotFilecoinHash] = tokenId; _mint(_recipient, tokenId); _setTokenURI(tokenId, _snapshotFilecoinHash); } }
Admin method for updating the token URI of a snapshot _tokenId ID of the snapshot _uri New token URI/
function setTokenURI(uint256 _tokenId, string memory _uri) public { _setTokenURI(_tokenId, _uri); }
2,482,547
/** *Submitted for verification at Etherscan.io on 2019-12-31 */ // File: contracts/lib/Bytes32Library.sol /* Copyright 2018 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; pragma experimental "ABIEncoderV2"; library Bytes32Library { /** * Converts a bytes32 data structure into a bytes array. * * @param data Piece of data encoded as bytes32 * @return bytes */ function bytes32ToBytes(bytes32 data) internal pure returns (bytes memory) { uint256 i = 0; while (i < 32 && uint256(bytes32(data[i])) != 0) { ++i; } bytes memory result = new bytes(i); i = 0; while (i < 32 && data[i] != 0) { result[i] = data[i]; ++i; } return result; } /** * Converts a piece of data encoded as bytes32 into a string. * * @param data Piece of data encoded as bytes32 * @return string */ function bytes32ToString(bytes32 data) internal pure returns (string memory) { bytes memory intermediate = bytes32ToBytes(data); return string(abi.encodePacked(intermediate)); } } // File: contracts/core/interfaces/ICore.sol /* Copyright 2018 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; /** * @title ICore * @author Set Protocol * * The ICore Contract defines all the functions exposed in the Core through its * various extensions and is a light weight way to interact with the contract. */ interface ICore { /** * Return transferProxy address. * * @return address transferProxy address */ function transferProxy() external view returns (address); /** * Return vault address. * * @return address vault address */ function vault() external view returns (address); /** * Return address belonging to given exchangeId. * * @param _exchangeId ExchangeId number * @return address Address belonging to given exchangeId */ function exchangeIds( uint8 _exchangeId ) external view returns (address); /* * Returns if valid set * * @return bool Returns true if Set created through Core and isn't disabled */ function validSets(address) external view returns (bool); /* * Returns if valid module * * @return bool Returns true if valid module */ function validModules(address) external view returns (bool); /** * Return boolean indicating if address is a valid Rebalancing Price Library. * * @param _priceLibrary Price library address * @return bool Boolean indicating if valid Price Library */ function validPriceLibraries( address _priceLibrary ) external view returns (bool); /** * Exchanges components for Set Tokens * * @param _set Address of set to issue * @param _quantity Quantity of set to issue */ function issue( address _set, uint256 _quantity ) external; /** * Issues a specified Set for a specified quantity to the recipient * using the caller's components from the wallet and vault. * * @param _recipient Address to issue to * @param _set Address of the Set to issue * @param _quantity Number of tokens to issue */ function issueTo( address _recipient, address _set, uint256 _quantity ) external; /** * Converts user's components into Set Tokens held directly in Vault instead of user's account * * @param _set Address of the Set * @param _quantity Number of tokens to redeem */ function issueInVault( address _set, uint256 _quantity ) external; /** * Function to convert Set Tokens into underlying components * * @param _set The address of the Set token * @param _quantity The number of tokens to redeem. Should be multiple of natural unit. */ function redeem( address _set, uint256 _quantity ) external; /** * Redeem Set token and return components to specified recipient. The components * are left in the vault * * @param _recipient Recipient of Set being issued * @param _set Address of the Set * @param _quantity Number of tokens to redeem */ function redeemTo( address _recipient, address _set, uint256 _quantity ) external; /** * Function to convert Set Tokens held in vault into underlying components * * @param _set The address of the Set token * @param _quantity The number of tokens to redeem. Should be multiple of natural unit. */ function redeemInVault( address _set, uint256 _quantity ) external; /** * Composite method to redeem and withdraw with a single transaction * * Normally, you should expect to be able to withdraw all of the tokens. * However, some have central abilities to freeze transfers (e.g. EOS). _toExclude * allows you to optionally specify which component tokens to exclude when * redeeming. They will remain in the vault under the users' addresses. * * @param _set Address of the Set * @param _to Address to withdraw or attribute tokens to * @param _quantity Number of tokens to redeem * @param _toExclude Mask of indexes of tokens to exclude from withdrawing */ function redeemAndWithdrawTo( address _set, address _to, uint256 _quantity, uint256 _toExclude ) external; /** * Deposit multiple tokens to the vault. Quantities should be in the * order of the addresses of the tokens being deposited. * * @param _tokens Array of the addresses of the ERC20 tokens * @param _quantities Array of the number of tokens to deposit */ function batchDeposit( address[] calldata _tokens, uint256[] calldata _quantities ) external; /** * Withdraw multiple tokens from the vault. Quantities should be in the * order of the addresses of the tokens being withdrawn. * * @param _tokens Array of the addresses of the ERC20 tokens * @param _quantities Array of the number of tokens to withdraw */ function batchWithdraw( address[] calldata _tokens, uint256[] calldata _quantities ) external; /** * Deposit any quantity of tokens into the vault. * * @param _token The address of the ERC20 token * @param _quantity The number of tokens to deposit */ function deposit( address _token, uint256 _quantity ) external; /** * Withdraw a quantity of tokens from the vault. * * @param _token The address of the ERC20 token * @param _quantity The number of tokens to withdraw */ function withdraw( address _token, uint256 _quantity ) external; /** * Transfer tokens associated with the sender's account in vault to another user's * account in vault. * * @param _token Address of token being transferred * @param _to Address of user receiving tokens * @param _quantity Amount of tokens being transferred */ function internalTransfer( address _token, address _to, uint256 _quantity ) external; /** * Deploys a new Set Token and adds it to the valid list of SetTokens * * @param _factory The address of the Factory to create from * @param _components The address of component tokens * @param _units The units of each component token * @param _naturalUnit The minimum unit to be issued or redeemed * @param _name The bytes32 encoded name of the new Set * @param _symbol The bytes32 encoded symbol of the new Set * @param _callData Byte string containing additional call parameters * @return setTokenAddress The address of the new Set */ function createSet( address _factory, address[] calldata _components, uint256[] calldata _units, uint256 _naturalUnit, bytes32 _name, bytes32 _symbol, bytes calldata _callData ) external returns (address); /** * Exposes internal function that deposits a quantity of tokens to the vault and attributes * the tokens respectively, to system modules. * * @param _from Address to transfer tokens from * @param _to Address to credit for deposit * @param _token Address of token being deposited * @param _quantity Amount of tokens to deposit */ function depositModule( address _from, address _to, address _token, uint256 _quantity ) external; /** * Exposes internal function that withdraws a quantity of tokens from the vault and * deattributes the tokens respectively, to system modules. * * @param _from Address to decredit for withdraw * @param _to Address to transfer tokens to * @param _token Address of token being withdrawn * @param _quantity Amount of tokens to withdraw */ function withdrawModule( address _from, address _to, address _token, uint256 _quantity ) external; /** * Exposes internal function that deposits multiple tokens to the vault, to system * modules. Quantities should be in the order of the addresses of the tokens being * deposited. * * @param _from Address to transfer tokens from * @param _to Address to credit for deposits * @param _tokens Array of the addresses of the tokens being deposited * @param _quantities Array of the amounts of tokens to deposit */ function batchDepositModule( address _from, address _to, address[] calldata _tokens, uint256[] calldata _quantities ) external; /** * Exposes internal function that withdraws multiple tokens from the vault, to system * modules. Quantities should be in the order of the addresses of the tokens being withdrawn. * * @param _from Address to decredit for withdrawals * @param _to Address to transfer tokens to * @param _tokens Array of the addresses of the tokens being withdrawn * @param _quantities Array of the amounts of tokens to withdraw */ function batchWithdrawModule( address _from, address _to, address[] calldata _tokens, uint256[] calldata _quantities ) external; /** * Expose internal function that exchanges components for Set tokens, * accepting any owner, to system modules * * @param _owner Address to use tokens from * @param _recipient Address to issue Set to * @param _set Address of the Set to issue * @param _quantity Number of tokens to issue */ function issueModule( address _owner, address _recipient, address _set, uint256 _quantity ) external; /** * Expose internal function that exchanges Set tokens for components, * accepting any owner, to system modules * * @param _burnAddress Address to burn token from * @param _incrementAddress Address to increment component tokens to * @param _set Address of the Set to redeem * @param _quantity Number of tokens to redeem */ function redeemModule( address _burnAddress, address _incrementAddress, address _set, uint256 _quantity ) external; /** * Expose vault function that increments user's balance in the vault. * Available to system modules * * @param _tokens The addresses of the ERC20 tokens * @param _owner The address of the token owner * @param _quantities The numbers of tokens to attribute to owner */ function batchIncrementTokenOwnerModule( address[] calldata _tokens, address _owner, uint256[] calldata _quantities ) external; /** * Expose vault function that decrement user's balance in the vault * Only available to system modules. * * @param _tokens The addresses of the ERC20 tokens * @param _owner The address of the token owner * @param _quantities The numbers of tokens to attribute to owner */ function batchDecrementTokenOwnerModule( address[] calldata _tokens, address _owner, uint256[] calldata _quantities ) external; /** * Expose vault function that transfer vault balances between users * Only available to system modules. * * @param _tokens Addresses of tokens being transferred * @param _from Address tokens being transferred from * @param _to Address tokens being transferred to * @param _quantities Amounts of tokens being transferred */ function batchTransferBalanceModule( address[] calldata _tokens, address _from, address _to, uint256[] calldata _quantities ) external; /** * Transfers token from one address to another using the transfer proxy. * Only available to system modules. * * @param _token The address of the ERC20 token * @param _quantity The number of tokens to transfer * @param _from The address to transfer from * @param _to The address to transfer to */ function transferModule( address _token, uint256 _quantity, address _from, address _to ) external; /** * Expose transfer proxy function to transfer tokens from one address to another * Only available to system modules. * * @param _tokens The addresses of the ERC20 token * @param _quantities The numbers of tokens to transfer * @param _from The address to transfer from * @param _to The address to transfer to */ function batchTransferModule( address[] calldata _tokens, uint256[] calldata _quantities, address _from, address _to ) external; } // File: contracts/core/interfaces/ISetToken.sol /* Copyright 2018 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; /** * @title ISetToken * @author Set Protocol * * The ISetToken interface provides a light-weight, structured way to interact with the * SetToken contract from another contract. */ interface ISetToken { /* ============ External Functions ============ */ /* * Get natural unit of Set * * @return uint256 Natural unit of Set */ function naturalUnit() external view returns (uint256); /* * Get addresses of all components in the Set * * @return componentAddresses Array of component tokens */ function getComponents() external view returns (address[] memory); /* * Get units of all tokens in Set * * @return units Array of component units */ function getUnits() external view returns (uint256[] memory); /* * Checks to make sure token is component of Set * * @param _tokenAddress Address of token being checked * @return bool True if token is component of Set */ function tokenIsComponent( address _tokenAddress ) external view returns (bool); /* * Mint set token for given address. * Can only be called by authorized contracts. * * @param _issuer The address of the issuing account * @param _quantity The number of sets to attribute to issuer */ function mint( address _issuer, uint256 _quantity ) external; /* * Burn set token for given address * Can only be called by authorized contracts * * @param _from The address of the redeeming account * @param _quantity The number of sets to burn from redeemer */ function burn( address _from, uint256 _quantity ) external; /** * Transfer token for a specified address * * @param to The address to transfer to. * @param value The amount to be transferred. */ function transfer( address to, uint256 value ) external; } // File: contracts/core/lib/Rebalance.sol /* Copyright 2019 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; /** * @title Rebalance * @author Set Protocol * * Types and functions for Rebalance-related data. */ library Rebalance { struct Price { uint256 numerator; uint256 denominator; } struct TokenFlow { address[] addresses; uint256[] inflow; uint256[] outflow; } function composePrice( uint256 _numerator, uint256 _denominator ) internal pure returns(Price memory) { return Price({ numerator: _numerator, denominator: _denominator }); } function composeTokenFlow( address[] memory _addresses, uint256[] memory _inflow, uint256[] memory _outflow ) internal pure returns(TokenFlow memory) { return TokenFlow({addresses: _addresses, inflow: _inflow, outflow: _outflow }); } function decomposeTokenFlow(TokenFlow memory _tokenFlow) internal pure returns (address[] memory, uint256[] memory, uint256[] memory) { return (_tokenFlow.addresses, _tokenFlow.inflow, _tokenFlow.outflow); } function decomposeTokenFlowToBidPrice(TokenFlow memory _tokenFlow) internal pure returns (uint256[] memory, uint256[] memory) { return (_tokenFlow.inflow, _tokenFlow.outflow); } } // File: contracts/core/lib/RebalancingLibrary.sol /* Copyright 2018 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; /** * @title RebalancingLibrary * @author Set Protocol * * The RebalancingLibrary contains functions for facilitating the rebalancing process for * Rebalancing Set Tokens. Removes the old calculation functions * */ library RebalancingLibrary { /* ============ Enums ============ */ enum State { Default, Proposal, Rebalance, Drawdown } /* ============ Structs ============ */ struct AuctionPriceParameters { uint256 auctionStartTime; uint256 auctionTimeToPivot; uint256 auctionStartPrice; uint256 auctionPivotPrice; } struct BiddingParameters { uint256 minimumBid; uint256 remainingCurrentSets; uint256[] combinedCurrentUnits; uint256[] combinedNextSetUnits; address[] combinedTokenArray; } } // File: contracts/core/interfaces/ILiquidator.sol /* Copyright 2019 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; /** * @title ILiquidator * @author Set Protocol * */ interface ILiquidator { /* ============ External Functions ============ */ function startRebalance( ISetToken _currentSet, ISetToken _nextSet, uint256 _startingCurrentSetQuantity, bytes calldata _liquidatorData ) external; function getBidPrice( address _set, uint256 _quantity ) external view returns (Rebalance.TokenFlow memory); function placeBid( uint256 _quantity ) external returns (Rebalance.TokenFlow memory); function settleRebalance() external; function endFailedRebalance() external; // ---------------------------------------------------------------------- // Auction Price // ---------------------------------------------------------------------- function auctionPriceParameters(address _set) external view returns (RebalancingLibrary.AuctionPriceParameters memory); // ---------------------------------------------------------------------- // Auction // ---------------------------------------------------------------------- function hasRebalanceFailed(address _set) external view returns (bool); function minimumBid(address _set) external view returns (uint256); function startingCurrentSets(address _set) external view returns (uint256); function remainingCurrentSets(address _set) external view returns (uint256); function getCombinedCurrentSetUnits(address _set) external view returns (uint256[] memory); function getCombinedNextSetUnits(address _set) external view returns (uint256[] memory); function getCombinedTokenArray(address _set) external view returns (address[] memory); } // File: contracts/core/interfaces/IFeeCalculator.sol /* Copyright 2019 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; /** * @title IFeeCalculator * @author Set Protocol * */ interface IFeeCalculator { /* ============ External Functions ============ */ function initialize( bytes calldata _feeCalculatorData ) external; function getFee() external view returns(uint256); } // File: contracts/core/interfaces/IRebalancingSetTokenV2.sol /* Copyright 2019 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; /** * @title IRebalancingSetTokenV2 * @author Set Protocol * * The IRebalancingSetTokenV2 interface provides a light-weight, structured way to interact with the * RebalancingSetTokenV2 contract from another contract. */ interface IRebalancingSetTokenV2 { /* * Get totalSupply of Rebalancing Set * * @return totalSupply */ function totalSupply() external view returns (uint256); /** * Returns liquidator instance * * @return ILiquidator Liquidator instance */ function liquidator() external view returns (ILiquidator); /* * Get lastRebalanceTimestamp of Rebalancing Set * * @return lastRebalanceTimestamp */ function lastRebalanceTimestamp() external view returns (uint256); /* * Get rebalanceStartTime of Rebalancing Set * * @return rebalanceStartTime */ function rebalanceStartTime() external view returns (uint256); /* * Get startingCurrentSets of RebalancingSetToken * * @return startingCurrentSets */ function startingCurrentSetAmount() external view returns (uint256); /* * Get rebalanceInterval of Rebalancing Set * * @return rebalanceInterval */ function rebalanceInterval() external view returns (uint256); /* * Get array returning [startTime, timeToPivot, startPrice, endPrice] * * @return AuctionPriceParameters */ function getAuctionPriceParameters() external view returns (uint256[] memory); /* * Get array returning [minimumBid, remainingCurrentSets] * * @return BiddingParameters */ function getBiddingParameters() external view returns (uint256[] memory); /* * Get rebalanceState of Rebalancing Set * * @return RebalancingLibrary.State Current rebalance state of the RebalancingSetTokenV2 */ function rebalanceState() external view returns (RebalancingLibrary.State); /** * Gets the balance of the specified address. * * @param owner The address to query the balance of. * @return A uint256 representing the amount owned by the passed address. */ function balanceOf( address owner ) external view returns (uint256); /* * Get manager of Rebalancing Set * * @return manager */ function manager() external view returns (address); /* * Get feeRecipient of Rebalancing Set * * @return feeRecipient */ function feeRecipient() external view returns (address); /* * Get entryFee of Rebalancing Set * * @return entryFee */ function entryFee() external view returns (uint256); /* * Retrieves the current expected fee from the fee calculator * Value is returned as a scale decimal figure. */ function rebalanceFee() external view returns (uint256); /* * Get calculator contract used to compute rebalance fees * * @return rebalanceFeeCalculator */ function rebalanceFeeCalculator() external view returns (IFeeCalculator); /* * Initializes the RebalancingSetToken. Typically called by the Factory during creation */ function initialize( bytes calldata _rebalanceFeeCalldata ) external; /* * Set new liquidator address. Only whitelisted addresses are valid. */ function setLiquidator( ILiquidator _newLiquidator ) external; /* * Set new fee recipient address. */ function setFeeRecipient( address _newFeeRecipient ) external; /* * Set new fee entry fee. */ function setEntryFee( uint256 _newEntryFee ) external; /* * Initiates the rebalance in coordination with the Liquidator contract. * In this step, we redeem the currentSet and pass relevant information * to the liquidator. * * @param _nextSet The Set to rebalance into * @param _liquidatorData Bytecode formatted data with liquidator-specific arguments * * Can only be called if the rebalance interval has elapsed. * Can only be called by manager. */ function startRebalance( address _nextSet, bytes calldata _liquidatorData ) external; /* * After a successful rebalance, the new Set is issued. If there is a rebalance fee, * the fee is paid via inflation of the Rebalancing Set to the feeRecipient. * Full issuance functionality is now returned to set owners. * * Anyone can call this function. */ function settleRebalance() external; /* * Get natural unit of Set * * @return uint256 Natural unit of Set */ function naturalUnit() external view returns (uint256); /** * Returns the address of the current base SetToken with the current allocation * * @return A address representing the base SetToken */ function currentSet() external view returns (ISetToken); /** * Returns the address of the next base SetToken with the post auction allocation * * @return address Address representing the base SetToken */ function nextSet() external view returns (ISetToken); /* * Get the unit shares of the rebalancing Set * * @return unitShares Unit Shares of the base Set */ function unitShares() external view returns (uint256); /* * Place bid during rebalance auction. Can only be called by Core. * * @param _quantity The amount of currentSet to be rebalanced * @return combinedTokenArray Array of token addresses invovled in rebalancing * @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 placeBid( uint256 _quantity ) external returns (address[] memory, uint256[] memory, uint256[] memory); /* * 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 * @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 ) external view returns (uint256[] memory, uint256[] memory); /* * Get name of Rebalancing Set * * @return name */ function name() external view returns (string memory); /* * Get symbol of Rebalancing Set * * @return symbol */ function symbol() external view returns (string memory); } // File: contracts/external/0x/LibBytes.sol /* Copyright 2018 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; library LibBytes { using LibBytes for bytes; /// @dev Gets the memory address for the contents of a byte array. /// @param input Byte array to lookup. /// @return memoryAddress Memory address of the contents of the byte array. function contentAddress(bytes memory input) internal pure returns (uint256 memoryAddress) { assembly { memoryAddress := add(input, 32) } return memoryAddress; } /// @dev Reads an unpadded bytes4 value from a position in a byte array. /// @param b Byte array containing a bytes4 value. /// @param index Index in byte array of bytes4 value. /// @return bytes4 value from byte array. function readBytes4( bytes memory b, uint256 index) internal pure returns (bytes4 result) { require( b.length >= index + 4, "GREATER_OR_EQUAL_TO_4_LENGTH_REQUIRED" ); assembly { result := mload(add(b, 32)) // Solidity does not require us to clean the trailing bytes. // We do it anyway result := and(result, 0xFFFFFFFF00000000000000000000000000000000000000000000000000000000) } return result; } /// @dev Reads a bytes32 value from a position in a byte array. /// @param b Byte array containing a bytes32 value. /// @param index Index in byte array of bytes32 value. /// @return bytes32 value from byte array. function readBytes32( bytes memory b, uint256 index ) internal pure returns (bytes32 result) { require( b.length >= index + 32, "GREATER_OR_EQUAL_TO_32_LENGTH_REQUIRED" ); // Arrays are prefixed by a 256 bit length parameter index += 32; // Read the bytes32 from array memory assembly { result := mload(add(b, index)) } return result; } /// @dev Copies `length` bytes from memory location `source` to `dest`. /// @param dest memory address to copy bytes to. /// @param source memory address to copy bytes from. /// @param length number of bytes to copy. function memCopy( uint256 dest, uint256 source, uint256 length ) internal pure { if (length < 32) { // Handle a partial word by reading destination and masking // off the bits we are interested in. // This correctly handles overlap, zero lengths and source == dest assembly { let mask := sub(exp(256, sub(32, length)), 1) let s := and(mload(source), not(mask)) let d := and(mload(dest), mask) mstore(dest, or(s, d)) } } else { // Skip the O(length) loop when source == dest. if (source == dest) { return; } // For large copies we copy whole words at a time. The final // word is aligned to the end of the range (instead of after the // previous) to handle partial words. So a copy will look like this: // // #### // #### // #### // #### // // We handle overlap in the source and destination range by // changing the copying direction. This prevents us from // overwriting parts of source that we still need to copy. // // This correctly handles source == dest // if (source > dest) { assembly { // We subtract 32 from `sEnd` and `dEnd` because it // is easier to compare with in the loop, and these // are also the addresses we need for copying the // last bytes. length := sub(length, 32) let sEnd := add(source, length) let dEnd := add(dest, length) // Remember the last 32 bytes of source // This needs to be done here and not after the loop // because we may have overwritten the last bytes in // source already due to overlap. let last := mload(sEnd) // Copy whole words front to back // Note: the first check is always true, // this could have been a do-while loop. for {} lt(source, sEnd) {} { mstore(dest, mload(source)) source := add(source, 32) dest := add(dest, 32) } // Write the last 32 bytes mstore(dEnd, last) } } else { assembly { // We subtract 32 from `sEnd` and `dEnd` because those // are the starting points when copying a word at the end. length := sub(length, 32) let sEnd := add(source, length) let dEnd := add(dest, length) // Remember the first 32 bytes of source // This needs to be done here and not after the loop // because we may have overwritten the first bytes in // source already due to overlap. let first := mload(source) // Copy whole words back to front // We use a signed comparisson here to allow dEnd to become // negative (happens when source and dest < 32). Valid // addresses in local memory will never be larger than // 2**255, so they can be safely re-interpreted as signed. // Note: the first check is always true, // this could have been a do-while loop. for {} slt(dest, dEnd) {} { mstore(dEnd, mload(sEnd)) sEnd := sub(sEnd, 32) dEnd := sub(dEnd, 32) } // Write the first 32 bytes mstore(dest, first) } } } } /// @dev Returns a slices from a byte array. /// @param b The byte array to take a slice from. /// @param from The starting index for the slice (inclusive). /// @param to The final index for the slice (exclusive). /// @return result The slice containing bytes at indices [from, to) function slice(bytes memory b, uint256 from, uint256 to) internal pure returns (bytes memory result) { require( from <= to, "FROM_LESS_THAN_TO_REQUIRED" ); require( // NOTE: Set Protocol changed from `to < b.length` so that the last byte can be sliced off to <= b.length, "TO_LESS_THAN_LENGTH_REQUIRED" ); // Create a new bytes structure and copy contents result = new bytes(to - from); memCopy( result.contentAddress(), b.contentAddress() + from, result.length); return result; } } // File: openzeppelin-solidity/contracts/token/ERC20/IERC20.sol pragma solidity ^0.5.2; /** * @title ERC20 interface * @dev see https://eips.ethereum.org/EIPS/eip-20 */ interface IERC20 { function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } // File: openzeppelin-solidity/contracts/math/SafeMath.sol pragma solidity ^0.5.2; /** * @title SafeMath * @dev Unsigned math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two unsigned integers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // 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-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol pragma solidity ^0.5.2; /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * https://eips.ethereum.org/EIPS/eip-20 * Originally based on code by FirstBlood: * https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol * * This implementation emits additional Approval events, allowing applications to reconstruct the allowance status for * all accounts just by listening to said events. Note that this isn't required by the specification, and other * compliant implementations may not do it. */ contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; uint256 private _totalSupply; /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev Gets the balance of the specified address. * @param owner The address to query the balance of. * @return A uint256 representing the amount owned by the passed address. */ function balanceOf(address owner) public view returns (uint256) { return _balances[owner]; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param owner address The address which owns the funds. * @param spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowed[owner][spender]; } /** * @dev Transfer token to a specified address * @param to The address to transfer to. * @param value The amount to be transferred. */ function transfer(address to, uint256 value) public returns (bool) { _transfer(msg.sender, to, value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param spender The address which will spend the funds. * @param value The amount of tokens to be spent. */ function approve(address spender, uint256 value) public returns (bool) { _approve(msg.sender, spender, value); return true; } /** * @dev Transfer tokens from one address to another. * Note that while this function emits an Approval event, this is not required as per the specification, * and other compliant implementations may not emit the event. * @param from address The address which you want to send tokens from * @param to address The address which you want to transfer to * @param value uint256 the amount of tokens to be transferred */ function transferFrom(address from, address to, uint256 value) public returns (bool) { _transfer(from, to, value); _approve(from, msg.sender, _allowed[from][msg.sender].sub(value)); return true; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when _allowed[msg.sender][spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * Emits an Approval event. * @param spender The address which will spend the funds. * @param addedValue The amount of tokens to increase the allowance by. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(msg.sender, spender, _allowed[msg.sender][spender].add(addedValue)); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when _allowed[msg.sender][spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * Emits an Approval event. * @param spender The address which will spend the funds. * @param subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(msg.sender, spender, _allowed[msg.sender][spender].sub(subtractedValue)); return true; } /** * @dev Transfer token for a specified addresses * @param from The address to transfer from. * @param to The address to transfer to. * @param value The amount to be transferred. */ function _transfer(address from, address to, uint256 value) internal { require(to != address(0)); _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(from, to, value); } /** * @dev Internal function that mints an amount of the token and assigns it to * an account. This encapsulates the modification of balances such that the * proper events are emitted. * @param account The account that will receive the created tokens. * @param value The amount that will be created. */ function _mint(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.add(value); _balances[account] = _balances[account].add(value); emit Transfer(address(0), account, value); } /** * @dev Internal function that burns an amount of the token of a given * account. * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burn(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); } /** * @dev Approve an address to spend another addresses' tokens. * @param owner The address that owns the tokens. * @param spender The address that will spend the tokens. * @param value The number of tokens that can be spent. */ function _approve(address owner, address spender, uint256 value) internal { require(spender != address(0)); require(owner != address(0)); _allowed[owner][spender] = value; emit Approval(owner, spender, value); } /** * @dev Internal function that burns an amount of the token of a given * account, deducting from the sender's allowance for said account. Uses the * internal burn function. * Emits an Approval event (reflecting the reduced allowance). * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burnFrom(address account, uint256 value) internal { _burn(account, value); _approve(account, msg.sender, _allowed[account][msg.sender].sub(value)); } } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20Detailed.sol pragma solidity ^0.5.2; /** * @title ERC20Detailed token * @dev The decimals are only for visualization purposes. * All the operations are done using the smallest and indivisible token unit, * just as on Ethereum all the operations are done in wei. */ contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor (string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } /** * @return the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @return the symbol of the token. */ function symbol() public view returns (string memory) { return _symbol; } /** * @return the number of decimals of the token. */ function decimals() public view returns (uint8) { return _decimals; } } // File: zos-lib/contracts/Initializable.sol pragma solidity >=0.4.24 <0.6.0; /** * @title Initializable * * @dev Helper contract to support initializer functions. To use it, replace * the constructor with a function that has the `initializer` modifier. * WARNING: Unlike constructors, initializer functions must be manually * invoked. This applies both to deploying an Initializable contract, as well * as extending an Initializable contract via inheritance. * WARNING: When used with inheritance, manual care must be taken to not invoke * a parent initializer twice, or ensure that all initializers are idempotent, * because this is not dealt with automatically as with constructors. */ contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private initializing; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. uint256 cs; assembly { cs := extcodesize(address) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } // File: contracts/core/interfaces/ISetFactory.sol /* Copyright 2018 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; /** * @title ISetFactory * @author Set Protocol * * The ISetFactory interface provides operability for authorized contracts * to interact with SetTokenFactory */ interface ISetFactory { /* ============ External Functions ============ */ /** * Return core address * * @return address core address */ function core() external returns (address); /** * Deploys a new Set Token and adds it to the valid list of SetTokens * * @param _components The address of component tokens * @param _units The units of each component token * @param _naturalUnit The minimum unit to be issued or redeemed * @param _name The bytes32 encoded name of the new Set * @param _symbol The bytes32 encoded symbol of the new Set * @param _callData Byte string containing additional call parameters * @return setTokenAddress The address of the new Set */ function createSet( address[] calldata _components, uint[] calldata _units, uint256 _naturalUnit, bytes32 _name, bytes32 _symbol, bytes calldata _callData ) external returns (address); } // File: contracts/core/interfaces/IWhiteList.sol /* Copyright 2018 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; /** * @title IWhiteList * @author Set Protocol * * The IWhiteList interface exposes the whitelist mapping to check components */ interface IWhiteList { /* ============ External Functions ============ */ /** * Validates address against white list * * @param _address Address to check * @return bool Whether passed in address is whitelisted */ function whiteList( address _address ) external view returns (bool); /** * Verifies an array of addresses against the whitelist * * @param _addresses Array of addresses to verify * @return bool Whether all addresses in the list are whitelsited */ function areValidAddresses( address[] calldata _addresses ) external view returns (bool); } // File: contracts/core/interfaces/IRebalancingSetFactory.sol /* Copyright 2018 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; /** * @title IRebalancingSetFactory * @author Set Protocol * * The IRebalancingSetFactory interface provides operability for authorized contracts * to interact with RebalancingSetTokenFactory */ contract IRebalancingSetFactory is ISetFactory { /** * Getter for minimumRebalanceInterval of RebalancingSetTokenFactory, used * to enforce rebalanceInterval when creating a RebalancingSetToken * * @return uint256 Minimum amount of time between rebalances in seconds */ function minimumRebalanceInterval() external returns (uint256); /** * Getter for minimumProposalPeriod of RebalancingSetTokenFactory, used * to enforce proposalPeriod when creating a RebalancingSetToken * * @return uint256 Minimum amount of time users can review proposals in seconds */ function minimumProposalPeriod() external returns (uint256); /** * Getter for minimumTimeToPivot of RebalancingSetTokenFactory, used * to enforce auctionTimeToPivot when proposing a rebalance * * @return uint256 Minimum amount of time before auction pivot reached */ function minimumTimeToPivot() external returns (uint256); /** * Getter for maximumTimeToPivot of RebalancingSetTokenFactory, used * to enforce auctionTimeToPivot when proposing a rebalance * * @return uint256 Maximum amount of time before auction pivot reached */ function maximumTimeToPivot() external returns (uint256); /** * Getter for minimumNaturalUnit of RebalancingSetTokenFactory * * @return uint256 Minimum natural unit */ function minimumNaturalUnit() external returns (uint256); /** * Getter for maximumNaturalUnit of RebalancingSetTokenFactory * * @return uint256 Maximum Minimum natural unit */ function maximumNaturalUnit() external returns (uint256); /** * Getter for rebalanceAuctionModule address on RebalancingSetTokenFactory * * @return address Address of rebalanceAuctionModule */ function rebalanceAuctionModule() external returns (address); } // File: contracts/core/interfaces/IVault.sol /* Copyright 2018 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; /** * @title IVault * @author Set Protocol * * The IVault interface provides a light-weight, structured way to interact with the Vault * contract from another contract. */ interface IVault { /* * Withdraws user's unassociated tokens to user account. Can only be * called by authorized core contracts. * * @param _token The address of the ERC20 token * @param _to The address to transfer token to * @param _quantity The number of tokens to transfer */ function withdrawTo( address _token, address _to, uint256 _quantity ) external; /* * Increment quantity owned of a token for a given address. Can * only be called by authorized core contracts. * * @param _token The address of the ERC20 token * @param _owner The address of the token owner * @param _quantity The number of tokens to attribute to owner */ function incrementTokenOwner( address _token, address _owner, uint256 _quantity ) external; /* * Decrement quantity owned of a token for a given address. Can only * be called by authorized core contracts. * * @param _token The address of the ERC20 token * @param _owner The address of the token owner * @param _quantity The number of tokens to deattribute to owner */ function decrementTokenOwner( address _token, address _owner, uint256 _quantity ) external; /** * Transfers tokens associated with one account to another account in the vault * * @param _token Address of token being transferred * @param _from Address token being transferred from * @param _to Address token being transferred to * @param _quantity Amount of tokens being transferred */ function transferBalance( address _token, address _from, address _to, uint256 _quantity ) external; /* * Withdraws user's unassociated tokens to user account. Can only be * called by authorized core contracts. * * @param _tokens The addresses of the ERC20 tokens * @param _owner The address of the token owner * @param _quantities The numbers of tokens to attribute to owner */ function batchWithdrawTo( address[] calldata _tokens, address _to, uint256[] calldata _quantities ) external; /* * Increment quantites owned of a collection of tokens for a given address. Can * only be called by authorized core contracts. * * @param _tokens The addresses of the ERC20 tokens * @param _owner The address of the token owner * @param _quantities The numbers of tokens to attribute to owner */ function batchIncrementTokenOwner( address[] calldata _tokens, address _owner, uint256[] calldata _quantities ) external; /* * Decrements quantites owned of a collection of tokens for a given address. Can * only be called by authorized core contracts. * * @param _tokens The addresses of the ERC20 tokens * @param _owner The address of the token owner * @param _quantities The numbers of tokens to attribute to owner */ function batchDecrementTokenOwner( address[] calldata _tokens, address _owner, uint256[] calldata _quantities ) external; /** * Transfers tokens associated with one account to another account in the vault * * @param _tokens Addresses of tokens being transferred * @param _from Address tokens being transferred from * @param _to Address tokens being transferred to * @param _quantities Amounts of tokens being transferred */ function batchTransferBalance( address[] calldata _tokens, address _from, address _to, uint256[] calldata _quantities ) external; /* * Get balance of particular contract for owner. * * @param _token The address of the ERC20 token * @param _owner The address of the token owner */ function getOwnerBalance( address _token, address _owner ) external view returns (uint256); } // File: contracts/lib/ScaleValidations.sol /* Copyright 2019 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; library ScaleValidations { using SafeMath for uint256; uint256 private constant ONE_HUNDRED_PERCENT = 1e18; uint256 private constant ONE_BASIS_POINT = 1e14; function validateLessThanEqualOneHundredPercent(uint256 _value) internal view { require(_value <= ONE_HUNDRED_PERCENT, "Must be <= 100%"); } function validateMultipleOfBasisPoint(uint256 _value) internal view { require( _value.mod(ONE_BASIS_POINT) == 0, "Must be multiple of 0.01%" ); } } // File: contracts/core/tokens/rebalancing-v2/RebalancingSetState.sol /* Copyright 2019 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; /** * @title RebalancingSetState * @author Set Protocol * */ contract RebalancingSetState { /* ============ State Variables ============ */ // ---------------------------------------------------------------------- // System Related // ---------------------------------------------------------------------- // Set Protocol's Core Contract ICore public core; // The Factory that created this Set IRebalancingSetFactory public factory; // Set Protocol's Vault contract IVault public vault; // The token whitelist that components are checked against during proposals IWhiteList public componentWhiteList; // WhiteList of liquidator contracts IWhiteList public liquidatorWhiteList; // Contract holding the state and logic required for rebalance liquidation // The Liquidator interacts closely with the Set during rebalances. ILiquidator public liquidator; // Contract responsible for calculation of rebalance fees IFeeCalculator public rebalanceFeeCalculator; // The account that is allowed to make proposals address public manager; // The account that receives any fees address public feeRecipient; // ---------------------------------------------------------------------- // Configuration // ---------------------------------------------------------------------- // Time in seconds that must elapsed from last rebalance to propose uint256 public rebalanceInterval; // Time in seconds after rebalanceStartTime before the Set believes the auction has failed uint256 public rebalanceFailPeriod; // Fee levied to feeRecipient every mint operation, paid during minting // Represents a decimal value scaled by 1e18 (e.g. 100% = 1e18 and 1% = 1e16) uint256 public entryFee; // ---------------------------------------------------------------------- // Current State // ---------------------------------------------------------------------- // The Set currently collateralizing the Rebalancing Set ISetToken public currentSet; // The number of currentSet per naturalUnit of the Rebalancing Set uint256 public unitShares; // The minimum issuable value of a Set uint256 public naturalUnit; // The current state of the Set (e.g. Default, Proposal, Rebalance, Drawdown) // Proposal is unused RebalancingLibrary.State public rebalanceState; // The number of rebalances in the Set's history; starts at index 0 uint256 public rebalanceIndex; // The timestamp of the last completed rebalance uint256 public lastRebalanceTimestamp; // ---------------------------------------------------------------------- // Live Rebalance State // ---------------------------------------------------------------------- // The proposal's SetToken to rebalance into ISetToken public nextSet; // The timestamp of the last rebalance was initiated at uint256 public rebalanceStartTime; // Whether a successful bid has been made during the rebalance. // In the case that the rebalance has failed, hasBidded is used // to determine whether the Set should be put into Drawdown or Default state. bool public hasBidded; // In the event a Set is put into the Drawdown state, these components // that can be withdrawn by users address[] internal failedRebalanceComponents; /* ============ Modifier ============ */ modifier onlyManager() { validateManager(); _; } /* ============ Events ============ */ event NewManagerAdded( address newManager, address oldManager ); event NewLiquidatorAdded( address newLiquidator, address oldLiquidator ); event NewEntryFee( uint256 newEntryFee, uint256 oldEntryFee ); event NewFeeRecipient( address newFeeRecipient, address oldFeeRecipient ); event EntryFeePaid( address indexed feeRecipient, uint256 feeQuantity ); event RebalanceStarted( address oldSet, address newSet, uint256 rebalanceIndex, uint256 currentSetQuantity ); event RebalanceSettled( address indexed feeRecipient, uint256 feeQuantity, uint256 feePercentage, uint256 rebalanceIndex, uint256 issueQuantity, uint256 unitShares ); /* ============ Setter Functions ============ */ /* * Set new manager address. */ function setManager( address _newManager ) external onlyManager { emit NewManagerAdded(_newManager, manager); manager = _newManager; } function setEntryFee( uint256 _newEntryFee ) external onlyManager { ScaleValidations.validateLessThanEqualOneHundredPercent(_newEntryFee); ScaleValidations.validateMultipleOfBasisPoint(_newEntryFee); emit NewEntryFee(_newEntryFee, entryFee); entryFee = _newEntryFee; } /* * Set new liquidator address. Only whitelisted addresses are valid. */ function setLiquidator( ILiquidator _newLiquidator ) external onlyManager { require( rebalanceState != RebalancingLibrary.State.Rebalance, "Invalid state" ); require( liquidatorWhiteList.whiteList(address(_newLiquidator)), "Not whitelisted" ); emit NewLiquidatorAdded(address(_newLiquidator), address(liquidator)); liquidator = _newLiquidator; } function setFeeRecipient( address _newFeeRecipient ) external onlyManager { emit NewFeeRecipient(_newFeeRecipient, feeRecipient); feeRecipient = _newFeeRecipient; } /* ============ Getter Functions ============ */ /* * Retrieves the current expected fee from the fee calculator * Value is returned as a scale decimal figure. */ function rebalanceFee() external view returns (uint256) { return rebalanceFeeCalculator.getFee(); } /* * Function for compatability with ISetToken interface. Returns currentSet. */ function getComponents() external view returns (address[] memory) { address[] memory components = new address[](1); components[0] = address(currentSet); return components; } /* * Function for compatability with ISetToken interface. Returns unitShares. */ function getUnits() external view returns (uint256[] memory) { uint256[] memory units = new uint256[](1); units[0] = unitShares; return units; } /* * Returns whether the address is the current set of the RebalancingSetToken. * Conforms to the ISetToken Interface. */ function tokenIsComponent( address _tokenAddress ) external view returns (bool) { return _tokenAddress == address(currentSet); } /* ============ Validations ============ */ function validateManager() internal view { require( msg.sender == manager, "Not manager" ); } function validateCallerIsCore() internal view { require( msg.sender == address(core), "Not Core" ); } function validateCallerIsModule() internal view { require( core.validModules(msg.sender), "Not approved module" ); } function validateRebalanceStateIs(RebalancingLibrary.State _requiredState) internal view { require( rebalanceState == _requiredState, "Invalid state" ); } function validateRebalanceStateIsNot(RebalancingLibrary.State _requiredState) internal view { require( rebalanceState != _requiredState, "Invalid state" ); } } // File: contracts/core/tokens/rebalancing-v2/BackwardCompatibility.sol /* Copyright 2019 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; /** * @title BackwardCompatibility * @author Set Protocol * * This module allows full backwards compatability with RebalancingSetTokenV1. It implements * all the same getter functions to allow upstream applications to make minimized changes * to support the new version. * * The following interfaces are not included: * - propose(address, address, uint256, uint256, uint256): Implementation would have *. been a revert. * - biddingParameters: RebalancingSetToken V1 biddingParameters reverts on call */ contract BackwardCompatibility is RebalancingSetState { /* ============ Empty Variables ============ */ // Deprecated auctionLibrary. Returns 0x00 to prevent reverts address public auctionLibrary; // Deprecated proposal period. Returns 0 to prevent reverts uint256 public proposalPeriod; // Deprecated proposal start time. Returns 0 to prevent reverts uint256 public proposalStartTime; /* ============ Getters ============ */ function getAuctionPriceParameters() external view returns (uint256[] memory) { RebalancingLibrary.AuctionPriceParameters memory params = liquidator.auctionPriceParameters( address(this) ); uint256[] memory auctionPriceParams = new uint256[](4); auctionPriceParams[0] = params.auctionStartTime; auctionPriceParams[1] = params.auctionTimeToPivot; auctionPriceParams[2] = params.auctionStartPrice; auctionPriceParams[2] = params.auctionPivotPrice; return auctionPriceParams; } function getCombinedCurrentUnits() external view returns (uint256[] memory) { return liquidator.getCombinedCurrentSetUnits(address(this)); } function getCombinedNextSetUnits() external view returns (uint256[] memory) { return liquidator.getCombinedNextSetUnits(address(this)); } function getCombinedTokenArray() external view returns (address[] memory) { return liquidator.getCombinedTokenArray(address(this)); } function getCombinedTokenArrayLength() external view returns (uint256) { return liquidator.getCombinedTokenArray(address(this)).length; } function startingCurrentSetAmount() external view returns (uint256) { return liquidator.startingCurrentSets(address(this)); } function auctionPriceParameters() external view returns (RebalancingLibrary.AuctionPriceParameters memory) { return liquidator.auctionPriceParameters(address(this)); } /* * Since structs with arrays cannot be retrieved, we return * minimumBid and remainingCurrentSets separately. * * @return biddingParams Array with minimumBid and remainingCurrentSets */ function getBiddingParameters() public view returns (uint256[] memory) { uint256[] memory biddingParams = new uint256[](2); biddingParams[0] = liquidator.minimumBid(address(this)); biddingParams[1] = liquidator.remainingCurrentSets(address(this)); return biddingParams; } function biddingParameters() external view returns (uint256, uint256) { uint256[] memory biddingParams = getBiddingParameters(); return (biddingParams[0], biddingParams[1]); } function getFailedAuctionWithdrawComponents() external view returns (address[] memory) { return failedRebalanceComponents; } } // File: openzeppelin-solidity/contracts/math/Math.sol pragma solidity ^0.5.2; /** * @title Math * @dev Assorted math operations */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Calculates the average of two numbers. Since these are integers, * averages of an even and odd number cannot be represented, and will be * rounded down. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // File: contracts/lib/AddressArrayUtils.sol // Pulled in from Cryptofin Solidity package in order to control Solidity compiler version // https://github.com/cryptofinlabs/cryptofin-solidity/blob/master/contracts/array-utils/AddressArrayUtils.sol pragma solidity 0.5.7; library AddressArrayUtils { /** * Finds the index of the first occurrence of the given element. * @param A The input array to search * @param a The value to find * @return Returns (index and isIn) for the first occurrence starting from index 0 */ function indexOf(address[] memory A, address a) internal pure returns (uint256, bool) { uint256 length = A.length; for (uint256 i = 0; i < length; i++) { if (A[i] == a) { return (i, true); } } return (0, false); } /** * Returns true if the value is present in the list. Uses indexOf internally. * @param A The input array to search * @param a The value to find * @return Returns isIn for the first occurrence starting from index 0 */ function contains(address[] memory A, address a) internal pure returns (bool) { bool isIn; (, isIn) = indexOf(A, a); return isIn; } /** * Returns the combination of the two arrays * @param A The first array * @param B The second array * @return Returns A extended by B */ function extend(address[] memory A, address[] memory B) internal pure returns (address[] memory) { uint256 aLength = A.length; uint256 bLength = B.length; address[] memory newAddresses = new address[](aLength + bLength); for (uint256 i = 0; i < aLength; i++) { newAddresses[i] = A[i]; } for (uint256 j = 0; j < bLength; j++) { newAddresses[aLength + j] = B[j]; } return newAddresses; } /** * Returns the array with a appended to A. * @param A The first array * @param a The value to append * @return Returns A appended by a */ function append(address[] memory A, address a) internal pure returns (address[] memory) { address[] memory newAddresses = new address[](A.length + 1); for (uint256 i = 0; i < A.length; i++) { newAddresses[i] = A[i]; } newAddresses[A.length] = a; return newAddresses; } /** * Returns the intersection of two arrays. Arrays are treated as collections, so duplicates are kept. * @param A The first array * @param B The second array * @return The intersection of the two arrays */ function intersect(address[] memory A, address[] memory B) internal pure returns (address[] memory) { uint256 length = A.length; bool[] memory includeMap = new bool[](length); uint256 newLength = 0; for (uint256 i = 0; i < length; i++) { if (contains(B, A[i])) { includeMap[i] = true; newLength++; } } address[] memory newAddresses = new address[](newLength); uint256 j = 0; for (uint256 k = 0; k < length; k++) { if (includeMap[k]) { newAddresses[j] = A[k]; j++; } } return newAddresses; } /** * Returns the union of the two arrays. Order is not guaranteed. * @param A The first array * @param B The second array * @return The union of the two arrays */ function union(address[] memory A, address[] memory B) internal pure returns (address[] memory) { address[] memory leftDifference = difference(A, B); address[] memory rightDifference = difference(B, A); address[] memory intersection = intersect(A, B); return extend(leftDifference, extend(intersection, rightDifference)); } /** * Computes the difference of two arrays. Assumes there are no duplicates. * @param A The first array * @param B The second array * @return The difference of the two arrays */ function difference(address[] memory A, address[] memory B) internal pure returns (address[] memory) { uint256 length = A.length; bool[] memory includeMap = new bool[](length); uint256 count = 0; // First count the new length because can't push for in-memory arrays for (uint256 i = 0; i < length; i++) { address e = A[i]; if (!contains(B, e)) { includeMap[i] = true; count++; } } address[] memory newAddresses = new address[](count); uint256 j = 0; for (uint256 k = 0; k < length; k++) { if (includeMap[k]) { newAddresses[j] = A[k]; j++; } } return newAddresses; } /** * Removes specified index from array * Resulting ordering is not guaranteed * @return Returns the new array and the removed entry */ function pop(address[] memory A, uint256 index) internal pure returns (address[] memory, address) { uint256 length = A.length; address[] memory newAddresses = new address[](length - 1); for (uint256 i = 0; i < index; i++) { newAddresses[i] = A[i]; } for (uint256 j = index + 1; j < length; j++) { newAddresses[j - 1] = A[j]; } return (newAddresses, A[index]); } /** * @return Returns the new array */ function remove(address[] memory A, address a) internal pure returns (address[] memory) { (uint256 index, bool isIn) = indexOf(A, a); if (!isIn) { revert(); } else { (address[] memory _A,) = pop(A, index); return _A; } } /** * Returns whether or not there's a duplicate. Runs in O(n^2). * @param A Array to search * @return Returns true if duplicate, false otherwise */ function hasDuplicate(address[] memory A) internal pure returns (bool) { if (A.length == 0) { return false; } for (uint256 i = 0; i < A.length - 1; i++) { for (uint256 j = i + 1; j < A.length; j++) { if (A[i] == A[j]) { return true; } } } return false; } /** * Returns whether the two arrays are equal. * @param A The first array * @param B The second array * @return True is the arrays are equal, false if not. */ function isEqual(address[] memory A, address[] memory B) internal pure returns (bool) { if (A.length != B.length) { return false; } for (uint256 i = 0; i < A.length; i++) { if (A[i] != B[i]) { return false; } } return true; } } // File: contracts/lib/CommonMath.sol /* Copyright 2018 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; library CommonMath { using SafeMath for uint256; uint256 public constant SCALE_FACTOR = 10 ** 18; uint256 public constant MAX_UINT_256 = 2 ** 256 - 1; /** * Returns scale factor equal to 10 ** 18 * * @return 10 ** 18 */ function scaleFactor() internal pure returns (uint256) { return SCALE_FACTOR; } /** * Calculates and returns the maximum value for a uint256 * * @return The maximum value for uint256 */ function maxUInt256() internal pure returns (uint256) { return MAX_UINT_256; } /** * Increases a value by the scale factor to allow for additional precision * during mathematical operations */ function scale( uint256 a ) internal pure returns (uint256) { return a.mul(SCALE_FACTOR); } /** * Divides a value by the scale factor to allow for additional precision * during mathematical operations */ function deScale( uint256 a ) internal pure returns (uint256) { return a.div(SCALE_FACTOR); } /** * @dev Performs the power on a specified value, reverts on overflow. */ function safePower( uint256 a, uint256 pow ) internal pure returns (uint256) { require(a > 0); uint256 result = 1; for (uint256 i = 0; i < pow; i++){ uint256 previousResult = result; // Using safemath multiplication prevents overflows result = previousResult.mul(a); } return result; } /** * Checks for rounding errors and returns value of potential partial amounts of a principal * * @param _principal Number fractional amount is derived from * @param _numerator Numerator of fraction * @param _denominator Denominator of fraction * @return uint256 Fractional amount of principal calculated */ function getPartialAmount( uint256 _principal, uint256 _numerator, uint256 _denominator ) internal pure returns (uint256) { // Get remainder of partial amount (if 0 not a partial amount) uint256 remainder = mulmod(_principal, _numerator, _denominator); // Return if not a partial amount if (remainder == 0) { return _principal.mul(_numerator).div(_denominator); } // Calculate error percentage uint256 errPercentageTimes1000000 = remainder.mul(1000000).div(_numerator.mul(_principal)); // Require error percentage is less than 0.1%. require( errPercentageTimes1000000 < 1000, "CommonMath.getPartialAmount: Rounding error exceeds bounds" ); return _principal.mul(_numerator).div(_denominator); } /* * Gets the rounded up log10 of passed value * * @param _value Value to calculate ceil(log()) on * @return uint256 Output value */ function ceilLog10( uint256 _value ) internal pure returns (uint256) { // Make sure passed value is greater than 0 require ( _value > 0, "CommonMath.ceilLog10: Value must be greater than zero." ); // Since log10(1) = 0, if _value = 1 return 0 if (_value == 1) return 0; // Calcualte ceil(log10()) uint256 x = _value - 1; uint256 result = 0; if (x >= 10 ** 64) { x /= 10 ** 64; result += 64; } if (x >= 10 ** 32) { x /= 10 ** 32; result += 32; } if (x >= 10 ** 16) { x /= 10 ** 16; result += 16; } if (x >= 10 ** 8) { x /= 10 ** 8; result += 8; } if (x >= 10 ** 4) { x /= 10 ** 4; result += 4; } if (x >= 100) { x /= 100; result += 2; } if (x >= 10) { result += 1; } return result + 1; } } // File: contracts/core/lib/SetTokenLibrary.sol /* Copyright 2018 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; library SetTokenLibrary { using SafeMath for uint256; struct SetDetails { uint256 naturalUnit; address[] components; uint256[] units; } /** * Validates that passed in tokens are all components of the Set * * @param _set Address of the Set * @param _tokens List of tokens to check */ function validateTokensAreComponents( address _set, address[] calldata _tokens ) external view { for (uint256 i = 0; i < _tokens.length; i++) { // Make sure all tokens are members of the Set require( ISetToken(_set).tokenIsComponent(_tokens[i]), "SetTokenLibrary.validateTokensAreComponents: Component must be a member of Set" ); } } /** * Validates that passed in quantity is a multiple of the natural unit of the Set. * * @param _set Address of the Set * @param _quantity Quantity to validate */ function isMultipleOfSetNaturalUnit( address _set, uint256 _quantity ) external view { require( _quantity.mod(ISetToken(_set).naturalUnit()) == 0, "SetTokenLibrary.isMultipleOfSetNaturalUnit: Quantity is not a multiple of nat unit" ); } /** * Validates that passed in quantity is a multiple of the natural unit of the Set. * * @param _core Address of Core * @param _set Address of the Set */ function requireValidSet( ICore _core, address _set ) internal view { require( _core.validSets(_set), "SetTokenLibrary: Must be an approved SetToken address" ); } /** * Retrieves the Set's natural unit, components, and units. * * @param _set Address of the Set * @return SetDetails Struct containing the natural unit, components, and units */ function getSetDetails( address _set ) internal view returns (SetDetails memory) { // Declare interface variables ISetToken setToken = ISetToken(_set); // Fetch set token properties uint256 naturalUnit = setToken.naturalUnit(); address[] memory components = setToken.getComponents(); uint256[] memory units = setToken.getUnits(); return SetDetails({ naturalUnit: naturalUnit, components: components, units: units }); } } // File: contracts/core/tokens/rebalancing-v2/RebalancingSettlement.sol /* Copyright 2019 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; /** * @title RebalancingSettlement * @author Set Protocol * */ contract RebalancingSettlement is ERC20, RebalancingSetState { using SafeMath for uint256; uint256 public constant SCALE_FACTOR = 10 ** 18; /* ============ Internal Functions ============ */ /* * Validates that the settle function can be called. */ function validateRebalancingSettlement() internal view { validateRebalanceStateIs(RebalancingLibrary.State.Rebalance); } /* * Issue nextSet to RebalancingSetToken; The issued Set is held in the Vault * * @param _issueQuantity Quantity of next Set to issue */ function issueNextSet( uint256 _issueQuantity ) internal { core.issueInVault( address(nextSet), _issueQuantity ); } /* * Updates state post-settlement. * * @param _nextUnitShares The new implied unit shares */ function transitionToDefault( uint256 _newUnitShares ) internal { rebalanceState = RebalancingLibrary.State.Default; lastRebalanceTimestamp = block.timestamp; currentSet = nextSet; unitShares = _newUnitShares; rebalanceIndex = rebalanceIndex.add(1); nextSet = ISetToken(address(0)); hasBidded = false; } /** * Calculate the amount of Sets to issue by using the component amounts in the * vault. */ function calculateSetIssueQuantity( ISetToken _setToken ) internal view returns (uint256) { // Collect data necessary to compute issueAmounts SetTokenLibrary.SetDetails memory setToken = SetTokenLibrary.getSetDetails(address(_setToken)); uint256 maxIssueAmount = calculateMaxIssueAmount(setToken); // Issue amount of Sets that is closest multiple of nextNaturalUnit to the maxIssueAmount // Since the initial division will round down to the nearest whole number when we multiply // by that same number we will return the closest multiple less than the maxIssueAmount uint256 issueAmount = maxIssueAmount.sub(maxIssueAmount.mod(setToken.naturalUnit)); return issueAmount; } /** * Calculates the fee and mints the rebalancing SetToken quantity to the recipient. * The minting is done without an increase to the total collateral controlled by the * rebalancing SetToken. In effect, the existing holders are paying the fee via inflation. * * @return feePercentage * @return feeQuantity */ function handleFees() internal returns (uint256, uint256) { // Represents a decimal value scaled by 1e18 (e.g. 100% = 1e18 and 1% = 1e16) uint256 feePercent = rebalanceFeeCalculator.getFee(); uint256 feeQuantity = calculateRebalanceFeeInflation(feePercent); if (feeQuantity > 0) { ERC20._mint(feeRecipient, feeQuantity); } return (feePercent, feeQuantity); } /** * Returns the new rebalance fee. The calculation for the fee involves implying * mint quantity so that the feeRecipient owns the fee percentage of the entire * supply of the Set. * * The formula to solve for fee is: * feeQuantity / feeQuantity + totalSupply = fee / scaleFactor * * The simplified formula utilized below is: * feeQuantity = fee * totalSupply / (scaleFactor - fee) * * @param _rebalanceFeePercent Fee levied to feeRecipient every rebalance, paid during settlement * @return uint256 New RebalancingSet issue quantity */ function calculateRebalanceFeeInflation( uint256 _rebalanceFeePercent ) internal view returns(uint256) { // fee * totalSupply uint256 a = _rebalanceFeePercent.mul(totalSupply()); // ScaleFactor (10e18) - fee uint256 b = SCALE_FACTOR.sub(_rebalanceFeePercent); return a.div(b); } /** * Calculates the new unitShares, defined as issueQuantity / naturalUnitsOutstanding * * @param _issueQuantity Amount of nextSets to issue * * @return uint256 New unitShares for the rebalancingSetToken */ function calculateNextSetNewUnitShares( uint256 _issueQuantity ) internal view returns (uint256) { // Calculate the amount of naturalUnits worth of rebalancingSetToken outstanding. uint256 naturalUnitsOutstanding = totalSupply().div(naturalUnit); // Divide final issueAmount by naturalUnitsOutstanding to get newUnitShares return _issueQuantity.div(naturalUnitsOutstanding); } /* ============ Private Functions ============ */ /** * Get the maximum possible issue amount of nextSet based on number of components owned by rebalancing * set token. * * @param _setToken Struct of Set Token details */ function calculateMaxIssueAmount( SetTokenLibrary.SetDetails memory _setToken ) private view returns (uint256) { uint256 maxIssueAmount = CommonMath.maxUInt256(); for (uint256 i = 0; i < _setToken.components.length; i++) { // Get amount of components in vault owned by rebalancingSetToken uint256 componentAmount = vault.getOwnerBalance( _setToken.components[i], address(this) ); // Calculate amount of Sets that can be issued from those components, if less than amount for other // components then set that as maxIssueAmount. We divide before multiplying so that we don't get // an amount that isn't a multiple of the naturalUnit uint256 componentIssueAmount = componentAmount.div(_setToken.units[i]).mul(_setToken.naturalUnit); if (componentIssueAmount < maxIssueAmount) { maxIssueAmount = componentIssueAmount; } } return maxIssueAmount; } } // File: contracts/core/tokens/rebalancing-v2/RebalancingFailure.sol /* Copyright 2019 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; /** * @title RebalancingFailure * @author Set Protocol * */ contract RebalancingFailure is RebalancingSetState, RebalancingSettlement { using SafeMath for uint256; using AddressArrayUtils for address[]; /* ============ Internal Functions ============ */ /* * Validations for failRebalance: * - State is Rebalance * - Either liquidator recognizes failure OR fail period breached on RB Set * * @param _quantity The amount of currentSet to be rebalanced */ function validateFailRebalance() internal view { // Token must be in Rebalance State validateRebalanceStateIs(RebalancingLibrary.State.Rebalance); // Failure triggers must be met require( liquidatorBreached() || failPeriodBreached(), "Triggers not breached" ); } /* * Determine the new Rebalance State. If there has been a bid, then we put it to * Drawdown, where the Set is effectively killed. If no bids, we reissue the currentSet. */ function getNewRebalanceState() internal view returns (RebalancingLibrary.State) { return hasBidded ? RebalancingLibrary.State.Drawdown : RebalancingLibrary.State.Default; } /* * Update state based on new Rebalance State. * * @param _newRebalanceState The new State to transition to */ function transitionToNewState( RebalancingLibrary.State _newRebalanceState ) internal { reissueSetIfRevertToDefault(_newRebalanceState); setWithdrawComponentsIfDrawdown(_newRebalanceState); rebalanceState = _newRebalanceState; rebalanceIndex = rebalanceIndex.add(1); lastRebalanceTimestamp = block.timestamp; nextSet = ISetToken(address(0)); hasBidded = false; } /* ============ Private Functions ============ */ /* * Returns whether the liquidator believes the rebalance has failed. * * @return If liquidator thinks rebalance failed */ function liquidatorBreached() private view returns (bool) { return liquidator.hasRebalanceFailed(address(this)); } /* * Returns whether the the fail time has elapsed, which means that a period * of time where the auction should have succeeded has not. * * @return If fail period has passed on Rebalancing Set Token */ function failPeriodBreached() private view returns(bool) { uint256 rebalanceFailTime = rebalanceStartTime.add(rebalanceFailPeriod); return block.timestamp >= rebalanceFailTime; } /* * If the determination is Default State, reissue the Set. */ function reissueSetIfRevertToDefault( RebalancingLibrary.State _newRebalanceState ) private { if (_newRebalanceState == RebalancingLibrary.State.Default) { uint256 issueQuantity = calculateSetIssueQuantity(currentSet); // If bid not placed, reissue current Set core.issueInVault( address(currentSet), issueQuantity ); } } /* * If the determination is Drawdown State, set the drawdown components which is the union of * the current and next Set components. */ function setWithdrawComponentsIfDrawdown( RebalancingLibrary.State _newRebalanceState ) private { if (_newRebalanceState == RebalancingLibrary.State.Drawdown) { address[] memory currentSetComponents = currentSet.getComponents(); address[] memory nextSetComponents = nextSet.getComponents(); failedRebalanceComponents = currentSetComponents.union(nextSetComponents); } } } // File: contracts/core/tokens/rebalancing-v2/Issuance.sol /* Copyright 2019 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; /** * @title Issuance * @author Set Protocol * * Default implementation of Rebalancing Set Token propose function */ contract Issuance is ERC20, RebalancingSetState { using SafeMath for uint256; using CommonMath for uint256; /* ============ Internal Functions ============ */ /* * Validate call to mint new Rebalancing Set Token * * - Make sure caller is Core * - Make sure state is not Rebalance or Drawdown */ function validateMint() internal view { validateCallerIsCore(); validateRebalanceStateIs(RebalancingLibrary.State.Default); } /* * Validate call to burn Rebalancing Set Token * * - Make sure state is not Rebalance or Drawdown * - Make sure sender is module when in drawdown, core otherwise */ function validateBurn() internal view { validateRebalanceStateIsNot(RebalancingLibrary.State.Rebalance); if (rebalanceState == RebalancingLibrary.State.Drawdown) { // In Drawdown Sets can only be burned as part of the withdrawal process validateCallerIsModule(); } else { // When in non-Rebalance or Drawdown state, check that function caller is Core // so that Sets can be redeemed validateCallerIsCore(); } } /* * Calculates entry fees and mints the feeRecipient a portion of the issue quantity. * * @param _quantity The number of rebalancing SetTokens the issuer mints * @return issueQuantityNetOfFees Quantity of rebalancing SetToken to mint issuer net of fees */ function handleEntryFees( uint256 _quantity ) internal returns(uint256) { // The entryFee is a scaled decimal figure by 10e18. We multiply the fee by the quantity // Then descale by 10e18 uint256 fee = _quantity.mul(entryFee).deScale(); if (fee > 0) { ERC20._mint(feeRecipient, fee); emit EntryFeePaid(feeRecipient, fee); } // Return the issue quantity less fees return _quantity.sub(fee); } } // File: contracts/core/tokens/rebalancing-v2/RebalancingBid.sol /* Copyright 2019 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; /** * @title RebalancingBid * @author Set Protocol * * Implementation of Rebalancing Set Token V2 bidding-related functionality. */ contract RebalancingBid is RebalancingSetState { using SafeMath for uint256; /* ============ Internal Functions ============ */ /* * Validates conditions to retrieve a Bid Price: * - State is Rebalance * - Quanity is greater than zero * * @param _quantity The amount of currentSet to be rebalanced */ function validateGetBidPrice( uint256 _quantity ) internal view { validateRebalanceStateIs(RebalancingLibrary.State.Rebalance); require( _quantity > 0, "Bid not > 0" ); } /* * Validations for placeBid: * - Module is sender * - getBidPrice validations * * @param _quantity The amount of currentSet to be rebalanced */ function validatePlaceBid( uint256 _quantity ) internal view { validateCallerIsModule(); validateGetBidPrice(_quantity); } /* * If a successful bid has been made, flip the hasBidded boolean. */ function updateHasBiddedIfNecessary() internal { if (!hasBidded) { hasBidded = true; } } } // File: contracts/core/tokens/rebalancing-v2/RebalancingStart.sol /* Copyright 2019 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; /** * @title RebalancingStart * @author Set Protocol * * Implementation of Rebalancing Set Token V2 start rebalance functionality */ contract RebalancingStart is RebalancingSetState { using SafeMath for uint256; /* ============ Internal Functions ============ */ /** * Validate that start rebalance can be called: * - Current state is Default * - rebalanceInterval has elapsed * - Proposed set is valid in Core * - Components in set are all valid * - NaturalUnits are multiples of each other * * @param _nextSet The Set to rebalance into */ function validateStartRebalance( ISetToken _nextSet ) internal view { validateRebalanceStateIs(RebalancingLibrary.State.Default); // Enough time must have passed from last rebalance to start a new proposal require( block.timestamp >= lastRebalanceTimestamp.add(rebalanceInterval), "Interval not elapsed" ); // New proposed Set must be a valid Set created by Core require( core.validSets(address(_nextSet)), "Invalid Set" ); // Check proposed components on whitelist. This is to ensure managers are unable to add contract addresses // to a propose that prohibit the set from carrying out an auction i.e. a token that only the manager possesses require( componentWhiteList.areValidAddresses(_nextSet.getComponents()), "Invalid component" ); // Check that the proposed set natural unit is a multiple of current set natural unit, or vice versa. // Done to make sure that when calculating token units there will are be rounding errors. require( naturalUnitsAreValid(currentSet, _nextSet), "Invalid natural unit" ); } /** * Calculates the maximum quantity of the currentSet that can be redeemed. This is defined * by how many naturalUnits worth of the Set there are. * * @return Maximum quantity of the current Set that can be redeemed */ function calculateStartingSetQuantity() internal view returns (uint256) { uint256 currentSetBalance = vault.getOwnerBalance(address(currentSet), address(this)); uint256 currentSetNaturalUnit = currentSet.naturalUnit(); // Rounds the redemption quantity to a multiple of the current Set natural unit return currentSetBalance.sub(currentSetBalance.mod(currentSetNaturalUnit)); } /** * Signals to the Liquidator to initiate the rebalance. * * @param _nextSet Next set instance * @param _startingCurrentSetQuantity Amount of currentSets the rebalance is initiated with * @param _liquidatorData Bytecode formatted data with liquidator-specific arguments */ function liquidatorRebalancingStart( ISetToken _nextSet, uint256 _startingCurrentSetQuantity, bytes memory _liquidatorData ) internal { liquidator.startRebalance( currentSet, _nextSet, _startingCurrentSetQuantity, _liquidatorData ); } /** * Updates rebalance-related state parameters. * * @param _nextSet The Set to rebalance into */ function transitionToRebalance(ISetToken _nextSet) internal { nextSet = _nextSet; rebalanceState = RebalancingLibrary.State.Rebalance; rebalanceStartTime = block.timestamp; } /* ============ Private Functions ============ */ /** * Check that the proposed set natural unit is a multiple of current set natural unit, or vice versa. * Done to make sure that when calculating token units there will be no rounding errors. * * @param _currentSet The current base SetToken * @param _nextSet The proposed SetToken */ function naturalUnitsAreValid( ISetToken _currentSet, ISetToken _nextSet ) private view returns (bool) { uint256 currentNaturalUnit = _currentSet.naturalUnit(); uint256 nextSetNaturalUnit = _nextSet.naturalUnit(); return Math.max(currentNaturalUnit, nextSetNaturalUnit).mod( Math.min(currentNaturalUnit, nextSetNaturalUnit) ) == 0; } } // File: contracts/core/tokens/RebalancingSetTokenV2.sol /* Copyright 2019 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; /** * @title RebalancingSetTokenV2 * @author Set Protocol * * Implementation of Rebalancing Set token V2. Major improvements vs. V1 include: * - Decouple the Rebalancing Set state and rebalance state from the rebalance execution (e.g. auction) * This allows us to rapidly iterate and build new liquidation mechanisms for rebalances. * - Proposals are removed in favor of starting an auction directly. * - The Set retains ability to fail an auction if the minimum fail time has elapsed. * - RebalanceAuctionModule execution should be backwards compatible with V1. * - Bidding and auction parameters state no longer live on this contract. They live on the liquidator * BackwardsComptability is used to allow retrieving of previous supported states. * - Introduces entry and rebalance fees, where rebalance fees are configurable based on an external * fee calculator contract */ contract RebalancingSetTokenV2 is ERC20, ERC20Detailed, Initializable, RebalancingSetState, BackwardCompatibility, Issuance, RebalancingStart, RebalancingBid, RebalancingSettlement, RebalancingFailure { /* ============ Constructor ============ */ /** * Constructor function for Rebalancing Set Token * * addressConfig [factory, manager, liquidator, initialSet, componentWhiteList, * liquidatorWhiteList, feeRecipient, rebalanceFeeCalculator] * [0]factory Factory used to create the Rebalancing Set * [1]manager Address that is able to propose the next Set * [2]liquidator Address of the liquidator contract * [3]initialSet Initial set that collateralizes the Rebalancing set * [4]componentWhiteList Whitelist that nextSet components are checked against during propose * [5]liquidatorWhiteList Whitelist of valid liquidators * [6]feeRecipient Address that receives any incentive fees * [7]rebalanceFeeCalculator Address to retrieve rebalance fee during settlement * * uintConfig [initialUnitShares, naturalUnit, rebalanceInterval, rebalanceFailPeriod, * lastRebalanceTimestamp, entryFee] * [0]initialUnitShares Units of currentSet that equals one share * [1]naturalUnit The minimum multiple of Sets that can be issued or redeemed * [2]rebalanceInterval: Minimum amount of time between rebalances * [3]rebalanceFailPeriod: Time after auctionStart where something in the rebalance has gone wrong * [4]lastRebalanceTimestamp: Time of the last rebalance; Allows customized deployments * [5]entryFee: Mint fee represented in a scaled decimal value (e.g. 100% = 1e18, 1% = 1e16) * * @param _addressConfig List of configuration addresses * @param _uintConfig List of uint addresses * @param _name The name of the new RebalancingSetTokenV2 * @param _symbol The symbol of the new RebalancingSetTokenV2 */ constructor( address[8] memory _addressConfig, uint256[6] memory _uintConfig, string memory _name, string memory _symbol ) public ERC20Detailed( _name, _symbol, 18 ) { factory = IRebalancingSetFactory(_addressConfig[0]); manager = _addressConfig[1]; liquidator = ILiquidator(_addressConfig[2]); currentSet = ISetToken(_addressConfig[3]); componentWhiteList = IWhiteList(_addressConfig[4]); liquidatorWhiteList = IWhiteList(_addressConfig[5]); feeRecipient = _addressConfig[6]; rebalanceFeeCalculator = IFeeCalculator(_addressConfig[7]); unitShares = _uintConfig[0]; naturalUnit = _uintConfig[1]; rebalanceInterval = _uintConfig[2]; rebalanceFailPeriod = _uintConfig[3]; lastRebalanceTimestamp = _uintConfig[4]; entryFee = _uintConfig[5]; core = ICore(factory.core()); vault = IVault(core.vault()); rebalanceState = RebalancingLibrary.State.Default; } /* * Intended to be called during creation by the RebalancingSetTokenFactory. Can only be initialized * once. This implementation initializes the rebalance fee. * * * @param _rebalanceFeeCalldata Bytes encoded rebalance fee represented as a scaled percentage value */ function initialize( bytes calldata _rebalanceFeeCalldata ) external initializer { rebalanceFeeCalculator.initialize(_rebalanceFeeCalldata); } /* ============ External Functions ============ */ /* * Initiates the rebalance in coordination with the Liquidator contract. * In this step, we redeem the currentSet and pass relevant information * to the liquidator. * * @param _nextSet The Set to rebalance into * @param _liquidatorData Bytecode formatted data with liquidator-specific arguments * * Can only be called if the rebalance interval has elapsed. * Can only be called by manager. */ function startRebalance( ISetToken _nextSet, bytes calldata _liquidatorData ) external onlyManager { RebalancingStart.validateStartRebalance(_nextSet); uint256 startingCurrentSetQuantity = RebalancingStart.calculateStartingSetQuantity(); core.redeemInVault(address(currentSet), startingCurrentSetQuantity); RebalancingStart.liquidatorRebalancingStart(_nextSet, startingCurrentSetQuantity, _liquidatorData); RebalancingStart.transitionToRebalance(_nextSet); emit RebalanceStarted( address(currentSet), address(nextSet), rebalanceIndex, startingCurrentSetQuantity ); } /* * Get token inflows and outflows required for bid from the Liquidator. * * @param _quantity The amount of currentSet to be rebalanced * @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 ) public view returns (uint256[] memory, uint256[] memory) { RebalancingBid.validateGetBidPrice(_quantity); return Rebalance.decomposeTokenFlowToBidPrice( liquidator.getBidPrice(address(this), _quantity) ); } /* * Place bid during rebalance auction. * * The intended caller is the RebalanceAuctionModule, which must be approved by Core. * Call Flow: * RebalanceAuctionModule -> RebalancingSetTokenV2 -> Liquidator * * @param _quantity The amount of currentSet to be rebalanced * @return combinedTokenArray Array of token addresses invovled in rebalancing * @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 placeBid( uint256 _quantity ) external returns (address[] memory, uint256[] memory, uint256[] memory) { RebalancingBid.validatePlaceBid(_quantity); // Place bid and get back inflow and outflow arrays Rebalance.TokenFlow memory tokenFlow = liquidator.placeBid(_quantity); RebalancingBid.updateHasBiddedIfNecessary(); return Rebalance.decomposeTokenFlow(tokenFlow); } /* * After a successful rebalance, the new Set is issued. If there is a rebalance fee, * the fee is paid via inflation of the Rebalancing Set to the feeRecipient. * Full issuance functionality is now returned to set owners. * * Anyone can call this function. */ function settleRebalance() external { RebalancingSettlement.validateRebalancingSettlement(); uint256 issueQuantity = RebalancingSettlement.calculateSetIssueQuantity(nextSet); // Calculates fees and mints Rebalancing Set to the feeRecipient, increasing supply (uint256 feePercent, uint256 feeQuantity) = RebalancingSettlement.handleFees(); uint256 newUnitShares = RebalancingSettlement.calculateNextSetNewUnitShares(issueQuantity); // The unit shares must result in a quantity greater than the number of natural units outstanding require( newUnitShares > 0, "Failed: unitshares is 0." ); RebalancingSettlement.issueNextSet(issueQuantity); liquidator.settleRebalance(); // Rebalance index is the current vs next rebalance emit RebalanceSettled( feeRecipient, feeQuantity, feePercent, rebalanceIndex, issueQuantity, newUnitShares ); RebalancingSettlement.transitionToDefault(newUnitShares); } /* * Ends a rebalance if there are any signs that there is a failure. * Possible failure reasons: * 1. The rebalance has elapsed the failRebalancePeriod * 2. The liquidator responds that the rebalance has failed * * Move to Drawdown state if bids have been placed. Reset to Default state if no bids placed. */ function endFailedRebalance() public { RebalancingFailure.validateFailRebalance(); RebalancingLibrary.State newRebalanceState = RebalancingFailure.getNewRebalanceState(); liquidator.endFailedRebalance(); RebalancingFailure.transitionToNewState(newRebalanceState); } /* * Mint set token for given address. If there if is an entryFee, calculates the fee and mints * the rebalancing SetToken to the feeRecipient. * * Can only be called by Core contract. * * @param _issuer The address of the issuing account * @param _quantity The number of sets to attribute to issuer */ function mint( address _issuer, uint256 _quantity ) external { Issuance.validateMint(); uint256 issueQuantityNetOfFees = Issuance.handleEntryFees(_quantity); ERC20._mint(_issuer, issueQuantityNetOfFees); } /* * Burn set token for given address. Can only be called by authorized contracts. * * @param _from The address of the redeeming account * @param _quantity The number of sets to burn from redeemer */ function burn( address _from, uint256 _quantity ) external { Issuance.validateBurn(); ERC20._burn(_from, _quantity); } /* ============ Backwards Compatability ============ */ /* * Alias for endFailedRebalance */ function endFailedAuction() external { endFailedRebalance(); } } // File: contracts/core/tokens/RebalancingSetTokenV2Factory.sol /* Copyright 2019 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; /** * @title RebalancingSetTokenV2Factory * @author Set Protocol * * RebalancingSetTokenV2Factory is a smart contract used to deploy new RebalancingSetTokenV2 contracts. * RebalancingSetTokenV2s deployed by the factory can only have their mint and burn functions * called by Core */ contract RebalancingSetTokenV2Factory { using LibBytes for bytes; using Bytes32Library for bytes32; /* ============ State Variables ============ */ // Address of the Core contract used to verify factory when creating a Set ICore public core; // Address of the WhiteList contract used to verify the tokens in a rebalance proposal IWhiteList public rebalanceComponentWhitelist; // Whitelist contract for approved liquidators IWhiteList public liquidatorWhitelist; // Whitelist contract for approved fee calcualtors IWhiteList public feeCalculatorWhitelist; // Minimum amount of time between rebalances in seconds uint256 public minimumRebalanceInterval; // Minimum fail auction period uint256 public minimumFailRebalancePeriod; // Maximum fail auction period uint256 public maximumFailRebalancePeriod; // Minimum number for the token natural unit // The bounds are used for calculations of unitShares and in settlement uint256 public minimumNaturalUnit; // Maximum number for the token natural unit uint256 public maximumNaturalUnit; // ============ Structs ============ struct InitRebalancingParameters { address manager; ILiquidator liquidator; address feeRecipient; address rebalanceFeeCalculator; uint256 rebalanceInterval; uint256 rebalanceFailPeriod; uint256 lastRebalanceTimestamp; uint256 entryFee; bytes rebalanceFeeCalculatorData; } /* ============ Constructor ============ */ /** * Set core. Also requires a minimum rebalance interval and minimum proposal periods that are enforced * on RebalancingSetTokenV2 * * @param _core Address of deployed core contract * @param _componentWhitelist Address of component whitelist contract * @param _liquidatorWhitelist Address of liquidator whitelist contract * @param _feeCalculatorWhitelist Address of feeCalculator whitelist contract * @param _minimumRebalanceInterval Minimum amount of time between rebalances in seconds * @param _minimumNaturalUnit Minimum number for the token natural unit * @param _maximumNaturalUnit Maximum number for the token natural unit */ constructor( ICore _core, IWhiteList _componentWhitelist, IWhiteList _liquidatorWhitelist, IWhiteList _feeCalculatorWhitelist, uint256 _minimumRebalanceInterval, uint256 _minimumFailRebalancePeriod, uint256 _maximumFailRebalancePeriod, uint256 _minimumNaturalUnit, uint256 _maximumNaturalUnit ) public { core = _core; rebalanceComponentWhitelist = _componentWhitelist; liquidatorWhitelist = _liquidatorWhitelist; feeCalculatorWhitelist = _feeCalculatorWhitelist; minimumRebalanceInterval = _minimumRebalanceInterval; minimumFailRebalancePeriod = _minimumFailRebalancePeriod; maximumFailRebalancePeriod = _maximumFailRebalancePeriod; minimumNaturalUnit = _minimumNaturalUnit; maximumNaturalUnit = _maximumNaturalUnit; } /* ============ External Functions ============ */ /** * Deploys a new RebalancingSetTokenV2 contract, conforming to IFactory * Can only be called by core contracts. * * * | CallData | Location | * |----------------------------|-------------------------------| * | manager | 32 | * | liquidator | 64 | * | feeRecipient | 96 | * | rebalanceFeeCalculator | 128 | * | rebalanceInterval | 160 | * | rebalanceFailPeriod | 192 | * | entryFee | 224 | * | rebalanceFeeCalculatorData | 256 to end | * * @param _components The address of component tokens * @param _units The units of each component token * -- Unused natural unit parameters, passed in to conform to IFactory -- * @param _name The bytes32 encoded name of the new RebalancingSetTokenV2 * @param _symbol The bytes32 encoded symbol of the new RebalancingSetTokenV2 * @param _callData Byte string containing additional call parameters * * @return setToken The address of the newly created SetToken */ function createSet( address[] calldata _components, uint256[] calldata _units, uint256 _naturalUnit, bytes32 _name, bytes32 _symbol, bytes calldata _callData ) external returns (address) { require( msg.sender == address(core), "Sender must be core" ); // Ensure component array only includes one address which will be the currentSet require( _components.length == 1 && _units.length == 1, "Components & units must be len 1" ); require( _units[0] > 0, "UnitShares not > 0" ); address startingSet = _components[0]; // Expect Set to rebalance to be valid and enabled Set require( core.validSets(startingSet), "Invalid SetToken" ); require( _naturalUnit >= minimumNaturalUnit && _naturalUnit <= maximumNaturalUnit, "Invalid natural unit" ); InitRebalancingParameters memory parameters = parseRebalanceSetCallData(_callData); require( parameters.manager != address(0), "Invalid manager" ); // Require liquidator address is non-zero and is whitelisted by the liquidatorWhitelist require( address(parameters.liquidator) != address(0) && liquidatorWhitelist.whiteList(address(parameters.liquidator)), "Invalid liquidator" ); // Require rebalance fee is whitelisted by the liquidatorWhitelist require( feeCalculatorWhitelist.whiteList(address(parameters.rebalanceFeeCalculator)), "Invalid fee calculator" ); require( parameters.rebalanceInterval >= minimumRebalanceInterval, "Rebalance interval too short" ); require( parameters.rebalanceFailPeriod >= minimumFailRebalancePeriod && parameters.rebalanceFailPeriod <= maximumFailRebalancePeriod, "Invalid Fail Period" ); require( parameters.lastRebalanceTimestamp <= block.timestamp, "Invalid RebalanceTimestamp" ); address rebalancingSet = address( new RebalancingSetTokenV2( [ address(this), // factory parameters.manager, // manager address(parameters.liquidator), // liquidator startingSet, // initialSet address(rebalanceComponentWhitelist), // componentWhiteList address(liquidatorWhitelist), // liquidatorWhiteList parameters.feeRecipient, // feeRecipient parameters.rebalanceFeeCalculator // rebalanceFeeCalculator ], [ _units[0], // unitShares _naturalUnit, // naturalUnit parameters.rebalanceInterval, // rebalanceInterval parameters.rebalanceFailPeriod, // rebalanceFailPeriod parameters.lastRebalanceTimestamp, // lastRebalanceTimestamp parameters.entryFee // entryFee ], _name.bytes32ToString(), _symbol.bytes32ToString() ) ); // Initaializes the RebalancingSetToken IRebalancingSetTokenV2(rebalancingSet).initialize(parameters.rebalanceFeeCalculatorData); return rebalancingSet; } /* ============ Private Functions ============ */ function parseRebalanceSetCallData( bytes memory _callData ) private pure returns (InitRebalancingParameters memory) { InitRebalancingParameters memory parameters; assembly { mstore(parameters, mload(add(_callData, 32))) // manager mstore(add(parameters, 32), mload(add(_callData, 64))) // liquidator mstore(add(parameters, 64), mload(add(_callData, 96))) // feeRecipient mstore(add(parameters, 96), mload(add(_callData, 128))) // rebalanceFeeCalculator mstore(add(parameters, 128), mload(add(_callData, 160))) // rebalanceInterval mstore(add(parameters, 160), mload(add(_callData, 192))) // rebalanceFailPeriod mstore(add(parameters, 192), mload(add(_callData, 224))) // lastRebalanceTimestamp mstore(add(parameters, 224), mload(add(_callData, 256))) // entryFee } // Extracts the fee calculator data from the remaining calldata parameters.rebalanceFeeCalculatorData = _callData.slice(256, _callData.length); return parameters; } }
Deploys a new RebalancingSetTokenV2 contract, conforming to IFactory Can only be called by core contracts. | CallData | Location | |----------------------------|-------------------------------| | manager | 32 | | liquidator | 64 | | feeRecipient | 96 | | rebalanceFeeCalculator | 128 | | rebalanceInterval | 160 | | rebalanceFailPeriod | 192 | | entryFee | 224 | | rebalanceFeeCalculatorData | 256 to end | _components The address of component tokens _units The units of each component token -- Unused natural unit parameters, passed in to conform to IFactory -- _name The bytes32 encoded name of the new RebalancingSetTokenV2 _symbol The bytes32 encoded symbol of the new RebalancingSetTokenV2 _callData Byte string containing additional call parameters return setToken The address of the newly created SetToken/ Ensure component array only includes one address which will be the currentSet Expect Set to rebalance to be valid and enabled Set Require liquidator address is non-zero and is whitelisted by the liquidatorWhitelist Require rebalance fee is whitelisted by the liquidatorWhitelist Initaializes the RebalancingSetToken
function createSet( address[] calldata _components, uint256[] calldata _units, uint256 _naturalUnit, bytes32 _name, bytes32 _symbol, bytes calldata _callData ) external returns (address) { require( msg.sender == address(core), "Sender must be core" ); require( _components.length == 1 && _units.length == 1, "Components & units must be len 1" ); require( _units[0] > 0, "UnitShares not > 0" ); address startingSet = _components[0]; require( core.validSets(startingSet), "Invalid SetToken" ); require( _naturalUnit >= minimumNaturalUnit && _naturalUnit <= maximumNaturalUnit, "Invalid natural unit" ); InitRebalancingParameters memory parameters = parseRebalanceSetCallData(_callData); require( parameters.manager != address(0), "Invalid manager" ); require( address(parameters.liquidator) != address(0) && liquidatorWhitelist.whiteList(address(parameters.liquidator)), "Invalid liquidator" ); require( feeCalculatorWhitelist.whiteList(address(parameters.rebalanceFeeCalculator)), "Invalid fee calculator" ); require( parameters.rebalanceInterval >= minimumRebalanceInterval, "Rebalance interval too short" ); require( parameters.rebalanceFailPeriod >= minimumFailRebalancePeriod && parameters.rebalanceFailPeriod <= maximumFailRebalancePeriod, "Invalid Fail Period" ); require( parameters.lastRebalanceTimestamp <= block.timestamp, "Invalid RebalanceTimestamp" ); address rebalancingSet = address( new RebalancingSetTokenV2( [ ], [ ], _name.bytes32ToString(), _symbol.bytes32ToString() ) ); IRebalancingSetTokenV2(rebalancingSet).initialize(parameters.rebalanceFeeCalculatorData); return rebalancingSet; }
6,405,829
// SPDX-License-Identifier: MIT pragma solidity 0.8.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-upgradeable/utils/math/MathUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol"; import "../../SinglePlus.sol"; import "../../interfaces/IConverter.sol"; import "../../interfaces/curve/ICurveFi.sol"; import "../../interfaces/badger/IBadgerSett.sol"; import "../../interfaces/badger/IBadgerTree.sol"; import "../../interfaces/uniswap/IUniswapRouter.sol"; /** * @dev Single plus for Badger sBTCCrv. */ contract BadgerSBTCCrvPlus is SinglePlus { using SafeERC20Upgradeable for IERC20Upgradeable; address public constant BADGER_SBTCCRV = address(0xd04c48A53c111300aD41190D63681ed3dAd998eC); address public constant BADGER_TREE = address(0x660802Fc641b154aBA66a62137e71f331B6d787A); address public constant WBTC = address(0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599); address public constant WETH = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); address public constant BADGER = address(0x3472A5A71965499acd81997a54BBA8D852C6E53d); address public constant DIGG = address(0x798D1bE841a82a273720CE31c822C61a67a601C3); address public constant SBTCCRV = address(0x075b1bb99792c9E1041bA13afEf80C91a1e70fB3); address public constant UNISWAP = address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); // Uniswap RouterV2 address public constant SUSHISWAP = address(0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F); // Sushiswap RouterV2 address public constant SBTC_SWAP = address(0x7fC77b5c7614E1533320Ea6DDc2Eb61fa00A9714); // sBTC swap /** * We use a converter to convert sBTCCrv --> bsBTCCrv because bsBTCCrv has a whitelist. * Therefore, we use a converter to facilitate testing bsBTCCrv+. * Once bsBTCCrv+ is whitelisted, we will upgrade the contract to replace the converter. */ address public converter; /** * @dev Initializes bsBTCCrv+. */ function initialize(address _converter) public initializer { SinglePlus.initialize(BADGER_SBTCCRV, "", ""); converter = _converter; } /** * @dev Harvest additional yield from the investment. * Only governance or strategist can call this function. */ function harvest(address[] calldata _tokens, uint256[] calldata _cumulativeAmounts, uint256 _index, uint256 _cycle, bytes32[] calldata _merkleProof, uint256[] calldata _amountsToClaim) public virtual onlyStrategist { // 1. Harvest from Badger Tree IBadgerTree(BADGER_TREE).claim(_tokens, _cumulativeAmounts, _index, _cycle, _merkleProof, _amountsToClaim); // 2. Sushi: Badger --> WBTC uint256 _badger = IERC20Upgradeable(BADGER).balanceOf(address(this)); if (_badger > 0) { IERC20Upgradeable(BADGER).approve(SUSHISWAP, _badger); address[] memory _path = new address[](2); _path[0] = BADGER; _path[1] = WBTC; IUniswapRouter(SUSHISWAP).swapExactTokensForTokens(_badger, uint256(0), _path, address(this), block.timestamp); } // 3: Uniswap: Digg --> WBTC uint256 _digg = IERC20Upgradeable(DIGG).balanceOf(address(this)); if (_digg > 0) { IERC20Upgradeable(DIGG).approve(UNISWAP, _digg); address[] memory _path = new address[](2); _path[0] = DIGG; _path[1] = WBTC; IUniswapRouter(UNISWAP).swapExactTokensForTokens(_digg, uint256(0), _path, address(this), block.timestamp); } // 4: WBTC --> sBTCCrv uint256 _wbtc = IERC20Upgradeable(WBTC).balanceOf(address(this)); if (_wbtc == 0) return; // If there is performance fee, charged in WBTC uint256 _fee = 0; if (performanceFee > 0) { _fee = _wbtc * performanceFee / PERCENT_MAX; IERC20Upgradeable(WBTC).safeTransfer(treasury, _fee); _wbtc -= _fee; } IERC20Upgradeable(WBTC).approve(SBTC_SWAP, _wbtc); ICurveFi(SBTC_SWAP).add_liquidity([0, _wbtc, 0], 0); // 5: sBTCCrv --> bsBTCCrv address _converter = converter; uint256 _sBTCCrv = IERC20Upgradeable(SBTCCRV).balanceOf(address(this)); IERC20Upgradeable(SBTCCRV).approve(_converter, _sBTCCrv); uint256 _before = IERC20Upgradeable(BADGER_SBTCCRV).balanceOf(address(this)); uint256 _target = _sBTCCrv * WAD / IBadgerSett(BADGER_SBTCCRV).getPricePerFullShare(); IConverter(_converter).convert(SBTCCRV, BADGER_SBTCCRV, _sBTCCrv, _target); uint256 _after = IERC20Upgradeable(BADGER_SBTCCRV).balanceOf(address(this)); require(_after >= _before + _target, "convert fail"); // Also it's a good time to rebase! rebase(); emit Harvested(BADGER_SBTCCRV, _wbtc, _fee); } /** * @dev Returns the amount of single plus token is worth for one underlying token, expressed in WAD. */ function _conversionRate() internal view virtual override returns (uint256) { // Both Badger's share price and Curve's virtual price are in WAD return IBadgerSett(BADGER_SBTCCRV).getPricePerFullShare() * ICurveFi(SBTC_SWAP).get_virtual_price() / WAD; } }
Harvest additional yield from the investment. Only governance or strategist can call this function./ 1. Harvest from Badger Tree 2. Sushi: Badger --> WBTC
function harvest(address[] calldata _tokens, uint256[] calldata _cumulativeAmounts, uint256 _index, uint256 _cycle, bytes32[] calldata _merkleProof, uint256[] calldata _amountsToClaim) public virtual onlyStrategist { IBadgerTree(BADGER_TREE).claim(_tokens, _cumulativeAmounts, _index, _cycle, _merkleProof, _amountsToClaim); uint256 _badger = IERC20Upgradeable(BADGER).balanceOf(address(this)); if (_badger > 0) { IERC20Upgradeable(BADGER).approve(SUSHISWAP, _badger); address[] memory _path = new address[](2); _path[0] = BADGER; _path[1] = WBTC; IUniswapRouter(SUSHISWAP).swapExactTokensForTokens(_badger, uint256(0), _path, address(this), block.timestamp); } if (_digg > 0) { IERC20Upgradeable(DIGG).approve(UNISWAP, _digg); address[] memory _path = new address[](2); _path[0] = DIGG; _path[1] = WBTC; IUniswapRouter(UNISWAP).swapExactTokensForTokens(_digg, uint256(0), _path, address(this), block.timestamp); } if (_wbtc == 0) return; if (performanceFee > 0) { _fee = _wbtc * performanceFee / PERCENT_MAX; IERC20Upgradeable(WBTC).safeTransfer(treasury, _fee); _wbtc -= _fee; } IERC20Upgradeable(WBTC).approve(SBTC_SWAP, _wbtc); ICurveFi(SBTC_SWAP).add_liquidity([0, _wbtc, 0], 0); uint256 _sBTCCrv = IERC20Upgradeable(SBTCCRV).balanceOf(address(this)); IERC20Upgradeable(SBTCCRV).approve(_converter, _sBTCCrv); uint256 _before = IERC20Upgradeable(BADGER_SBTCCRV).balanceOf(address(this)); uint256 _target = _sBTCCrv * WAD / IBadgerSett(BADGER_SBTCCRV).getPricePerFullShare(); IConverter(_converter).convert(SBTCCRV, BADGER_SBTCCRV, _sBTCCrv, _target); uint256 _after = IERC20Upgradeable(BADGER_SBTCCRV).balanceOf(address(this)); require(_after >= _before + _target, "convert fail"); emit Harvested(BADGER_SBTCCRV, _wbtc, _fee); }
1,065,836