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/97/0xc204aD2e7B78b5B33a2606b8Fd0945963d7A30A5/sources/project_/contracts/ERC20Deflationary.sol
Performs all the functionalities that are enabled./ Burn Reflect
function _afterTokenTransfer(ValuesFromAmount memory values) internal virtual { if (_autoBurnEnabled) { _tokenBalances[address(this)] += values.tBurnFee; _reflectionBalances[address(this)] += values.rBurnFee; _approve(address(this), _msgSender(), values.tBurnFee); burnFrom(address(this), values.tBurnFee); } if (_rewardEnabled) { _distributeFee(values.rRewardFee, values.tRewardFee); } }
3,288,485
./full_match/137/0xa4f9BDcD96C48A276Cc686870A3e0d2de534Ba57/sources/ArkenDexV3.sol
performs chained getAmountIn calculations on any number of pairs
function getAmountsIn( address factory, uint256 amountOut, address[] memory path, uint256 amountAfterFee ) 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] ); amounts[i - 1] = getAmountIn( amounts[i], reserveIn, reserveOut, amountAfterFee ); } }
3,738,334
pragma solidity ^0.4.21; 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 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; } } /// @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens /// @author Dieter Shirley <<span class="__cf_email__" data-cfemail="c5a1a0b1a085a4bdacaaa8bfa0abeba6aa">[email&#160;protected]</span>> (https://github.com/dete) contract ERC721 { // Required methods function totalSupply() public view returns (uint256 total); function balanceOf(address _owner) public view returns (uint256 balance); function ownerOf(uint256 _tokenId) public view returns (address owner); function approve(address _to, uint256 _tokenId) public; function transfer(address _to, uint256 _tokenId) public; function transferFrom(address _from, address _to, uint256 _tokenId) public; // Events event Transfer(address from, address to, uint256 tokenId); event Approval(address owner, address approved, uint256 tokenId); // Optional function name() public view returns (string name); function symbol() public view returns (string symbol); // function tokensOfOwner(address _owner) external view returns (uint256[] tokenIds); // function tokenMetadata(uint256 _tokenId, string _preferredTransport) public view returns (string infoUrl); // ERC-165 Compatibility (https://github.com/ethereum/EIPs/issues/165) // function supportsInterface(bytes4 _interfaceID) external view returns (bool); } contract SmartSignature is ERC721{ using SafeMath for uint256; event Bought (uint256 indexed _tokenId, address indexed _owner, uint256 _price); event Sold (uint256 indexed _tokenId, address indexed _owner, uint256 _price); event Transfer(address indexed _from, address indexed _to, uint256 _tokenId); event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId); address private owner; uint256 counter; mapping (uint256 => address) private ownerOfToken; mapping (uint256 => uint256) private priceOfToken; mapping (uint256 => address) private approvedOfToken; mapping (uint256 => address) private creatorOfToken; mapping (uint256 => uint256) private parentOfToken; mapping (uint256 => uint256) private balanceOfToken; mapping (uint256 => uint256) private free1OfToken; mapping (uint256 => uint256) private free2OfToken; function SmartSignature () public { owner = msg.sender; creatorOfToken[counter] = ownerOfToken[counter] = msg.sender; priceOfToken[counter] = 1 ether; parentOfToken[counter] = 0; free1OfToken[counter] = 0; free2OfToken[counter] = 0; counter += 1; } /* Modifiers */ modifier onlyOwner(uint256 _tokenId) { require(ownerOfToken[_tokenId] == msg.sender); _; } modifier onlyCreator(uint256 _tokenId) { require(creatorOfToken[_tokenId] == msg.sender); _; } modifier onlyRoot() { require(creatorOfToken[0] == msg.sender); _; } /* Owner */ function setCreator (address _creator, uint _tokenId) onlyCreator(_tokenId) public { creatorOfToken[_tokenId] = _creator; } /* Judge Fake Token */ function judgeFakeToken (uint256 _tokenId) onlyRoot() public { creatorOfToken[_tokenId] = msg.sender; } function judgeFakeTokenAndTransfer (uint256 _tokenId, address _plaintiff) onlyRoot() public { creatorOfToken[_tokenId] = _plaintiff; } /* Withdraw */ function withdrawAllFromRoot () onlyRoot() public { uint256 t = balanceOfToken[0]; balanceOfToken[0] = 0; msg.sender.transfer(t); } function withdrawAllFromToken (uint256 _tokenId) onlyCreator(_tokenId) public { uint256 t = balanceOfToken[_tokenId]; uint256 r = t / 20; balanceOfToken[_tokenId] = 0; balanceOfToken[parentOfToken[_tokenId]] += r; msg.sender.transfer(t - r); } function withdrawAmountFromToken (uint256 _tokenId, uint256 t) onlyCreator(_tokenId) public { if (t > balanceOfToken[_tokenId]) t = balanceOfToken[_tokenId]; uint256 r = t / 20; balanceOfToken[_tokenId] = 0; balanceOfToken[parentOfToken[_tokenId]] += r; msg.sender.transfer(t - r); } function withdrawAll() public { require(msg.sender == owner); owner.transfer(this.balance); } /* Buying */ function calculateNextPrice (uint256 _price) public view returns (uint256 _nextPrice) { return _price.mul(117).div(98); } function calculateDevCut (uint256 _price) public view returns (uint256 _devCut) { return _price.div(20); // 5% } function buy (uint256 _tokenId) payable public { require(priceOf(_tokenId) > 0); require(ownerOf(_tokenId) != address(0)); require(msg.value >= priceOf(_tokenId)); require(ownerOf(_tokenId) != msg.sender); require(!isContract(msg.sender)); require(msg.sender != address(0)); require(now >= free1OfToken[_tokenId]); address oldOwner = ownerOf(_tokenId); address newOwner = msg.sender; uint256 price = priceOf(_tokenId); uint256 excess = msg.value.sub(price); _transfer(oldOwner, newOwner, _tokenId); priceOfToken[_tokenId] = nextPriceOf(_tokenId); Bought(_tokenId, newOwner, price); Sold(_tokenId, oldOwner, price); // Devevloper&#39;s cut which is left in contract and accesed by // `withdrawAll` and `withdrawAmountTo` methods. uint256 devCut = calculateDevCut(price); // Transfer payment to old owner minus the developer&#39;s cut. oldOwner.transfer(price.sub(devCut)); uint256 shareHolderCut = devCut.div(20); ownerOfToken[parentOfToken[_tokenId]].transfer(shareHolderCut); balanceOfToken[_tokenId] += devCut.sub(shareHolderCut); if (excess > 0) { newOwner.transfer(excess); } } /* ERC721 */ function name() public view returns (string name) { return "smartsignature.io"; } function symbol() public view returns (string symbol) { return "SSI"; } function totalSupply() public view returns (uint256 _totalSupply) { return counter; } function balanceOf (address _owner) public view returns (uint256 _balance) { uint256 t = 0; for (uint256 i = 0; i < counter; i++) { if (ownerOf(i) == _owner) { t++; } } return t; } function ownerOf (uint256 _tokenId) public view returns (address _owner) { return ownerOfToken[_tokenId]; } function creatorOf (uint256 _tokenId) public view returns (address _creator) { return creatorOfToken[_tokenId]; } function parentOf (uint256 _tokenId) public view returns (uint256 _parent) { return parentOfToken[_tokenId]; } function free1Of (uint256 _tokenId) public view returns (uint256 _free) { return free1OfToken[_tokenId]; } function free2Of (uint256 _tokenId) public view returns (uint256 _free) { return free2OfToken[_tokenId]; } function balanceFromToken (uint256 _tokenId) public view returns (uint256 _balance) { return balanceOfToken[_tokenId]; } function tokensOf (address _owner) public view returns (uint256[] _tokenIds) { uint256[] memory tokens = new uint256[](balanceOf(_owner)); uint256 tokenCounter = 0; for (uint256 i = 0; i < counter; i++) { if (ownerOf(i) == _owner) { tokens[tokenCounter] = i; tokenCounter += 1; } } return tokens; } function tokenExists (uint256 _tokenId) public view returns (bool _exists) { return priceOf(_tokenId) > 0; } function approvedFor(uint256 _tokenId) public view returns (address _approved) { return approvedOfToken[_tokenId]; } function approve(address _to, uint256 _tokenId) public { require(msg.sender != _to); require(tokenExists(_tokenId)); require(ownerOf(_tokenId) == msg.sender); if (_to == 0) { if (approvedOfToken[_tokenId] != 0) { delete approvedOfToken[_tokenId]; Approval(msg.sender, 0, _tokenId); } } else { approvedOfToken[_tokenId] = _to; Approval(msg.sender, _to, _tokenId); } } /* Transferring a country to another owner will entitle the new owner the profits from `buy` */ function transfer(address _to, uint256 _tokenId) public { require(msg.sender == ownerOf(_tokenId)); _transfer(msg.sender, _to, _tokenId); } function transferFrom(address _from, address _to, uint256 _tokenId) public { require(approvedFor(_tokenId) == msg.sender); _transfer(_from, _to, _tokenId); } function _transfer(address _from, address _to, uint256 _tokenId) internal { require(tokenExists(_tokenId)); require(ownerOf(_tokenId) == _from); require(_to != address(0)); require(_to != address(this)); ownerOfToken[_tokenId] = _to; approvedOfToken[_tokenId] = 0; Transfer(_from, _to, _tokenId); } /* Read */ function priceOf (uint256 _tokenId) public view returns (uint256 _price) { return priceOfToken[_tokenId]; } function nextPriceOf (uint256 _tokenId) public view returns (uint256 _nextPrice) { return calculateNextPrice(priceOf(_tokenId)); } function allOf (uint256 _tokenId) external view returns (address _owner, address _creator, uint256 _price, uint256 _nextPrice) { return (ownerOfToken[_tokenId], creatorOfToken[_tokenId], priceOfToken[_tokenId], nextPriceOf(_tokenId)); } /* Util */ function isContract(address addr) internal view returns (bool) { uint size; assembly { size := extcodesize(addr) } // solium-disable-line return size > 0; } function changePrice(uint256 _tokenId, uint256 _price, uint256 _frozen1, uint256 _frozen2) onlyOwner(_tokenId) public { require(now >= free2OfToken[_tokenId]); priceOfToken[_tokenId] = _price; free1OfToken[_tokenId] = now + _frozen1; free2OfToken[_tokenId] = now + _frozen1 + _frozen2; } function issueToken(uint256 _price, uint256 _frozen1, uint256 _frozen2, uint256 _parent) public { require(_parent <= counter); creatorOfToken[counter] = ownerOfToken[counter] = msg.sender; priceOfToken[counter] = _price; parentOfToken[counter] = _parent; free1OfToken[counter] = now + _frozen1; free2OfToken[counter] = now + _frozen1 + _frozen2; counter += 1; } }
Devevloper&39;s cut which is left in contract and accesed by `withdrawAll` and `withdrawAmountTo` methods. Transfer payment to old owner minus the developer&39;s cut.
function buy (uint256 _tokenId) payable public { require(priceOf(_tokenId) > 0); require(ownerOf(_tokenId) != address(0)); require(msg.value >= priceOf(_tokenId)); require(ownerOf(_tokenId) != msg.sender); require(!isContract(msg.sender)); require(msg.sender != address(0)); require(now >= free1OfToken[_tokenId]); address oldOwner = ownerOf(_tokenId); address newOwner = msg.sender; uint256 price = priceOf(_tokenId); uint256 excess = msg.value.sub(price); _transfer(oldOwner, newOwner, _tokenId); priceOfToken[_tokenId] = nextPriceOf(_tokenId); Bought(_tokenId, newOwner, price); Sold(_tokenId, oldOwner, price); uint256 devCut = calculateDevCut(price); oldOwner.transfer(price.sub(devCut)); uint256 shareHolderCut = devCut.div(20); ownerOfToken[parentOfToken[_tokenId]].transfer(shareHolderCut); balanceOfToken[_tokenId] += devCut.sub(shareHolderCut); if (excess > 0) { newOwner.transfer(excess); } }
6,644,908
// SPDX-License-Identifier: MIT // From https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/GSN/Context.sol // Subject to the MIT license. 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; } } // SPDX-License-Identifier: MIT // From https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/EnumerableSet.sol // Subject to the MIT license. 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(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(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(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(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.5.0; interface IERC20 { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function decimals() external view 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); } // SPDX-License-Identifier: MIT // From https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/access/Ownable.sol // Subject to the MIT license. pragma solidity >=0.6.0 <0.8.0; import "./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 () internal { 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; } } // SPDX-License-Identifier: MIT // From https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/ReentrancyGuard.sol // Subject to the MIT license. 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 // From https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/math/SafeMath.sol // Subject to the MIT license. 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, 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; } } // SPDX-License-Identifier: MIT // Generates SpacePort contracts and registers them in the SpaceFactory pragma solidity 0.6.12; import "./Spaceportv1.sol"; import "./SafeMath.sol"; import "./Ownable.sol"; import "./IERC20.sol"; import "./TransferHelper.sol"; import "./SpaceportHelper.sol"; interface ISpaceportFactory { function registerSpaceport (address _spaceportAddress) external; function spaceportIsRegistered(address _spaceportAddress) external view returns (bool); } interface IPlasmaswapLocker { function lockLPToken (address _lpToken, uint256 _amount, uint256 _unlock_date, address payable _withdrawer) external payable; } contract SpaceportGeneratorv1 is Ownable { using SafeMath for uint256; ISpaceportFactory public SPACEPORT_FACTORY; ISpaceportSettings public SPACEPORT_SETTINGS; struct SpaceportParams { uint256 amount; // the amount of spaceport tokens up for presale uint256 tokenPrice; // 1 base token = ? s_tokens, fixed price uint256 maxSpendPerBuyer; // maximum base token BUY amount per account uint256 hardcap; uint256 softcap; uint256 liquidityPercent; // divided by 1000 uint256 listingRate; // sale token listing price on plasmaswap uint256 startblock; uint256 endblock; uint256 lockPeriod; // unix timestamp -> e.g. 2 weeks } constructor() public { SPACEPORT_FACTORY = ISpaceportFactory(0x67019Edf7E115d17086e1660b577CAdccc57dFf3); SPACEPORT_SETTINGS = ISpaceportSettings(0x90De443BDC372f9aA944cF18fb6c82980807Cb0a); } /** * @notice Creates a new Spaceport contract and verify it in the SpaceportFactory.sol. */ function createSpaceport ( address payable _spaceportOwner, IERC20 _spaceportToken, IERC20 _baseToken, uint256[10] memory uint_params, uint256[2] memory vesting_params ) public payable { SpaceportParams memory params; params.amount = uint_params[0]; params.tokenPrice = uint_params[1]; params.maxSpendPerBuyer = uint_params[2]; params.hardcap = uint_params[3]; params.softcap = uint_params[4]; params.liquidityPercent = uint_params[5]; params.listingRate = uint_params[6]; params.startblock = uint_params[7]; params.endblock = uint_params[8]; params.lockPeriod = uint_params[9]; if (params.lockPeriod < 4 weeks) { params.lockPeriod = 4 weeks; } // Charge ETH fee for contract creation require(msg.value == SPACEPORT_SETTINGS.getEthCreationFee(), 'FEE NOT MET'); SPACEPORT_SETTINGS.getEthAddress().transfer(SPACEPORT_SETTINGS.getEthCreationFee()); require(params.amount >= 10000, 'MIN DIVIS'); // minimum divisibility require(params.endblock.sub(params.startblock) <= SPACEPORT_SETTINGS.getMaxSpaceportLength()); require(params.tokenPrice.mul(params.hardcap) > 0, 'INVALID PARAMS'); // ensure no overflow for future calculations require(params.liquidityPercent >= 300 && params.liquidityPercent <= 1000, 'MIN LIQUIDITY'); // 30% minimum liquidity lock uint256 tokensRequiredForSpaceport = SpaceportHelper.calculateAmountRequired(params.amount, params.tokenPrice, params.listingRate, params.liquidityPercent, SPACEPORT_SETTINGS.getTokenFee()); Spaceportv1 newSpaceport = new Spaceportv1(address(this)); TransferHelper.safeTransferFrom(address(_spaceportToken), address(msg.sender), address(newSpaceport), tokensRequiredForSpaceport); newSpaceport.init1(_spaceportOwner, params.amount, params.tokenPrice, params.maxSpendPerBuyer, params.hardcap, params.softcap, params.liquidityPercent, params.listingRate, params.startblock, params.endblock, params.lockPeriod); newSpaceport.init2(_baseToken, _spaceportToken, SPACEPORT_SETTINGS.getBaseFee(), SPACEPORT_SETTINGS.getTokenFee(), SPACEPORT_SETTINGS.getEthAddress(), SPACEPORT_SETTINGS.getTokenAddress(), vesting_params[0], vesting_params[1]); SPACEPORT_FACTORY.registerSpaceport(address(newSpaceport)); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "./SafeMath.sol"; library SpaceportHelper { using SafeMath for uint256; function calculateAmountRequired (uint256 _amount, uint256 _tokenPrice, uint256 _listingRate, uint256 _liquidityPercent, uint256 _tokenFee) public pure returns (uint256) { uint256 listingRatePercent = _listingRate.mul(1000).div(_tokenPrice); uint256 plfiTokenFee = _amount.mul(_tokenFee).div(1000); uint256 amountMinusFee = _amount.sub(plfiTokenFee); uint256 liquidityRequired = amountMinusFee.mul(_liquidityPercent).mul(listingRatePercent).div(1000000); uint256 tokensRequiredForSpaceport = _amount.add(liquidityRequired).add(plfiTokenFee); return tokensRequiredForSpaceport; } } // SPDX-License-Identifier: MIT // SpacePort v.1 pragma solidity 0.6.12; import "./TransferHelper.sol"; import "./EnumerableSet.sol"; import "./SafeMath.sol"; import "./ReentrancyGuard.sol"; import "./IERC20.sol"; interface IPlasmaswapFactory { function getPair(address tokenA, address tokenB) external view returns (address pair); function createPair(address tokenA, address tokenB) external returns (address pair); } interface ISpaceportLockForwarder { function lockLiquidity (IERC20 _baseToken, IERC20 _saleToken, uint256 _baseAmount, uint256 _saleAmount, uint256 _unlock_date, address payable _withdrawer) external; function plasmaswapPairIsInitialised (address _token0, address _token1) external view returns (bool); } interface IWETH { function deposit() external payable; function transfer(address to, uint value) external returns (bool); function withdraw(uint) external; } interface ISpaceportSettings { function getMaxSpaceportLength () external view returns (uint256); function getRound1Length () external view returns (uint256); function userHoldsSufficientRound1Token (address _user) external view returns (bool); function getBaseFee () external view returns (uint256); function getTokenFee () external view returns (uint256); function getEthAddress () external view returns (address payable); function getTokenAddress () external view returns (address payable); function getEthCreationFee () external view returns (uint256); } contract Spaceportv1 is ReentrancyGuard { using SafeMath for uint256; using EnumerableSet for EnumerableSet.AddressSet; event spaceportUserDeposit(uint256 value); event spaceportUserWithdrawTokens(uint256 value); event spaceportUserWithdrawBaseTokens(uint256 value); event spaceportOwnerWithdrawTokens(); event spaceportAddLiquidity(); event spaceportForceFailIfPairExists(); event spaceportForceFailByPlfi(); event spaceportUpdateBlocks(uint256 start, uint256 end); /// @notice Spaceport Contract Version, used to choose the correct ABI to decode the contract uint256 public CONTRACT_VERSION = 1; struct SpaceportInfo { address payable SPACEPORT_OWNER; IERC20 S_TOKEN; // sale token IERC20 B_TOKEN; // base token // usually WETH (ETH) uint256 TOKEN_PRICE; // 1 base token = ? s_tokens, fixed price uint256 MAX_SPEND_PER_BUYER; // maximum base token BUY amount per account uint256 AMOUNT; // the amount of spaceport tokens up for presale uint256 HARDCAP; uint256 SOFTCAP; uint256 LIQUIDITY_PERCENT; // divided by 1000 - to be locked ! uint256 LISTING_RATE; // fixed rate at which the token will list on plasmaswap - start rate uint256 START_BLOCK; uint256 END_BLOCK; uint256 LOCK_PERIOD; // unix timestamp -> e.g. 2 weeks bool SPACEPORT_IN_ETH; // if this flag is true the Spaceport is raising ETH, otherwise an ERC20 token such as DAI } struct SpaceportVesting { uint256 vestingCliff; uint256 vestingEnd; } struct SpaceportFeeInfo { uint256 PLFI_BASE_FEE; // divided by 1000 uint256 PLFI_TOKEN_FEE; // divided by 1000 address payable BASE_FEE_ADDRESS; address payable TOKEN_FEE_ADDRESS; } struct SpaceportStatus { bool WHITELIST_ONLY; // if set to true only whitelisted members may participate bool LP_GENERATION_COMPLETE; // final flag required to end a Spaceport and enable withdrawls bool FORCE_FAILED; // set this flag to force fail the Spaceport uint256 TOTAL_BASE_COLLECTED; // total base currency raised (usually ETH) uint256 TOTAL_TOKENS_SOLD; // total Spaceport tokens sold uint256 TOTAL_TOKENS_WITHDRAWN; // total tokens withdrawn post successful Spaceport uint256 TOTAL_BASE_WITHDRAWN; // total base tokens withdrawn on Spaceport failure uint256 ROUND1_LENGTH; // in blocks uint256 NUM_BUYERS; // number of unique participants uint256 LP_GENERATION_COMPLETE_TIME; // the date when LP is done } struct BuyerInfo { uint256 baseDeposited; // total base token (usually ETH) deposited by user, can be withdrawn on presale failure uint256 tokensOwed; // num Spaceport tokens a user is owed, can be withdrawn on presale success uint256 tokensClaimed; uint256 lastUpdate; } SpaceportVesting public SPACEPORT_VESTING; SpaceportInfo public SPACEPORT_INFO; SpaceportFeeInfo public SPACEPORT_FEE_INFO; SpaceportStatus public STATUS; address public SPACEPORT_GENERATOR; ISpaceportLockForwarder public SPACEPORT_LOCK_FORWARDER; ISpaceportSettings public SPACEPORT_SETTINGS; address PLFI_DEV_ADDRESS; IPlasmaswapFactory public PLASMASWAP_FACTORY; IWETH public WETH; mapping(address => BuyerInfo) public BUYERS; EnumerableSet.AddressSet private WHITELIST; constructor(address _spaceportGenerator) public { SPACEPORT_GENERATOR = _spaceportGenerator; PLASMASWAP_FACTORY = IPlasmaswapFactory(0xd87Ad19db2c4cCbf897106dE034D52e3DD90ea60); WETH = IWETH(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); SPACEPORT_SETTINGS = ISpaceportSettings(0x90De443BDC372f9aA944cF18fb6c82980807Cb0a); SPACEPORT_LOCK_FORWARDER = ISpaceportLockForwarder(0x5AD2A6181B1bc6aCAbd7bad268102d68DE54A4eE); PLFI_DEV_ADDRESS = 0x37CB8941348f04E783f67E19AD937f48DD7355D9; } function init1 ( address payable _spaceportOwner, uint256 _amount, uint256 _tokenPrice, uint256 _maxEthPerBuyer, uint256 _hardcap, uint256 _softcap, uint256 _liquidityPercent, uint256 _listingRate, uint256 _startblock, uint256 _endblock, uint256 _lockPeriod ) external { require(msg.sender == SPACEPORT_GENERATOR, 'FORBIDDEN'); SPACEPORT_INFO.SPACEPORT_OWNER = _spaceportOwner; SPACEPORT_INFO.AMOUNT = _amount; SPACEPORT_INFO.TOKEN_PRICE = _tokenPrice; SPACEPORT_INFO.MAX_SPEND_PER_BUYER = _maxEthPerBuyer; SPACEPORT_INFO.HARDCAP = _hardcap; SPACEPORT_INFO.SOFTCAP = _softcap; SPACEPORT_INFO.LIQUIDITY_PERCENT = _liquidityPercent; SPACEPORT_INFO.LISTING_RATE = _listingRate; SPACEPORT_INFO.START_BLOCK = _startblock; SPACEPORT_INFO.END_BLOCK = _endblock; SPACEPORT_INFO.LOCK_PERIOD = _lockPeriod; } function init2 ( IERC20 _baseToken, IERC20 _spaceportToken, uint256 _plfiBaseFee, uint256 _plfiTokenFee, address payable _baseFeeAddress, address payable _tokenFeeAddress, uint256 _vestingCliff, uint256 _vestingEnd ) external { require(msg.sender == SPACEPORT_GENERATOR, 'FORBIDDEN'); // require(!SPACEPORT_LOCK_FORWARDER.plasmaswapPairIsInitialised(address(_spaceportToken), address(_baseToken)), 'PAIR INITIALISED'); SPACEPORT_INFO.SPACEPORT_IN_ETH = address(_baseToken) == address(WETH); SPACEPORT_INFO.S_TOKEN = _spaceportToken; SPACEPORT_INFO.B_TOKEN = _baseToken; SPACEPORT_FEE_INFO.PLFI_BASE_FEE = _plfiBaseFee; SPACEPORT_FEE_INFO.PLFI_TOKEN_FEE = _plfiTokenFee; SPACEPORT_FEE_INFO.BASE_FEE_ADDRESS = _baseFeeAddress; SPACEPORT_FEE_INFO.TOKEN_FEE_ADDRESS = _tokenFeeAddress; STATUS.ROUND1_LENGTH = SPACEPORT_SETTINGS.getRound1Length(); SPACEPORT_VESTING.vestingCliff = _vestingCliff; SPACEPORT_VESTING.vestingEnd = _vestingEnd; } modifier onlySpaceportOwner() { require(SPACEPORT_INFO.SPACEPORT_OWNER == msg.sender, "NOT SPACEPORT OWNER"); _; } function spaceportStatus () public view returns (uint256) { if (STATUS.FORCE_FAILED) { return 3; // FAILED - force fail } if ((block.number > SPACEPORT_INFO.END_BLOCK) && (STATUS.TOTAL_BASE_COLLECTED < SPACEPORT_INFO.SOFTCAP)) { return 3; // FAILED - softcap not met by end block } if (STATUS.TOTAL_BASE_COLLECTED >= SPACEPORT_INFO.HARDCAP) { return 2; // SUCCESS - hardcap met } if ((block.number > SPACEPORT_INFO.END_BLOCK) && (STATUS.TOTAL_BASE_COLLECTED >= SPACEPORT_INFO.SOFTCAP)) { return 2; // SUCCESS - endblock and soft cap reached } if ((block.number >= SPACEPORT_INFO.START_BLOCK) && (block.number <= SPACEPORT_INFO.END_BLOCK)) { return 1; // ACTIVE - deposits enabled } return 0; // QUED - awaiting start block } // accepts msg.value for eth or _amount for ERC20 tokens function userDeposit (uint256 _amount) external payable nonReentrant { require(spaceportStatus() == 1, 'NOT ACTIVE'); // ACTIVE if (STATUS.WHITELIST_ONLY) { require(WHITELIST.contains(msg.sender), 'NOT WHITELISTED'); } // Spaceport Round 1 - require participant to hold a certain token and balance if (block.number < SPACEPORT_INFO.START_BLOCK + STATUS.ROUND1_LENGTH) { // 276 blocks = 1 hour require(SPACEPORT_SETTINGS.userHoldsSufficientRound1Token(msg.sender), 'INSUFFICENT ROUND 1 TOKEN BALANCE'); } BuyerInfo storage buyer = BUYERS[msg.sender]; uint256 amount_in = SPACEPORT_INFO.SPACEPORT_IN_ETH ? msg.value : _amount; uint256 allowance = SPACEPORT_INFO.MAX_SPEND_PER_BUYER.sub(buyer.baseDeposited); uint256 remaining = SPACEPORT_INFO.HARDCAP - STATUS.TOTAL_BASE_COLLECTED; allowance = allowance > remaining ? remaining : allowance; if (amount_in > allowance) { amount_in = allowance; } uint256 tokensSold = amount_in.mul(SPACEPORT_INFO.TOKEN_PRICE).div(10 ** uint256(SPACEPORT_INFO.B_TOKEN.decimals())); require(tokensSold > 0, 'ZERO TOKENS'); if (buyer.baseDeposited == 0) { STATUS.NUM_BUYERS++; } buyer.baseDeposited = buyer.baseDeposited.add(amount_in); buyer.tokensOwed = buyer.tokensOwed.add(tokensSold); buyer.lastUpdate = block.timestamp; STATUS.TOTAL_BASE_COLLECTED = STATUS.TOTAL_BASE_COLLECTED.add(amount_in); STATUS.TOTAL_TOKENS_SOLD = STATUS.TOTAL_TOKENS_SOLD.add(tokensSold); // return unused ETH if (SPACEPORT_INFO.SPACEPORT_IN_ETH && amount_in < msg.value) { msg.sender.transfer(msg.value.sub(amount_in)); } // deduct non ETH token from user if (!SPACEPORT_INFO.SPACEPORT_IN_ETH) { TransferHelper.safeTransferFrom(address(SPACEPORT_INFO.B_TOKEN), msg.sender, address(this), amount_in); } emit spaceportUserDeposit(amount_in); } // withdraw spaceport tokens // percentile withdrawls allows fee on transfer or rebasing tokens to still work function userWithdrawTokens () external nonReentrant { require(STATUS.LP_GENERATION_COMPLETE, 'AWAITING LP GENERATION'); BuyerInfo storage buyer = BUYERS[msg.sender]; require(STATUS.LP_GENERATION_COMPLETE_TIME + SPACEPORT_VESTING.vestingCliff < block.timestamp, "vesting cliff : not time yet"); if (buyer.lastUpdate < STATUS.LP_GENERATION_COMPLETE_TIME ) { buyer.lastUpdate = STATUS.LP_GENERATION_COMPLETE_TIME; } uint256 tokensOwed = 0; if(STATUS.LP_GENERATION_COMPLETE_TIME + SPACEPORT_VESTING.vestingEnd < block.timestamp) { tokensOwed = buyer.tokensOwed.sub(buyer.tokensClaimed); } else { tokensOwed = buyer.tokensOwed.mul(block.timestamp - buyer.lastUpdate).div(SPACEPORT_VESTING.vestingEnd); } buyer.lastUpdate = block.timestamp; buyer.tokensClaimed = buyer.tokensClaimed.add(tokensOwed); require(tokensOwed > 0, 'NOTHING TO CLAIM'); require(buyer.tokensClaimed <= buyer.tokensOwed, 'CLAIM TOKENS ERROR'); STATUS.TOTAL_TOKENS_WITHDRAWN = STATUS.TOTAL_TOKENS_WITHDRAWN.add(tokensOwed); TransferHelper.safeTransfer(address(SPACEPORT_INFO.S_TOKEN), msg.sender, tokensOwed); emit spaceportUserWithdrawTokens(tokensOwed); } // on spaceport failure // percentile withdrawls allows fee on transfer or rebasing tokens to still work function userWithdrawBaseTokens () external nonReentrant { require(spaceportStatus() == 3, 'NOT FAILED'); // FAILED BuyerInfo storage buyer = BUYERS[msg.sender]; uint256 baseRemainingDenominator = STATUS.TOTAL_BASE_COLLECTED.sub(STATUS.TOTAL_BASE_WITHDRAWN); uint256 remainingBaseBalance = SPACEPORT_INFO.SPACEPORT_IN_ETH ? address(this).balance : SPACEPORT_INFO.B_TOKEN.balanceOf(address(this)); uint256 tokensOwed = remainingBaseBalance.mul(buyer.baseDeposited).div(baseRemainingDenominator); require(tokensOwed > 0, 'NOTHING TO WITHDRAW'); STATUS.TOTAL_BASE_WITHDRAWN = STATUS.TOTAL_BASE_WITHDRAWN.add(buyer.baseDeposited); buyer.baseDeposited = 0; TransferHelper.safeTransferBaseToken(address(SPACEPORT_INFO.B_TOKEN), msg.sender, tokensOwed, !SPACEPORT_INFO.SPACEPORT_IN_ETH); emit spaceportUserWithdrawBaseTokens(tokensOwed); } // failure // allows the owner to withdraw the tokens they sent for presale & initial liquidity function ownerWithdrawTokens () external onlySpaceportOwner { require(spaceportStatus() == 3); // FAILED TransferHelper.safeTransfer(address(SPACEPORT_INFO.S_TOKEN), SPACEPORT_INFO.SPACEPORT_OWNER, SPACEPORT_INFO.S_TOKEN.balanceOf(address(this))); emit spaceportOwnerWithdrawTokens(); } // Can be called at any stage before or during the presale to cancel it before it ends. // If the pair already exists on plasmaswap and it contains the presale token as liquidity // the final stage of the presale 'addLiquidity()' will fail. This function // allows anyone to end the presale prematurely to release funds in such a case. function forceFailIfPairExists () external { require(!STATUS.LP_GENERATION_COMPLETE && !STATUS.FORCE_FAILED); if (SPACEPORT_LOCK_FORWARDER.plasmaswapPairIsInitialised(address(SPACEPORT_INFO.S_TOKEN), address(SPACEPORT_INFO.B_TOKEN))) { STATUS.FORCE_FAILED = true; emit spaceportForceFailIfPairExists(); } } // if something goes wrong in LP generation function forceFailByPlfi () external { require(msg.sender == PLFI_DEV_ADDRESS); STATUS.FORCE_FAILED = true; emit spaceportForceFailByPlfi(); } // on spaceport success, this is the final step to end the spaceport, lock liquidity and enable withdrawls of the sale token. // This function does not use percentile distribution. Rebasing mechanisms, fee on transfers, or any deflationary logic // are not taken into account at this stage to ensure stated liquidity is locked and the pool is initialised according to // the spaceport parameters and fixed prices. function addLiquidity() external nonReentrant { require(!STATUS.LP_GENERATION_COMPLETE, 'GENERATION COMPLETE'); require(spaceportStatus() == 2, 'NOT SUCCESS'); // SUCCESS // Fail the spaceport if the pair exists and contains spaceport token liquidity if (SPACEPORT_LOCK_FORWARDER.plasmaswapPairIsInitialised(address(SPACEPORT_INFO.S_TOKEN), address(SPACEPORT_INFO.B_TOKEN))) { STATUS.FORCE_FAILED = true; return; } uint256 plfiBaseFee = STATUS.TOTAL_BASE_COLLECTED.mul(SPACEPORT_FEE_INFO.PLFI_BASE_FEE).div(1000); // base token liquidity uint256 baseLiquidity = STATUS.TOTAL_BASE_COLLECTED.sub(plfiBaseFee).mul(SPACEPORT_INFO.LIQUIDITY_PERCENT).div(1000); if (SPACEPORT_INFO.SPACEPORT_IN_ETH) { WETH.deposit{value : baseLiquidity}(); } TransferHelper.safeApprove(address(SPACEPORT_INFO.B_TOKEN), address(SPACEPORT_LOCK_FORWARDER), baseLiquidity); // sale token liquidity uint256 tokenLiquidity = baseLiquidity.mul(SPACEPORT_INFO.LISTING_RATE).div(10 ** uint256(SPACEPORT_INFO.B_TOKEN.decimals())); TransferHelper.safeApprove(address(SPACEPORT_INFO.S_TOKEN), address(SPACEPORT_LOCK_FORWARDER), tokenLiquidity); SPACEPORT_LOCK_FORWARDER.lockLiquidity(SPACEPORT_INFO.B_TOKEN, SPACEPORT_INFO.S_TOKEN, baseLiquidity, tokenLiquidity, block.timestamp + SPACEPORT_INFO.LOCK_PERIOD, SPACEPORT_INFO.SPACEPORT_OWNER); // transfer fees uint256 plfiTokenFee = STATUS.TOTAL_TOKENS_SOLD.mul(SPACEPORT_FEE_INFO.PLFI_TOKEN_FEE).div(1000); TransferHelper.safeTransferBaseToken(address(SPACEPORT_INFO.B_TOKEN), SPACEPORT_FEE_INFO.BASE_FEE_ADDRESS, plfiBaseFee, !SPACEPORT_INFO.SPACEPORT_IN_ETH); TransferHelper.safeTransfer(address(SPACEPORT_INFO.S_TOKEN), SPACEPORT_FEE_INFO.TOKEN_FEE_ADDRESS, plfiTokenFee); // burn unsold tokens uint256 remainingSBalance = SPACEPORT_INFO.S_TOKEN.balanceOf(address(this)); if (remainingSBalance > STATUS.TOTAL_TOKENS_SOLD) { uint256 burnAmount = remainingSBalance.sub(STATUS.TOTAL_TOKENS_SOLD); TransferHelper.safeTransfer(address(SPACEPORT_INFO.S_TOKEN), 0x6Ad6fd6282cCe6eBB65Ab8aBCBD1ae5057D4B1DB, burnAmount); } // send remaining base tokens to spaceport owner uint256 remainingBaseBalance = SPACEPORT_INFO.SPACEPORT_IN_ETH ? address(this).balance : SPACEPORT_INFO.B_TOKEN.balanceOf(address(this)); TransferHelper.safeTransferBaseToken(address(SPACEPORT_INFO.B_TOKEN), SPACEPORT_INFO.SPACEPORT_OWNER, remainingBaseBalance, !SPACEPORT_INFO.SPACEPORT_IN_ETH); STATUS.LP_GENERATION_COMPLETE = true; STATUS.LP_GENERATION_COMPLETE_TIME = block.timestamp; emit spaceportAddLiquidity(); } function updateMaxSpendLimit(uint256 _maxSpend) external onlySpaceportOwner { SPACEPORT_INFO.MAX_SPEND_PER_BUYER = _maxSpend; } // postpone or bring a spaceport forward, this will only work when a presale is inactive. function updateBlocks(uint256 _startBlock, uint256 _endBlock) external onlySpaceportOwner { require(SPACEPORT_INFO.START_BLOCK > block.number); require(_endBlock.sub(_startBlock) <= SPACEPORT_SETTINGS.getMaxSpaceportLength()); SPACEPORT_INFO.START_BLOCK = _startBlock; SPACEPORT_INFO.END_BLOCK = _endBlock; emit spaceportUpdateBlocks(_startBlock, _endBlock); } // editable at any stage of the presale function setWhitelistFlag(bool _flag) external onlySpaceportOwner { STATUS.WHITELIST_ONLY = _flag; } // editable at any stage of the presale function editWhitelist(address[] memory _users, bool _add) external onlySpaceportOwner { if (_add) { for (uint i = 0; i < _users.length; i++) { WHITELIST.add(_users[i]); } } else { for (uint i = 0; i < _users.length; i++) { WHITELIST.remove(_users[i]); } } } // whitelist getters function getWhitelistedUsersLength () external view returns (uint256) { return WHITELIST.length(); } function getWhitelistedUserAtIndex (uint256 _index) external view returns (address) { return WHITELIST.at(_index); } function getUserWhitelistStatus (address _user) external view returns (bool) { return WHITELIST.contains(_user); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; /** helper methods for interacting with ERC20 tokens that do not consistently return true/false with the addition of a transfer function to send eth or an erc20 token */ library TransferHelper { function safeApprove(address token, address to, uint value) internal { (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 { (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 { (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'); } // sends ETH or an erc20 token function safeTransferBaseToken(address token, address payable to, uint value, bool isERC20) internal { if (!isERC20) { to.transfer(value); } else { (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED'); } } }
Can be called at any stage before or during the presale to cancel it before it ends. If the pair already exists on plasmaswap and it contains the presale token as liquidity the final stage of the presale 'addLiquidity()' will fail. This function allows anyone to end the presale prematurely to release funds in such a case.
function forceFailIfPairExists () external { require(!STATUS.LP_GENERATION_COMPLETE && !STATUS.FORCE_FAILED); if (SPACEPORT_LOCK_FORWARDER.plasmaswapPairIsInitialised(address(SPACEPORT_INFO.S_TOKEN), address(SPACEPORT_INFO.B_TOKEN))) { STATUS.FORCE_FAILED = true; emit spaceportForceFailIfPairExists(); } }
6,972,949
//Address: 0xad56c554f32d51526475d541f5deaabe1534854d //Contract name: GenevieveCrowdsale //Balance: 0 Ether //Verification Date: 1/20/2018 //Transacion Count: 205 // CODE STARTS HERE pragma solidity ^0.4.15; contract ContractReceiver { function tokenFallback(address _from, uint _value, bytes _data){ } } /* New ERC23 contract interface */ contract ERC223 { uint public totalSupply; function balanceOf(address who) constant returns (uint); function name() constant returns (string _name); function symbol() constant returns (string _symbol); function decimals() constant returns (uint8 _decimals); function totalSupply() constant returns (uint256 _supply); function transfer(address to, uint value) returns (bool ok); function transfer(address to, uint value, bytes data) returns (bool ok); function transfer(address to, uint value, bytes data, string custom_fallback) returns (bool ok); function transferFrom(address from, address to, uint256 value) returns (bool); event Transfer(address indexed from, address indexed to, uint value, bytes indexed data); } // The GXVC token ERC223 contract GXVCToken { // Token public variables string public name; string public symbol; uint8 public decimals; string public version = 'v0.2'; uint256 public totalSupply; bool locked; address rootAddress; address Owner; uint multiplier = 10000000000; // For 10 decimals address swapperAddress; // Can bypass a lock mapping(address => uint256) balances; mapping(address => mapping(address => uint256)) allowed; mapping(address => bool) freezed; event Transfer(address indexed from, address indexed to, uint value, bytes indexed data); event Approval(address indexed owner, address indexed spender, uint256 value); // Modifiers modifier onlyOwner() { if ( msg.sender != rootAddress && msg.sender != Owner ) revert(); _; } modifier onlyRoot() { if ( msg.sender != rootAddress ) revert(); _; } modifier isUnlocked() { if ( locked && msg.sender != rootAddress && msg.sender != Owner ) revert(); _; } modifier isUnfreezed(address _to) { if ( freezed[msg.sender] || freezed[_to] ) revert(); _; } // Safe math function safeAdd(uint x, uint y) internal returns (uint z) { require((z = x + y) >= x); } function safeSub(uint x, uint y) internal returns (uint z) { require((z = x - y) <= x); } // GXC Token constructor function GXVCToken() { locked = true; totalSupply = 160000000 * multiplier; // 160,000,000 tokens * 10 decimals name = 'Genevieve VC'; symbol = 'GXVC'; decimals = 10; rootAddress = msg.sender; Owner = msg.sender; balances[rootAddress] = totalSupply; allowed[rootAddress][swapperAddress] = totalSupply; } // ERC223 Access functions function name() constant returns (string _name) { return name; } function symbol() constant returns (string _symbol) { return symbol; } function decimals() constant returns (uint8 _decimals) { return decimals; } function totalSupply() constant returns (uint256 _totalSupply) { return totalSupply; } // Only root function function changeRoot(address _newrootAddress) onlyRoot returns(bool){ allowed[rootAddress][swapperAddress] = 0; // Removes allowance to old rootAddress rootAddress = _newrootAddress; allowed[_newrootAddress][swapperAddress] = totalSupply; // Gives allowance to new rootAddress return true; } // Only owner functions function changeOwner(address _newOwner) onlyOwner returns(bool){ Owner = _newOwner; return true; } function changeSwapperAdd(address _newSwapper) onlyOwner returns(bool){ allowed[rootAddress][swapperAddress] = 0; // Removes allowance to old rootAddress swapperAddress = _newSwapper; allowed[rootAddress][_newSwapper] = totalSupply; // Gives allowance to new rootAddress return true; } function unlock() onlyOwner returns(bool) { locked = false; return true; } function lock() onlyOwner returns(bool) { locked = true; return true; } function freeze(address _address) onlyOwner returns(bool) { freezed[_address] = true; return true; } function unfreeze(address _address) onlyOwner returns(bool) { freezed[_address] = false; return true; } function burn(uint256 _value) onlyOwner returns(bool) { bytes memory empty; if ( balances[msg.sender] < _value ) revert(); balances[msg.sender] = safeSub( balances[msg.sender] , _value ); totalSupply = safeSub( totalSupply, _value ); Transfer(msg.sender, 0x0, _value , empty); return true; } // Public getters function isFreezed(address _address) constant returns(bool) { return freezed[_address]; } function isLocked() constant returns(bool) { return locked; } // Public functions (from https://github.com/Dexaran/ERC223-token-standard/tree/Recommended) // Function that is called when a user or another contract wants to transfer funds to an address that has a non-standard fallback function function transfer(address _to, uint _value, bytes _data, string _custom_fallback) isUnlocked isUnfreezed(_to) returns (bool success) { if(isContract(_to)) { if (balances[msg.sender] < _value) return false; balances[msg.sender] = safeSub( balances[msg.sender] , _value ); balances[_to] = safeAdd( balances[_to] , _value ); ContractReceiver receiver = ContractReceiver(_to); receiver.call.value(0)(bytes4(sha3(_custom_fallback)), msg.sender, _value, _data); Transfer(msg.sender, _to, _value, _data); return true; } else { return transferToAddress(_to, _value, _data); } } // Function that is called when a user or another contract wants to transfer funds to an address with tokenFallback function function transfer(address _to, uint _value, bytes _data) isUnlocked isUnfreezed(_to) returns (bool success) { if(isContract(_to)) { return transferToContract(_to, _value, _data); } else { return transferToAddress(_to, _value, _data); } } // Standard function transfer similar to ERC20 transfer with no _data. // Added due to backwards compatibility reasons. function transfer(address _to, uint _value) isUnlocked isUnfreezed(_to) returns (bool success) { bytes memory empty; if(isContract(_to)) { return transferToContract(_to, _value, empty); } else { return transferToAddress(_to, _value, empty); } } //assemble the given address bytecode. If bytecode exists then the _addr is a contract. function isContract(address _addr) private returns (bool is_contract) { uint length; assembly { //retrieve the size of the code on target address, this needs assembly length := extcodesize(_addr) } return (length>0); } //function that is called when transaction target is an address function transferToAddress(address _to, uint _value, bytes _data) private returns (bool success) { if (balances[msg.sender] < _value) return false; balances[msg.sender] = safeSub(balances[msg.sender], _value); balances[_to] = safeAdd(balances[_to], _value); Transfer(msg.sender, _to, _value, _data); return true; } //function that is called when transaction target is a contract function transferToContract(address _to, uint _value, bytes _data) private returns (bool success) { if (balances[msg.sender] < _value) return false; balances[msg.sender] = safeSub(balances[msg.sender] , _value); balances[_to] = safeAdd(balances[_to] , _value); ContractReceiver receiver = ContractReceiver(_to); receiver.tokenFallback(msg.sender, _value, _data); Transfer(msg.sender, _to, _value, _data); return true; } function transferFrom(address _from, address _to, uint256 _value) public returns(bool) { if ( locked && msg.sender != swapperAddress ) return false; if ( freezed[_from] || freezed[_to] ) return false; // Check if destination address is freezed if ( balances[_from] < _value ) return false; // Check if the sender has enough if ( _value > allowed[_from][msg.sender] ) return false; // Check allowance balances[_from] = safeSub(balances[_from] , _value); // Subtract from the sender balances[_to] = safeAdd(balances[_to] , _value); // Add the same to the recipient allowed[_from][msg.sender] = safeSub( allowed[_from][msg.sender] , _value ); bytes memory empty; if ( isContract(_to) ) { ContractReceiver receiver = ContractReceiver(_to); receiver.tokenFallback(_from, _value, empty); } Transfer(_from, _to, _value , empty); return true; } function balanceOf(address _owner) constant returns(uint256 balance) { return balances[_owner]; } function approve(address _spender, uint _value) returns(bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) constant returns(uint256) { return allowed[_owner][_spender]; } } /** * @title Math * @dev Assorted math operations */ library Math { function max64(uint64 a, uint64 b) internal pure returns (uint64) { return a >= b ? a : b; } function min64(uint64 a, uint64 b) internal pure returns (uint64) { return a < b ? a : b; } function max256(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } function min256(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } } /** * @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 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 Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; Unpause(); } } contract Dec { function decimals() public view returns (uint8); } contract ERC20 { function transfer(address,uint256); } contract KeeToken { // Stub function icoBalanceOf(address from, address ico) external view returns (uint) ; } contract KeeHole { using SafeMath for uint256; KeeToken token; uint256 pos; uint256[] slots; uint256[] bonuses; uint256 threshold; uint256 maxTokensInTier; uint256 rate; uint256 tokenDiv; function KeeHole() public { token = KeeToken(0x72D32ac1c5E66BfC5b08806271f8eEF915545164); slots.push(100); slots.push(200); slots.push(500); slots.push(1200); bonuses.push(5); bonuses.push(3); bonuses.push(2); bonuses.push(1); threshold = 5; rate = 10000; tokenDiv = 100000000; // 10^18 / 10^10 maxTokensInTier = 25000 * (10 ** 10); } mapping (address => bool) hasParticipated; // getBonusAmount - calculates any bonus due. // only one bonus per account function getBonusAmount(uint256 amount) public returns (uint256 bonus) { if (hasParticipated[msg.sender]) return 0; if ( token.icoBalanceOf(msg.sender,this) < threshold ) return 0; if (pos>=slots.length) return 0; bonus = (amount.mul(bonuses[pos])).div(100); slots[pos]--; if (slots[pos] == 0) pos++; bonus = Math.min256(maxTokensInTier,bonus); hasParticipated[msg.sender] = true; return; } // this function is not const because it writes hasParticipated function getTokenAmount(uint256 ethDeposit) public returns (uint256 numTokens) { numTokens = (ethDeposit.mul(rate)).div(tokenDiv); numTokens = numTokens.add(getBonusAmount(numTokens)); } } contract GenevieveCrowdsale is Ownable, Pausable, KeeHole { using SafeMath for uint256; // The token being sold GXVCToken public token; KeeHole public keeCrytoken; // owner of GXVC tokens address public tokenSpender; // start and end times uint256 public startTimestamp; uint256 public endTimestamp; // address where funds are collected address public hardwareWallet; mapping (address => uint256) public deposits; uint256 public numberOfPurchasers; // how many token units a buyer gets per wei comes from keeUser // uint256 public rate; // amount of raised money in wei uint256 public weiRaised; uint256 public weiToRaise; uint256 public tokensSold; uint256 public minContribution = 1 finney; event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); event MainSaleClosed(); uint256 public weiRaisedInPresale = 0 ether; uint256 public tokensSoldInPresale = 0 * 10 ** 18; // REGISTRY FUNCTIONS mapping (address => bool) public registered; address public registrar; function setReg(address _newReg) external onlyOwner { registrar = _newReg; } function register(address participant) external { require(msg.sender == registrar); registered[participant] = true; } // END OF REGISTRY FUNCTIONS function setCoin(GXVCToken _coin) external onlyOwner { token = _coin; } function setWallet(address _wallet) external onlyOwner { hardwareWallet = _wallet; } function GenevieveCrowdsale() public { token = GXVCToken(0x22F0AF8D78851b72EE799e05F54A77001586B18A); startTimestamp = 1516453200; endTimestamp = 1519563600; hardwareWallet = 0x6Bc63d12D5AAEBe4dc86785053d7E4f09077b89E; tokensSoldInPresale = 0; // 187500 weiToRaise = 10000 * (10 ** 18); tokenSpender = 0x6835706E8e58544deb6c4EC59d9815fF6C20417f; // Bal = 104605839.665805634 GXVC minContribution = 1 finney; require(startTimestamp >= now); require(endTimestamp >= startTimestamp); } // check if valid purchase modifier validPurchase { // REGISTRY REQUIREMENT require(registered[msg.sender]); // END OF REGISTRY REQUIREMENT require(now >= startTimestamp); require(now < endTimestamp); require(msg.value >= minContribution); require(weiRaised.add(msg.value) <= weiToRaise); _; } // @return true if crowdsale event has ended function hasEnded() public constant returns (bool) { if (now > endTimestamp) return true; if (weiRaised >= weiToRaise.sub(minContribution)) return true; return false; } // low level token purchase function function buyTokens(address beneficiary, uint256 weiAmount) internal validPurchase whenNotPaused { require(beneficiary != 0x0); if (deposits[beneficiary] == 0) { numberOfPurchasers++; } deposits[beneficiary] = weiAmount.add(deposits[beneficiary]); // calculate token amount to be created uint256 tokens = getTokenAmount(weiAmount); // update state weiRaised = weiRaised.add(weiAmount); tokensSold = tokensSold.add(tokens); require(token.transferFrom(tokenSpender, beneficiary, tokens)); TokenPurchase(msg.sender, beneficiary, weiAmount, tokens); hardwareWallet.transfer(this.balance); } // fallback function can be used to buy tokens function () public payable { buyTokens(msg.sender,msg.value); } function emergencyERC20Drain( ERC20 theToken, uint amount ) { theToken.transfer(owner, amount); } }
Standard function transfer similar to ERC20 transfer with no _data. Added due to backwards compatibility reasons.
function transfer(address _to, uint _value) isUnlocked isUnfreezed(_to) returns (bool success) { bytes memory empty; if(isContract(_to)) { return transferToContract(_to, _value, empty); } else { return transferToAddress(_to, _value, empty); } }
7,278,554
pragma solidity 0.4.23; // // This source file is part of the current-contracts open source project // Copyright 2018 Zerion LLC // Licensed under Apache License v2.0 // // @title Abstract ERC20 token interface contract AbstractToken { function balanceOf(address owner) public view returns (uint256 balance); function transfer(address to, uint256 value) public returns (bool success); function transferFrom(address from, address to, uint256 value) public returns (bool success); function approve(address spender, uint256 value) public returns (bool success); 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 Owned { address public owner = msg.sender; address public potentialOwner; modifier onlyOwner { require(msg.sender == owner); _; } modifier onlyPotentialOwner { require(msg.sender == potentialOwner); _; } event NewOwner(address old, address current); event NewPotentialOwner(address old, address potential); function setOwner(address _new) public onlyOwner { emit NewPotentialOwner(owner, _new); potentialOwner = _new; } function confirmOwnership() public onlyPotentialOwner { emit NewOwner(owner, potentialOwner); owner = potentialOwner; potentialOwner = address(0); } } // @title SafeMath contract - Math operations with safety checks. // @author OpenZeppelin: https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/math/SafeMath.sol contract 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) { return a / b; } /** * @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; } /** * @dev Raises `a` to the `b`th power, throws on overflow. */ function pow(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a ** b; assert(c >= a); return c; } } /// Implements ERC 20 Token standard: https://github.com/ethereum/EIPs/issues/20 contract StandardToken is AbstractToken, Owned, SafeMath { /* * Data structures */ mapping (address => uint256) internal balances; mapping (address => mapping (address => uint256)) internal allowed; uint256 public totalSupply; /* * Read and write storage functions */ /// @dev Transfers sender's tokens to a given address. Returns success. /// @param _to Address of token receiver. /// @param _value Number of tokens to transfer. function transfer(address _to, uint256 _value) public returns (bool success) { return _transfer(msg.sender, _to, _value); } /// @dev Allows allowed third party to transfer tokens from one address to another. Returns success. /// @param _from Address from where tokens are withdrawn. /// @param _to Address to where tokens are sent. /// @param _value Number of tokens to transfer. function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(allowed[_from][msg.sender] >= _value); allowed[_from][msg.sender] -= _value; return _transfer(_from, _to, _value); } /// @dev Returns number of tokens owned by given address. /// @param _owner Address of token owner. function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } /// @dev Sets approved amount of tokens for spender. Returns success. /// @param _spender Address of allowed account. /// @param _value Number of approved tokens. function approve(address _spender, uint256 _value) public returns (bool success) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /* * Read storage functions */ /// @dev Returns number of allowed tokens for given address. /// @param _owner Address of token owner. /// @param _spender Address of token spender. function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return allowed[_owner][_spender]; } /** * @dev Private transfer, can only be called by this contract. * @param _from The address of the sender. * @param _to The address of the recipient. * @param _value The amount to send. * @return success True if the transfer was successful, or throws. */ function _transfer(address _from, address _to, uint256 _value) private returns (bool success) { require(_to != address(0)); require(balances[_from] >= _value); balances[_from] -= _value; balances[_to] = add(balances[_to], _value); emit Transfer(_from, _to, _value); return true; } } /// @title Token contract - Implements Standard ERC20 with additional features. /// @author Zerion - <[email protected]> contract Token is StandardToken { // Time of the contract creation uint256 public creationTime; function Token() public { /* solium-disable-next-line security/no-block-members */ creationTime = now; } /// @dev Owner can transfer out any accidentally sent ERC20 tokens function transferERC20Token(AbstractToken _token, address _to, uint256 _value) public onlyOwner returns (bool success) { require(_token.balanceOf(address(this)) >= _value); uint256 receiverBalance = _token.balanceOf(_to); require(_token.transfer(_to, _value)); uint256 receiverNewBalance = _token.balanceOf(_to); assert(receiverNewBalance == add(receiverBalance, _value)); return true; } /// @dev Increases approved amount of tokens for spender. Returns success. function increaseApproval(address _spender, uint256 _value) public returns (bool success) { allowed[msg.sender][_spender] = add(allowed[msg.sender][_spender], _value); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /// @dev Decreases approved amount of tokens for spender. Returns success. function decreaseApproval(address _spender, uint256 _value) public returns (bool success) { uint256 oldValue = allowed[msg.sender][_spender]; if (_value > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = sub(oldValue, _value); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } // @title Token contract - Implements Standard ERC20 Token for NEXO project. /// @author Zerion - <[email protected]> contract NexoToken is Token { /// TOKEN META DATA string constant public name = 'Nexo'; string constant public symbol = 'NEXO'; uint8 constant public decimals = 18; /// ALOCATIONS // To calculate vesting periods we assume that 1 month is always equal to 30 days /*** Initial Investors' tokens ***/ // 525,000,000 (52.50%) tokens are distributed among initial investors // These tokens will be distributed without vesting address public investorsAllocation = address(0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF); uint256 public investorsTotal = 525000000e18; /*** Overdraft Reserves ***/ // 250,000,000 (25%) tokens will be eventually available for overdraft // These tokens will be distributed monthly with a 6 month cliff within a year // 41,666,666 tokens will be unlocked every month after the cliff // 4 tokens will be unlocked without vesting to ensure that total amount sums up to 250,000,000. address public overdraftAllocation = address(0x1111111111111111111111111111111111111111); uint256 public overdraftTotal = 250000000e18; uint256 public overdraftPeriodAmount = 41666666e18; uint256 public overdraftUnvested = 4e18; uint256 public overdraftCliff = 5 * 30 days; uint256 public overdraftPeriodLength = 30 days; uint8 public overdraftPeriodsNumber = 6; /*** Tokens reserved for Founders and Team ***/ // 112,500,000 (11.25%) tokens will be eventually available for the team // These tokens will be distributed every 3 month without a cliff within 4 years // 7,031,250 tokens will be unlocked every 3 month address public teamAllocation = address(0x2222222222222222222222222222222222222222); uint256 public teamTotal = 112500000e18; uint256 public teamPeriodAmount = 7031250e18; uint256 public teamUnvested = 0; uint256 public teamCliff = 0; uint256 public teamPeriodLength = 3 * 30 days; uint8 public teamPeriodsNumber = 16; /*** Tokens reserved for Community Building and Airdrop Campaigns ***/ // 60,000,000 (6%) tokens will be eventually available for the community // 10,000,002 tokens will be available instantly without vesting // 49,999,998 tokens will be distributed every 3 month without a cliff within 18 months // 8,333,333 tokens will be unlocked every 3 month address public communityAllocation = address(0x3333333333333333333333333333333333333333); uint256 public communityTotal = 60000000e18; uint256 public communityPeriodAmount = 8333333e18; uint256 public communityUnvested = 10000002e18; uint256 public communityCliff = 0; uint256 public communityPeriodLength = 3 * 30 days; uint8 public communityPeriodsNumber = 6; /*** Tokens reserved for Advisors, Legal and PR ***/ // 52,500,000 (5.25%) tokens will be eventually available for advisers // 25,000,008 tokens will be available instantly without vesting // 27 499 992 tokens will be distributed monthly without a cliff within 12 months // 2,291,666 tokens will be unlocked every month address public advisersAllocation = address(0x4444444444444444444444444444444444444444); uint256 public advisersTotal = 52500000e18; uint256 public advisersPeriodAmount = 2291666e18; uint256 public advisersUnvested = 25000008e18; uint256 public advisersCliff = 0; uint256 public advisersPeriodLength = 30 days; uint8 public advisersPeriodsNumber = 12; /// CONSTRUCTOR function NexoToken() public { // Overall, 1,000,000,000 tokens exist totalSupply = 1000000000e18; balances[investorsAllocation] = investorsTotal; balances[overdraftAllocation] = overdraftTotal; balances[teamAllocation] = teamTotal; balances[communityAllocation] = communityTotal; balances[advisersAllocation] = advisersTotal; // Unlock some tokens without vesting allowed[investorsAllocation][msg.sender] = investorsTotal; allowed[overdraftAllocation][msg.sender] = overdraftUnvested; allowed[communityAllocation][msg.sender] = communityUnvested; allowed[advisersAllocation][msg.sender] = advisersUnvested; } /// DISTRIBUTION function distributeInvestorsTokens(address _to, uint256 _amountWithDecimals) public onlyOwner { require(transferFrom(investorsAllocation, _to, _amountWithDecimals)); } /// VESTING function withdrawOverdraftTokens(address _to, uint256 _amountWithDecimals) public onlyOwner { allowed[overdraftAllocation][msg.sender] = allowance(overdraftAllocation, msg.sender); require(transferFrom(overdraftAllocation, _to, _amountWithDecimals)); } function withdrawTeamTokens(address _to, uint256 _amountWithDecimals) public onlyOwner { allowed[teamAllocation][msg.sender] = allowance(teamAllocation, msg.sender); require(transferFrom(teamAllocation, _to, _amountWithDecimals)); } function withdrawCommunityTokens(address _to, uint256 _amountWithDecimals) public onlyOwner { allowed[communityAllocation][msg.sender] = allowance(communityAllocation, msg.sender); require(transferFrom(communityAllocation, _to, _amountWithDecimals)); } function withdrawAdvisersTokens(address _to, uint256 _amountWithDecimals) public onlyOwner { allowed[advisersAllocation][msg.sender] = allowance(advisersAllocation, msg.sender); require(transferFrom(advisersAllocation, _to, _amountWithDecimals)); } /// @dev Overrides StandardToken.sol function function allowance(address _owner, address _spender) public view returns (uint256 remaining) { if (_spender != owner) { return allowed[_owner][_spender]; } uint256 unlockedTokens; uint256 spentTokens; if (_owner == overdraftAllocation) { unlockedTokens = _calculateUnlockedTokens( overdraftCliff, overdraftPeriodLength, overdraftPeriodAmount, overdraftPeriodsNumber, overdraftUnvested ); spentTokens = sub(overdraftTotal, balanceOf(overdraftAllocation)); } else if (_owner == teamAllocation) { unlockedTokens = _calculateUnlockedTokens( teamCliff, teamPeriodLength, teamPeriodAmount, teamPeriodsNumber, teamUnvested ); spentTokens = sub(teamTotal, balanceOf(teamAllocation)); } else if (_owner == communityAllocation) { unlockedTokens = _calculateUnlockedTokens( communityCliff, communityPeriodLength, communityPeriodAmount, communityPeriodsNumber, communityUnvested ); spentTokens = sub(communityTotal, balanceOf(communityAllocation)); } else if (_owner == advisersAllocation) { unlockedTokens = _calculateUnlockedTokens( advisersCliff, advisersPeriodLength, advisersPeriodAmount, advisersPeriodsNumber, advisersUnvested ); spentTokens = sub(advisersTotal, balanceOf(advisersAllocation)); } else { return allowed[_owner][_spender]; } return sub(unlockedTokens, spentTokens); } /// @dev Overrides Owned.sol function function confirmOwnership() public onlyPotentialOwner { // Forbid the old owner to distribute investors' tokens allowed[investorsAllocation][owner] = 0; // Allow the new owner to distribute investors' tokens allowed[investorsAllocation][msg.sender] = balanceOf(investorsAllocation); // Forbid the old owner to withdraw any tokens from the reserves allowed[overdraftAllocation][owner] = 0; allowed[teamAllocation][owner] = 0; allowed[communityAllocation][owner] = 0; allowed[advisersAllocation][owner] = 0; super.confirmOwnership(); } function _calculateUnlockedTokens( uint256 _cliff, uint256 _periodLength, uint256 _periodAmount, uint8 _periodsNumber, uint256 _unvestedAmount ) private view returns (uint256) { /* solium-disable-next-line security/no-block-members */ if (now < add(creationTime, _cliff)) { return _unvestedAmount; } /* solium-disable-next-line security/no-block-members */ uint256 periods = div(sub(now, add(creationTime, _cliff)), _periodLength); periods = periods > _periodsNumber ? _periodsNumber : periods; return add(_unvestedAmount, mul(periods, _periodAmount)); } }
Decreases approved amount of tokens for spender. Returns success.
function decreaseApproval(address _spender, uint256 _value) public returns (bool success) { uint256 oldValue = allowed[msg.sender][_spender]; if (_value > oldValue) { allowed[msg.sender][_spender] = 0; allowed[msg.sender][_spender] = sub(oldValue, _value); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; }
489,369
./partial_match/56/0xDca31a4d1cA28080B0b6a02DEAd39AaA602CaF8C/sources/JetfuelVaultV2.sol
The entrypoint of funds into the system. People deposit with this function into the vault. The vault is then in charge of sending funds into the strategy./
function deposit(uint256 _amount) public nonReentrant { uint256 _pool = balance(); token.safeTransferFrom(msg.sender, address(this), _amount); earn(); uint256 _after = balance(); uint256 shares = 0; if (totalSupply() == 0) { shares = _amount; shares = (_amount.mul(totalSupply())).div(_pool); } _mint(msg.sender, shares); }
11,164,095
pragma solidity ^0.4.24; // File: node_modules\zeppelin-solidity\contracts\math\SafeMath.sol /** * @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 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @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 a / b; } /** * @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 c) { c = a + b; assert(c >= a); return c; } } // File: node_modules\zeppelin-solidity\contracts\token\ERC20\ERC20Basic.sol /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * See https://github.com/ethereum/EIPs/issues/179 */ 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); } // File: node_modules\zeppelin-solidity\contracts\token\ERC20\ERC20.sol /** * @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 ); } // File: node_modules\zeppelin-solidity\contracts\token\ERC20\SafeERC20.sol /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure. * 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 { function safeTransfer(ERC20Basic token, address to, uint256 value) internal { require(token.transfer(to, value)); } function safeTransferFrom( ERC20 token, address from, address to, uint256 value ) internal { require(token.transferFrom(from, to, value)); } function safeApprove(ERC20 token, address spender, uint256 value) internal { require(token.approve(spender, value)); } } // File: node_modules\zeppelin-solidity\contracts\crowdsale\Crowdsale.sol /** * @title Crowdsale * @dev Crowdsale is a base contract for managing a token crowdsale, * allowing investors to purchase tokens with ether. This contract implements * such functionality in its most fundamental form and can be extended to provide additional * functionality and/or custom behavior. * The external interface represents the basic interface for purchasing tokens, and conform * the base architecture for crowdsales. They are *not* intended to be modified / overriden. * The internal interface conforms the extensible and modifiable surface of crowdsales. Override * the methods to add functionality. Consider using 'super' where appropiate to concatenate * behavior. */ contract Crowdsale { using SafeMath for uint256; using SafeERC20 for ERC20; // The token being sold ERC20 public token; // Address where funds are collected address public wallet; // How many token units a buyer gets per wei. // The rate is the conversion between wei and the smallest and indivisible token unit. // So, if you are using a rate of 1 with a DetailedERC20 token with 3 decimals called TOK // 1 wei will give you 1 unit, or 0.001 TOK. uint256 public rate; // Amount of wei raised uint256 public weiRaised; /** * Event for token 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 TokenPurchase( address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount ); /** * @param _rate Number of token units a buyer gets per wei * @param _wallet Address where collected funds will be forwarded to * @param _token Address of the token being sold */ constructor(uint256 _rate, address _wallet, ERC20 _token) public { require(_rate > 0); require(_wallet != address(0)); require(_token != address(0)); rate = _rate; wallet = _wallet; token = _token; } // ----------------------------------------- // Crowdsale external interface // ----------------------------------------- /** * @dev fallback function ***DO NOT OVERRIDE*** */ function () external payable { buyTokens(msg.sender); } /** * @dev low level token purchase ***DO NOT OVERRIDE*** * @param _beneficiary Address performing the token purchase */ function buyTokens(address _beneficiary) public payable { uint256 weiAmount = msg.value; _preValidatePurchase(_beneficiary, weiAmount); // calculate token amount to be created uint256 tokens = _getTokenAmount(weiAmount); // update state weiRaised = weiRaised.add(weiAmount); _processPurchase(_beneficiary, tokens); emit TokenPurchase( msg.sender, _beneficiary, weiAmount, tokens ); _updatePurchasingState(_beneficiary, weiAmount); _forwardFunds(); _postValidatePurchase(_beneficiary, weiAmount); } // ----------------------------------------- // Internal interface (extensible) // ----------------------------------------- /** * @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use super to concatenate validations. * @param _beneficiary Address performing the token purchase * @param _weiAmount Value in wei involved in the purchase */ function _preValidatePurchase( address _beneficiary, uint256 _weiAmount ) internal { require(_beneficiary != address(0)); require(_weiAmount != 0); } /** * @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid conditions are not met. * @param _beneficiary Address performing the token purchase * @param _weiAmount Value in wei involved in the purchase */ function _postValidatePurchase( address _beneficiary, uint256 _weiAmount ) internal { // optional override } /** * @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends its tokens. * @param _beneficiary Address performing the token purchase * @param _tokenAmount Number of tokens to be emitted */ function _deliverTokens( address _beneficiary, uint256 _tokenAmount ) internal { token.safeTransfer(_beneficiary, _tokenAmount); } /** * @dev Executed when a purchase has been validated and is ready to be executed. Not necessarily emits/sends tokens. * @param _beneficiary Address receiving the tokens * @param _tokenAmount Number of tokens to be purchased */ function _processPurchase( address _beneficiary, uint256 _tokenAmount ) internal { _deliverTokens(_beneficiary, _tokenAmount); } /** * @dev Override for extensions that require an internal state to check for validity (current user contributions, etc.) * @param _beneficiary Address receiving the tokens * @param _weiAmount Value in wei involved in the purchase */ function _updatePurchasingState( address _beneficiary, uint256 _weiAmount ) internal { // optional override } /** * @dev Override to extend the way in which ether is converted to tokens. * @param _weiAmount Value in wei to be converted into tokens * @return Number of tokens that can be purchased with the specified _weiAmount */ function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) { return _weiAmount.mul(rate); } /** * @dev Determines how ETH is stored/forwarded on purchases. */ function _forwardFunds() internal { wallet.transfer(msg.value); } } // File: node_modules\zeppelin-solidity\contracts\ownership\Ownable.sol /** * @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; } } // File: node_modules\zeppelin-solidity\contracts\crowdsale\validation\TimedCrowdsale.sol /** * @title TimedCrowdsale * @dev Crowdsale accepting contributions only within a time frame. */ contract TimedCrowdsale is Crowdsale { using SafeMath for uint256; uint256 public openingTime; uint256 public closingTime; /** * @dev Reverts if not in crowdsale time range. */ modifier onlyWhileOpen { // solium-disable-next-line security/no-block-members require(block.timestamp >= openingTime && block.timestamp <= closingTime); _; } /** * @dev Constructor, takes crowdsale opening and closing times. * @param _openingTime Crowdsale opening time * @param _closingTime Crowdsale closing time */ constructor(uint256 _openingTime, uint256 _closingTime) public { // solium-disable-next-line security/no-block-members require(_openingTime >= block.timestamp); require(_closingTime >= _openingTime); openingTime = _openingTime; closingTime = _closingTime; } /** * @dev Checks whether the period in which the crowdsale is open has already elapsed. * @return Whether crowdsale period has elapsed */ function hasClosed() public view returns (bool) { // solium-disable-next-line security/no-block-members return block.timestamp > closingTime; } /** * @dev Extend parent behavior requiring to be within contributing period * @param _beneficiary Token purchaser * @param _weiAmount Amount of wei contributed */ function _preValidatePurchase( address _beneficiary, uint256 _weiAmount ) internal onlyWhileOpen { super._preValidatePurchase(_beneficiary, _weiAmount); } } // File: node_modules\zeppelin-solidity\contracts\crowdsale\distribution\FinalizableCrowdsale.sol /** * @title FinalizableCrowdsale * @dev Extension of Crowdsale where an owner can do extra work * after finishing. */ contract FinalizableCrowdsale is TimedCrowdsale, Ownable { using SafeMath for uint256; bool public isFinalized = false; event Finalized(); /** * @dev Must be called after crowdsale ends, to do some extra finalization * work. Calls the contract's finalization function. */ function finalize() onlyOwner public { require(!isFinalized); require(hasClosed()); finalization(); emit Finalized(); isFinalized = true; } /** * @dev Can be overridden to add finalization logic. The overriding function * should call super.finalization() to ensure the chain of finalization is * executed entirely. */ function finalization() internal { } } // File: node_modules\zeppelin-solidity\contracts\token\ERC20\BasicToken.sol /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ 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]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit 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) { return balances[_owner]; } } // File: node_modules\zeppelin-solidity\contracts\token\ERC20\StandardToken.sol /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * https://github.com/ethereum/EIPs/issues/20 * 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); emit 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; emit 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, uint256 _addedValue ) public returns (bool) { 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 * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval( address _spender, uint256 _subtractedValue ) public returns (bool) { uint256 oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } // File: node_modules\zeppelin-solidity\contracts\token\ERC20\MintableToken.sol /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * 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); _; } modifier hasMintPermission() { require(msg.sender == owner); _; } /** * @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 ) hasMintPermission canMint public returns (bool) { totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; emit MintFinished(); return true; } } // File: node_modules\zeppelin-solidity\contracts\crowdsale\emission\MintedCrowdsale.sol /** * @title MintedCrowdsale * @dev Extension of Crowdsale contract whose tokens are minted in each purchase. * Token ownership should be transferred to MintedCrowdsale for minting. */ contract MintedCrowdsale is Crowdsale { /** * @dev Overrides delivery by minting tokens upon purchase. * @param _beneficiary Token purchaser * @param _tokenAmount Number of tokens to be minted */ function _deliverTokens( address _beneficiary, uint256 _tokenAmount ) internal { require(MintableToken(token).mint(_beneficiary, _tokenAmount)); } } // File: node_modules\zeppelin-solidity\contracts\token\ERC20\CappedToken.sol /** * @title Capped token * @dev Mintable token with a token cap. */ contract CappedToken is MintableToken { uint256 public cap; constructor(uint256 _cap) public { require(_cap > 0); cap = _cap; } /** * @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 returns (bool) { require(totalSupply_.add(_amount) <= cap); return super.mint(_to, _amount); } } // File: node_modules\zeppelin-solidity\contracts\math\Math.sol /** * @title Math * @dev Assorted math operations */ library Math { function max64(uint64 a, uint64 b) internal pure returns (uint64) { return a >= b ? a : b; } function min64(uint64 a, uint64 b) internal pure returns (uint64) { return a < b ? a : b; } function max256(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } function min256(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } } // File: node_modules\zeppelin-solidity\contracts\payment\Escrow.sol /** * @title Escrow * @dev Base escrow contract, holds funds destinated to a payee until they * withdraw them. The contract that uses the escrow as its payment method * should be its owner, and provide public methods redirecting to the escrow's * deposit and withdraw. */ contract Escrow is Ownable { using SafeMath for uint256; event Deposited(address indexed payee, uint256 weiAmount); event Withdrawn(address indexed payee, uint256 weiAmount); mapping(address => uint256) private deposits; function depositsOf(address _payee) public view returns (uint256) { return deposits[_payee]; } /** * @dev Stores the sent amount as credit to be withdrawn. * @param _payee The destination address of the funds. */ function deposit(address _payee) public onlyOwner payable { uint256 amount = msg.value; deposits[_payee] = deposits[_payee].add(amount); emit Deposited(_payee, amount); } /** * @dev Withdraw accumulated balance for a payee. * @param _payee The address whose funds will be withdrawn and transferred to. */ function withdraw(address _payee) public onlyOwner { uint256 payment = deposits[_payee]; assert(address(this).balance >= payment); deposits[_payee] = 0; _payee.transfer(payment); emit Withdrawn(_payee, payment); } } // File: node_modules\zeppelin-solidity\contracts\payment\ConditionalEscrow.sol /** * @title ConditionalEscrow * @dev Base abstract escrow to only allow withdrawal if a condition is met. */ contract ConditionalEscrow is Escrow { /** * @dev Returns whether an address is allowed to withdraw their funds. To be * implemented by derived contracts. * @param _payee The destination address of the funds. */ function withdrawalAllowed(address _payee) public view returns (bool); function withdraw(address _payee) public { require(withdrawalAllowed(_payee)); super.withdraw(_payee); } } // File: node_modules\zeppelin-solidity\contracts\payment\RefundEscrow.sol /** * @title RefundEscrow * @dev Escrow that holds funds for a beneficiary, deposited from multiple parties. * The contract owner may close the deposit period, and allow for either withdrawal * by the beneficiary, or refunds to the depositors. */ contract RefundEscrow is Ownable, ConditionalEscrow { enum State { Active, Refunding, Closed } event Closed(); event RefundsEnabled(); State public state; address public beneficiary; /** * @dev Constructor. * @param _beneficiary The beneficiary of the deposits. */ constructor(address _beneficiary) public { require(_beneficiary != address(0)); beneficiary = _beneficiary; state = State.Active; } /** * @dev Stores funds that may later be refunded. * @param _refundee The address funds will be sent to if a refund occurs. */ function deposit(address _refundee) public payable { require(state == State.Active); super.deposit(_refundee); } /** * @dev Allows for the beneficiary to withdraw their funds, rejecting * further deposits. */ function close() public onlyOwner { require(state == State.Active); state = State.Closed; emit Closed(); } /** * @dev Allows for refunds to take place, rejecting further deposits. */ function enableRefunds() public onlyOwner { require(state == State.Active); state = State.Refunding; emit RefundsEnabled(); } /** * @dev Withdraws the beneficiary's funds. */ function beneficiaryWithdraw() public { require(state == State.Closed); beneficiary.transfer(address(this).balance); } /** * @dev Returns whether refundees can withdraw their deposits (be refunded). */ function withdrawalAllowed(address _payee) public view returns (bool) { return state == State.Refunding; } } // File: contracts\ClinicAllRefundEscrow.sol /** * @title ClinicAllRefundEscrow * @dev Escrow that holds funds for a beneficiary, deposited from multiple parties. * The contract owner may close the deposit period, and allow for either withdrawal * by the beneficiary, or refunds to the depositors. */ contract ClinicAllRefundEscrow is RefundEscrow { using Math for uint256; struct RefundeeRecord { bool isRefunded; uint256 index; } mapping(address => RefundeeRecord) public refundees; address[] internal refundeesList; event Deposited(address indexed payee, uint256 weiAmount); event Withdrawn(address indexed payee, uint256 weiAmount); mapping(address => uint256) private deposits; mapping(address => uint256) private beneficiaryDeposits; // Amount of wei deposited by beneficiary uint256 public beneficiaryDepositedAmount; // Amount of wei deposited by investors to CrowdSale uint256 public investorsDepositedToCrowdSaleAmount; /** * @dev Constructor. * @param _beneficiary The beneficiary of the deposits. */ constructor(address _beneficiary) RefundEscrow(_beneficiary) public { } function depositsOf(address _payee) public view returns (uint256) { return deposits[_payee]; } function beneficiaryDepositsOf(address _payee) public view returns (uint256) { return beneficiaryDeposits[_payee]; } /** * @dev Stores funds that may later be refunded. * @param _refundee The address funds will be sent to if a refund occurs. */ function deposit(address _refundee) public payable { uint256 amount = msg.value; beneficiaryDeposits[_refundee] = beneficiaryDeposits[_refundee].add(amount); beneficiaryDepositedAmount = beneficiaryDepositedAmount.add(amount); } /** * @dev Stores funds that may later be refunded. * @param _refundee The address funds will be sent to if a refund occurs. * @param _value The amount of funds will be sent to if a refund occurs. */ function depositFunds(address _refundee, uint256 _value) public onlyOwner { require(state == State.Active, "Funds deposition is possible only in the Active state."); uint256 amount = _value; deposits[_refundee] = deposits[_refundee].add(amount); investorsDepositedToCrowdSaleAmount = investorsDepositedToCrowdSaleAmount.add(amount); emit Deposited(_refundee, amount); RefundeeRecord storage _data = refundees[_refundee]; _data.isRefunded = false; if (_data.index == uint256(0)) { refundeesList.push(_refundee); _data.index = refundeesList.length.sub(1); } } /** * @dev Allows for the beneficiary to withdraw their funds, rejecting * further deposits. */ function close() public onlyOwner { super.close(); } function withdraw(address _payee) public onlyOwner { require(state == State.Refunding, "Funds withdrawal is possible only in the Refunding state."); require(depositsOf(_payee) > 0, "An investor should have non-negative deposit for withdrawal."); RefundeeRecord storage _data = refundees[_payee]; require(_data.isRefunded == false, "An investor should not be refunded."); uint256 payment = deposits[_payee]; assert(address(this).balance >= payment); deposits[_payee] = 0; investorsDepositedToCrowdSaleAmount = investorsDepositedToCrowdSaleAmount.sub(payment); _payee.transfer(payment); emit Withdrawn(_payee, payment); _data.isRefunded = true; removeRefundeeByIndex(_data.index); } /** @dev Owner can do manual refund here if investore has "BAD" money @param _payee address of investor that needs to refund with next manual ETH sending */ function manualRefund(address _payee) public onlyOwner { require(depositsOf(_payee) > 0, "An investor should have non-negative deposit for withdrawal."); RefundeeRecord storage _data = refundees[_payee]; require(_data.isRefunded == false, "An investor should not be refunded."); deposits[_payee] = 0; _data.isRefunded = true; removeRefundeeByIndex(_data.index); } /** * @dev Remove refundee referenced index from the internal list * @param _indexToDelete An index in an array for deletion */ function removeRefundeeByIndex(uint256 _indexToDelete) private { if ((refundeesList.length > 0) && (_indexToDelete < refundeesList.length)) { uint256 _lastIndex = refundeesList.length.sub(1); refundeesList[_indexToDelete] = refundeesList[_lastIndex]; refundeesList.length--; } } /** * @dev Get refundee list length */ function refundeesListLength() public onlyOwner view returns (uint256) { return refundeesList.length; } /** * @dev Auto refund * @param _txFee The cost of executing refund code */ function withdrawChunk(uint256 _txFee, uint256 _chunkLength) public onlyOwner returns (uint256, address[]) { require(state == State.Refunding, "Funds withdrawal is possible only in the Refunding state."); uint256 _refundeesCount = refundeesList.length; require(_chunkLength >= _refundeesCount); require(_txFee > 0, "Transaction fee should be above zero."); require(_refundeesCount > 0, "List of investors should not be empty."); uint256 _weiRefunded = 0; require(address(this).balance > (_chunkLength.mul(_txFee)), "Account's ballance should allow to pay all tx fees."); address[] memory _refundeesListCopy = new address[](_chunkLength); uint256 i; for (i = 0; i < _chunkLength; i++) { address _refundee = refundeesList[i]; RefundeeRecord storage _data = refundees[_refundee]; if (_data.isRefunded == false) { if (depositsOf(_refundee) > _txFee) { uint256 _deposit = depositsOf(_refundee); if (_deposit > _txFee) { _weiRefunded = _weiRefunded.add(_deposit); uint256 _paymentWithoutTxFee = _deposit.sub(_txFee); _refundee.transfer(_paymentWithoutTxFee); emit Withdrawn(_refundee, _paymentWithoutTxFee); _data.isRefunded = true; _refundeesListCopy[i] = _refundee; } } } } for (i = 0; i < _chunkLength; i++) { if (address(0) != _refundeesListCopy[i]) { RefundeeRecord storage _dataCleanup = refundees[_refundeesListCopy[i]]; require(_dataCleanup.isRefunded == true, "Investors in this list should be refunded."); removeRefundeeByIndex(_dataCleanup.index); } } return (_weiRefunded, _refundeesListCopy); } /** * @dev Auto refund * @param _txFee The cost of executing refund code */ function withdrawEverything(uint256 _txFee) public onlyOwner returns (uint256, address[]) { require(state == State.Refunding, "Funds withdrawal is possible only in the Refunding state."); return withdrawChunk(_txFee, refundeesList.length); } /** * @dev Withdraws the part of beneficiary's funds. */ function beneficiaryWithdrawChunk(uint256 _value) public onlyOwner { require(_value <= address(this).balance, "Withdraw part can not be more than current balance"); beneficiaryDepositedAmount = beneficiaryDepositedAmount.sub(_value); beneficiary.transfer(_value); } /** * @dev Withdraws all beneficiary's funds. */ function beneficiaryWithdrawAll() public onlyOwner { uint256 _value = address(this).balance; beneficiaryDepositedAmount = beneficiaryDepositedAmount.sub(_value); beneficiary.transfer(_value); } } // File: node_modules\zeppelin-solidity\contracts\lifecycle\TokenDestructible.sol /** * @title TokenDestructible: * @author Remco Bloemen <remco@2π.com> * @dev Base contract that can be destroyed by owner. All funds in contract including * listed tokens will be sent to the owner. */ contract TokenDestructible is Ownable { constructor() public payable { } /** * @notice Terminate contract and refund to owner * @param tokens List of addresses of ERC20 or ERC20Basic token contracts to refund. * @notice The called token contracts could try to re-enter this contract. Only supply token contracts you trust. */ function destroy(address[] tokens) onlyOwner public { // Transfer tokens to owner for (uint256 i = 0; i < tokens.length; i++) { ERC20Basic token = ERC20Basic(tokens[i]); uint256 balance = token.balanceOf(this); token.transfer(owner, balance); } // Transfer Eth to owner and terminate contract selfdestruct(owner); } } // File: node_modules\zeppelin-solidity\contracts\token\ERC20\BurnableToken.sol /** * @title Burnable Token * @dev Token that can be irreversibly burned (destroyed). */ 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 { _burn(msg.sender, _value); } function _burn(address _who, uint256 _value) internal { require(_value <= balances[_who]); // no need to require value <= totalSupply, since that would imply the // sender's balance is greater than the totalSupply, which *should* be an assertion failure balances[_who] = balances[_who].sub(_value); totalSupply_ = totalSupply_.sub(_value); emit Burn(_who, _value); emit Transfer(_who, address(0), _value); } } // File: node_modules\zeppelin-solidity\contracts\token\ERC20\DetailedERC20.sol /** * @title DetailedERC20 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 DetailedERC20 is ERC20 { string public name; string public symbol; uint8 public decimals; constructor(string _name, string _symbol, uint8 _decimals) public { name = _name; symbol = _symbol; decimals = _decimals; } } // File: node_modules\zeppelin-solidity\contracts\lifecycle\Pausable.sol /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; emit Unpause(); } } // File: node_modules\zeppelin-solidity\contracts\token\ERC20\PausableToken.sol /** * @title Pausable token * @dev StandardToken modified with pausable transfers. **/ contract PausableToken is StandardToken, Pausable { function transfer( address _to, uint256 _value ) public whenNotPaused returns (bool) { return super.transfer(_to, _value); } function transferFrom( address _from, address _to, uint256 _value ) public whenNotPaused returns (bool) { return super.transferFrom(_from, _to, _value); } function approve( address _spender, uint256 _value ) public whenNotPaused returns (bool) { return super.approve(_spender, _value); } function increaseApproval( address _spender, uint _addedValue ) public whenNotPaused returns (bool success) { return super.increaseApproval(_spender, _addedValue); } function decreaseApproval( address _spender, uint _subtractedValue ) public whenNotPaused returns (bool success) { return super.decreaseApproval(_spender, _subtractedValue); } } // File: contracts\TransferableToken.sol /** * @title TransferableToken * @dev Base contract which allows to implement transfer for token. */ contract TransferableToken is Ownable { event TransferOn(); event TransferOff(); bool public transferable = false; /** * @dev Modifier to make a function callable only when the contract is not transferable. */ modifier whenNotTransferable() { require(!transferable); _; } /** * @dev Modifier to make a function callable only when the contract is transferable. */ modifier whenTransferable() { require(transferable); _; } /** * @dev called by the owner to enable transfers */ function transferOn() onlyOwner whenNotTransferable public { transferable = true; emit TransferOn(); } /** * @dev called by the owner to disable transfers */ function transferOff() onlyOwner whenTransferable public { transferable = false; emit TransferOff(); } } // File: contracts\ClinicAllToken.sol contract ClinicAllToken is MintableToken, DetailedERC20, CappedToken, PausableToken, BurnableToken, TokenDestructible, TransferableToken { constructor ( string _name, string _symbol, uint8 _decimals, uint256 _cap ) DetailedERC20(_name, _symbol, _decimals) CappedToken(_cap) public { } /*/ * Refund event when ICO didn't pass soft cap and we refund ETH to investors + burn ERC-20 tokens from investors balances /*/ function burnAfterRefund(address _who) public onlyOwner { uint256 _value = balances[_who]; _burn(_who, _value); } /*/ * Allow transfers only if token is transferable /*/ function transfer( address _to, uint256 _value ) public whenTransferable returns (bool) { return super.transfer(_to, _value); } /*/ * Allow transfers only if token is transferable /*/ function transferFrom( address _from, address _to, uint256 _value ) public whenTransferable returns (bool) { return super.transferFrom(_from, _to, _value); } function transferToPrivateInvestor( address _from, address _to, uint256 _value ) public onlyOwner returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(_from, _to, _value); return true; } function burnPrivateSale(address privateSaleWallet, uint256 _value) public onlyOwner { _burn(privateSaleWallet, _value); } } // File: node_modules\zeppelin-solidity\contracts\ownership\rbac\Roles.sol /** * @title Roles * @author Francisco Giordano (@frangio) * @dev Library for managing addresses assigned to a Role. * See RBAC.sol for example usage. */ library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev give an address access to this role */ function add(Role storage role, address addr) internal { role.bearer[addr] = true; } /** * @dev remove an address' access to this role */ function remove(Role storage role, address addr) internal { role.bearer[addr] = false; } /** * @dev check if an address has this role * // reverts */ function check(Role storage role, address addr) view internal { require(has(role, addr)); } /** * @dev check if an address has this role * @return bool */ function has(Role storage role, address addr) view internal returns (bool) { return role.bearer[addr]; } } // File: node_modules\zeppelin-solidity\contracts\ownership\rbac\RBAC.sol /** * @title RBAC (Role-Based Access Control) * @author Matt Condon (@Shrugs) * @dev Stores and provides setters and getters for roles and addresses. * Supports unlimited numbers of roles and addresses. * See //contracts/mocks/RBACMock.sol for an example of usage. * This RBAC method uses strings to key roles. It may be beneficial * for you to write your own implementation of this interface using Enums or similar. * It's also recommended that you define constants in the contract, like ROLE_ADMIN below, * to avoid typos. */ contract RBAC { using Roles for Roles.Role; mapping (string => Roles.Role) private roles; event RoleAdded(address indexed operator, string role); event RoleRemoved(address indexed operator, string role); /** * @dev reverts if addr does not have role * @param _operator address * @param _role the name of the role * // reverts */ function checkRole(address _operator, string _role) view public { roles[_role].check(_operator); } /** * @dev determine if addr has role * @param _operator address * @param _role the name of the role * @return bool */ function hasRole(address _operator, string _role) view public returns (bool) { return roles[_role].has(_operator); } /** * @dev add a role to an address * @param _operator address * @param _role the name of the role */ function addRole(address _operator, string _role) internal { roles[_role].add(_operator); emit RoleAdded(_operator, _role); } /** * @dev remove a role from an address * @param _operator address * @param _role the name of the role */ function removeRole(address _operator, string _role) internal { roles[_role].remove(_operator); emit RoleRemoved(_operator, _role); } /** * @dev modifier to scope access to a single role (uses msg.sender as addr) * @param _role the name of the role * // reverts */ modifier onlyRole(string _role) { checkRole(msg.sender, _role); _; } /** * @dev modifier to scope access to a set of roles (uses msg.sender as addr) * @param _roles the names of the roles to scope access to * // reverts * * @TODO - when solidity supports dynamic arrays as arguments to modifiers, provide this * see: https://github.com/ethereum/solidity/issues/2467 */ // modifier onlyRoles(string[] _roles) { // bool hasAnyRole = false; // for (uint8 i = 0; i < _roles.length; i++) { // if (hasRole(msg.sender, _roles[i])) { // hasAnyRole = true; // break; // } // } // require(hasAnyRole); // _; // } } // File: contracts\Managed.sol /** * @title Managed * @dev The Whitelist contract has a whitelist of addresses, and provides basic authorization control functions. * This simplifies the implementation of "user permissions". */ contract Managed is Ownable, RBAC { string public constant ROLE_MANAGER = "manager"; /** * @dev Throws if operator is not whitelisted. */ modifier onlyManager() { checkRole(msg.sender, ROLE_MANAGER); _; } /** * @dev set an address as a manager * @param _operator address * @return true if the address was added to the whitelist, false if the address was already in the whitelist */ function setManager(address _operator) public onlyOwner { addRole(_operator, ROLE_MANAGER); } /** * @dev delete an address as a manager * @param _operator address * @return true if the address was deleted from the whitelist, false if the address wasn't already in the whitelist */ function removeManager(address _operator) public onlyOwner { removeRole(_operator, ROLE_MANAGER); } } // File: contracts\Limited.sol /** * @title LimitedCrowdsale * @dev Crowdsale in which only limited number of tokens can be bought. */ contract Limited is Managed { using SafeMath for uint256; mapping(address => uint256) public limitsList; /** * @dev Reverts if beneficiary has no limit. Can be used when extending this contract. */ modifier isLimited(address _payee) { require(limitsList[_payee] > 0, "An investor is limited if it has a limit."); _; } /** * @dev Reverts if beneficiary want to buy more tickets than limit allows. Can be used when extending this contract. */ modifier doesNotExceedLimit(address _payee, uint256 _tokenAmount, uint256 _tokenBalance, uint256 kycLimitEliminator) { if(_tokenBalance.add(_tokenAmount) >= kycLimitEliminator) { require(_tokenBalance.add(_tokenAmount) <= getLimit(_payee), "An investor should not exceed its limit on buying."); } _; } /** * @dev Returns limits for _payee. * @param _payee Address to get token limits */ function getLimit(address _payee) public view returns (uint256) { return limitsList[_payee]; } /** * @dev Adds limits to addresses. * @param _payees Addresses to set limit * @param _limits Limit values to set to addresses */ function addAddressesLimits(address[] _payees, uint256[] _limits) public onlyManager { require(_payees.length == _limits.length, "Array sizes should be equal."); for (uint256 i = 0; i < _payees.length; i++) { addLimit(_payees[i], _limits[i]); } } /** * @dev Adds limit to address. * @param _payee Address to set limit * @param _limit Limit value to set to address */ function addLimit(address _payee, uint256 _limit) public onlyManager { limitsList[_payee] = _limit; } /** * @dev Removes single address-limit record. * @param _payee Address to be removed */ function removeLimit(address _payee) external onlyManager { limitsList[_payee] = 0; } } // File: node_modules\zeppelin-solidity\contracts\access\Whitelist.sol /** * @title Whitelist * @dev The Whitelist contract has a whitelist of addresses, and provides basic authorization control functions. * This simplifies the implementation of "user permissions". */ contract Whitelist is Ownable, RBAC { string public constant ROLE_WHITELISTED = "whitelist"; /** * @dev Throws if operator is not whitelisted. * @param _operator address */ modifier onlyIfWhitelisted(address _operator) { checkRole(_operator, ROLE_WHITELISTED); _; } /** * @dev add an address to the whitelist * @param _operator address * @return true if the address was added to the whitelist, false if the address was already in the whitelist */ function addAddressToWhitelist(address _operator) onlyOwner public { addRole(_operator, ROLE_WHITELISTED); } /** * @dev getter to determine if address is in whitelist */ function whitelist(address _operator) public view returns (bool) { return hasRole(_operator, ROLE_WHITELISTED); } /** * @dev add addresses to the whitelist * @param _operators addresses * @return true if at least one address was added to the whitelist, * false if all addresses were already in the whitelist */ function addAddressesToWhitelist(address[] _operators) onlyOwner public { for (uint256 i = 0; i < _operators.length; i++) { addAddressToWhitelist(_operators[i]); } } /** * @dev remove an address from the whitelist * @param _operator address * @return true if the address was removed from the whitelist, * false if the address wasn't in the whitelist in the first place */ function removeAddressFromWhitelist(address _operator) onlyOwner public { removeRole(_operator, ROLE_WHITELISTED); } /** * @dev remove addresses from the whitelist * @param _operators addresses * @return true if at least one address was removed from the whitelist, * false if all addresses weren't in the whitelist in the first place */ function removeAddressesFromWhitelist(address[] _operators) onlyOwner public { for (uint256 i = 0; i < _operators.length; i++) { removeAddressFromWhitelist(_operators[i]); } } } // File: contracts\ManagedWhitelist.sol /** * @title ManagedWhitelist * @dev The Whitelist contract has a whitelist of addresses, and provides basic authorization control functions. * This simplifies the implementation of "user permissions". */ contract ManagedWhitelist is Managed, Whitelist { /** * @dev add an address to the whitelist * @param _operator address * @return true if the address was added to the whitelist, false if the address was already in the whitelist */ function addAddressToWhitelist(address _operator) public onlyManager { addRole(_operator, ROLE_WHITELISTED); } /** * @dev add addresses to the whitelist * @param _operators addresses * @return true if at least one address was added to the whitelist, * false if all addresses were already in the whitelist */ function addAddressesToWhitelist(address[] _operators) public onlyManager { for (uint256 i = 0; i < _operators.length; i++) { addAddressToWhitelist(_operators[i]); } } /** * @dev remove an address from the whitelist * @param _operator address * @return true if the address was removed from the whitelist, * false if the address wasn't in the whitelist in the first place */ function removeAddressFromWhitelist(address _operator) public onlyManager { removeRole(_operator, ROLE_WHITELISTED); } /** * @dev remove addresses from the whitelist * @param _operators addresses * @return true if at least one address was removed from the whitelist, * false if all addresses weren't in the whitelist in the first place */ function removeAddressesFromWhitelist(address[] _operators) public onlyManager { for (uint256 i = 0; i < _operators.length; i++) { removeAddressFromWhitelist(_operators[i]); } } } // File: contracts\ClinicAllCrowdsale.sol /// @title ClinicAll crowdsale contract /// @dev ClinicAll crowdsale contract contract ClinicAllCrowdsale is Crowdsale, FinalizableCrowdsale, MintedCrowdsale, ManagedWhitelist, Limited { constructor ( uint256 _tokenLimitSupply, uint256 _rate, address _wallet, address _privateSaleWallet, ERC20 _token, uint256 _openingTime, uint256 _closingTime, uint256 _discountTokenAmount, uint256 _discountTokenPercent, uint256 _preSaleClosingTime, uint256 _softCapLimit, ClinicAllRefundEscrow _vault, uint256 _buyLimitSupplyMin, uint256 _buyLimitSupplyMax, uint256 _kycLimitEliminator ) Crowdsale(_rate, _wallet, _token) TimedCrowdsale(_openingTime, _closingTime) public { privateSaleWallet = _privateSaleWallet; tokenSupplyLimit = _tokenLimitSupply; discountTokenAmount = _discountTokenAmount; discountTokenPercent = _discountTokenPercent; preSaleClosingTime = _preSaleClosingTime; softCapLimit = _softCapLimit; vault = _vault; buyLimitSupplyMin = _buyLimitSupplyMin; buyLimitSupplyMax = _buyLimitSupplyMax; kycLimitEliminator = _kycLimitEliminator; } using SafeMath for uint256; // refund vault used to hold funds while crowdsale is running ClinicAllRefundEscrow public vault; /*/ * Properties, constants /*/ //address public walletPrivateSaler; // Limit of tokens for supply during ICO public sale uint256 public tokenSupplyLimit; // Limit of tokens with discount on current contract uint256 public discountTokenAmount; // Percent value for discount tokens uint256 public discountTokenPercent; // Time when we finish pre sale uint256 public preSaleClosingTime; // Minimum amount of funds to be raised in weis uint256 public softCapLimit; // Min buy limit for each investor uint256 public buyLimitSupplyMin; // Max buy limit for each investor uint256 public buyLimitSupplyMax; // KYC Limit Eliminator for small and big investors uint256 public kycLimitEliminator; // Address where private sale funds are collected address public privateSaleWallet; // Private sale tokens supply limit uint256 public privateSaleSupplyLimit; // Public functions /*/ * @dev CrowdSale manager is able to change rate value during ICO * @param _rate wei to CHT tokens exchange rate */ function updateRate(uint256 _rate) public onlyManager { require(_rate != 0, "Exchange rate should not be 0."); rate = _rate; } /*/ * @dev CrowdSale manager is able to change min and max buy limit for investors during ICO * @param _min Minimal amount of tokens that could be bought * @param _max Maximum amount of tokens that could be bought */ function updateBuyLimitRange(uint256 _min, uint256 _max) public onlyOwner { require(_min != 0, "Minimal buy limit should not be 0."); require(_max != 0, "Maximal buy limit should not be 0."); require(_max > _min, "Maximal buy limit should be greater than minimal buy limit."); buyLimitSupplyMin = _min; buyLimitSupplyMax = _max; } /*/ * @dev CrowdSale manager is able to change Kyc Limit Eliminator for investors during ICO * @param _value amount of tokens that should be as eliminator */ function updateKycLimitEliminator(uint256 _value) public onlyOwner { require(_value != 0, "Kyc Eliminator should not be 0."); kycLimitEliminator = _value; } /** * @dev Investors can claim refunds here if crowdsale is unsuccessful */ function claimRefund() public { require(isFinalized, "Claim refunds is only possible if the ICO is finalized."); require(!goalReached(), "Claim refunds is only possible if the soft cap goal has not been reached."); uint256 deposit = vault.depositsOf(msg.sender); vault.withdraw(msg.sender); weiRaised = weiRaised.sub(deposit); ClinicAllToken(token).burnAfterRefund(msg.sender); } /** @dev Owner can claim full refund if a crowdsale is unsuccessful @param _txFee Transaction fee that will be deducted from an invested sum */ function claimRefundChunk(uint256 _txFee, uint256 _chunkLength) public onlyOwner { require(isFinalized, "Claim refunds is only possible if the ICO is finalized."); require(!goalReached(), "Claim refunds is only possible if the soft cap goal has not been reached."); uint256 _weiRefunded; address[] memory _refundeesList; (_weiRefunded, _refundeesList) = vault.withdrawChunk(_txFee, _chunkLength); weiRaised = weiRaised.sub(_weiRefunded); for (uint256 i = 0; i < _refundeesList.length; i++) { ClinicAllToken(token).burnAfterRefund(_refundeesList[i]); } } /** * @dev Get refundee list length */ function refundeesListLength() public onlyOwner view returns (uint256) { return vault.refundeesListLength(); } /** * @dev Checks whether the period in which the crowdsale is open has already elapsed. * @return Whether crowdsale period has elapsed */ function hasClosed() public view returns (bool) { return ((block.timestamp > closingTime) || tokenSupplyLimit <= token.totalSupply()); } /** * @dev Checks whether funding goal was reached. * @return Whether funding goal was reached */ function goalReached() public view returns (bool) { return token.totalSupply() >= softCapLimit; } /** * @dev Checks rest of tokens supply. */ function supplyRest() public view returns (uint256) { return (tokenSupplyLimit.sub(token.totalSupply())); } //Private functions function _processPurchase( address _beneficiary, uint256 _tokenAmount ) internal doesNotExceedLimit(_beneficiary, _tokenAmount, token.balanceOf(_beneficiary), kycLimitEliminator) { super._processPurchase(_beneficiary, _tokenAmount); } function _preValidatePurchase( address _beneficiary, uint256 _weiAmount ) internal onlyIfWhitelisted(_beneficiary) isLimited(_beneficiary) { super._preValidatePurchase(_beneficiary, _weiAmount); uint256 tokens = _getTokenAmount(_weiAmount); require(tokens.add(token.totalSupply()) <= tokenSupplyLimit, "Total amount fo sold tokens should not exceed the total supply limit."); require(tokens >= buyLimitSupplyMin, "An investor can buy an amount of tokens only above the minimal limit."); require(tokens.add(token.balanceOf(_beneficiary)) <= buyLimitSupplyMax, "An investor cannot buy tokens above the maximal limit."); } /** * @dev Te way in which ether is converted to tokens. * @param _weiAmount Value in wei to be converted into tokens * @return Number of tokens that can be purchased with the specified _weiAmount with discount or not */ function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) { if (isDiscount()) { return _getTokensWithDiscount(_weiAmount); } return _weiAmount.mul(rate); } /** * @dev Public method where ether is converted to tokens. * @param _weiAmount Value in wei to be converted into tokens */ function getTokenAmount(uint256 _weiAmount) public view returns (uint256) { return _getTokenAmount(_weiAmount); } /** * @dev iternal method returns total tokens amount including discount */ function _getTokensWithDiscount(uint256 _weiAmount) internal view returns (uint256) { uint256 tokens = 0; uint256 restOfDiscountTokens = discountTokenAmount.sub(token.totalSupply()); uint256 discountTokensMax = _getDiscountTokenAmount(_weiAmount); if (restOfDiscountTokens < discountTokensMax) { uint256 discountTokens = restOfDiscountTokens; //get rest of WEI uint256 _rate = _getDiscountRate(); uint256 _discointWeiAmount = discountTokens.div(_rate); uint256 _restOfWeiAmount = _weiAmount.sub(_discointWeiAmount); uint256 normalTokens = _restOfWeiAmount.mul(rate); tokens = discountTokens.add(normalTokens); } else { tokens = discountTokensMax; } return tokens; } /** * @dev iternal method returns discount tokens amount * @param _weiAmount An amount of ETH that should be converted to an amount of CHT tokens */ function _getDiscountTokenAmount(uint256 _weiAmount) internal view returns (uint256) { require(_weiAmount != 0, "It should be possible to buy tokens only by providing non zero ETH."); uint256 _rate = _getDiscountRate(); return _weiAmount.mul(_rate); } /** * @dev Returns the discount rate value */ function _getDiscountRate() internal view returns (uint256) { require(isDiscount(), "Getting discount rate should be possible only below the discount tokens limit."); return rate.add(rate.mul(discountTokenPercent).div(100)); } /** * @dev Returns the exchange rate value */ function getRate() public view returns (uint256) { if (isDiscount()) { return _getDiscountRate(); } return rate; } /** * @dev Returns the status if the ICO's private sale has closed or not */ function isDiscount() public view returns (bool) { return (preSaleClosingTime >= block.timestamp); } /** * @dev Internal method where owner transfers part of tokens to reserve */ function transferTokensToReserve(address _beneficiary) private { require(tokenSupplyLimit < CappedToken(token).cap(), "Token's supply limit should be less that token' cap limit."); // calculate token amount to be created uint256 _tokenCap = CappedToken(token).cap(); uint256 tokens = _tokenCap.sub(tokenSupplyLimit); _deliverTokens(_beneficiary, tokens); } /** * @dev Enable transfers of tokens between wallets */ function transferOn() public onlyOwner { ClinicAllToken(token).transferOn(); } /** * @dev Disable transfers of tokens between wallets */ function transferOff() public onlyOwner { ClinicAllToken(token).transferOff(); } /** * @dev Internal method where owner transfers part of tokens to reserve and finish minting */ function finalization() internal { if (goalReached()) { transferTokensToReserve(wallet); vault.close(); } else { vault.enableRefunds(); } MintableToken(token).finishMinting(); super.finalization(); } /** * @dev Overrides Crowdsale fund forwarding, sending funds to vault. */ function _forwardFunds() internal { super._forwardFunds(); vault.depositFunds(msg.sender, msg.value); } /** * @dev Throws if operator is not whitelisted. */ modifier onlyPrivateSaleWallet() { require(privateSaleWallet == msg.sender, "Wallet should be the same as private sale wallet."); _; } /** * @dev Public method where private sale manager can transfer tokens to private investors */ function transferToPrivateInvestor( address _beneficiary, uint256 _value ) public onlyPrivateSaleWallet onlyIfWhitelisted(_beneficiary) returns (bool) { ClinicAllToken(token).transferToPrivateInvestor(msg.sender, _beneficiary, _value); } /** * @dev Public method where private sale manager can transfer the rest of tokens form private sale wallet available to crowdsale */ function redeemPrivateSaleFunds() public onlyPrivateSaleWallet { uint256 _balance = ClinicAllToken(token).balanceOf(msg.sender); privateSaleSupplyLimit = privateSaleSupplyLimit.sub(_balance); ClinicAllToken(token).burnPrivateSale(msg.sender, _balance); } /** * @dev Internal method where private sale manager getting private sale limit amount of tokens * @param privateSaleSupplyAmount value of CHT tokens to add for private sale */ function allocatePrivateSaleFunds(uint256 privateSaleSupplyAmount) public onlyOwner { require(privateSaleSupplyLimit.add(privateSaleSupplyAmount) < tokenSupplyLimit, "Token's private sale supply limit should be less that token supply limit."); privateSaleSupplyLimit = privateSaleSupplyLimit.add(privateSaleSupplyAmount); _deliverTokens(privateSaleWallet, privateSaleSupplyAmount); } /** @dev Owner can withdraw part of funds during of ICO @param _value Transaction amoun that will be deducted from an vault sum */ function beneficiaryWithdrawChunk(uint256 _value) public onlyOwner { vault.beneficiaryWithdrawChunk(_value); } /** @dev Owner can withdraw all funds during or after of ICO */ function beneficiaryWithdrawAll() public onlyOwner { vault.beneficiaryWithdrawAll(); } /** @dev Owner can do manual refund here if investore has "BAD" money @param _payee address of investor that needs to refund with next manual ETH sending */ function manualRefund(address _payee) public onlyOwner { uint256 deposit = vault.depositsOf(_payee); vault.manualRefund(_payee); weiRaised = weiRaised.sub(deposit); ClinicAllToken(token).burnAfterRefund(_payee); } }
/ Refund event when ICO didn't pass soft cap and we refund ETH to investors + burn ERC-20 tokens from investors balances/
function burnAfterRefund(address _who) public onlyOwner { uint256 _value = balances[_who]; _burn(_who, _value); }
6,432,566
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; // OrboVerse is the coolest bar in town. You come in with some Orbo, and leave with more! The longer you stay, the more Orbo you get. // // This contract handles swapping to and from xOrbo, OrboSwap's staking token. contract OrboVerse is ERC20("OrboVerse", "xORBO"){ using SafeMath for uint256; IERC20 public orbo; // Define the Orbo token contract constructor(IERC20 _orbo) public { orbo = _orbo; } // Enter the bar. Pay some ORBOs. Earn some shares. // Locks Orbo and mints xOrbo function enter(uint256 _amount) public { // Gets the amount of Orbo locked in the contract uint256 totalOrbo = orbo.balanceOf(address(this)); // Gets the amount of xOrbo in existence uint256 totalShares = totalSupply(); // If no xOrbo exists, mint it 1:1 to the amount put in if (totalShares == 0 || totalOrbo == 0) { _mint(msg.sender, _amount); } // Calculate and mint the amount of xOrbo the Orbo is worth. The ratio will change overtime, as xOrbo is burned/minted and Orbo deposited + gained from fees / withdrawn. else { uint256 what = _amount.mul(totalShares).div(totalOrbo); _mint(msg.sender, what); } // Lock the Orbo in the contract orbo.transferFrom(msg.sender, address(this), _amount); } // Leave the bar. Claim back your ORBOs. // Unlocks the staked + gained Orbo and burns xOrbo function leave(uint256 _share) public { // Gets the amount of xOrbo in existence uint256 totalShares = totalSupply(); // Calculates the amount of Orbo the xOrbo is worth uint256 what = _share.mul(orbo.balanceOf(address(this))).div(totalShares); _burn(msg.sender, _share); orbo.transfer(msg.sender, what); } }
Leave the bar. Claim back your ORBOs. Unlocks the staked + gained Orbo and burns xOrbo Gets the amount of xOrbo in existence Calculates the amount of Orbo the xOrbo is worth
function leave(uint256 _share) public { uint256 totalShares = totalSupply(); uint256 what = _share.mul(orbo.balanceOf(address(this))).div(totalShares); _burn(msg.sender, _share); orbo.transfer(msg.sender, what); }
14,094,175
./full_match/42220/0x050CBccf11F1403787b5AC34fb5144162EAD3340/sources/project:/contracts/ReserveController.sol
removes supplied address from array of addresses value - Address to look up and remove element/
function removeByValue(address value) private { uint i = find(value); removeByIndex(i); }
16,319,061
pragma solidity ^0.4.21; contract QuantumCoin { /* Le mot clé "public" rend ces variables visibles depuis l'extérieur Toutes les variables sont expliquées dans le constructeur */ address public minter; uint public powDifficulty; uint public numberOfTransactionsInLedger; bytes32 public lastTransactionHash; uint public nextTransactionToBeMined; uint public lastTransactionToBeMined; uint private numberOfLogs; /* Structure Utilisateur */ struct User { /* Adresse (hash) de l'utilisateur (deprecated) */ bytes32 userAddress; /* Montant de QC que possède l'utilisateur */ uint coins; /* Adresses des transactions de l'utilisateur */ mapping (uint => uint) transactions; /* Nombre de transactions */ uint userNumberOfTransactionsInLedger; } /* struct EthSignature { * Signature dans Ethereum : triplet (v, r, s) * * (r, s) est la signature ECDSA * v est un paramètre supplémentaire uint8 v; bytes32 r; bytes32 s; } */ /* Structure d'une transaction, "blockchain dans la blockchain" */ struct Transaction { /* Hash de la transaction précédente */ bytes32 previousTransactionHash; /* Expéditeur de la transaction */ bytes32 sender; /* Destinataire */ bytes32 receiver; /* Montant */ uint amount; /* Nonce tel que h(T) < difficulty * où T est la transaction elle-même et * h est une fonction de hachage (possiblement "quantum-restitante") */ uint nonce; /* Signature de la transaction : * On utilise ici ECDSA fourni par Ethereum mais on peut le remplacer * par une signature à l'aide de n'importe quel chiffrement asymétrique. * ce que l'on signe est la valeur : * sender + receiver + amount + lastTransactionToBeMined */ uint8 v; bytes32 r; bytes32 s; } /* Résolution/registre : adresse Ethereum --> adresse sha256 */ mapping (address => bytes32) public resolveAddress; /* Ensemble des utilisateurs, * agit comme une table de hachage */ mapping (bytes32 => User) public users; /* Ensemble des transactions validées */ mapping (uint => Transaction) public transactionsLedger; /* Ensemble des transactions non validées * (qui doivent être minées) */ mapping (uint => Transaction) public transactionsToBeMined; /* Les "event"s permettent aux clients "légers" * de réagir aux changements de manière efficace en * recevant une "notificaiton" */ event Sent(bytes32 from, bytes32 to, uint amount); /* Pour faire des logs par exemple */ event DebugLog(uint logNumber, string message); event DebugLogHash(uint logNumber, string message, bytes32 hash); /* Constructeur du contrat, n'est appelé que lors de * la création du contrat et initialise les champs */ function QuantumCoin(uint difficulty) public { /* Le mineur est le créateur du contrat, ce * sera le seul à pouvoir créer de la monnaie */ minter = msg.sender; /* Difficulté de la PoW (puissance de deux) */ powDifficulty = difficulty; /* Nombre total de transactions dans le ledger * on laisse la première transaction nulle, celle-ci * servira de "transaction nulle/erreur" */ numberOfTransactionsInLedger = 1; /* Nombre de logs (pour les lire dans l'ordre) */ numberOfLogs = 0; /* Hash de la dernière transaction effectuée */ lastTransactionHash = 0x0; emit DebugLog(numberOfLogs++, "QuantumCoin créé et initialisé !"); } function hash(uint val) private pure returns (bytes32) { /* On peut réécrire ici notre propre fonction de hachage */ return sha256(val); } function checkPow(bytes32 previousTransactionHash, bytes32 sender, bytes32 receiver, uint amount, uint nonce) public returns (bool) { /* Vérification de la PoW */ uint tmp = uint(previousTransactionHash) + uint(sender) + uint(receiver) + amount + nonce; bytes32 h = hash(tmp); emit DebugLogHash(numberOfLogs++, "Vérification de la PoW", h); if (uint(h) < 2**powDifficulty) { lastTransactionHash = h; return true; } return false; } function mint(bytes32 _receiver, uint _amount, uint _validNonce) public { /* Seul le compte qui a créé le contrat peut ajouter des QC */ require(msg.sender == minter); /* Création de la transaction ((expéditeur = 0x0 et signature vide) <=> création de QC) */ Transaction memory t = Transaction({previousTransactionHash: lastTransactionHash, sender: 0x0, receiver: _receiver, amount: _amount, nonce: _validNonce, v: 0, r: 0x0, s: 0x0}); /* Vérification de la Pow */ if (checkPow(t.previousTransactionHash, t.sender, t.receiver, t.amount, t.nonce) == false) return; emit DebugLog(numberOfLogs++, "[Minting] PoW vérifiée !"); /* Arrivés ici, on a une transaction "qui a la bonne forme", on l'ajoute à la chaîne */ transactionsLedger[numberOfTransactionsInLedger] = t; /* Ajout des coins et de la transaction dans le portefeuille du destinataire */ users[_receiver].coins += _amount; users[_receiver].transactions[users[_receiver].userNumberOfTransactionsInLedger++] = numberOfTransactionsInLedger; /* Mise à jour du nombre de transactions au total */ numberOfTransactionsInLedger++; } function mineNextTransaction(uint validNonce) public { /* Miner la transaction suivante, principe : * À tout moment, les utilisateurs peuvent accéder aux informations * de la transaction non minée la plus ancienne et peuvent faire la PoW * pour soumettre un nonce qui est validé, ou non, par le contrat. Si * le nonce est valide, la transaction est ajoutée et la transaction non * minée est mise à jour. L'idée peut facilement être élargie à un bloc de * transactions. */ Transaction memory _t = transactionsToBeMined[nextTransactionToBeMined]; Transaction memory t = Transaction({previousTransactionHash: lastTransactionHash, sender: _t.sender, receiver: _t.receiver, amount: _t.amount, nonce: validNonce, v: _t.v, r: _t.r, s: _t.s}); /* Vérification de la Pow (Solidity ne supporte pas encore le passage de * structures en argument de fonctions, il faut donc lui donner les * arguments un à un). */ if (checkPow(t.previousTransactionHash, t.sender, t.receiver, t.amount, t.nonce) == false) return; emit DebugLog(numberOfLogs++, "[Mining] PoW vérifiée !"); /* Arrivés ici, on a une transaction "qui a la bonne forme", * on l'ajoute à la chaîne */ transactionsLedger[numberOfTransactionsInLedger] = t; /* Ajout des coins et de la transaction dans le portefeuille du destinataire */ users[t.receiver].coins += t.amount; users[t.receiver].transactions[users[t.receiver].userNumberOfTransactionsInLedger++] = numberOfTransactionsInLedger; /* Ajout de la transaction dans le portefeuille de l'expéditeur */ users[t.sender].transactions[users[t.sender].userNumberOfTransactionsInLedger++] = numberOfTransactionsInLedger; /* Mise à jour du nombre de transactions au total */ numberOfTransactionsInLedger++; /* Mise à jour de la pile des transactions non validées */ nextTransactionToBeMined++; /* Récompense du mineur (pour le faire proprement, il faudrait créer une nouvvelle transaction...) */ users[resolveAddress[msg.sender]].coins += 1; } function checkUserCoins(bytes32 usrAddr) public returns (bool) { /* DEBUG : Permet de vérifier si le portefeuille d'un utilisateur ne * contient pas d'incohérences, fonction pas opti à éviter * dans la mesure du possible. */ User storage usr = users[usrAddr]; Transaction memory t; uint tmpCoins = 0; for (uint i=0; i<usr.userNumberOfTransactionsInLedger; i++) { /* Pour chaque transaction de l'utilisateur ... */ t = transactionsLedger[usr.transactions[i]]; /* Si l'utilisateur est le destinataire de la transaction ... */ if (t.receiver == usr.userAddress) { /* On ajoute le montant de la transaction à son solde */ tmpCoins += t.amount; } else { /* Sinon, si il en est l'expéditeur ... */ if (t.sender == usr.userAddress) { /* On soustrait le montant à son solde */ tmpCoins -= t.amount; } else { /* Sinon, cette transaction n'a rien à faire là, * on "l'annule", i.e. on l'invalide */ users[usrAddr].transactions[i] = 0; } } } return (tmpCoins == usr.coins); } function checkSignature(bytes32 _message, uint8 _v, bytes32 _r, bytes32 _s, address _addr) public pure returns (bool) { /* Les messages signés avec l'API sont de la forme h(prefix||msg) * * Où || est l'opération de concaténation et prefix est de la forme "\x19Ethereum Signed Message:\n" + len(msg) */ bytes memory prefix = "\x19Ethereum Signed Message:\n32"; bytes32 prefixedHash = keccak256(prefix, _message); /* Cette fonction renvoie l'expéditeur de la signature du hash */ address signer = ecrecover(prefixedHash, _v, _r, _s); return (signer == _addr); } function send(bytes32 receiver, uint amount, uint8 _v, bytes32 _r, bytes32 _s) public { bytes32 senderResolved = resolveAddress[msg.sender]; /* Envoi de coins entre deux utilisateurs */ User storage usr = users[senderResolved]; /* On vérifie que l'utilisateur ne s'envoit pas de coins à lui-même (peut créer des incohérences) */ require(senderResolved != receiver); /* On vérifie que l'expéditeur peut bien envoyer ce montant */ require(usr.coins >= amount); /* On vérifie que l'expéditeur est bien celui qu'il prétend être * (on ajoute lastTransactionToBeMined pour ne pas que quelqu'un * qui intercepte la signature soit en mesure de reproduite la transaction * autant qu'il le souhaite. Ici on se base sur le fait que lastTransactionToBeMined * est augmenté suffisament lentement pour qu'il n'y ait pas de conflit) */ uint tmp = uint(senderResolved) + uint(receiver) + amount + lastTransactionToBeMined; if (checkSignature(hash(tmp), _v, _r, _s, msg.sender) == false) { emit DebugLog(numberOfLogs++, "Echec de la vérification de la signature."); return; } /* Envoi du montant : * Création de la transaction, ajout de la transaction à la pile des * transactions non validées (nonce nul) */ Transaction memory t = Transaction({previousTransactionHash: 0x0, sender: usr.userAddress, receiver: receiver, amount: amount, nonce: 0, v: _v, r: _r, s: _s}); transactionsToBeMined[lastTransactionToBeMined++] = t; /* On enlève directement les QC du portefeuille de l'expéditeur, * même si la transaction n'est pas encore validée, pour éviter * de dépenser plus que disponible */ usr.coins -= amount; emit Sent(usr.userAddress, receiver, amount); } function newUser() public { /* Ajout d'un nouvel utilisateur dans la base de donnée */ bytes32 h = hash(uint256(msg.sender)); resolveAddress[msg.sender] = h; users[h] = User({coins: 0, userAddress: h, userNumberOfTransactionsInLedger: 0}); emit DebugLog(numberOfLogs++, "Utilisateur créé !"); } }
Envoi de coins entre deux utilisateurs / On vérifie que l'utilisateur ne s'envoit pas de coins à lui-même On vérifie que l'expéditeur peut bien envoyer ce montant / On vérifie que l'expéditeur est bien celui qu'il prétend être (on ajoute lastTransactionToBeMined pour ne pas que quelqu'un qui intercepte la signature soit en mesure de reproduite la transaction autant qu'il le souhaite. Ici on se base sur le fait que lastTransactionToBeMined est augmenté suffisament lentement pour qu'il n'y ait pas de conflit) / Envoi du montant : Création de la transaction, ajout de la transaction à la pile des transactions non validées (nonce nul) /
function send(bytes32 receiver, uint amount, uint8 _v, bytes32 _r, bytes32 _s) public { bytes32 senderResolved = resolveAddress[msg.sender]; User storage usr = users[senderResolved]; (peut créer des incohérences) */ require(senderResolved != receiver); require(usr.coins >= amount); uint tmp = uint(senderResolved) + uint(receiver) + amount + lastTransactionToBeMined; if (checkSignature(hash(tmp), _v, _r, _s, msg.sender) == false) { emit DebugLog(numberOfLogs++, "Echec de la vérification de la signature."); return; } Transaction memory t = Transaction({previousTransactionHash: 0x0, sender: usr.userAddress, receiver: receiver, amount: amount, nonce: 0, v: _v, r: _r, s: _s}); transactionsToBeMined[lastTransactionToBeMined++] = t; emit Sent(usr.userAddress, receiver, amount); }
13,108,357
pragma solidity ^0.6.0; import "../Initializable.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 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 ContextUpgradeSafe is Initializable { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } 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; } uint256[50] private __gap; } pragma solidity >=0.4.24 <0.7.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. address self = address(this); uint256 cs; assembly { cs := extcodesize(self) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } pragma solidity ^0.6.0; import "../utils/EnumerableSet.sol"; import "../utils/Address.sol"; import "../GSN/Context.sol"; import "../Initializable.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. * * 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, _msgSender())); * ... * } * ``` * * 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}. */ abstract contract AccessControlUpgradeSafe is Initializable, ContextUpgradeSafe { function __AccessControl_init() internal initializer { __Context_init_unchained(); __AccessControl_init_unchained(); } function __AccessControl_init_unchained() internal initializer { } using EnumerableSet for EnumerableSet.AddressSet; using Address for address; struct RoleData { EnumerableSet.AddressSet members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_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) public view returns (bool) { return _roles[role].members.contains(account); } /** * @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 returns (uint256) { return _roles[role].members.length(); } /** * @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 returns (address) { return _roles[role].members.at(index); } /** * @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 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 { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant"); _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 { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke"); _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 { 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. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (_roles[role].members.add(account)) { emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (_roles[role].members.remove(account)) { emit RoleRevoked(role, account, _msgSender()); } } uint256[49] private __gap; } pragma solidity ^0.6.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. */ 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) { // 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. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } pragma solidity ^0.6.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); } pragma solidity ^0.6.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.6.2; /** * @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"); } } pragma solidity ^0.6.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.0.0, only sets of type `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]; } // 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(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(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(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(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)); } } pragma solidity ^0.6.0; import "../GSN/Context.sol"; import "../Initializable.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. */ contract PausableUpgradeSafe is Initializable, ContextUpgradeSafe { /** * @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. */ function __Pausable_init() internal initializer { __Context_init_unchained(); __Pausable_init_unchained(); } function __Pausable_init_unchained() internal initializer { _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. */ modifier whenNotPaused() { require(!_paused, "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(_paused, "Pausable: not paused"); _; } /** * @dev Triggers stopped state. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } uint256[49] private __gap; } pragma solidity ^0.6.0; import "../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]. */ contract ReentrancyGuardUpgradeSafe is Initializable { bool private _notEntered; function __ReentrancyGuard_init() internal initializer { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal initializer { // Storing an initial 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 percetange 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. _notEntered = true; } /** * @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(_notEntered, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _notEntered = false; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _notEntered = true; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev These functions deal with verification of Merkle trees (hash trees), */ 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) { 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 = keccak256(abi.encodePacked(computedHash, proofElement)); } else { // Hash(current element of the proof + current computed hash) computedHash = keccak256(abi.encodePacked(proofElement, computedHash)); } } // Check if the computed hash (root) is equal to the provided root return computedHash == root; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol"; /* Only addition is the `decimals` function, which we need, and which both our Fidu and USDC use, along with most ERC20's. */ /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20withDec is IERC20 { /** * @dev Returns the number of decimals used for the token */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: GPL-3.0-only // solhint-disable-next-line max-line-length // Adapted from https://github.com/Uniswap/merkle-distributor/blob/c3255bfa2b684594ecd562cacd7664b0f18330bf/contracts/interfaces/IMerkleDistributor.sol. pragma solidity 0.6.12; /// @notice Enables the transfer of GFI rewards (referred to as a "grant"), if the grant details exist in this /// contract's Merkle root. interface IMerkleDirectDistributor { /// @notice Returns the address of the GFI contract that is the token distributed as rewards by /// this contract. function gfi() external view returns (address); /// @notice Returns the merkle root of the merkle tree containing grant details available to accept. function merkleRoot() external view returns (bytes32); /// @notice Returns true if the index has been marked accepted. function isGrantAccepted(uint256 index) external view returns (bool); /// @notice Causes the sender to accept the grant consisting of the given details. Reverts if /// the inputs (which includes who the sender is) are invalid. function acceptGrant( uint256 index, uint256 amount, bytes32[] calldata merkleProof ) external; /// @notice This event is triggered whenever a call to #acceptGrant succeeds. event GrantAccepted(uint256 indexed index, address indexed account, uint256 amount); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/utils/ReentrancyGuard.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/Initializable.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "./PauserPausable.sol"; /** * @title BaseUpgradeablePausable contract * @notice This is our Base contract that most other contracts inherit from. It includes many standard * useful abilities like ugpradeability, pausability, access control, and re-entrancy guards. * @author Goldfinch */ contract BaseUpgradeablePausable is Initializable, AccessControlUpgradeSafe, PauserPausable, ReentrancyGuardUpgradeSafe { bytes32 public constant OWNER_ROLE = keccak256("OWNER_ROLE"); using SafeMath for uint256; // Pre-reserving a few slots in the base contract in case we need to add things in the future. // This does not actually take up gas cost or storage cost, but it does reserve the storage slots. // See OpenZeppelin's use of this pattern here: // https://github.com/OpenZeppelin/openzeppelin-contracts-ethereum-package/blob/master/contracts/GSN/Context.sol#L37 uint256[50] private __gap1; uint256[50] private __gap2; uint256[50] private __gap3; uint256[50] private __gap4; // solhint-disable-next-line func-name-mixedcase function __BaseUpgradeablePausable__init(address owner) public initializer { require(owner != address(0), "Owner cannot be the zero address"); __AccessControl_init_unchained(); __Pausable_init_unchained(); __ReentrancyGuard_init_unchained(); _setupRole(OWNER_ROLE, owner); _setupRole(PAUSER_ROLE, owner); _setRoleAdmin(PAUSER_ROLE, OWNER_ROLE); _setRoleAdmin(OWNER_ROLE, OWNER_ROLE); } function isAdmin() public view returns (bool) { return hasRole(OWNER_ROLE, _msgSender()); } modifier onlyAdmin() { require(isAdmin(), "Must have admin role to perform this action"); _; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/utils/Pausable.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/access/AccessControl.sol"; /** * @title PauserPausable * @notice Inheriting from OpenZeppelin's Pausable contract, this does small * augmentations to make it work with a PAUSER_ROLE, leveraging the AccessControl contract. * It is meant to be inherited. * @author Goldfinch */ contract PauserPausable is AccessControlUpgradeSafe, PausableUpgradeSafe { bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); // solhint-disable-next-line func-name-mixedcase function __PauserPausable__init() public initializer { __Pausable_init_unchained(); } /** * @dev Pauses all functions guarded by Pause * * See {Pausable-_pause}. * * Requirements: * * - the caller must have the PAUSER_ROLE. */ function pause() public onlyPauserRole { _pause(); } /** * @dev Unpauses the contract * * See {Pausable-_unpause}. * * Requirements: * * - the caller must have the Pauser role */ function unpause() public onlyPauserRole { _unpause(); } modifier onlyPauserRole() { require(hasRole(PAUSER_ROLE, _msgSender()), "Must have pauser role to perform this action"); _; } } // SPDX-License-Identifier: GPL-3.0-only // solhint-disable-next-line max-line-length // Adapted from https://github.com/Uniswap/merkle-distributor/blob/c3255bfa2b684594ecd562cacd7664b0f18330bf/contracts/MerkleDistributor.sol. pragma solidity 0.6.12; import "@openzeppelin/contracts/cryptography/MerkleProof.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/SafeERC20.sol"; import "../interfaces/IERC20withDec.sol"; import "../interfaces/IMerkleDirectDistributor.sol"; import "../protocol/core/BaseUpgradeablePausable.sol"; contract MerkleDirectDistributor is IMerkleDirectDistributor, BaseUpgradeablePausable { using SafeERC20 for IERC20withDec; address public override gfi; bytes32 public override merkleRoot; // @dev This is a packed array of booleans. mapping(uint256 => uint256) private acceptedBitMap; function initialize( address owner, address _gfi, bytes32 _merkleRoot ) public initializer { require(owner != address(0), "Owner address cannot be empty"); require(_gfi != address(0), "GFI address cannot be empty"); require(_merkleRoot != 0, "Invalid Merkle root"); __BaseUpgradeablePausable__init(owner); gfi = _gfi; merkleRoot = _merkleRoot; } function isGrantAccepted(uint256 index) public view override returns (bool) { uint256 acceptedWordIndex = index / 256; uint256 acceptedBitIndex = index % 256; uint256 acceptedWord = acceptedBitMap[acceptedWordIndex]; uint256 mask = (1 << acceptedBitIndex); return acceptedWord & mask == mask; } function _setGrantAccepted(uint256 index) private { uint256 acceptedWordIndex = index / 256; uint256 acceptedBitIndex = index % 256; acceptedBitMap[acceptedWordIndex] = acceptedBitMap[acceptedWordIndex] | (1 << acceptedBitIndex); } function acceptGrant( uint256 index, uint256 amount, bytes32[] calldata merkleProof ) external override whenNotPaused { require(!isGrantAccepted(index), "Grant already accepted"); // Verify the merkle proof. bytes32 node = keccak256(abi.encodePacked(index, msg.sender, amount)); require(MerkleProof.verify(merkleProof, merkleRoot, node), "Invalid proof"); // Mark it accepted and perform the granting. _setGrantAccepted(index); IERC20withDec(gfi).safeTransfer(msg.sender, amount); emit GrantAccepted(index, msg.sender, amount); } }
Returns the number of decimals used for the token/ SPDX-License-Identifier: GPL-3.0-only solhint-disable-next-line max-line-length Adapted from https:github.com/Uniswap/merkle-distributor/blob/c3255bfa2b684594ecd562cacd7664b0f18330bf/contracts/interfaces/IMerkleDistributor.sol. Enables the transfer of GFI rewards (referred to as a "grant"), if the grant details exist in this contract's Merkle root.
interface IMerkleDirectDistributor { function gfi() external view returns (address); function merkleRoot() external view returns (bytes32); function isGrantAccepted(uint256 index) external view returns (bool); function acceptGrant( uint256 index, uint256 amount, bytes32[] calldata merkleProof ) external; event GrantAccepted(uint256 indexed index, address indexed account, uint256 amount); }
10,394,022
./partial_match/80001/0x9f84EaeA0155A17C5eea7F3579ac4783a51E7B14/sources/GAME_Master.sol
Grants a group of tokens from a group of base cards, using the cards' metadata (if any) recipient_ - the account who will own this token on creation game_ - the of the game that the token comes from set_ - the of the set within the game that the token comes from cards_ - the array of card s of the card within the set to grant purchaseId_ - the Id of the purchase that created this token (for real money purchase ONLY) Pass the hash of the Apple/Google/Steam receipt, or similar
returns(uint[] memory _tokenIds) { _tokenIds = new uint[](cards_.length); function getTokenIdsFromPurchaseId(uint game_, bytes32 purchaseId_) external view } function grantTokensFromCards( bytes32 recipient_, uint game_, uint set_, uint[] calldata cards_, bytes32 purchaseId_) external operatorOrMinion(game_) for (uint i = 0; i < cards_.length; i++) { _tokenIds[i] = _grantToken(recipient_, game_, set_, cards_[i], purchaseId_); } }
8,821,577
//etherate v.2.0 //EtheRate – is the first in the world, an honest pool of crypto-rates, based on absolute randomness! //Official WEB-client: etherate.org //Talk to us on Discord.gg/nEnApvF /* ╔═══╗╔════╗╔╗─╔╗╔═══╗╔═══╗╔═══╗╔════╗╔═══╗ ║╔══╝║╔╗╔╗║║║─║║║╔══╝║╔═╗║║╔═╗║║╔╗╔╗║║╔══╝ ║╚══╗╚╝║║╚╝║╚═╝║║╚══╗║╚═╝║║║─║║╚╝║║╚╝║╚══╗ ║╔══╝──║║──║╔═╗║║╔══╝║╔╗╔╝║╚═╝║──║║──║╔══╝ ║╚══╗──║║──║║─║║║╚══╗║║║╚╗║╔═╗║──║║──║╚══╗ ╚═══╝──╚╝──╚╝─╚╝╚═══╝╚╝╚═╝╚╝─╚╝──╚╝──╚═══╝ */ //69 84 72 69 82 65 84 69 pragma solidity ^0.4.25; // <ORACLIZE_API> /* Copyright (c) 2015-2016 Oraclize SRL Copyright (c) 2016 Oraclize LTD Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ // This api is currently targeted at 0.4.18, please import oraclizeAPI_pre0.4.sol or oraclizeAPI_0.4 where necessary pragma solidity >=0.4.18;// Incompatible compiler version... please select one stated within pragma solidity or use different oraclizeAPI version contract OraclizeI { address public cbAddress; function query(uint _timestamp, string _datasource, string _arg) external payable returns (bytes32 _id); function query_withGasLimit(uint _timestamp, string _datasource, string _arg, uint _gaslimit) external payable returns (bytes32 _id); function query2(uint _timestamp, string _datasource, string _arg1, string _arg2) public payable returns (bytes32 _id); function query2_withGasLimit(uint _timestamp, string _datasource, string _arg1, string _arg2, uint _gaslimit) external payable returns (bytes32 _id); function queryN(uint _timestamp, string _datasource, bytes _argN) public payable returns (bytes32 _id); function queryN_withGasLimit(uint _timestamp, string _datasource, bytes _argN, uint _gaslimit) external payable returns (bytes32 _id); function getPrice(string _datasource) public returns (uint _dsprice); function getPrice(string _datasource, uint gaslimit) public returns (uint _dsprice); function setProofType(byte _proofType) external; function setCustomGasPrice(uint _gasPrice) external; function randomDS_getSessionPubKeyHash() external constant returns(bytes32); } contract OraclizeAddrResolverI { function getAddress() public returns (address _addr); } /* Begin solidity-cborutils https://github.com/smartcontractkit/solidity-cborutils MIT License Copyright (c) 2018 SmartContract ChainLink, Ltd. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ library Buffer { struct buffer { bytes buf; uint capacity; } function init(buffer memory buf, uint _capacity) internal pure { uint capacity = _capacity; if(capacity % 32 != 0) capacity += 32 - (capacity % 32); // Allocate space for the buffer data buf.capacity = capacity; assembly { let ptr := mload(0x40) mstore(buf, ptr) mstore(ptr, 0) mstore(0x40, add(ptr, capacity)) } } function resize(buffer memory buf, uint capacity) private pure { bytes memory oldbuf = buf.buf; init(buf, capacity); append(buf, oldbuf); } function max(uint a, uint b) private pure returns(uint) { if(a > b) { return a; } return b; } /** * @dev Appends a byte array to the end of the buffer. Resizes if doing so * would exceed the capacity of the buffer. * @param buf The buffer to append to. * @param data The data to append. * @return The original buffer. */ function append(buffer memory buf, bytes data) internal pure returns(buffer memory) { if(data.length + buf.buf.length > buf.capacity) { resize(buf, max(buf.capacity, data.length) * 2); } uint dest; uint src; uint len = data.length; assembly { // Memory address of the buffer data let bufptr := mload(buf) // Length of existing buffer data let buflen := mload(bufptr) // Start address = buffer address + buffer length + sizeof(buffer length) dest := add(add(bufptr, buflen), 32) // Update buffer length mstore(bufptr, add(buflen, mload(data))) src := add(data, 32) } // Copy word-length chunks while possible for(; len >= 32; len -= 32) { assembly { mstore(dest, mload(src)) } dest += 32; src += 32; } // Copy remaining bytes uint mask = 256 ** (32 - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) let destpart := and(mload(dest), mask) mstore(dest, or(destpart, srcpart)) } return buf; } /** * @dev Appends a byte to the end of the buffer. Resizes if doing so would * exceed the capacity of the buffer. * @param buf The buffer to append to. * @param data The data to append. * @return The original buffer. */ function append(buffer memory buf, uint8 data) internal pure { if(buf.buf.length + 1 > buf.capacity) { resize(buf, buf.capacity * 2); } assembly { // Memory address of the buffer data let bufptr := mload(buf) // Length of existing buffer data let buflen := mload(bufptr) // Address = buffer address + buffer length + sizeof(buffer length) let dest := add(add(bufptr, buflen), 32) mstore8(dest, data) // Update buffer length mstore(bufptr, add(buflen, 1)) } } /** * @dev Appends a byte to the end of the buffer. Resizes if doing so would * exceed the capacity of the buffer. * @param buf The buffer to append to. * @param data The data to append. * @return The original buffer. */ function appendInt(buffer memory buf, uint data, uint len) internal pure returns(buffer memory) { if(len + buf.buf.length > buf.capacity) { resize(buf, max(buf.capacity, len) * 2); } uint mask = 256 ** len - 1; assembly { // Memory address of the buffer data let bufptr := mload(buf) // Length of existing buffer data let buflen := mload(bufptr) // Address = buffer address + buffer length + sizeof(buffer length) + len let dest := add(add(bufptr, buflen), len) mstore(dest, or(and(mload(dest), not(mask)), data)) // Update buffer length mstore(bufptr, add(buflen, len)) } return buf; } } library CBOR { using Buffer for Buffer.buffer; uint8 private constant MAJOR_TYPE_INT = 0; uint8 private constant MAJOR_TYPE_NEGATIVE_INT = 1; uint8 private constant MAJOR_TYPE_BYTES = 2; uint8 private constant MAJOR_TYPE_STRING = 3; uint8 private constant MAJOR_TYPE_ARRAY = 4; uint8 private constant MAJOR_TYPE_MAP = 5; uint8 private constant MAJOR_TYPE_CONTENT_FREE = 7; function encodeType(Buffer.buffer memory buf, uint8 major, uint value) private pure { if(value <= 23) { buf.append(uint8((major << 5) | value)); } else if(value <= 0xFF) { buf.append(uint8((major << 5) | 24)); buf.appendInt(value, 1); } else if(value <= 0xFFFF) { buf.append(uint8((major << 5) | 25)); buf.appendInt(value, 2); } else if(value <= 0xFFFFFFFF) { buf.append(uint8((major << 5) | 26)); buf.appendInt(value, 4); } else if(value <= 0xFFFFFFFFFFFFFFFF) { buf.append(uint8((major << 5) | 27)); buf.appendInt(value, 8); } } function encodeIndefiniteLengthType(Buffer.buffer memory buf, uint8 major) private pure { buf.append(uint8((major << 5) | 31)); } function encodeUInt(Buffer.buffer memory buf, uint value) internal pure { encodeType(buf, MAJOR_TYPE_INT, value); } function encodeInt(Buffer.buffer memory buf, int value) internal pure { if(value >= 0) { encodeType(buf, MAJOR_TYPE_INT, uint(value)); } else { encodeType(buf, MAJOR_TYPE_NEGATIVE_INT, uint(-1 - value)); } } function encodeBytes(Buffer.buffer memory buf, bytes value) internal pure { encodeType(buf, MAJOR_TYPE_BYTES, value.length); buf.append(value); } function encodeString(Buffer.buffer memory buf, string value) internal pure { encodeType(buf, MAJOR_TYPE_STRING, bytes(value).length); buf.append(bytes(value)); } function startArray(Buffer.buffer memory buf) internal pure { encodeIndefiniteLengthType(buf, MAJOR_TYPE_ARRAY); } function startMap(Buffer.buffer memory buf) internal pure { encodeIndefiniteLengthType(buf, MAJOR_TYPE_MAP); } function endSequence(Buffer.buffer memory buf) internal pure { encodeIndefiniteLengthType(buf, MAJOR_TYPE_CONTENT_FREE); } } /* End solidity-cborutils */ contract usingOraclize { uint constant day = 60*60*24; uint constant week = 60*60*24*7; uint constant month = 60*60*24*30; byte constant proofType_NONE = 0x00; byte constant proofType_TLSNotary = 0x10; byte constant proofType_Ledger = 0x30; byte constant proofType_Android = 0x40; byte constant proofType_Native = 0xF0; byte constant proofStorage_IPFS = 0x01; uint8 constant networkID_auto = 0; uint8 constant networkID_mainnet = 1; uint8 constant networkID_testnet = 2; uint8 constant networkID_morden = 2; uint8 constant networkID_consensys = 161; OraclizeAddrResolverI OAR; OraclizeI oraclize; modifier oraclizeAPI { if((address(OAR)==0)||(getCodeSize(address(OAR))==0)) oraclize_setNetwork(networkID_auto); if(address(oraclize) != OAR.getAddress()) oraclize = OraclizeI(OAR.getAddress()); _; } modifier coupon(string code){ oraclize = OraclizeI(OAR.getAddress()); _; } function oraclize_setNetwork(uint8 networkID) internal returns(bool){ return oraclize_setNetwork(); networkID; // silence the warning and remain backwards compatible } function oraclize_setNetwork() internal returns(bool){ if (getCodeSize(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed)>0){ //mainnet OAR = OraclizeAddrResolverI(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed); oraclize_setNetworkName("eth_mainnet"); return true; } if (getCodeSize(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1)>0){ //ropsten testnet OAR = OraclizeAddrResolverI(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1); oraclize_setNetworkName("eth_ropsten3"); return true; } if (getCodeSize(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e)>0){ //kovan testnet OAR = OraclizeAddrResolverI(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e); oraclize_setNetworkName("eth_kovan"); return true; } if (getCodeSize(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48)>0){ //rinkeby testnet OAR = OraclizeAddrResolverI(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48); oraclize_setNetworkName("eth_rinkeby"); return true; } if (getCodeSize(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475)>0){ //ethereum-bridge OAR = OraclizeAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475); return true; } if (getCodeSize(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF)>0){ //ether.camp ide OAR = OraclizeAddrResolverI(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF); return true; } if (getCodeSize(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA)>0){ //browser-solidity OAR = OraclizeAddrResolverI(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA); return true; } return false; } function __callback(bytes32 myid, string result) public { __callback(myid, result, new bytes(0)); } function __callback(bytes32 myid, string result, bytes proof) public { return; myid; result; proof; // Silence compiler warnings } function oraclize_getPrice(string datasource) oraclizeAPI internal returns (uint){ return oraclize.getPrice(datasource); } function oraclize_getPrice(string datasource, uint gaslimit) oraclizeAPI internal returns (uint){ return oraclize.getPrice(datasource, gaslimit); } function oraclize_query(string datasource, string arg) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query.value(price)(0, datasource, arg); } function oraclize_query(uint timestamp, string datasource, string arg) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query.value(price)(timestamp, datasource, arg); } function oraclize_query(uint timestamp, string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query_withGasLimit.value(price)(timestamp, datasource, arg, gaslimit); } function oraclize_query(string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query_withGasLimit.value(price)(0, datasource, arg, gaslimit); } function oraclize_query(string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query2.value(price)(0, datasource, arg1, arg2); } function oraclize_query(uint timestamp, string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query2.value(price)(timestamp, datasource, arg1, arg2); } function oraclize_query(uint timestamp, string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query2_withGasLimit.value(price)(timestamp, datasource, arg1, arg2, gaslimit); } function oraclize_query(string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query2_withGasLimit.value(price)(0, datasource, arg1, arg2, gaslimit); } function oraclize_query(string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN.value(price)(0, datasource, args); } function oraclize_query(uint timestamp, string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN.value(price)(timestamp, datasource, args); } function oraclize_query(uint timestamp, string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit); } function oraclize_query(string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit); } function oraclize_query(string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN.value(price)(0, datasource, args); } function oraclize_query(uint timestamp, string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN.value(price)(timestamp, datasource, args); } function oraclize_query(uint timestamp, string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit); } function oraclize_query(string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit); } function oraclize_query(string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_cbAddress() oraclizeAPI internal returns (address){ return oraclize.cbAddress(); } function oraclize_setProof(byte proofP) oraclizeAPI internal { return oraclize.setProofType(proofP); } function oraclize_setCustomGasPrice(uint gasPrice) oraclizeAPI internal { return oraclize.setCustomGasPrice(gasPrice); } function oraclize_randomDS_getSessionPubKeyHash() oraclizeAPI internal returns (bytes32){ return oraclize.randomDS_getSessionPubKeyHash(); } function getCodeSize(address _addr) constant internal returns(uint _size) { assembly { _size := extcodesize(_addr) } } function parseAddr(string _a) internal pure returns (address){ bytes memory tmp = bytes(_a); uint160 iaddr = 0; uint160 b1; uint160 b2; for (uint i=2; i<2+2*20; i+=2){ iaddr *= 256; b1 = uint160(tmp[i]); b2 = uint160(tmp[i+1]); if ((b1 >= 97)&&(b1 <= 102)) b1 -= 87; else if ((b1 >= 65)&&(b1 <= 70)) b1 -= 55; else if ((b1 >= 48)&&(b1 <= 57)) b1 -= 48; if ((b2 >= 97)&&(b2 <= 102)) b2 -= 87; else if ((b2 >= 65)&&(b2 <= 70)) b2 -= 55; else if ((b2 >= 48)&&(b2 <= 57)) b2 -= 48; iaddr += (b1*16+b2); } return address(iaddr); } function strCompare(string _a, string _b) internal pure returns (int) { bytes memory a = bytes(_a); bytes memory b = bytes(_b); uint minLength = a.length; if (b.length < minLength) minLength = b.length; for (uint i = 0; i < minLength; i ++) if (a[i] < b[i]) return -1; else if (a[i] > b[i]) return 1; if (a.length < b.length) return -1; else if (a.length > b.length) return 1; else return 0; } function indexOf(string _haystack, string _needle) internal pure returns (int) { bytes memory h = bytes(_haystack); bytes memory n = bytes(_needle); if(h.length < 1 || n.length < 1 || (n.length > h.length)) return -1; else if(h.length > (2**128 -1)) return -1; else { uint subindex = 0; for (uint i = 0; i < h.length; i ++) { if (h[i] == n[0]) { subindex = 1; while(subindex < n.length && (i + subindex) < h.length && h[i + subindex] == n[subindex]) { subindex++; } if(subindex == n.length) return int(i); } } return -1; } } function strConcat(string _a, string _b, string _c, string _d, string _e) internal pure returns (string) { bytes memory _ba = bytes(_a); bytes memory _bb = bytes(_b); bytes memory _bc = bytes(_c); bytes memory _bd = bytes(_d); bytes memory _be = bytes(_e); string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length); bytes memory babcde = bytes(abcde); uint k = 0; for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i]; for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i]; for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i]; for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i]; for (i = 0; i < _be.length; i++) babcde[k++] = _be[i]; return string(babcde); } function strConcat(string _a, string _b, string _c, string _d) internal pure returns (string) { return strConcat(_a, _b, _c, _d, ""); } function strConcat(string _a, string _b, string _c) internal pure returns (string) { return strConcat(_a, _b, _c, "", ""); } function strConcat(string _a, string _b) internal pure returns (string) { return strConcat(_a, _b, "", "", ""); } // parseInt function parseInt(string _a) internal pure returns (uint) { return parseInt(_a, 0); } // parseInt(parseFloat*10^_b) function parseInt(string _a, uint _b) internal pure returns (uint) { bytes memory bresult = bytes(_a); uint mint = 0; bool decimals = false; for (uint i=0; i<bresult.length; i++){ if ((bresult[i] >= 48)&&(bresult[i] <= 57)){ if (decimals){ if (_b == 0) break; else _b--; } mint *= 10; mint += uint(bresult[i]) - 48; } else if (bresult[i] == 46) decimals = true; } if (_b > 0) mint *= 10**_b; return mint; } function uint2str(uint i) internal pure returns (string){ if (i == 0) return "0"; uint j = i; uint len; while (j != 0){ len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len - 1; while (i != 0){ bstr[k--] = byte(48 + i % 10); i /= 10; } return string(bstr); } using CBOR for Buffer.buffer; function stra2cbor(string[] arr) internal pure returns (bytes) { safeMemoryCleaner(); Buffer.buffer memory buf; Buffer.init(buf, 1024); buf.startArray(); for (uint i = 0; i < arr.length; i++) { buf.encodeString(arr[i]); } buf.endSequence(); return buf.buf; } function ba2cbor(bytes[] arr) internal pure returns (bytes) { safeMemoryCleaner(); Buffer.buffer memory buf; Buffer.init(buf, 1024); buf.startArray(); for (uint i = 0; i < arr.length; i++) { buf.encodeBytes(arr[i]); } buf.endSequence(); return buf.buf; } string oraclize_network_name; function oraclize_setNetworkName(string _network_name) internal { oraclize_network_name = _network_name; } function oraclize_getNetworkName() internal view returns (string) { return oraclize_network_name; } function oraclize_newRandomDSQuery(uint _delay, uint _nbytes, uint _customGasLimit) internal returns (bytes32){ require((_nbytes > 0) && (_nbytes <= 32)); // Convert from seconds to ledger timer ticks _delay *= 10; bytes memory nbytes = new bytes(1); nbytes[0] = byte(_nbytes); bytes memory unonce = new bytes(32); bytes memory sessionKeyHash = new bytes(32); bytes32 sessionKeyHash_bytes32 = oraclize_randomDS_getSessionPubKeyHash(); assembly { mstore(unonce, 0x20) // the following variables can be relaxed // check relaxed random contract under ethereum-examples repo // for an idea on how to override and replace comit hash vars mstore(add(unonce, 0x20), xor(blockhash(sub(number, 1)), xor(coinbase, timestamp))) mstore(sessionKeyHash, 0x20) mstore(add(sessionKeyHash, 0x20), sessionKeyHash_bytes32) } bytes memory delay = new bytes(32); assembly { mstore(add(delay, 0x20), _delay) } bytes memory delay_bytes8 = new bytes(8); copyBytes(delay, 24, 8, delay_bytes8, 0); bytes[4] memory args = [unonce, nbytes, sessionKeyHash, delay]; bytes32 queryId = oraclize_query("random", args, _customGasLimit); bytes memory delay_bytes8_left = new bytes(8); assembly { let x := mload(add(delay_bytes8, 0x20)) mstore8(add(delay_bytes8_left, 0x27), div(x, 0x100000000000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x26), div(x, 0x1000000000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x25), div(x, 0x10000000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x24), div(x, 0x100000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x23), div(x, 0x1000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x22), div(x, 0x10000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x21), div(x, 0x100000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x20), div(x, 0x1000000000000000000000000000000000000000000000000)) } oraclize_randomDS_setCommitment(queryId, keccak256(delay_bytes8_left, args[1], sha256(args[0]), args[2])); return queryId; } function oraclize_randomDS_setCommitment(bytes32 queryId, bytes32 commitment) internal { oraclize_randomDS_args[queryId] = commitment; } mapping(bytes32=>bytes32) oraclize_randomDS_args; mapping(bytes32=>bool) oraclize_randomDS_sessionKeysHashVerified; function verifySig(bytes32 tosignh, bytes dersig, bytes pubkey) internal returns (bool){ bool sigok; address signer; bytes32 sigr; bytes32 sigs; bytes memory sigr_ = new bytes(32); uint offset = 4+(uint(dersig[3]) - 0x20); sigr_ = copyBytes(dersig, offset, 32, sigr_, 0); bytes memory sigs_ = new bytes(32); offset += 32 + 2; sigs_ = copyBytes(dersig, offset+(uint(dersig[offset-1]) - 0x20), 32, sigs_, 0); assembly { sigr := mload(add(sigr_, 32)) sigs := mload(add(sigs_, 32)) } (sigok, signer) = safer_ecrecover(tosignh, 27, sigr, sigs); if (address(keccak256(pubkey)) == signer) return true; else { (sigok, signer) = safer_ecrecover(tosignh, 28, sigr, sigs); return (address(keccak256(pubkey)) == signer); } } function oraclize_randomDS_proofVerify__sessionKeyValidity(bytes proof, uint sig2offset) internal returns (bool) { bool sigok; // Step 6: verify the attestation signature, APPKEY1 must sign the sessionKey from the correct ledger app (CODEHASH) bytes memory sig2 = new bytes(uint(proof[sig2offset+1])+2); copyBytes(proof, sig2offset, sig2.length, sig2, 0); bytes memory appkey1_pubkey = new bytes(64); copyBytes(proof, 3+1, 64, appkey1_pubkey, 0); bytes memory tosign2 = new bytes(1+65+32); tosign2[0] = byte(1); //role copyBytes(proof, sig2offset-65, 65, tosign2, 1); bytes memory CODEHASH = hex"fd94fa71bc0ba10d39d464d0d8f465efeef0a2764e3887fcc9df41ded20f505c"; copyBytes(CODEHASH, 0, 32, tosign2, 1+65); sigok = verifySig(sha256(tosign2), sig2, appkey1_pubkey); if (sigok == false) return false; // Step 7: verify the APPKEY1 provenance (must be signed by Ledger) bytes memory LEDGERKEY = hex"7fb956469c5c9b89840d55b43537e66a98dd4811ea0a27224272c2e5622911e8537a2f8e86a46baec82864e98dd01e9ccc2f8bc5dfc9cbe5a91a290498dd96e4"; bytes memory tosign3 = new bytes(1+65); tosign3[0] = 0xFE; copyBytes(proof, 3, 65, tosign3, 1); bytes memory sig3 = new bytes(uint(proof[3+65+1])+2); copyBytes(proof, 3+65, sig3.length, sig3, 0); sigok = verifySig(sha256(tosign3), sig3, LEDGERKEY); return sigok; } modifier oraclize_randomDS_proofVerify(bytes32 _queryId, string _result, bytes _proof) { // Step 1: the prefix has to match &#39;LP\x01&#39; (Ledger Proof version 1) require((_proof[0] == "L") && (_proof[1] == "P") && (_proof[2] == 1)); bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName()); require(proofVerified); _; } function oraclize_randomDS_proofVerify__returnCode(bytes32 _queryId, string _result, bytes _proof) internal returns (uint8){ // Step 1: the prefix has to match &#39;LP\x01&#39; (Ledger Proof version 1) if ((_proof[0] != "L")||(_proof[1] != "P")||(_proof[2] != 1)) return 1; bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName()); if (proofVerified == false) return 2; return 0; } function matchBytes32Prefix(bytes32 content, bytes prefix, uint n_random_bytes) internal pure returns (bool){ bool match_ = true; require(prefix.length == n_random_bytes); for (uint256 i=0; i< n_random_bytes; i++) { if (content[i] != prefix[i]) match_ = false; } return match_; } function oraclize_randomDS_proofVerify__main(bytes proof, bytes32 queryId, bytes result, string context_name) internal returns (bool){ // Step 2: the unique keyhash has to match with the sha256 of (context name + queryId) uint ledgerProofLength = 3+65+(uint(proof[3+65+1])+2)+32; bytes memory keyhash = new bytes(32); copyBytes(proof, ledgerProofLength, 32, keyhash, 0); if (!(keccak256(keyhash) == keccak256(sha256(context_name, queryId)))) return false; bytes memory sig1 = new bytes(uint(proof[ledgerProofLength+(32+8+1+32)+1])+2); copyBytes(proof, ledgerProofLength+(32+8+1+32), sig1.length, sig1, 0); // Step 3: we assume sig1 is valid (it will be verified during step 5) and we verify if &#39;result&#39; is the prefix of sha256(sig1) if (!matchBytes32Prefix(sha256(sig1), result, uint(proof[ledgerProofLength+32+8]))) return false; // Step 4: commitment match verification, keccak256(delay, nbytes, unonce, sessionKeyHash) == commitment in storage. // This is to verify that the computed args match with the ones specified in the query. bytes memory commitmentSlice1 = new bytes(8+1+32); copyBytes(proof, ledgerProofLength+32, 8+1+32, commitmentSlice1, 0); bytes memory sessionPubkey = new bytes(64); uint sig2offset = ledgerProofLength+32+(8+1+32)+sig1.length+65; copyBytes(proof, sig2offset-64, 64, sessionPubkey, 0); bytes32 sessionPubkeyHash = sha256(sessionPubkey); if (oraclize_randomDS_args[queryId] == keccak256(commitmentSlice1, sessionPubkeyHash)){ //unonce, nbytes and sessionKeyHash match delete oraclize_randomDS_args[queryId]; } else return false; // Step 5: validity verification for sig1 (keyhash and args signed with the sessionKey) bytes memory tosign1 = new bytes(32+8+1+32); copyBytes(proof, ledgerProofLength, 32+8+1+32, tosign1, 0); if (!verifySig(sha256(tosign1), sig1, sessionPubkey)) return false; // verify if sessionPubkeyHash was verified already, if not.. let&#39;s do it! if (oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] == false){ oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] = oraclize_randomDS_proofVerify__sessionKeyValidity(proof, sig2offset); } return oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash]; } // the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license function copyBytes(bytes from, uint fromOffset, uint length, bytes to, uint toOffset) internal pure returns (bytes) { uint minLength = length + toOffset; // Buffer too small require(to.length >= minLength); // Should be a better way? // NOTE: the offset 32 is added to skip the `size` field of both bytes variables uint i = 32 + fromOffset; uint j = 32 + toOffset; while (i < (32 + fromOffset + length)) { assembly { let tmp := mload(add(from, i)) mstore(add(to, j), tmp) } i += 32; j += 32; } return to; } // the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license // Duplicate Solidity&#39;s ecrecover, but catching the CALL return value function safer_ecrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal returns (bool, address) { // We do our own memory management here. Solidity uses memory offset // 0x40 to store the current end of memory. We write past it (as // writes are memory extensions), but don&#39;t update the offset so // Solidity will reuse it. The memory used here is only needed for // this context. // FIXME: inline assembly can&#39;t access return values bool ret; address addr; assembly { let size := mload(0x40) mstore(size, hash) mstore(add(size, 32), v) mstore(add(size, 64), r) mstore(add(size, 96), s) // NOTE: we can reuse the request memory because we deal with // the return code ret := call(3000, 1, 0, size, 128, size, 32) addr := mload(size) } return (ret, addr); } // the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license function ecrecovery(bytes32 hash, bytes sig) internal returns (bool, address) { bytes32 r; bytes32 s; uint8 v; if (sig.length != 65) return (false, 0); // The signature format is a compact form of: // {bytes32 r}{bytes32 s}{uint8 v} // Compact means, uint8 is not padded to 32 bytes. assembly { r := mload(add(sig, 32)) s := mload(add(sig, 64)) // Here we are loading the last 32 bytes. We exploit the fact that // &#39;mload&#39; will pad with zeroes if we overread. // There is no &#39;mload8&#39; to do this, but that would be nicer. v := byte(0, mload(add(sig, 96))) // Alternative solution: // &#39;byte&#39; is not working due to the Solidity parser, so lets // use the second best option, &#39;and&#39; // v := and(mload(add(sig, 65)), 255) } // albeit non-transactional signatures are not specified by the YP, one would expect it // to match the YP range of [27, 28] // // geth uses [0, 1] and some clients have followed. This might change, see: // https://github.com/ethereum/go-ethereum/issues/2053 if (v < 27) v += 27; if (v != 27 && v != 28) return (false, 0); return safer_ecrecover(hash, v, r, s); } function safeMemoryCleaner() internal pure { assembly { let fmem := mload(0x40) codecopy(fmem, codesize, sub(msize, fmem)) } } } // </ORACLIZE_API> contract Permissions { //LOGS event LOG_ChangePermissions(address indexed _called, address indexed _agent, uint8 _value); event LOG_ChangeRegulator(address indexed _called, bool _value); //LOGS* //PARAMETRS //ARRAYS mapping(address => uint8) public agents; //ARRAYS bool public communityRegulator; //PARAMETRS* //MODIFIERS modifier onlyADM() { require(agents[msg.sender] == 1); _; } //MODIFIERS* //FUNCTIONS //CHANGE FUNCTIONS function changePermissions(address _agent, uint8 _value) public onlyADM() { require(msg.sender != _agent); require(_value <= 1); agents[_agent] = _value; LOG_ChangePermissions(msg.sender, _agent, _value); } function changeRegulator(bool _value) public onlyADM() { communityRegulator = _value; LOG_ChangeRegulator(msg.sender, _value); } //CHANGE FUNCTIONS* //FUNCTIONS* //CONSTRUSTOR function Permissions() { agents[msg.sender] = 1; } //CONSTRUCTOR* } contract Accounting is Permissions { //LOGS event LOG_AcceptWei(address indexed _from, uint256 _wei, uint8 indexed _type); event LOG_WithdrawWei(address indexed _called, address indexed _to, uint256 _wei, uint8 indexed _type); event LOG_ChangeOraclizeAccountingSettings(address indexed _called, uint256 _OAS_idOraclizeAccountingSettings, uint256 _OAS_oraclizeRandomGas, uint256 _OAS_oraclizeRandomGwei); //LOGS* //PARAMETRS //ACCOUNTING CONSTANTS (ACns) uint256 constant public ACns_WeiInFinney = 1000000000000000; uint256 constant public ACns_WeiInGwei = 1000000000; //ACCOUNTING CONSTANTS (ACns)* //ACCOUNTING PARAMETRS (AP) uint256 public AP_totalBalanceCommissionWei; uint256 public AP_totalBalanceDonateWei; uint256 public AP_nowRoundBankBalanceWei; //ACCOUNTING PARAMETRS (AP)* //ORACLIZE ACCOUNTING SETTINGS (OAS) uint256 public OAS_idOraclizeAccountingSettings; uint256 public OAS_oraclizeRandomGas; uint256 public OAS_oraclizeRandomGwei; //ORACLIZE ACCOUNTING SETTINGS (OAS)* //PARAMETRS* //MODIFIERS //MODIFIERS* //FUNCTIONS //PAYABLE FUNCTIONS function () payable //Thank you very much ;-) { AP_totalBalanceDonateWei = AP_totalBalanceDonateWei + msg.value; LOG_AcceptWei(msg.sender, msg.value, 1); } //PAYABLE FUNCTIONS* //ACTION FUNCTIONS function withdrawTotalBalanceDonateWei(address _to) public onlyADM() { _to.transfer(AP_totalBalanceDonateWei); LOG_WithdrawWei(msg.sender, _to, AP_totalBalanceDonateWei, 1); AP_totalBalanceDonateWei = 0; } function withdrawTotalBalanceCommissionWei(address _to) public onlyADM() { _to.transfer(AP_totalBalanceCommissionWei); LOG_WithdrawWei(msg.sender, _to, AP_totalBalanceCommissionWei, 2); AP_totalBalanceCommissionWei = 0; } //ACTION FUNCTIONS* //CHANGE FUNCTIONS function changeOraclizeAccountingSettings(uint256 _OAS_oraclizeRandomGas) public onlyADM() { OAS_idOraclizeAccountingSettings++; OAS_oraclizeRandomGas = _OAS_oraclizeRandomGas; OAS_oraclizeRandomGwei = _OAS_oraclizeRandomGas * 20; LOG_ChangeOraclizeAccountingSettings(msg.sender, OAS_idOraclizeAccountingSettings, OAS_oraclizeRandomGas, OAS_oraclizeRandomGwei); } //CHANGE FUNCTIONS* //FUNCTIONS* //CONSTRUSTOR //CONSTRUCTOR* } contract GameBase is Accounting, usingOraclize { //LOGS event LOG_ChangeGameSettings (address indexed _called, uint256 _GP_roundNum, uint256 _GS_idGameSettings, uint256 _GS_betSizeFinney, uint256 _GS_maxAmountBets, uint256 _GS_minStartAgentAmountBets, uint256 _GS_maxAgentAmountBets, uint256 _GS_maxAmountBetsInOneTransaction, uint8 _GS_commissionPct, bool _GS_commissionType, uint256 _GS_betTimeoutSec); event LOG_ChangeStatusGame(address indexed _called, uint256 _GP_roundNum, uint8 _status); //LOGS* //PARAMETRS //GAME SETTINGS (GS) uint256 public GS_idGameSettings; uint256 public GS_betSizeFinney; uint256 public GS_maxAmountBets; uint256 public GS_minStartAgentAmountBets; uint256 public GS_maxAgentAmountBets; uint256 public GS_maxAmountBetsInOneTransaction; uint8 public GS_commissionPct; bool public GS_commissionType; uint256 public GS_betTimeoutSec; //GAME SETTINGS (GS)* //GAME PARAMETRS (GP) uint256 public GP_roundNum; uint256 public GP_amountBets; uint256 public GP_lastBetTimeSec; uint8 public GP_statusGame; //GAME PARAMETRS ARRAYS (GPA) mapping(address => uint256) internal GPA_agentAddressId; address[] internal GPA_agentIdAddress; uint256[] internal GPA_agentIdBetsSum; uint256[] internal GPA_betNumAgentId; //GAME PARAMETRS ARRAYS (GPA)* //GAME PARAMETRS (GP)* //PARAMETRS* //MODIFIERS modifier onlyNoBets() { require(GP_amountBets == 0); _; } modifier stop() { require(GP_statusGame == 0); _; } //MODIFIERS* //FUNCTIONS //ACTION FUNCTIONS function withdrawAllWei(address _to) public onlyADM() onlyNoBets() { LOG_WithdrawWei(msg.sender, _to, this.balance, 3); _to.transfer(this.balance); AP_totalBalanceDonateWei = 0; AP_totalBalanceCommissionWei = 0; } //ACTION FUNCTIONS* //CHANGE FUNCTIONS function changeGameSettings (uint256 _GS_betSizeFinney, uint256 _GS_maxAmountBets, uint256 _GS_minStartAgentAmountBets, uint256 _GS_maxAgentAmountBets, uint256 _GS_maxAmountBetsInOneTransaction, uint8 _GS_commissionPct, bool _GS_commissionType, uint256 _GS_betTimeoutSec) public onlyADM() onlyNoBets() { require(OAS_oraclizeRandomGwei > 0); require(_GS_betSizeFinney <= 10000); require(_GS_maxAmountBets <= 1000000 && _GS_maxAmountBets >= 3); require(_GS_maxAmountBetsInOneTransaction <= 150); require(_GS_minStartAgentAmountBets <= _GS_maxAmountBetsInOneTransaction); require(_GS_minStartAgentAmountBets <= _GS_maxAgentAmountBets); require(_GS_maxAgentAmountBets < _GS_maxAmountBets); require(_GS_commissionPct <= 99); GS_idGameSettings++; GS_betSizeFinney = _GS_betSizeFinney; GS_maxAmountBets = _GS_maxAmountBets; GS_minStartAgentAmountBets = _GS_minStartAgentAmountBets; GS_maxAgentAmountBets = _GS_maxAgentAmountBets; GS_maxAmountBetsInOneTransaction = _GS_maxAmountBetsInOneTransaction; GS_commissionPct = _GS_commissionPct; GS_commissionType = _GS_commissionType; GS_betTimeoutSec = _GS_betTimeoutSec; LOG_ChangeGameSettings (msg.sender, GP_roundNum, GS_idGameSettings, _GS_betSizeFinney, _GS_maxAmountBets, _GS_minStartAgentAmountBets, _GS_maxAgentAmountBets, _GS_maxAmountBetsInOneTransaction, _GS_commissionPct, _GS_commissionType, _GS_betTimeoutSec); } function changeStatusGame(uint8 _value) public onlyADM() onlyNoBets() { require(_value <= 1); GP_statusGame = _value; LOG_ChangeStatusGame(msg.sender, GP_roundNum, _value); } //CHANGE FUNCTIONS* //GET FUNCTIONS function getAgentIdByAddress(address _agentAddress) public constant returns(uint256) { uint256 value; uint256 id = GPA_agentAddressId[_agentAddress]; if (id != 0 && id <= GPA_agentIdAddress.length) { if (GPA_agentIdAddress[id - 1] == _agentAddress) { value = GPA_agentAddressId[_agentAddress]; } } return value; } function getAgentAdressById(uint256 _agentId) public constant returns(address) { address value; if (_agentId > 0 && _agentId <= GPA_agentIdAddress.length) { value = GPA_agentIdAddress[_agentId - 1]; } return value; } function getBetsSumByAgentId(uint256 _agentId) public constant returns(uint256) { uint256 value; if (_agentId > 0 && _agentId <= GPA_agentIdBetsSum.length) { value = GPA_agentIdBetsSum[_agentId - 1]; } return value; } function getAgentIdByPositionBet(uint256 _positionBet) public constant returns(uint256) { uint256 value; if (_positionBet > 0 && _positionBet <= GPA_betNumAgentId.length) { value = GPA_betNumAgentId[_positionBet - 1]; } return value; } function getAgentsAmount() public constant returns(uint256) { return GPA_agentIdAddress.length; } //GET FUNCTIONS* //FUNCTIONS* //CONSTRUSTOR function GameBase() { GP_roundNum = 1; } //CONSTRUCTOR* } contract Game is GameBase { //LOGS event LOG_Request_CallbackOraclize(address indexed _called, uint256 _GP_roundNum, uint256 _OAS_idOraclizeAccountingSettings, bytes32 _queryId, uint8 _type); event LOG_ForciblyRequest_CallbackOraclize(address _called, uint256 _GP_roundNum, uint8 _confirmType); event LOG_CallbackOraclize(uint256 _GP_roundNum, bytes32 _queryId, bytes _proof); event LOG_Bet(address indexed _agent, uint256 _agentId, uint256 _GP_roundNum, uint256 _GS_idGameSettings, uint256 _amountBets, uint256 _spentFinney); event LOG_Win(address indexed _agent, uint256 _agentId, uint256 _GP_roundNum, uint256 _GS_idGameSettings, uint256 _GP_amountBets, uint256 _betsSum, uint256 _spentFinney, uint256 _winWei, uint256 _luckyNumber); event LOG_Commision(uint256 _GP_roundNum, uint256 _GS_idGameSettings, uint256 _AP_nowRoundBankBalanceWei, uint256 _GS_commissionPct, uint256 _commisionWei); //LOGS* //PARAMETRS //PARAMETRS* //FUNCTIONS //ACTION FUNCTIONS function bet() payable public { require(GP_statusGame == 1); uint256 amountBets; amountBets = (msg.value / ACns_WeiInFinney) / GS_betSizeFinney; require(amountBets > 0); uint256 agentId; agentId = getAgentIdByAddress(msg.sender); require(amountBets >= GS_minStartAgentAmountBets || agentId != 0); if ((amountBets + GP_amountBets) > GS_maxAmountBets) { amountBets = GS_maxAmountBets - GP_amountBets; } if ((amountBets + getBetsSumByAgentId(agentId)) > GS_maxAgentAmountBets) { amountBets = GS_maxAgentAmountBets - getBetsSumByAgentId(agentId); } if (amountBets > GS_maxAmountBetsInOneTransaction) { amountBets = GS_maxAmountBetsInOneTransaction; } require(amountBets > 0); if (agentId == 0) { GPA_agentIdAddress.push(msg.sender); agentId = GPA_agentIdAddress.length; GPA_agentAddressId[msg.sender] = agentId; GPA_agentIdBetsSum.push(0); } GPA_agentIdBetsSum[agentId - 1] = getBetsSumByAgentId(agentId) + amountBets; while (GPA_betNumAgentId.length < GP_amountBets + amountBets) { GPA_betNumAgentId.push(agentId); } uint256 amountBetsSizeWei = amountBets * GS_betSizeFinney * ACns_WeiInFinney; LOG_AcceptWei(msg.sender, msg.value, 2); LOG_WithdrawWei(msg.sender, msg.sender, msg.value - amountBetsSizeWei, 4); msg.sender.transfer(msg.value - amountBetsSizeWei); LOG_Bet(msg.sender, agentId, GP_roundNum, GS_idGameSettings, amountBets, amountBets * GS_betSizeFinney); AP_nowRoundBankBalanceWei = AP_nowRoundBankBalanceWei + amountBetsSizeWei; GP_amountBets = GP_amountBets + amountBets; GP_lastBetTimeSec = block.timestamp; if (GP_amountBets > GS_maxAmountBets - GS_minStartAgentAmountBets) { uint256 oraclizeRandomWei = OAS_oraclizeRandomGwei * ACns_WeiInGwei; if (AP_nowRoundBankBalanceWei > oraclizeRandomWei) { GP_statusGame = 2; LOG_ChangeStatusGame(msg.sender, GP_roundNum, GP_statusGame); AP_nowRoundBankBalanceWei = AP_nowRoundBankBalanceWei - oraclizeRandomWei; request_callback(1); } else { GP_statusGame = 3; LOG_ChangeStatusGame(msg.sender, GP_roundNum, GP_statusGame); } } } function play(uint256 _luckyNumber) private { uint256 winnerId = getAgentIdByPositionBet(_luckyNumber); address winnerAddress = getAgentAdressById(winnerId); uint256 commissionSizeWei; if (GS_commissionType) { commissionSizeWei = AP_nowRoundBankBalanceWei / 100 * GS_commissionPct; } else { commissionSizeWei = (GP_amountBets - getBetsSumByAgentId(winnerId)) * (GS_betSizeFinney * ACns_WeiInFinney) / 100 * GS_commissionPct; } AP_totalBalanceCommissionWei = AP_totalBalanceCommissionWei + commissionSizeWei; AP_nowRoundBankBalanceWei = AP_nowRoundBankBalanceWei - commissionSizeWei; LOG_Commision(GP_roundNum, GS_idGameSettings, AP_nowRoundBankBalanceWei, GS_commissionPct, commissionSizeWei); winnerAddress.transfer(AP_nowRoundBankBalanceWei); LOG_WithdrawWei(msg.sender, winnerAddress, AP_nowRoundBankBalanceWei, 5); LOG_Win(winnerAddress, winnerId, GP_roundNum, GS_idGameSettings, GP_amountBets, getBetsSumByAgentId(winnerId), getBetsSumByAgentId(winnerId) * GS_betSizeFinney, AP_nowRoundBankBalanceWei, _luckyNumber); GP_statusGame = 1; GP_amountBets = 0; GP_roundNum++; AP_nowRoundBankBalanceWei = 0; delete GPA_agentIdAddress; delete GPA_agentIdBetsSum; delete GPA_betNumAgentId; } function thisIsTheEnd(address _to) public onlyADM() onlyNoBets() { selfdestruct(_to); } //ACTION FUNCTIONS* //ORACLIZE QUERIES function request_callback(uint8 _type) private { bytes32 queryId = oraclize_newRandomDSQuery(0, 7, OAS_oraclizeRandomGas); LOG_Request_CallbackOraclize(msg.sender, GP_roundNum, OAS_idOraclizeAccountingSettings, queryId, _type); } function forciblyRequest_callback() payable public { uint8 confirm; if (GP_statusGame == 3 && (agents[msg.sender] == 1 || communityRegulator)) { confirm = 1; } if (GP_statusGame == 2 && (agents[msg.sender] == 1 || communityRegulator)) { confirm = 2; } if (GP_statusGame == 1 && (block.timestamp > GP_lastBetTimeSec + GS_betTimeoutSec) && (agents[msg.sender] == 1 || communityRegulator)) { confirm = 3; } if (confirm > 0) { uint256 oraclizeRandomWei = OAS_oraclizeRandomGwei * ACns_WeiInGwei; require(msg.value >= oraclizeRandomWei); msg.sender.transfer(msg.value - oraclizeRandomWei); if (confirm != 2) { GP_statusGame = 2; LOG_ChangeStatusGame(msg.sender, GP_roundNum, GP_statusGame); } LOG_ForciblyRequest_CallbackOraclize(msg.sender, GP_roundNum, confirm); request_callback(2); } } function __callback(bytes32 _queryId, string _result, bytes _proof) public { require(msg.sender == oraclize_cbAddress()); require (oraclize_randomDS_proofVerify__returnCode(_queryId, _result, _proof) == 0); require(GP_statusGame == 2); LOG_CallbackOraclize(GP_roundNum, _queryId, _proof); play(uint(sha3(_result)) % GP_amountBets + 1); } function startRequest_callback() payable public onlyADM() onlyNoBets() stop() { bytes32 queryId = oraclize_newRandomDSQuery(0, 7, 100000); LOG_Request_CallbackOraclize(msg.sender, 0, 100000, queryId, 0); } //ORACLIZE QUERIES* //CONSTRUSTOR function Game() { oraclize_setProof(proofType_Ledger); } //CONSTRUSTOR* } //Official Blog: medium.com/etherate //&#169; EtheRate Core Team
ORACLIZE QUERIESCONSTRUSTOR
function Game() { oraclize_setProof(proofType_Ledger); }
2,302,446
./full_match/84531/0x3b2Da38EeE92a0Ce9E8642f272a5bCa2a6Ac3A3c/sources/contracts/guild-core/GuildOracle.sol
Gets the address of the Chainlink oracle. return The address of the Chainlink oracle./
function getOracle() external view returns (address) { return _oracle; }
14,312,987
./full_match/80001/0xB59b1C4aeF63ef7B5fE446F1b51c798db1b08108/sources/contracts/OasisUser.sol
Create new user and store in mapping for specified account
function _createUser(address _account, string memory _name) external onlyOwner { address account = _account; require( !allUsers[account].registered, "You have already created an account!" ); allUsers[account] = User(true, _name); }
5,669,223
pragma solidity >=0.5.17 <0.8.4; import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; import '@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol'; import '@openzeppelin/contracts/utils/math/SafeMath.sol'; import '@openzeppelin/contracts/utils/math/Math.sol'; import '../BaseStrategy.sol'; import './../../enums/ProtocolEnum.sol'; import './../../external/harvest/HarvestVault.sol'; import './../../external/harvest/HarvestStakePool.sol'; import './../../external/uniswap/IUniswapV2.sol'; //import './../../external/curve/ICurveFi.sol'; import './../../external/sushi/Sushi.sol'; import './../../dex/uniswap/SwapFarm2UsdtInUniswapV2.sol'; contract HarvestUSDTStrategy is BaseStrategy, SwapFarm2UsdtInUniswapV2{ using SafeERC20 for IERC20; using SafeMath for uint256; //待投的币种 IERC20 public constant baseToken = IERC20(0xdAC17F958D2ee523a2206206994597C13D831ec7); //待投池地址 address public fVault = address(0x053c80eA73Dc6941F518a68E2FC52Ac45BDE7c9C); //质押池地址 address public fPool = address(0x6ac4a7AB91E6fD098E13B7d347c6d4d1494994a2); //Farm Token address public rewardToken = address(0xa0246c9032bC3A600820415aE600c6388619A14D); //uni v2 address address constant uniV2Address = address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); //WETH address constant WETH = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); //curve pool address address constant curvePool = address(0x80466c64868E1ab14a1Ddf27A676C3fcBE638Fe5); //sushi address address constant sushiAddress = address(0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F); //上次doHardwork按币本位计价的资产总值 uint256 internal lastTotalAssets = 0; //当日赎回 uint256 internal dailyWithdrawAmount = 0; constructor(address _vault){ address[] memory tokens = new address[](1); tokens[0] = address(baseToken); initialize("HarvestUSDTStrategy", uint16(ProtocolEnum.Harvest), _vault, tokens); } /** * 计算基础币与其它币种的数量关系 * 如该池是CrvEURS池,underlying是USDT数量,返回的则是 EURS、SEUR的数量 **/ function calculate(uint256 amountUnderlying) external override view returns (uint256[] memory,uint256[] memory){ uint256[] memory tokenAmountArr = new uint256[](1); tokenAmountArr[0] = amountUnderlying; return (tokenAmountArr, tokenAmountArr); } function withdrawAllToVault() external onlyVault override { uint stakingAmount = HarvestStakePool(fPool).balanceOf(address(this)); if (stakingAmount > 0){ _claimRewards(); HarvestStakePool(fPool).withdraw(stakingAmount); HarvestVault(fVault).withdraw(stakingAmount); } uint256 withdrawAmount = baseToken.balanceOf(address(this)); if (withdrawAmount > 0){ baseToken.safeTransfer(address(vault),withdrawAmount); dailyWithdrawAmount += withdrawAmount; } } /** * amountUnderlying:需要的基础代币数量 **/ function withdrawToVault(uint256 amountUnderlying) external onlyVault override { uint256 balance = baseToken.balanceOf(address(this)); if (balance >= amountUnderlying){ baseToken.safeTransfer(address(vault),amountUnderlying); } else { uint256 missAmount = amountUnderlying - balance; uint256 shares = missAmount.mul(10 ** HarvestVault(fVault).decimals()).div(HarvestVault(fVault).getPricePerFullShare()); if (shares > 0){ uint256 stakeAmount = HarvestStakePool(fPool).balanceOf(address(this)); shares = Math.min(shares,stakeAmount); HarvestStakePool(fPool).withdraw(shares); HarvestVault(fVault).withdraw(shares); uint256 withdrawAmount = baseToken.balanceOf(address(this)); baseToken.safeTransfer(address(vault),withdrawAmount); dailyWithdrawAmount += withdrawAmount; } } } /** * 第三方池的净值 **/ function getPricePerFullShare() external override view returns (uint256) { return HarvestVault(fVault).getPricePerFullShare(); } /** * 已经投资的underlying数量,策略实际投入的是不同的稳定币,这里涉及待投稳定币与underlying之间的换算 **/ function investedUnderlyingBalance() external override view returns (uint256) { uint stakingAmount = HarvestStakePool(fPool).balanceOf(address(this)); uint baseTokenBalance = baseToken.balanceOf(address(this)); uint prs = HarvestVault(fVault).getPricePerFullShare(); return stakingAmount .mul(prs) .div(10 ** IERC20Metadata(fVault).decimals()) .add(baseTokenBalance); } /** * 查看策略投资池子的总数量(priced in want) **/ function getInvestVaultAssets() external override view returns (uint256) { return HarvestVault(fVault).getPricePerFullShare() .mul(IERC20(fVault).totalSupply()) .div(10 ** IERC20Metadata(fVault).decimals()); } /** * 针对策略的作业: * 1.提矿 & 换币(矿币换成策略所需的稳定币?) * 2.计算apy * 3.投资 **/ function doHardWorkInner() internal override { uint256 rewards = 0; if (HarvestStakePool(fPool).balanceOf(address(this)) > 0){ rewards = _claimRewards(); } _updateApy(rewards); _invest(); lastTotalAssets = HarvestStakePool(fPool).balanceOf(address(this)) .mul(HarvestVault(fVault).getPricePerFullShare()) .div(10 ** IERC20Metadata(fVault).decimals()); lastDoHardworkTimestamp = block.timestamp; dailyWithdrawAmount = 0; } function _claimRewards() internal returns (uint256) { HarvestStakePool(fPool).getReward(); uint256 amount = IERC20(rewardToken).balanceOf(address(this)); if (amount == 0){ return 0; } //兑换成investToken //TODO::当Farm数量大于50时先从uniV2换成ETH然后再从curve换 uint256 balanceBeforeSwap = IERC20(baseToken).balanceOf(address(this)); if(amount>10**15){ swapFarm2UsdtInUniswapV2(amount,0,1800); uint256 balanceAfterSwap = IERC20(baseToken).balanceOf(address(this)); return balanceAfterSwap - balanceBeforeSwap; } return 0; } function _updateApy(uint256 _rewards) internal { // 第一次投资时lastTotalAssets为0,不用计算apy if (lastTotalAssets > 0 && lastDoHardworkTimestamp > 0){ uint256 totalAssets = HarvestStakePool(fPool).balanceOf(address(this)) .mul(HarvestVault(fVault).getPricePerFullShare()) .div(10 ** IERC20Metadata(fVault).decimals()); int assetsDelta = int(totalAssets) + int(dailyWithdrawAmount) + int(_rewards) - int(lastTotalAssets); calculateProfitRate(lastTotalAssets,assetsDelta); } } function _invest() internal { uint256 balance = baseToken.balanceOf(address(this)); if (balance > 0) { baseToken.safeApprove(fVault, 0); baseToken.safeApprove(fVault, balance); HarvestVault(fVault).deposit(balance); //stake uint256 lpAmount = IERC20(fVault).balanceOf(address(this)); IERC20(fVault).safeApprove(fPool, 0); IERC20(fVault).safeApprove(fPool, lpAmount); HarvestStakePool(fPool).stake(lpAmount); lastTotalAssets = HarvestStakePool(fPool).balanceOf(address(this)).mul(HarvestVault(fVault).getPricePerFullShare()).div(10 ** IERC20Metadata(fVault).decimals()); } } /** * 策略迁移 **/ function migrate(address _newStrategy) external override { } } // 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 "../../../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; // 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 no longer needed starting with Solidity 0.8. 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; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.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); } /** * @dev Returns the ceiling of the division of two numbers. * * This differs from standard division with `/` in that it rounds up instead * of rounding down. */ function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b - 1) / b can overflow on addition, so we distribute. return a / b + (a % b == 0 ? 0 : 1); } } pragma solidity >=0.5.17 <0.8.4; import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; import '@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol'; import '@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol'; import '@openzeppelin/contracts/utils/math/SafeMath.sol'; import './IStrategy.sol'; import '../vault/IVault.sol'; abstract contract BaseStrategy { using SafeMath for uint256; using SafeERC20 for IERC20; string public name; uint16 public protocol; IVault public vault; address[] public tokens; uint256 internal constant BASIS_PRECISION = 1e18; //基础收益率,初始化时为1000000 uint256 internal basisProfitRate; //有效时长,用于计算apy,若策略没有资金时,不算在有效时长内 uint256 internal effectiveTime; //上次doHardwork的时间 uint256 public lastDoHardworkTimestamp = 0; function getTokens() external view returns (address[] memory) { return tokens; } function setApy(uint256 nextBasisProfitRate, uint256 nextEffectiveTime) external onlyGovernance { basisProfitRate = nextBasisProfitRate; effectiveTime = nextEffectiveTime; vault.strategyUpdate(this.investedUnderlyingBalance(),apy()); } //10000表示100%,当前apy的算法是一直累计过去的变化,有待改进 function apy() public view returns (uint256) { if (basisProfitRate <= BASIS_PRECISION) { return 0; } if (effectiveTime == 0) { return 0; } return (31536000 * (basisProfitRate - BASIS_PRECISION) * 10000) / (BASIS_PRECISION * effectiveTime); } modifier onlyGovernance() { require(msg.sender == vault.governance(), '!only governance'); _; } modifier onlyVault() { require(msg.sender == address(vault), '!only vault'); _; } function initialize( string memory _name, uint16 _protocol, address _vault, address[] memory _tokens ) internal { name = _name; protocol = _protocol; vault = IVault(_vault); tokens = _tokens; effectiveTime = 0; basisProfitRate = BASIS_PRECISION; } /** * 计算基础币与其它币种的数量关系 * 如该池是CrvEURS池,underlying是USDT数量,返回的则是 EURS、SEUR的数量 **/ function calculate(uint256 amountUnderlying) external view virtual returns (uint256[] memory, uint256[] memory); function withdrawAllToVault() external virtual; /** * amountUnderlying:需要的基础代币数量 **/ function withdrawToVault(uint256 amountUnderlying) external virtual; /** * 第三方池的净值 **/ function getPricePerFullShare() external view virtual returns (uint256); /** * 已经投资的underlying数量,策略实际投入的是不同的稳定币,这里涉及待投稳定币与underlying之间的换算 **/ function investedUnderlyingBalance() external view virtual returns (uint256); /** * 查看策略投资池子的总资产 **/ function getInvestVaultAssets() external view virtual returns (uint256); /** * 针对策略的作业: * 1.提矿 & 换币(矿币换成策略所需的稳定币?) * 2.计算apy * 3.投资 **/ function doHardWork() external onlyGovernance{ doHardWorkInner(); vault.strategyUpdate(this.investedUnderlyingBalance(),apy()); lastDoHardworkTimestamp = block.timestamp; } function doHardWorkInner() internal virtual; function calculateProfitRate(uint256 previousInvestedAssets,int assetsDelta) internal { if (assetsDelta < 0)return; uint256 secondDelta = block.timestamp - lastDoHardworkTimestamp; if (secondDelta > 10 && assetsDelta != 0){ effectiveTime += secondDelta; uint256 dailyProfitRate = uint256(assetsDelta>0?assetsDelta:-assetsDelta) * BASIS_PRECISION / previousInvestedAssets; if (assetsDelta > 0){ basisProfitRate = (BASIS_PRECISION + dailyProfitRate) * basisProfitRate / BASIS_PRECISION; } else { basisProfitRate = (BASIS_PRECISION - dailyProfitRate) * basisProfitRate / BASIS_PRECISION; } } } /** * 策略迁移 **/ function migrate(address _newStrategy) external virtual; } pragma solidity ^0.8.0; enum ProtocolEnum { Yearn, Harvest, Dodo, Curve, Pickle, Liquity, TrueFi } pragma solidity ^0.8.0; interface HarvestVault { function deposit(uint256) external; function withdraw(uint256) external; function withdrawAll() external; function doHardWork() external; function underlyingBalanceWithInvestment() view external returns (uint256); function getPricePerFullShare() external view returns (uint256); // function pricePerShare() external view returns (uint256); function decimals() external view returns (uint256); function balance() external view returns (uint256); } pragma solidity ^0.8.0; interface HarvestStakePool { function balanceOf(address account) external view returns (uint256); function getReward() external; function stake(uint256 amount) external; function rewardPerToken() external view returns (uint256); function withdraw(uint256 amount) external; function exit() external; } pragma solidity =0.8.0; interface IUniswapV2 { function swapExactTokensForETH( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapTokensForExactETH( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); } pragma solidity =0.8.0; interface Sushi { function swapExactTokensForETH( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapTokensForExactETH( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); } pragma solidity >=0.5.17 <=0.8.0; import '@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol'; import './SwapInUniswapV2.sol'; interface ISwapFarm2UsdtInUniswapV2 { function swapFarm2UsdtInUniswapV2( uint256 _amount, uint256 _minReturn, uint256 _timeout ) external returns (uint256[] memory); } contract SwapFarm2UsdtInUniswapV2 is SwapInUniswapV2 { address private FARM_ADDRESS = address(0xa0246c9032bC3A600820415aE600c6388619A14D); address private WETH_ADDRESS = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); address private USDT_ADDRESS = address(0xdAC17F958D2ee523a2206206994597C13D831ec7); /** * farm => usdt */ function swapFarm2UsdtInUniswapV2( uint256 _amount, uint256 _minReturn, uint256 _timeout ) internal returns (uint256[] memory) { require(_amount > 0, '_amount>0'); require(_minReturn >= 0, '_minReturn>=0'); address[] memory _path = new address[](3); _path[0] = FARM_ADDRESS; _path[1] = WETH_ADDRESS; _path[2] = USDT_ADDRESS; return this.swap(FARM_ADDRESS, _amount, _minReturn, _path, address(this), _timeout); } } // 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); } 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 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"; /** * @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); } pragma solidity >=0.5.17 <0.8.4; interface IStrategy { // function underlying() external view returns (address); function vault() external view returns (address); function name() external pure returns (string calldata); /** * 第三方池需要的代币地址列表 **/ function getTokens() external view returns (address[] memory); function apy() external view returns (uint256); /** * 计算基础币与其它币种的数量关系 * 如该池是CrvEURS池,underlying是USDT数量,返回的则是 EURS、SEUR的数量 **/ function calculate(uint256 amountUnderlying) external view returns (uint256[] memory); function withdrawAllToVault() external; /** * amountUnderlying:需要的基础代币数量 **/ function withdrawToVault(uint256 amountUnderlying) external; /** * 第三方池的净值 **/ function getPricePerFullShare() external view returns (uint256); /** * 已经投资的underlying数量,策略实际投入的是不同的稳定币,这里涉及待投稳定币与underlying之间的换算 **/ function investedUnderlyingBalance() external view returns (uint256); /** * 查看策略投资池子的总数量(priced in want) **/ function getInvestVaultAssets() external view returns (uint256); /** * 针对策略的作业: * 1.提矿 & 换币(矿币换成策略所需的稳定币?) * 2.计算apy * 3.投资 **/ function doHardWork() external; /** * 策略迁移 **/ function migrate(address _newStrategy) external virtual; } pragma solidity >=0.5.17 <0.8.4; interface IVault { function name() external view returns (string calldata); function symbol() external view returns (string calldata); function decimals() external view returns (uint256); function governance() external view returns (address); /** * USDT地址 **/ function underlying() external view returns (address); /** * Vault净值 **/ function getPricePerFullShare() external view returns (uint256); /** * 总锁仓量 **/ function tlv() external view returns (uint256); function deposit(uint256 amountWei) external; function withdraw(uint256 numberOfShares) external; function addStrategy(address _strategy) external; function removeStrategy(address _strategy) external; function strategyUpdate(uint256 newTotalAssets, uint256 apy) external; /** * 策略列表 **/ function strategies() external view returns (address[] memory); /** * 分两种情况: * 不足一周时,维持Vault中USDT数量占总资金的5%,多余的投入到apy高的策略中,不足时从低apy策略中赎回份额来补够 * 到达一周时,统计各策略apy,按照资金配比规则进行调仓(统计各策略需要的稳定币数量,在Vault中汇总后再分配) **/ function doHardWork() external; struct StrategyState { uint256 totalAssets; //当前总资产 uint256 totalDebt; //投入未返还成本 } function strategyState(address strategyAddress) external view returns (StrategyState memory); /** * 获取总成本 */ function totalCapital() external view returns (uint256); /** * 获取总估值 */ function totalAssets() external view returns (uint256); /** * 获取策略投资总额 */ function strategyTotalAssetsValue() external view returns (uint256); } pragma solidity >=0.5.17 <=0.8.0; import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; import '@openzeppelin/contracts/token/ERC20/ERC20.sol'; import '@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol'; import './../../external/uniswap/IUniswapV2.sol'; contract SwapInUniswapV2 { using SafeERC20 for IERC20; address private uniswapV2Address = address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); function swap( address fromToken, uint256 _amount, uint256 _minReturn, address[] memory _path, address recipient, uint256 _timeout ) public returns (uint256[] memory) { require(_amount > 0, '_amount>0'); require(_minReturn >= 0, '_minReturn>=0'); IERC20(fromToken).safeApprove(uniswapV2Address, 0); IERC20(fromToken).safeApprove(uniswapV2Address, _amount); try IUniswapV2(uniswapV2Address).swapExactTokensForTokens( _amount, _minReturn, _path, recipient, block.timestamp + _timeout ) returns (uint256[] memory amounts){ return amounts; }catch{ } uint256[] memory amounts = new uint256[](2); amounts[0] = 0; amounts[1] = 0; return amounts; } } // 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 guidelines: functions revert instead * of 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 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; } }
10000表示100%,当前apy的算法是一直累计过去的变化,有待改进
function apy() public view returns (uint256) { if (basisProfitRate <= BASIS_PRECISION) { return 0; } if (effectiveTime == 0) { return 0; } return (31536000 * (basisProfitRate - BASIS_PRECISION) * 10000) / (BASIS_PRECISION * effectiveTime); }
6,894,693
./full_match/1/0x3883500A0721c09DC824421B00F79ae524569E09/sources/@gearbox-protocol/core-v2/contracts/adapters/AbstractAdapter.sol
Approves a token from the Credit Account to the target contract token Token to be approved amount Amount to be approved
function _approveToken(address token, uint256 amount) internal { creditManager.approveCreditAccount( msg.sender, targetContract, token, amount ); }
17,154,357
pragma solidity ^0.4.25; contract Conquest { /*================================= = EVENTS = =================================*/ event onHiveCreated ( address indexed player, uint256 number, uint256 time ); event onDroneCreated ( address indexed player, uint256 number, uint256 time ); event onEnemyDestroyed ( address indexed player, uint256 time ); /*================================= = MODIFIERS = =================================*/ modifier onlyAdministrator() { address _customerAddress = msg.sender; require(administrator_ == _customerAddress); _; } /*================================= = CONFIGURABLES = ==================================*/ uint256 internal ACTIVATION_TIME = 1544988600; // when hives can be created bool internal contractActivated_ = true; bool internal payedOut_ = false; uint256 internal hiveCost_ = 0.075 ether; uint256 internal droneCost_ = 0.01 ether; uint256 internal hiveXCommanderFee_ = 50; // 50% from Hives to Commander uint256 internal droneXCommanderFee_ = 15; // 15% from Drones to Commander uint256 internal droneXHiveFee_ = 415; // 41.5% from Drones to Commander (base 1000) uint8 internal amountHives_ = 8; uint8 internal dronesPerDay_ = 20; // default 20 bool internal conquesting_ = true; bool internal conquested_ = false; /*================================= = DATASET = =================================*/ address internal administrator_; address internal fundTHCAddress_; address internal fundP3DAddress_; uint256 internal pot_; mapping (address => Pilot) internal pilots_; address internal commander_; address[] internal hives_; address[] internal drones_; //uint256 internal DEATH_TIME; uint256 internal dronePopulation_; /*================================= = PUBLIC FUNCTIONS = =================================*/ constructor() public { commander_ = address(this); administrator_ = 0x28436C7453EbA01c6EcbC8a9cAa975f0ADE6Fff1; fundTHCAddress_ = 0x9674D14AF3EE5dDcD59D3bdcA7435E11bA0ced18; fundP3DAddress_ = 0xC0c001140319C5f114F8467295b1F22F86929Ad0; } function startNewRound() public { // Conquesting needs to be finished require(!conquesting_); // payout everybody into their vaults if (!payedOut_) { _payout(); } // reset all values _resetGame(); } // VAULT function withdrawVault() public { address _player = msg.sender; uint256 _balance = pilots_[_player].vault; // Player must have ether in vault require(_balance > 0); // withdraw everything pilots_[_player].vault = 0; // payouts _player.transfer(_balance); } function createCarrierFromVault() public { address _player = msg.sender; uint256 _vault = pilots_[_player].vault; // Player must have enough ether available in vault require(_vault >= hiveCost_); pilots_[_player].vault = _vault - hiveCost_; _createHiveInternal(_player); } function createDroneFromVault() public { address _player = msg.sender; uint256 _vault = pilots_[_player].vault; // Player must have enough ether available in vault require(_vault >= droneCost_); pilots_[_player].vault = _vault - droneCost_; _createDroneInternal(_player); } // WALLET function createCarrier() public payable { address _player = msg.sender; require(msg.value == hiveCost_); // requires exact amount of ether _createHiveInternal(_player); } function createDrone() public payable { address _player = msg.sender; require(msg.value == droneCost_); // requires exact amount of ether _createDroneInternal(_player); } /* View Functions and Helpers */ function openAt() public view returns(uint256) { return ACTIVATION_TIME; } function getHives() public view returns(address[]) { return hives_; } function getDrones() public view returns(address[]) { return drones_; } /*function populationIncrease() public view returns(uint256) { return drones_.length - dronePopulation_; }*/ function commander() public view returns(address) { return commander_; } function conquesting() public view returns(bool) { return conquesting_; } function getCommanderPot() public view returns(uint256) { // total values uint256 _hivesIncome = hives_.length * hiveCost_; // total hives pot addition uint256 _dronesIncome = drones_.length * droneCost_; // total drones pot addition uint256 _pot = pot_ + _hivesIncome + _dronesIncome; // old pot may feeds this round uint256 _fee = _pot / 10; // 10% _pot = _pot - _fee; // 90% residual _hivesIncome = (_hivesIncome * 9) / 10; _dronesIncome = (_dronesIncome * 9) / 10; // relative values uint256 _toCommander = (_hivesIncome * hiveXCommanderFee_) / 100 + // 50% from Hives to Commander (_dronesIncome * droneXCommanderFee_) / 100; // 15% from Drones to Commander return _toCommander; } function getHivePot() public view returns(uint256) { // total values uint256 _hivesIncome = hives_.length * hiveCost_; // total hives pot addition uint256 _dronesIncome = drones_.length * droneCost_; // total drones pot addition uint256 _pot = pot_ + _hivesIncome + _dronesIncome; // old pot may feeds this round uint256 _fee = _pot / 10; // 10% _pot = _pot - _fee; // 90% residual _hivesIncome = (_hivesIncome * 9) / 10; _dronesIncome = (_dronesIncome * 9) / 10; // relative values uint256 _toHives = (_dronesIncome * droneXHiveFee_) / 1000; // 41,5% from Drones to Hives return _toHives; } function getDronePot() public view returns(uint256) { // total values uint256 _hivesIncome = hives_.length * hiveCost_; // total hives pot addition uint256 _dronesIncome = drones_.length * droneCost_; // total drones pot addition uint256 _pot = pot_ + _hivesIncome + _dronesIncome; // old pot may feeds this round uint256 _fee = _pot / 10; // 10% _pot = _pot - _fee; // 90% residual _hivesIncome = (_hivesIncome * 9) / 10; _dronesIncome = (_dronesIncome * 9) / 10; // relative values uint256 _toCommander = (_hivesIncome * hiveXCommanderFee_) / 100 + // 50% from Hives to Commander (_dronesIncome * droneXCommanderFee_) / 100; // 15% from Drones to Commander uint256 _toHives = (_dronesIncome * droneXHiveFee_) / 1000; // 41,5% from Drones to Hives uint256 _toDrones = _pot - _toHives - _toCommander; // residual goes to squad return _toDrones; } function vaultOf(address _player) public view returns(uint256) { return pilots_[_player].vault; } function lastFlight(address _player) public view returns(uint256) { return pilots_[_player].lastFlight; } /* Setter */ function setGameStatus(bool _active) onlyAdministrator() public { contractActivated_ = _active; } /*================================= = PRIVATE FUNCTIONS = =================================*/ function _createDroneInternal(address _player) internal { require(hives_.length == amountHives_); // all hives must be created require(conquesting_); // Conquesting must be in progress require(now > pilots_[_player].lastFlight + 60 seconds); // 1 drone per minute per address // check if certain amount of Drones have been built // otherwise round ends /*if (now > DEATH_TIME) { if (populationIncrease() >= dronesPerDay_) { dronePopulation_ = drones_.length; // remember last drone population DEATH_TIME = DEATH_TIME + 24 hours; // set new death time limit // after increasing death time, "now" can still have exceeded it if (now > DEATH_TIME) { conquesting_ = false; return; } } else { conquesting_ = false; return; } }*/ // release new drone drones_.push(_player); pilots_[_player].lastFlight = now; emit onDroneCreated(_player, drones_.length, now); // try to kill the Enemy _figthEnemy(_player); } function _createHiveInternal(address _player) internal { require(now >= ACTIVATION_TIME); // round starts automatically at this time require(hives_.length < amountHives_); // limited hive amount require(!ownsHive(_player), "Player already owns a hive"); // does not own a hive yet // open hive hives_.push(_player); // activate death time of 24 hours /*if (hives_.length == amountHives_) { DEATH_TIME = now + 24 hours; }*/ emit onHiveCreated(_player, hives_.length, now); } function _figthEnemy(address _player) internal { uint256 _drones = drones_.length; // is that Drone the killer? uint256 _drone = uint256(keccak256(abi.encodePacked(block.timestamp, block.difficulty, _player, _drones))) % 289; // Enemy has been killed if (_drone == 42) { conquesting_ = false; conquested_ = true; emit onEnemyDestroyed(_player, now); } } /** * Payout Commander, Hives and Drone Squad */ function _payout() internal { // total values uint256 _hivesIncome = amountHives_ * hiveCost_; uint256 _dronesIncome = drones_.length * droneCost_; uint256 _pot = pot_ + _hivesIncome + _dronesIncome; // old pot may feeds this round uint256 _fee = _pot / 10; // 10% _pot = _pot - _fee; // 90% residual _hivesIncome = (_hivesIncome * 9) / 10; _dronesIncome = (_dronesIncome * 9) / 10; // relative values uint256 _toCommander = (_hivesIncome * hiveXCommanderFee_) / 100 + // 50% from Hives to Commander (_dronesIncome * droneXCommanderFee_) / 100; // 15% from Drones to Commander uint256 _toHives = (_dronesIncome * droneXHiveFee_) / 1000; // 41,5% from Drones to Hives uint256 _toHive = _toHives / 8; // 1/8 to each hive uint256 _toDrones = _pot - _toHives - _toCommander; // residual goes to squad // only payout Hives and Drones if they have conquested if (conquested_) { // payout hives for (uint8 i = 0; i < 8; i++) { address _ownerHive = hives_[i]; pilots_[_ownerHive].vault = pilots_[_ownerHive].vault + _toHive; _pot = _pot - _toHive; } // payout drones uint256 _squadSize; if (drones_.length >= 4) { _squadSize = 4; } // 4 drones available else { _squadSize = drones_.length; } // less than 4 drones available // iterate 1-4 drones for (uint256 j = (drones_.length - _squadSize); j < drones_.length; j++) { address _ownerDrone = drones_[j]; pilots_[_ownerDrone].vault = pilots_[_ownerDrone].vault + (_toDrones / _squadSize); _pot = _pot - (_toDrones / _squadSize); } } // payout Commander if contract is not queen if (commander_ != address(this)) { pilots_[commander_].vault = pilots_[commander_].vault + _toCommander; _pot = _pot - _toCommander; } // payout Fee fundTHCAddress_.transfer(_fee / 2); // 50% -> THC fundP3DAddress_.transfer(_fee / 2); // 50% -> P3D // excess goes to next rounds pot pot_ = _pot; payedOut_ = true; } /** * Prepare next round by resetting all values to default */ function _resetGame() internal { // start new round if contract is active if (contractActivated_) { address _winner = drones_[drones_.length - 1]; commander_ = _winner; hives_.length = 0; drones_.length = 0; dronePopulation_ = 0; conquesting_ = true; conquested_ = false; payedOut_ = false; ACTIVATION_TIME = now + 5 minutes; } } /* Helper */ function ownsHive(address _player) internal view returns(bool) { for (uint8 i = 0; i < hives_.length; i++) { if (hives_[i] == _player) { return true; } } return false; } /*================================= = DATA TYPES = =================================*/ struct Pilot { uint256 vault; uint256 lastFlight; } }
Player must have enough ether available in vault
function createDroneFromVault() public { address _player = msg.sender; uint256 _vault = pilots_[_player].vault; require(_vault >= droneCost_); pilots_[_player].vault = _vault - droneCost_; _createDroneInternal(_player); }
12,660,050
./full_match/1/0xc258fF338322b6852C281936D4EdEff8AdfF23eE/sources/lib/prb-math/src/UD60x18.sol
Converts a simple integer to UD60x18 by multiplying it by `UNIT`. Requirements: - x must be less than or equal to `MAX_UD60x18` divided by `UNIT`. x The basic integer to convert. result The same number converted to UD60x18.
function toUD60x18(uint256 x) pure returns (UD60x18 result) { if (x > uMAX_UD60x18 / uUNIT) { revert PRBMathUD60x18__ToUD60x18Overflow(x); } unchecked { result = wrap(x * uUNIT); } }
4,833,928
pragma solidity ^0.5.0; pragma experimental ABIEncoderV2; /** * @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); } /** * @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, "SafeMath#mul: OVERFLOW"); 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, "SafeMath#div: DIVISION_BY_ZERO"); 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, "SafeMath#sub: UNDERFLOW"); 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, "SafeMath#add: OVERFLOW"); 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, "SafeMath#mod: DIVISION_BY_ZERO"); 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 { using SafeMath for uint256; mapping (address => uint256) internal _balances; mapping (address => mapping (address => uint256)) internal _allowed; event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); uint256 internal _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)); } } interface IUniswapExchange { event TokenPurchase(address indexed buyer, uint256 indexed eth_sold, uint256 indexed tokens_bought); event EthPurchase(address indexed buyer, uint256 indexed tokens_sold, uint256 indexed eth_bought); event AddLiquidity(address indexed provider, uint256 indexed eth_amount, uint256 indexed token_amount); event RemoveLiquidity(address indexed provider, uint256 indexed eth_amount, uint256 indexed token_amount); /** * @notice Convert ETH to Tokens. * @dev User specifies exact input (msg.value). * @dev User cannot specify minimum output or deadline. */ function () external payable; /** * @dev Pricing function for converting between ETH && Tokens. * @param input_amount Amount of ETH or Tokens being sold. * @param input_reserve Amount of ETH or Tokens (input type) in exchange reserves. * @param output_reserve Amount of ETH or Tokens (output type) in exchange reserves. * @return Amount of ETH or Tokens bought. */ function getInputPrice(uint256 input_amount, uint256 input_reserve, uint256 output_reserve) external view returns (uint256); /** * @dev Pricing function for converting between ETH && Tokens. * @param output_amount Amount of ETH or Tokens being bought. * @param input_reserve Amount of ETH or Tokens (input type) in exchange reserves. * @param output_reserve Amount of ETH or Tokens (output type) in exchange reserves. * @return Amount of ETH or Tokens sold. */ function getOutputPrice(uint256 output_amount, uint256 input_reserve, uint256 output_reserve) external view returns (uint256); /** * @notice Convert ETH to Tokens. * @dev User specifies exact input (msg.value) && minimum output. * @param min_tokens Minimum Tokens bought. * @param deadline Time after which this transaction can no longer be executed. * @return Amount of Tokens bought. */ function ethToTokenSwapInput(uint256 min_tokens, uint256 deadline) external payable returns (uint256); /** * @notice Convert ETH to Tokens && transfers Tokens to recipient. * @dev User specifies exact input (msg.value) && minimum output * @param min_tokens Minimum Tokens bought. * @param deadline Time after which this transaction can no longer be executed. * @param recipient The address that receives output Tokens. * @return Amount of Tokens bought. */ function ethToTokenTransferInput(uint256 min_tokens, uint256 deadline, address recipient) external payable returns(uint256); /** * @notice Convert ETH to Tokens. * @dev User specifies maximum input (msg.value) && exact output. * @param tokens_bought Amount of tokens bought. * @param deadline Time after which this transaction can no longer be executed. * @return Amount of ETH sold. */ function ethToTokenSwapOutput(uint256 tokens_bought, uint256 deadline) external payable returns(uint256); /** * @notice Convert ETH to Tokens && transfers Tokens to recipient. * @dev User specifies maximum input (msg.value) && exact output. * @param tokens_bought Amount of tokens bought. * @param deadline Time after which this transaction can no longer be executed. * @param recipient The address that receives output Tokens. * @return Amount of ETH sold. */ function ethToTokenTransferOutput(uint256 tokens_bought, uint256 deadline, address recipient) external payable returns (uint256); /** * @notice Convert Tokens to ETH. * @dev User specifies exact input && minimum output. * @param tokens_sold Amount of Tokens sold. * @param min_eth Minimum ETH purchased. * @param deadline Time after which this transaction can no longer be executed. * @return Amount of ETH bought. */ function tokenToEthSwapInput(uint256 tokens_sold, uint256 min_eth, uint256 deadline) external returns (uint256); /** * @notice Convert Tokens to ETH && transfers ETH to recipient. * @dev User specifies exact input && minimum output. * @param tokens_sold Amount of Tokens sold. * @param min_eth Minimum ETH purchased. * @param deadline Time after which this transaction can no longer be executed. * @param recipient The address that receives output ETH. * @return Amount of ETH bought. */ function tokenToEthTransferInput(uint256 tokens_sold, uint256 min_eth, uint256 deadline, address recipient) external returns (uint256); /** * @notice Convert Tokens to ETH. * @dev User specifies maximum input && exact output. * @param eth_bought Amount of ETH purchased. * @param max_tokens Maximum Tokens sold. * @param deadline Time after which this transaction can no longer be executed. * @return Amount of Tokens sold. */ function tokenToEthSwapOutput(uint256 eth_bought, uint256 max_tokens, uint256 deadline) external returns (uint256); /** * @notice Convert Tokens to ETH && transfers ETH to recipient. * @dev User specifies maximum input && exact output. * @param eth_bought Amount of ETH purchased. * @param max_tokens Maximum Tokens sold. * @param deadline Time after which this transaction can no longer be executed. * @param recipient The address that receives output ETH. * @return Amount of Tokens sold. */ function tokenToEthTransferOutput(uint256 eth_bought, uint256 max_tokens, uint256 deadline, address recipient) external returns (uint256); /** * @notice Convert Tokens (token) to Tokens (token_addr). * @dev User specifies exact input && minimum output. * @param tokens_sold Amount of Tokens sold. * @param min_tokens_bought Minimum Tokens (token_addr) purchased. * @param min_eth_bought Minimum ETH purchased as intermediary. * @param deadline Time after which this transaction can no longer be executed. * @param token_addr The address of the token being purchased. * @return Amount of Tokens (token_addr) bought. */ function tokenToTokenSwapInput( uint256 tokens_sold, uint256 min_tokens_bought, uint256 min_eth_bought, uint256 deadline, address token_addr) external returns (uint256); /** * @notice Convert Tokens (token) to Tokens (token_addr) && transfers * Tokens (token_addr) to recipient. * @dev User specifies exact input && minimum output. * @param tokens_sold Amount of Tokens sold. * @param min_tokens_bought Minimum Tokens (token_addr) purchased. * @param min_eth_bought Minimum ETH purchased as intermediary. * @param deadline Time after which this transaction can no longer be executed. * @param recipient The address that receives output ETH. * @param token_addr The address of the token being purchased. * @return Amount of Tokens (token_addr) bought. */ function tokenToTokenTransferInput( uint256 tokens_sold, uint256 min_tokens_bought, uint256 min_eth_bought, uint256 deadline, address recipient, address token_addr) external returns (uint256); /** * @notice Convert Tokens (token) to Tokens (token_addr). * @dev User specifies maximum input && exact output. * @param tokens_bought Amount of Tokens (token_addr) bought. * @param max_tokens_sold Maximum Tokens (token) sold. * @param max_eth_sold Maximum ETH purchased as intermediary. * @param deadline Time after which this transaction can no longer be executed. * @param token_addr The address of the token being purchased. * @return Amount of Tokens (token) sold. */ function tokenToTokenSwapOutput( uint256 tokens_bought, uint256 max_tokens_sold, uint256 max_eth_sold, uint256 deadline, address token_addr) external returns (uint256); /** * @notice Convert Tokens (token) to Tokens (token_addr) && transfers * Tokens (token_addr) to recipient. * @dev User specifies maximum input && exact output. * @param tokens_bought Amount of Tokens (token_addr) bought. * @param max_tokens_sold Maximum Tokens (token) sold. * @param max_eth_sold Maximum ETH purchased as intermediary. * @param deadline Time after which this transaction can no longer be executed. * @param recipient The address that receives output ETH. * @param token_addr The address of the token being purchased. * @return Amount of Tokens (token) sold. */ function tokenToTokenTransferOutput( uint256 tokens_bought, uint256 max_tokens_sold, uint256 max_eth_sold, uint256 deadline, address recipient, address token_addr) external returns (uint256); /** * @notice Convert Tokens (token) to Tokens (exchange_addr.token). * @dev Allows trades through contracts that were not deployed from the same factory. * @dev User specifies exact input && minimum output. * @param tokens_sold Amount of Tokens sold. * @param min_tokens_bought Minimum Tokens (token_addr) purchased. * @param min_eth_bought Minimum ETH purchased as intermediary. * @param deadline Time after which this transaction can no longer be executed. * @param exchange_addr The address of the exchange for the token being purchased. * @return Amount of Tokens (exchange_addr.token) bought. */ function tokenToExchangeSwapInput( uint256 tokens_sold, uint256 min_tokens_bought, uint256 min_eth_bought, uint256 deadline, address exchange_addr) external returns (uint256); /** * @notice Convert Tokens (token) to Tokens (exchange_addr.token) && transfers * Tokens (exchange_addr.token) to recipient. * @dev Allows trades through contracts that were not deployed from the same factory. * @dev User specifies exact input && minimum output. * @param tokens_sold Amount of Tokens sold. * @param min_tokens_bought Minimum Tokens (token_addr) purchased. * @param min_eth_bought Minimum ETH purchased as intermediary. * @param deadline Time after which this transaction can no longer be executed. * @param recipient The address that receives output ETH. * @param exchange_addr The address of the exchange for the token being purchased. * @return Amount of Tokens (exchange_addr.token) bought. */ function tokenToExchangeTransferInput( uint256 tokens_sold, uint256 min_tokens_bought, uint256 min_eth_bought, uint256 deadline, address recipient, address exchange_addr) external returns (uint256); /** * @notice Convert Tokens (token) to Tokens (exchange_addr.token). * @dev Allows trades through contracts that were not deployed from the same factory. * @dev User specifies maximum input && exact output. * @param tokens_bought Amount of Tokens (token_addr) bought. * @param max_tokens_sold Maximum Tokens (token) sold. * @param max_eth_sold Maximum ETH purchased as intermediary. * @param deadline Time after which this transaction can no longer be executed. * @param exchange_addr The address of the exchange for the token being purchased. * @return Amount of Tokens (token) sold. */ function tokenToExchangeSwapOutput( uint256 tokens_bought, uint256 max_tokens_sold, uint256 max_eth_sold, uint256 deadline, address exchange_addr) external returns (uint256); /** * @notice Convert Tokens (token) to Tokens (exchange_addr.token) && transfers * Tokens (exchange_addr.token) to recipient. * @dev Allows trades through contracts that were not deployed from the same factory. * @dev User specifies maximum input && exact output. * @param tokens_bought Amount of Tokens (token_addr) bought. * @param max_tokens_sold Maximum Tokens (token) sold. * @param max_eth_sold Maximum ETH purchased as intermediary. * @param deadline Time after which this transaction can no longer be executed. * @param recipient The address that receives output ETH. * @param exchange_addr The address of the exchange for the token being purchased. * @return Amount of Tokens (token) sold. */ function tokenToExchangeTransferOutput( uint256 tokens_bought, uint256 max_tokens_sold, uint256 max_eth_sold, uint256 deadline, address recipient, address exchange_addr) external returns (uint256); /***********************************| | Getter Functions | |__________________________________*/ /** * @notice external price function for ETH to Token trades with an exact input. * @param eth_sold Amount of ETH sold. * @return Amount of Tokens that can be bought with input ETH. */ function getEthToTokenInputPrice(uint256 eth_sold) external view returns (uint256); /** * @notice external price function for ETH to Token trades with an exact output. * @param tokens_bought Amount of Tokens bought. * @return Amount of ETH needed to buy output Tokens. */ function getEthToTokenOutputPrice(uint256 tokens_bought) external view returns (uint256); /** * @notice external price function for Token to ETH trades with an exact input. * @param tokens_sold Amount of Tokens sold. * @return Amount of ETH that can be bought with input Tokens. */ function getTokenToEthInputPrice(uint256 tokens_sold) external view returns (uint256); /** * @notice external price function for Token to ETH trades with an exact output. * @param eth_bought Amount of output ETH. * @return Amount of Tokens needed to buy output ETH. */ function getTokenToEthOutputPrice(uint256 eth_bought) external view returns (uint256); /** * @return Address of Token that is sold on this exchange. */ function tokenAddress() external view returns (address); /** * @return Address of factory that created this exchange. */ function factoryAddress() external view returns (address); /***********************************| | Liquidity Functions | |__________________________________*/ /** * @notice Deposit ETH && Tokens (token) at current ratio to mint UNI tokens. * @dev min_liquidity does nothing when total UNI supply is 0. * @param min_liquidity Minimum number of UNI sender will mint if total UNI supply is greater than 0. * @param max_tokens Maximum number of tokens deposited. Deposits max amount if total UNI supply is 0. * @param deadline Time after which this transaction can no longer be executed. * @return The amount of UNI minted. */ function addLiquidity(uint256 min_liquidity, uint256 max_tokens, uint256 deadline) external payable returns (uint256); /** * @dev Burn UNI tokens to withdraw ETH && Tokens at current ratio. * @param amount Amount of UNI burned. * @param min_eth Minimum ETH withdrawn. * @param min_tokens Minimum Tokens withdrawn. * @param deadline Time after which this transaction can no longer be executed. * @return The amount of ETH && Tokens withdrawn. */ function removeLiquidity(uint256 amount, uint256 min_eth, uint256 min_tokens, uint256 deadline) external returns (uint256, uint256); } interface IUniswapFactory { event NewExchange(address indexed token, address indexed exchange); function initializeFactory(address template) external; function createExchange(address token) external returns (address payable); function getExchange(address token) external view returns (address payable); function getToken(address token) external view returns (address); function getTokenWihId(uint256 token_id) external view returns (address); } contract UniswapExchange is ERC20 { /***********************************| | Variables && Events | |__________________________________*/ // Variables bytes32 public name; // Uniswap V1 bytes32 public symbol; // UNI-V1 uint256 public decimals; // 18 IERC20 token; // address of the ERC20 token traded on this contract IUniswapFactory factory; // interface for the factory that created this contract // Events event TokenPurchase(address indexed buyer, uint256 indexed eth_sold, uint256 indexed tokens_bought); event EthPurchase(address indexed buyer, uint256 indexed tokens_sold, uint256 indexed eth_bought); event AddLiquidity(address indexed provider, uint256 indexed eth_amount, uint256 indexed token_amount); event RemoveLiquidity(address indexed provider, uint256 indexed eth_amount, uint256 indexed token_amount); /***********************************| | Constsructor | |__________________________________*/ /** * @dev This function acts as a contract constructor which is not currently supported in contracts deployed * using create_with_code_of(). It is called once by the factory during contract creation. */ function setup(address token_addr) public { require( address(factory) == address(0) && address(token) == address(0) && token_addr != address(0), "INVALID_ADDRESS" ); factory = IUniswapFactory(msg.sender); token = IERC20(token_addr); name = 0x556e697377617020563100000000000000000000000000000000000000000000; symbol = 0x554e492d56310000000000000000000000000000000000000000000000000000; decimals = 18; } /***********************************| | Exchange Functions | |__________________________________*/ /** * @notice Convert ETH to Tokens. * @dev User specifies exact input (msg.value). * @dev User cannot specify minimum output or deadline. */ function () external payable { ethToTokenInput(msg.value, 1, block.timestamp, msg.sender, msg.sender); } /** * @dev Pricing function for converting between ETH && Tokens. * @param input_amount Amount of ETH or Tokens being sold. * @param input_reserve Amount of ETH or Tokens (input type) in exchange reserves. * @param output_reserve Amount of ETH or Tokens (output type) in exchange reserves. * @return Amount of ETH or Tokens bought. */ function getInputPrice(uint256 input_amount, uint256 input_reserve, uint256 output_reserve) public view returns (uint256) { require(input_reserve > 0 && output_reserve > 0, "INVALID_VALUE"); uint256 input_amount_with_fee = input_amount.mul(997); uint256 numerator = input_amount_with_fee.mul(output_reserve); uint256 denominator = input_reserve.mul(1000).add(input_amount_with_fee); return numerator / denominator; } /** * @dev Pricing function for converting between ETH && Tokens. * @param output_amount Amount of ETH or Tokens being bought. * @param input_reserve Amount of ETH or Tokens (input type) in exchange reserves. * @param output_reserve Amount of ETH or Tokens (output type) in exchange reserves. * @return Amount of ETH or Tokens sold. */ function getOutputPrice(uint256 output_amount, uint256 input_reserve, uint256 output_reserve) public view returns (uint256) { require(input_reserve > 0 && output_reserve > 0); uint256 numerator = input_reserve.mul(output_amount).mul(1000); uint256 denominator = (output_reserve.sub(output_amount)).mul(997); return (numerator / denominator).add(1); } function ethToTokenInput(uint256 eth_sold, uint256 min_tokens, uint256 deadline, address buyer, address recipient) private returns (uint256) { require(deadline >= block.timestamp && eth_sold > 0 && min_tokens > 0); uint256 token_reserve = token.balanceOf(address(this)); uint256 tokens_bought = getInputPrice(eth_sold, address(this).balance.sub(eth_sold), token_reserve); require(tokens_bought >= min_tokens); require(token.transfer(recipient, tokens_bought)); emit TokenPurchase(buyer, eth_sold, tokens_bought); return tokens_bought; } /** * @notice Convert ETH to Tokens. * @dev User specifies exact input (msg.value) && minimum output. * @param min_tokens Minimum Tokens bought. * @param deadline Time after which this transaction can no longer be executed. * @return Amount of Tokens bought. */ function ethToTokenSwapInput(uint256 min_tokens, uint256 deadline) public payable returns (uint256) { return ethToTokenInput(msg.value, min_tokens, deadline, msg.sender, msg.sender); } /** * @notice Convert ETH to Tokens && transfers Tokens to recipient. * @dev User specifies exact input (msg.value) && minimum output * @param min_tokens Minimum Tokens bought. * @param deadline Time after which this transaction can no longer be executed. * @param recipient The address that receives output Tokens. * @return Amount of Tokens bought. */ function ethToTokenTransferInput(uint256 min_tokens, uint256 deadline, address recipient) public payable returns(uint256) { require(recipient != address(this) && recipient != address(0)); return ethToTokenInput(msg.value, min_tokens, deadline, msg.sender, recipient); } function ethToTokenOutput(uint256 tokens_bought, uint256 max_eth, uint256 deadline, address payable buyer, address recipient) private returns (uint256) { require(deadline >= block.timestamp && tokens_bought > 0 && max_eth > 0); uint256 token_reserve = token.balanceOf(address(this)); uint256 eth_sold = getOutputPrice(tokens_bought, address(this).balance.sub(max_eth), token_reserve); // Throws if eth_sold > max_eth uint256 eth_refund = max_eth.sub(eth_sold); if (eth_refund > 0) { buyer.transfer(eth_refund); } require(token.transfer(recipient, tokens_bought)); emit TokenPurchase(buyer, eth_sold, tokens_bought); return eth_sold; } /** * @notice Convert ETH to Tokens. * @dev User specifies maximum input (msg.value) && exact output. * @param tokens_bought Amount of tokens bought. * @param deadline Time after which this transaction can no longer be executed. * @return Amount of ETH sold. */ function ethToTokenSwapOutput(uint256 tokens_bought, uint256 deadline) public payable returns(uint256) { return ethToTokenOutput(tokens_bought, msg.value, deadline, msg.sender, msg.sender); } /** * @notice Convert ETH to Tokens && transfers Tokens to recipient. * @dev User specifies maximum input (msg.value) && exact output. * @param tokens_bought Amount of tokens bought. * @param deadline Time after which this transaction can no longer be executed. * @param recipient The address that receives output Tokens. * @return Amount of ETH sold. */ function ethToTokenTransferOutput(uint256 tokens_bought, uint256 deadline, address recipient) public payable returns (uint256) { require(recipient != address(this) && recipient != address(0)); return ethToTokenOutput(tokens_bought, msg.value, deadline, msg.sender, recipient); } function tokenToEthInput(uint256 tokens_sold, uint256 min_eth, uint256 deadline, address buyer, address payable recipient) private returns (uint256) { require(deadline >= block.timestamp && tokens_sold > 0 && min_eth > 0); uint256 token_reserve = token.balanceOf(address(this)); uint256 eth_bought = getInputPrice(tokens_sold, token_reserve, address(this).balance); uint256 wei_bought = eth_bought; require(wei_bought >= min_eth); recipient.transfer(wei_bought); require(token.transferFrom(buyer, address(this), tokens_sold)); emit EthPurchase(buyer, tokens_sold, wei_bought); return wei_bought; } /** * @notice Convert Tokens to ETH. * @dev User specifies exact input && minimum output. * @param tokens_sold Amount of Tokens sold. * @param min_eth Minimum ETH purchased. * @param deadline Time after which this transaction can no longer be executed. * @return Amount of ETH bought. */ function tokenToEthSwapInput(uint256 tokens_sold, uint256 min_eth, uint256 deadline) public returns (uint256) { return tokenToEthInput(tokens_sold, min_eth, deadline, msg.sender, msg.sender); } /** * @notice Convert Tokens to ETH && transfers ETH to recipient. * @dev User specifies exact input && minimum output. * @param tokens_sold Amount of Tokens sold. * @param min_eth Minimum ETH purchased. * @param deadline Time after which this transaction can no longer be executed. * @param recipient The address that receives output ETH. * @return Amount of ETH bought. */ function tokenToEthTransferInput(uint256 tokens_sold, uint256 min_eth, uint256 deadline, address payable recipient) public returns (uint256) { require(recipient != address(this) && recipient != address(0)); return tokenToEthInput(tokens_sold, min_eth, deadline, msg.sender, recipient); } function tokenToEthOutput(uint256 eth_bought, uint256 max_tokens, uint256 deadline, address buyer, address payable recipient) private returns (uint256) { require(deadline >= block.timestamp && eth_bought > 0); uint256 token_reserve = token.balanceOf(address(this)); uint256 tokens_sold = getOutputPrice(eth_bought, token_reserve, address(this).balance); // tokens sold is always > 0 require(max_tokens >= tokens_sold); recipient.transfer(eth_bought); require(token.transferFrom(buyer, address(this), tokens_sold)); emit EthPurchase(buyer, tokens_sold, eth_bought); return tokens_sold; } /** * @notice Convert Tokens to ETH. * @dev User specifies maximum input && exact output. * @param eth_bought Amount of ETH purchased. * @param max_tokens Maximum Tokens sold. * @param deadline Time after which this transaction can no longer be executed. * @return Amount of Tokens sold. */ function tokenToEthSwapOutput(uint256 eth_bought, uint256 max_tokens, uint256 deadline) public returns (uint256) { return tokenToEthOutput(eth_bought, max_tokens, deadline, msg.sender, msg.sender); } /** * @notice Convert Tokens to ETH && transfers ETH to recipient. * @dev User specifies maximum input && exact output. * @param eth_bought Amount of ETH purchased. * @param max_tokens Maximum Tokens sold. * @param deadline Time after which this transaction can no longer be executed. * @param recipient The address that receives output ETH. * @return Amount of Tokens sold. */ function tokenToEthTransferOutput(uint256 eth_bought, uint256 max_tokens, uint256 deadline, address payable recipient) public returns (uint256) { require(recipient != address(this) && recipient != address(0)); return tokenToEthOutput(eth_bought, max_tokens, deadline, msg.sender, recipient); } function tokenToTokenInput( uint256 tokens_sold, uint256 min_tokens_bought, uint256 min_eth_bought, uint256 deadline, address buyer, address recipient, address payable exchange_addr) private returns (uint256) { require(deadline >= block.timestamp && tokens_sold > 0 && min_tokens_bought > 0 && min_eth_bought > 0); require(exchange_addr != address(this) && exchange_addr != address(0)); uint256 token_reserve = token.balanceOf(address(this)); uint256 eth_bought = getInputPrice(tokens_sold, token_reserve, address(this).balance); uint256 wei_bought = eth_bought; require(wei_bought >= min_eth_bought); require(token.transferFrom(buyer, address(this), tokens_sold)); uint256 tokens_bought = IUniswapExchange(exchange_addr).ethToTokenTransferInput.value(wei_bought)(min_tokens_bought, deadline, recipient); emit EthPurchase(buyer, tokens_sold, wei_bought); return tokens_bought; } /** * @notice Convert Tokens (token) to Tokens (token_addr). * @dev User specifies exact input && minimum output. * @param tokens_sold Amount of Tokens sold. * @param min_tokens_bought Minimum Tokens (token_addr) purchased. * @param min_eth_bought Minimum ETH purchased as intermediary. * @param deadline Time after which this transaction can no longer be executed. * @param token_addr The address of the token being purchased. * @return Amount of Tokens (token_addr) bought. */ function tokenToTokenSwapInput( uint256 tokens_sold, uint256 min_tokens_bought, uint256 min_eth_bought, uint256 deadline, address token_addr) public returns (uint256) { address payable exchange_addr = factory.getExchange(token_addr); return tokenToTokenInput(tokens_sold, min_tokens_bought, min_eth_bought, deadline, msg.sender, msg.sender, exchange_addr); } /** * @notice Convert Tokens (token) to Tokens (token_addr) && transfers * Tokens (token_addr) to recipient. * @dev User specifies exact input && minimum output. * @param tokens_sold Amount of Tokens sold. * @param min_tokens_bought Minimum Tokens (token_addr) purchased. * @param min_eth_bought Minimum ETH purchased as intermediary. * @param deadline Time after which this transaction can no longer be executed. * @param recipient The address that receives output ETH. * @param token_addr The address of the token being purchased. * @return Amount of Tokens (token_addr) bought. */ function tokenToTokenTransferInput( uint256 tokens_sold, uint256 min_tokens_bought, uint256 min_eth_bought, uint256 deadline, address recipient, address token_addr) public returns (uint256) { address payable exchange_addr = factory.getExchange(token_addr); return tokenToTokenInput(tokens_sold, min_tokens_bought, min_eth_bought, deadline, msg.sender, recipient, exchange_addr); } function tokenToTokenOutput( uint256 tokens_bought, uint256 max_tokens_sold, uint256 max_eth_sold, uint256 deadline, address buyer, address recipient, address payable exchange_addr) private returns (uint256) { require(deadline >= block.timestamp && (tokens_bought > 0 && max_eth_sold > 0)); require(exchange_addr != address(this) && exchange_addr != address(0)); uint256 eth_bought = IUniswapExchange(exchange_addr).getEthToTokenOutputPrice(tokens_bought); uint256 token_reserve = token.balanceOf(address(this)); uint256 tokens_sold = getOutputPrice(eth_bought, token_reserve, address(this).balance); // tokens sold is always > 0 require(max_tokens_sold >= tokens_sold && max_eth_sold >= eth_bought); require(token.transferFrom(buyer, address(this), tokens_sold)); uint256 eth_sold = IUniswapExchange(exchange_addr).ethToTokenTransferOutput.value(eth_bought)(tokens_bought, deadline, recipient); emit EthPurchase(buyer, tokens_sold, eth_bought); return tokens_sold; } /** * @notice Convert Tokens (token) to Tokens (token_addr). * @dev User specifies maximum input && exact output. * @param tokens_bought Amount of Tokens (token_addr) bought. * @param max_tokens_sold Maximum Tokens (token) sold. * @param max_eth_sold Maximum ETH purchased as intermediary. * @param deadline Time after which this transaction can no longer be executed. * @param token_addr The address of the token being purchased. * @return Amount of Tokens (token) sold. */ function tokenToTokenSwapOutput( uint256 tokens_bought, uint256 max_tokens_sold, uint256 max_eth_sold, uint256 deadline, address token_addr) public returns (uint256) { address payable exchange_addr = factory.getExchange(token_addr); return tokenToTokenOutput(tokens_bought, max_tokens_sold, max_eth_sold, deadline, msg.sender, msg.sender, exchange_addr); } /** * @notice Convert Tokens (token) to Tokens (token_addr) && transfers * Tokens (token_addr) to recipient. * @dev User specifies maximum input && exact output. * @param tokens_bought Amount of Tokens (token_addr) bought. * @param max_tokens_sold Maximum Tokens (token) sold. * @param max_eth_sold Maximum ETH purchased as intermediary. * @param deadline Time after which this transaction can no longer be executed. * @param recipient The address that receives output ETH. * @param token_addr The address of the token being purchased. * @return Amount of Tokens (token) sold. */ function tokenToTokenTransferOutput( uint256 tokens_bought, uint256 max_tokens_sold, uint256 max_eth_sold, uint256 deadline, address recipient, address token_addr) public returns (uint256) { address payable exchange_addr = factory.getExchange(token_addr); return tokenToTokenOutput(tokens_bought, max_tokens_sold, max_eth_sold, deadline, msg.sender, recipient, exchange_addr); } /** * @notice Convert Tokens (token) to Tokens (exchange_addr.token). * @dev Allows trades through contracts that were not deployed from the same factory. * @dev User specifies exact input && minimum output. * @param tokens_sold Amount of Tokens sold. * @param min_tokens_bought Minimum Tokens (token_addr) purchased. * @param min_eth_bought Minimum ETH purchased as intermediary. * @param deadline Time after which this transaction can no longer be executed. * @param exchange_addr The address of the exchange for the token being purchased. * @return Amount of Tokens (exchange_addr.token) bought. */ function tokenToExchangeSwapInput( uint256 tokens_sold, uint256 min_tokens_bought, uint256 min_eth_bought, uint256 deadline, address payable exchange_addr) public returns (uint256) { return tokenToTokenInput(tokens_sold, min_tokens_bought, min_eth_bought, deadline, msg.sender, msg.sender, exchange_addr); } /** * @notice Convert Tokens (token) to Tokens (exchange_addr.token) && transfers * Tokens (exchange_addr.token) to recipient. * @dev Allows trades through contracts that were not deployed from the same factory. * @dev User specifies exact input && minimum output. * @param tokens_sold Amount of Tokens sold. * @param min_tokens_bought Minimum Tokens (token_addr) purchased. * @param min_eth_bought Minimum ETH purchased as intermediary. * @param deadline Time after which this transaction can no longer be executed. * @param recipient The address that receives output ETH. * @param exchange_addr The address of the exchange for the token being purchased. * @return Amount of Tokens (exchange_addr.token) bought. */ function tokenToExchangeTransferInput( uint256 tokens_sold, uint256 min_tokens_bought, uint256 min_eth_bought, uint256 deadline, address recipient, address payable exchange_addr) public returns (uint256) { require(recipient != address(this)); return tokenToTokenInput(tokens_sold, min_tokens_bought, min_eth_bought, deadline, msg.sender, recipient, exchange_addr); } /** * @notice Convert Tokens (token) to Tokens (exchange_addr.token). * @dev Allows trades through contracts that were not deployed from the same factory. * @dev User specifies maximum input && exact output. * @param tokens_bought Amount of Tokens (token_addr) bought. * @param max_tokens_sold Maximum Tokens (token) sold. * @param max_eth_sold Maximum ETH purchased as intermediary. * @param deadline Time after which this transaction can no longer be executed. * @param exchange_addr The address of the exchange for the token being purchased. * @return Amount of Tokens (token) sold. */ function tokenToExchangeSwapOutput( uint256 tokens_bought, uint256 max_tokens_sold, uint256 max_eth_sold, uint256 deadline, address payable exchange_addr) public returns (uint256) { return tokenToTokenOutput(tokens_bought, max_tokens_sold, max_eth_sold, deadline, msg.sender, msg.sender, exchange_addr); } /** * @notice Convert Tokens (token) to Tokens (exchange_addr.token) && transfers * Tokens (exchange_addr.token) to recipient. * @dev Allows trades through contracts that were not deployed from the same factory. * @dev User specifies maximum input && exact output. * @param tokens_bought Amount of Tokens (token_addr) bought. * @param max_tokens_sold Maximum Tokens (token) sold. * @param max_eth_sold Maximum ETH purchased as intermediary. * @param deadline Time after which this transaction can no longer be executed. * @param recipient The address that receives output ETH. * @param exchange_addr The address of the exchange for the token being purchased. * @return Amount of Tokens (token) sold. */ function tokenToExchangeTransferOutput( uint256 tokens_bought, uint256 max_tokens_sold, uint256 max_eth_sold, uint256 deadline, address recipient, address payable exchange_addr) public returns (uint256) { require(recipient != address(this)); return tokenToTokenOutput(tokens_bought, max_tokens_sold, max_eth_sold, deadline, msg.sender, recipient, exchange_addr); } /***********************************| | Getter Functions | |__________________________________*/ /** * @notice Public price function for ETH to Token trades with an exact input. * @param eth_sold Amount of ETH sold. * @return Amount of Tokens that can be bought with input ETH. */ function getEthToTokenInputPrice(uint256 eth_sold) public view returns (uint256) { require(eth_sold > 0); uint256 token_reserve = token.balanceOf(address(this)); return getInputPrice(eth_sold, address(this).balance, token_reserve); } /** * @notice Public price function for ETH to Token trades with an exact output. * @param tokens_bought Amount of Tokens bought. * @return Amount of ETH needed to buy output Tokens. */ function getEthToTokenOutputPrice(uint256 tokens_bought) public view returns (uint256) { require(tokens_bought > 0); uint256 token_reserve = token.balanceOf(address(this)); uint256 eth_sold = getOutputPrice(tokens_bought, address(this).balance, token_reserve); return eth_sold; } /** * @notice Public price function for Token to ETH trades with an exact input. * @param tokens_sold Amount of Tokens sold. * @return Amount of ETH that can be bought with input Tokens. */ function getTokenToEthInputPrice(uint256 tokens_sold) public view returns (uint256) { require(tokens_sold > 0); uint256 token_reserve = token.balanceOf(address(this)); uint256 eth_bought = getInputPrice(tokens_sold, token_reserve, address(this).balance); return eth_bought; } /** * @notice Public price function for Token to ETH trades with an exact output. * @param eth_bought Amount of output ETH. * @return Amount of Tokens needed to buy output ETH. */ function getTokenToEthOutputPrice(uint256 eth_bought) public view returns (uint256) { require(eth_bought > 0); uint256 token_reserve = token.balanceOf(address(this)); return getOutputPrice(eth_bought, token_reserve, address(this).balance); } /** * @return Address of Token that is sold on this exchange. */ function tokenAddress() public view returns (address) { return address(token); } /** * @return Address of factory that created this exchange. */ function factoryAddress() public view returns (address) { return address(factory); } /***********************************| | Liquidity Functions | |__________________________________*/ /** * @notice Deposit ETH && Tokens (token) at current ratio to mint UNI tokens. * @dev min_liquidity does nothing when total UNI supply is 0. * @param min_liquidity Minimum number of UNI sender will mint if total UNI supply is greater than 0. * @param max_tokens Maximum number of tokens deposited. Deposits max amount if total UNI supply is 0. * @param deadline Time after which this transaction can no longer be executed. * @return The amount of UNI minted. */ function addLiquidity(uint256 min_liquidity, uint256 max_tokens, uint256 deadline) public payable returns (uint256) { require(deadline > block.timestamp && max_tokens > 0 && msg.value > 0, 'UniswapExchange#addLiquidity: INVALID_ARGUMENT'); uint256 total_liquidity = _totalSupply; if (total_liquidity > 0) { require(min_liquidity > 0); uint256 eth_reserve = address(this).balance.sub(msg.value); uint256 token_reserve = token.balanceOf(address(this)); uint256 token_amount = (msg.value.mul(token_reserve) / eth_reserve).add(1); uint256 liquidity_minted = msg.value.mul(total_liquidity) / eth_reserve; require(max_tokens >= token_amount && liquidity_minted >= min_liquidity); _balances[msg.sender] = _balances[msg.sender].add(liquidity_minted); _totalSupply = total_liquidity.add(liquidity_minted); require(token.transferFrom(msg.sender, address(this), token_amount)); emit AddLiquidity(msg.sender, msg.value, token_amount); emit Transfer(address(0), msg.sender, liquidity_minted); return liquidity_minted; } else { require(address(factory) != address(0) && address(token) != address(0) && msg.value >= 1000000000, "INVALID_VALUE"); require(factory.getExchange(address(token)) == address(this)); uint256 token_amount = max_tokens; uint256 initial_liquidity = address(this).balance; _totalSupply = initial_liquidity; _balances[msg.sender] = initial_liquidity; require(token.transferFrom(msg.sender, address(this), token_amount)); emit AddLiquidity(msg.sender, msg.value, token_amount); emit Transfer(address(0), msg.sender, initial_liquidity); return initial_liquidity; } } /** * @dev Burn UNI tokens to withdraw ETH && Tokens at current ratio. * @param amount Amount of UNI burned. * @param min_eth Minimum ETH withdrawn. * @param min_tokens Minimum Tokens withdrawn. * @param deadline Time after which this transaction can no longer be executed. * @return The amount of ETH && Tokens withdrawn. */ function removeLiquidity(uint256 amount, uint256 min_eth, uint256 min_tokens, uint256 deadline) public returns (uint256, uint256) { require(amount > 0 && deadline > block.timestamp && min_eth > 0 && min_tokens > 0); uint256 total_liquidity = _totalSupply; require(total_liquidity > 0); uint256 token_reserve = token.balanceOf(address(this)); uint256 eth_amount = amount.mul(address(this).balance) / total_liquidity; uint256 token_amount = amount.mul(token_reserve) / total_liquidity; require(eth_amount >= min_eth && token_amount >= min_tokens); _balances[msg.sender] = _balances[msg.sender].sub(amount); _totalSupply = total_liquidity.sub(amount); msg.sender.transfer(eth_amount); require(token.transfer(msg.sender, token_amount)); emit RemoveLiquidity(msg.sender, eth_amount, token_amount); emit Transfer(msg.sender, address(0), amount); return (eth_amount, token_amount); } } contract UniswapFactory { /***********************************| | Events And Variables | |__________________________________*/ event NewExchange(address indexed token, address indexed exchange); address public exchangeTemplate; uint256 public tokenCount; mapping (address => address) internal token_to_exchange; mapping (address => address) internal exchange_to_token; mapping (uint256 => address) internal id_to_token; /***********************************| | Factory Functions | |__________________________________*/ function initializeFactory(address template) public { require(exchangeTemplate == address(0), "exchangeTemplate is null address"); require(template != address(0), "template is null address"); exchangeTemplate = template; } function createExchange(address token) public returns (address) { require(token != address(0), "token address is null"); require(exchangeTemplate != address(0), "exchangeTemplate is null address"); require(token_to_exchange[token] == address(0), "token_to_exchange is null"); UniswapExchange exchange = new UniswapExchange(); exchange.setup(token); token_to_exchange[token] = address(exchange); exchange_to_token[address(exchange)] = token; uint256 token_id = tokenCount + 1; tokenCount = token_id; id_to_token[token_id] = token; emit NewExchange(token, address(exchange)); return address(exchange); } /***********************************| | Getter Functions | |__________________________________*/ function getExchange(address token) public view returns (address) { return token_to_exchange[token]; } function getToken(address exchange) public view returns (address) { return exchange_to_token[exchange]; } function getTokenWithId(uint256 token_id) public view returns (address) { return id_to_token[token_id]; } }
| This function acts as a contract constructor which is not currently supported in contracts deployed using create_with_code_of(). It is called once by the factory during contract creation./
function setup(address token_addr) public { require( address(factory) == address(0) && address(token) == address(0) && token_addr != address(0), "INVALID_ADDRESS" ); factory = IUniswapFactory(msg.sender); token = IERC20(token_addr); name = 0x556e697377617020563100000000000000000000000000000000000000000000; symbol = 0x554e492d56310000000000000000000000000000000000000000000000000000; decimals = 18; } |__________________________________*/
6,356,037
./partial_match/1/0xB9DFFBb4ac8705A463D0FB76fBA4CFC8b2B075b6/sources/CVXStaker.sol
function get_balances() external view returns (uint256[] memory);
interface ICurvePool { function balances(uint256 i) external view returns (uint256); function remove_liquidity_one_coin( uint256 burn_amount, int128 coin_idx, uint256 min_received ) external returns (uint256); function remove_liquidity( uint256 burn_amount, uint256[2] memory amounts ) external returns (uint256[2] memory); function add_liquidity( uint256[2] memory amounts, uint256 min_mint_amount ) external returns (uint256); function calc_token_amount( uint256[2] memory _amounts, bool _is_deposit ) external view returns (uint256); function exchange( int128 i, int128 j, uint256 dx, uint256 min_dy ) external returns (uint256); function get_virtual_price() external view returns (uint256); }
4,172,623
./full_match/5/0x3970800843Cd84dAA6CA114541A3d0Cba3b5b793/sources/contracts/Lottery.sol
FUNCIONES GET:Balance actual del contrato:
function getContractBalance() public view returns(uint){ return address(this).balance; }
1,959,001
./partial_match/4/0x9c33DE22AA1764A8eE9563A1868741ACca2be3c4/sources/VotingContract.sol
Определение того, голосовал пользователь уже или еще нет/
function areVoted(address elector) public view isBallotExist returns(bool) { uint i = 0; bool flag = false; address[] memory electors = ballots[ballots.length - 1].areVotedElectors; while (!flag && i < electors.length) { if (electors[i] == elector) { flag = true; } i++; } return flag; }
8,746,194
//Address: 0x2737e022e8bf733b05fa0706b0e80003a576ccb4 //Contract name: TokenValueRelayer //Balance: 0 Ether //Verification Date: 2/2/2018 //Transacion Count: 162 // CODE STARTS HERE pragma solidity ^0.4.11; /* The authentication manager details user accounts that have access to certain priviledges and keeps a permanent ledger of who has and has had these rights. */ contract AuthenticationManager { /* Map addresses to admins */ mapping (address => bool) adminAddresses; /* Map addresses to account readers */ mapping (address => bool) accountReaderAddresses; /* Map addresses to account minters */ mapping (address => bool) accountMinterAddresses; /* Details of all admins that have ever existed */ address[] adminAudit; /* Details of all account readers that have ever existed */ address[] accountReaderAudit; /* Details of all account minters that have ever existed */ address[] accountMinterAudit; /* Fired whenever an admin is added to the contract. */ event AdminAdded(address addedBy, address admin); /* Fired whenever an admin is removed from the contract. */ event AdminRemoved(address removedBy, address admin); /* Fired whenever an account-reader contract is added. */ event AccountReaderAdded(address addedBy, address account); /* Fired whenever an account-reader contract is removed. */ event AccountReaderRemoved(address removedBy, address account); /* Fired whenever an account-minter contract is added. */ event AccountMinterAdded(address addedBy, address account); /* Fired whenever an account-minter contract is removed. */ event AccountMinterRemoved(address removedBy, address account); /* When this contract is first setup we use the creator as the first admin */ function AuthenticationManager() { /* Set the first admin to be the person creating the contract */ adminAddresses[msg.sender] = true; AdminAdded(0, msg.sender); adminAudit.length++; adminAudit[adminAudit.length - 1] = msg.sender; } /* Gets whether or not the specified address is currently an admin */ function isCurrentAdmin(address _address) constant returns (bool) { return adminAddresses[_address]; } /* Gets whether or not the specified address has ever been an admin */ function isCurrentOrPastAdmin(address _address) constant returns (bool) { for (uint256 i = 0; i < adminAudit.length; i++) if (adminAudit[i] == _address) return true; return false; } /* Gets whether or not the specified address is currently an account reader */ function isCurrentAccountReader(address _address) constant returns (bool) { return accountReaderAddresses[_address]; } /* Gets whether or not the specified address has ever been an admin */ function isCurrentOrPastAccountReader(address _address) constant returns (bool) { for (uint256 i = 0; i < accountReaderAudit.length; i++) if (accountReaderAudit[i] == _address) return true; return false; } /* Gets whether or not the specified address is currently an account minter */ function isCurrentAccountMinter(address _address) constant returns (bool) { return accountMinterAddresses[_address]; } /* Gets whether or not the specified address has ever been an admin */ function isCurrentOrPastAccountMinter(address _address) constant returns (bool) { for (uint256 i = 0; i < accountMinterAudit.length; i++) if (accountMinterAudit[i] == _address) return true; return false; } /* Adds a user to our list of admins */ function addAdmin(address _address) { /* Ensure we're an admin */ if (!isCurrentAdmin(msg.sender)) throw; // Fail if this account is already admin if (adminAddresses[_address]) throw; // Add the user adminAddresses[_address] = true; AdminAdded(msg.sender, _address); adminAudit.length++; adminAudit[adminAudit.length - 1] = _address; } /* Removes a user from our list of admins but keeps them in the history audit */ function removeAdmin(address _address) { /* Ensure we're an admin */ if (!isCurrentAdmin(msg.sender)) throw; /* Don't allow removal of self */ if (_address == msg.sender) throw; // Fail if this account is already non-admin if (!adminAddresses[_address]) throw; /* Remove this admin user */ adminAddresses[_address] = false; AdminRemoved(msg.sender, _address); } /* Adds a user/contract to our list of account readers */ function addAccountReader(address _address) { /* Ensure we're an admin */ if (!isCurrentAdmin(msg.sender)) throw; // Fail if this account is already in the list if (accountReaderAddresses[_address]) throw; // Add the account reader accountReaderAddresses[_address] = true; AccountReaderAdded(msg.sender, _address); accountReaderAudit.length++; accountReaderAudit[accountReaderAudit.length - 1] = _address; } /* Removes a user/contracts from our list of account readers but keeps them in the history audit */ function removeAccountReader(address _address) { /* Ensure we're an admin */ if (!isCurrentAdmin(msg.sender)) throw; // Fail if this account is already not in the list if (!accountReaderAddresses[_address]) throw; /* Remove this account reader */ accountReaderAddresses[_address] = false; AccountReaderRemoved(msg.sender, _address); } /* Add a contract to our list of account minters */ function addAccountMinter(address _address) { /* Ensure we're an admin */ if (!isCurrentAdmin(msg.sender)) throw; // Fail if this account is already in the list if (accountMinterAddresses[_address]) throw; // Add the minter accountMinterAddresses[_address] = true; AccountMinterAdded(msg.sender, _address); accountMinterAudit.length++; accountMinterAudit[accountMinterAudit.length - 1] = _address; } /* Removes a user/contracts from our list of account readers but keeps them in the history audit */ function removeAccountMinter(address _address) { /* Ensure we're an admin */ if (!isCurrentAdmin(msg.sender)) throw; // Fail if this account is already not in the list if (!accountMinterAddresses[_address]) throw; /* Remove this minter account */ accountMinterAddresses[_address] = false; AccountMinterRemoved(msg.sender, _address); } } /* The TokenValue Relayer contract is responsible to keep a track of token value that can be audited at a later time. */ contract TokenValueRelayer { /* Represents the value of the token at a particular moment in time. */ struct TokenValueRepresentation { uint256 value; string currency; uint256 timestamp; } /* An array defining all the token values in history. */ TokenValueRepresentation[] public values; /* Defines the admin contract we interface with for credentails. */ AuthenticationManager authenticationManager; /* Fired when the token value is updated by an admin. */ event TokenValue(uint256 value, string currency, uint256 timestamp); /* This modifier allows a method to only be called by current admins */ modifier adminOnly { if (!authenticationManager.isCurrentAdmin(msg.sender)) throw; _; } /* Create our contract and specify the location of other addresses. */ function TokenValueRelayer(address _authenticationManagerAddress) { /* Setup access to our other contracts and validate their versions */ authenticationManager = AuthenticationManager(_authenticationManagerAddress); } /* Returns how many token values are present in the history. */ function tokenValueCount() constant returns (uint256 _count) { _count = values.length; } /* Defines the current value of the token. */ function tokenValuePublish(uint256 _value, string _currency, uint256 _timestamp) adminOnly { values.length++; values[values.length - 1] = TokenValueRepresentation(_value, _currency,_timestamp); /* Audit this */ TokenValue(_value, _currency, _timestamp); } }
Gets whether or not the specified address is currently an account minter /
function isCurrentAccountMinter(address _address) constant returns (bool) { return accountMinterAddresses[_address]; }
6,347,070
//Address: 0x4a184673b7247ea15227d8f738a0627e0b17d72a //Contract name: Minewar //Balance: 0.045868561800982743 Ether //Verification Date: 6/11/2018 //Transacion Count: 1981 // CODE STARTS HERE pragma solidity ^0.4.2; 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; } function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } } contract Minewar { uint256 round = 0; uint256 public deadline; uint256 public CRTSTAL_MINING_PERIOD = 86400; uint256 public SHARE_CRYSTAL = 10 * CRTSTAL_MINING_PERIOD; uint256 public HALF_TIME = 12 hours; uint256 public ROUND_TIME = 7 days; uint256 BASE_PRICE = 0.005 ether; uint256 RANK_LIST_LIMIT = 1000; //miner info mapping(uint256 => MinerData) private minerData; uint256 private numberOfMiners; // plyer info mapping(address => PlyerData) private players; //booster info uint256 private numberOfBoosts; mapping(uint256 => BoostData) private boostData; //order info uint256 private numberOfOrders; mapping(uint256 => BuyOrderData) private buyOrderData; mapping(uint256 => SellOrderData) private sellOrderData; uint256 private numberOfRank; address[21] rankList; address public sponsor; uint256 public sponsorLevel; address public administrator; /*** DATATYPES ***/ struct PlyerData { uint256 round; mapping(uint256 => uint256) minerCount; uint256 hashrate; uint256 crystals; uint256 lastUpdateTime; } struct MinerData { uint256 basePrice; uint256 baseProduct; uint256 limit; } struct BoostData { address owner; uint256 boostRate; uint256 startingLevel; uint256 startingTime; uint256 halfLife; } struct BuyOrderData { address owner; string title; string description; uint256 unitPrice; uint256 amount; } struct SellOrderData { address owner; string title; string description; uint256 unitPrice; uint256 amount; } function Minewar() public { administrator = msg.sender; numberOfMiners = 8; numberOfBoosts = 5; numberOfOrders = 5; numberOfRank = 21; //init miner data // price, prod. limit minerData[0] = MinerData(10, 10, 10); //lv1 minerData[1] = MinerData(100, 200, 2); //lv2 minerData[2] = MinerData(400, 800, 4); //lv3 minerData[3] = MinerData(1600, 3200, 8); //lv4 minerData[4] = MinerData(6400, 12800, 16); //lv5 minerData[5] = MinerData(25600, 51200, 32); //lv6 minerData[6] = MinerData(204800, 409600, 64); //lv7 minerData[7] = MinerData(1638400, 1638400, 65536); //lv8 startNewRound(); } function startNewRound() private { deadline = SafeMath.add(now, ROUND_TIME); round = SafeMath.add(round, 1); initData(); } function initData() private { sponsor = administrator; sponsorLevel = 5; //init booster data boostData[0] = BoostData(0, 150, 1, now, HALF_TIME); boostData[1] = BoostData(0, 175, 1, now, HALF_TIME); boostData[2] = BoostData(0, 200, 1, now, HALF_TIME); boostData[3] = BoostData(0, 225, 1, now, HALF_TIME); boostData[4] = BoostData(msg.sender, 250, 2, now, HALF_TIME); //init order data uint256 idx; for (idx = 0; idx < numberOfOrders; idx++) { buyOrderData[idx] = BuyOrderData(0, "title", "description", 0, 0); sellOrderData[idx] = SellOrderData(0, "title", "description", 0, 0); } for (idx = 0; idx < numberOfRank; idx++) { rankList[idx] = 0; } } function lottery() public { require(now >= deadline); uint256 balance = SafeMath.div(SafeMath.mul(this.balance, 90), 100); administrator.transfer(SafeMath.div(SafeMath.mul(this.balance, 5), 100)); uint8[10] memory profit = [30,20,10,8,7,5,5,5,5,5]; for(uint256 idx = 0; idx < 10; idx++){ if(rankList[idx] != 0){ rankList[idx].transfer(SafeMath.div(SafeMath.mul(balance,profit[idx]),100)); } } startNewRound(); } function getRankList() public view returns(address[21]) { return rankList; } //sponser function becomeSponsor() public payable { require(now <= deadline); require(msg.value >= getSponsorFee()); sponsor.transfer(getCurrentPrice(sponsorLevel)); sponsor = msg.sender; sponsorLevel = SafeMath.add(sponsorLevel, 1); } function getSponsorFee() public view returns(uint256 sponsorFee) { sponsorFee = getCurrentPrice(SafeMath.add(sponsorLevel, 1)); } //-------------------------------------------------------------------------- // Miner //-------------------------------------------------------------------------- function getFreeMiner(address ref) public { require(now <= deadline); PlyerData storage p = players[msg.sender]; require(p.round != round); //reset player data if(p.hashrate > 0){ for (uint idx = 1; idx < numberOfMiners; idx++) { p.minerCount[idx] = 0; } } p.crystals = 0; p.round = round; //free miner p.lastUpdateTime = now; p.minerCount[0] = 1; MinerData storage m0 = minerData[0]; p.hashrate = m0.baseProduct; //send referral if (ref != msg.sender) { PlyerData storage referral = players[ref]; if(referral.round == round){ p.crystals = SafeMath.add(p.crystals, SHARE_CRYSTAL); referral.crystals = SafeMath.add(referral.crystals, SHARE_CRYSTAL); } } } function buyMiner(uint256[] minerNumbers) public { require(now <= deadline); require(players[msg.sender].round == round); require(minerNumbers.length == numberOfMiners); uint256 minerIdx = 0; MinerData memory m; for (; minerIdx < numberOfMiners; minerIdx++) { m = minerData[minerIdx]; if(minerNumbers[minerIdx] > m.limit || minerNumbers[minerIdx] < 0){ revert(); } } updateCrytal(msg.sender); PlyerData storage p = players[msg.sender]; uint256 price = 0; uint256 minerNumber = 0; for (minerIdx = 0; minerIdx < numberOfMiners; minerIdx++) { minerNumber = minerNumbers[minerIdx]; if (minerNumber > 0) { m = minerData[minerIdx]; price = SafeMath.add(price, SafeMath.mul(m.basePrice, minerNumber)); } } price = SafeMath.mul(price, CRTSTAL_MINING_PERIOD); if(p.crystals < price){ revert(); } for (minerIdx = 0; minerIdx < numberOfMiners; minerIdx++) { minerNumber = minerNumbers[minerIdx]; if (minerNumber > 0) { m = minerData[minerIdx]; p.minerCount[minerIdx] = SafeMath.min(m.limit, SafeMath.add(p.minerCount[minerIdx], minerNumber)); } } p.crystals = SafeMath.sub(p.crystals, price); updateHashrate(msg.sender); } function getPlayerData(address addr) public view returns (uint256 crystals, uint256 lastupdate, uint256 hashratePerDay, uint256[8] miners, uint256 hasBoost) { PlyerData storage p = players[addr]; if(p.round != round){ p = players[0]; } crystals = SafeMath.div(p.crystals, CRTSTAL_MINING_PERIOD); lastupdate = p.lastUpdateTime; hashratePerDay = p.hashrate; uint256 i = 0; for(i = 0; i < numberOfMiners; i++) { miners[i] = p.minerCount[i]; } hasBoost = hasBooster(addr); } function getHashratePerDay(address minerAddr) public view returns (uint256 personalProduction) { PlyerData storage p = players[minerAddr]; personalProduction = p.hashrate; uint256 boosterIdx = hasBooster(minerAddr); if (boosterIdx != 999) { BoostData storage b = boostData[boosterIdx]; personalProduction = SafeMath.div(SafeMath.mul(personalProduction, b.boostRate), 100); } } //-------------------------------------------------------------------------- // BOOSTER //-------------------------------------------------------------------------- function buyBooster(uint256 idx) public payable { require(now <= deadline); require(players[msg.sender].round == round); require(idx < numberOfBoosts); BoostData storage b = boostData[idx]; if(msg.value < getBoosterPrice(idx) || msg.sender == b.owner){ revert(); } address beneficiary = b.owner; sponsor.transfer(devFee(getBoosterPrice(idx))); beneficiary.transfer(getBoosterPrice(idx) / 2); updateCrytal(msg.sender); updateCrytal(beneficiary); uint256 level = getCurrentLevel(b.startingLevel, b.startingTime, b.halfLife); b.startingLevel = SafeMath.add(level, 1); b.startingTime = now; // transfer ownership b.owner = msg.sender; } function getBoosterData(uint256 idx) public view returns (address owner,uint256 boostRate, uint256 startingLevel, uint256 startingTime, uint256 currentPrice, uint256 halfLife) { require(idx < numberOfBoosts); owner = boostData[idx].owner; boostRate = boostData[idx].boostRate; startingLevel = boostData[idx].startingLevel; startingTime = boostData[idx].startingTime; currentPrice = getBoosterPrice(idx); halfLife = boostData[idx].halfLife; } function getBoosterPrice(uint256 index) public view returns (uint256) { BoostData storage booster = boostData[index]; return getCurrentPrice(getCurrentLevel(booster.startingLevel, booster.startingTime, booster.halfLife)); } function hasBooster(address addr) public view returns (uint256 boostIdx) { boostIdx = 999; for(uint256 i = 0; i < numberOfBoosts; i++){ uint256 revert_i = numberOfBoosts - i - 1; if(boostData[revert_i].owner == addr){ boostIdx = revert_i; break; } } } //-------------------------------------------------------------------------- // Market //-------------------------------------------------------------------------- function buyCrystalDemand(uint256 amount, uint256 unitPrice,string title, string description) public payable { require(now <= deadline); require(players[msg.sender].round == round); require(unitPrice > 0); require(amount >= 1000); require(amount * unitPrice <= msg.value); uint256 lowestIdx = getLowestUnitPriceIdxFromBuy(); BuyOrderData storage o = buyOrderData[lowestIdx]; if(o.amount > 10 && unitPrice <= o.unitPrice){ revert(); } uint256 balance = SafeMath.mul(o.amount, o.unitPrice); if (o.owner != 0){ o.owner.transfer(balance); } o.owner = msg.sender; o.unitPrice = unitPrice; o.title = title; o.description = description; o.amount = amount; } function sellCrystal(uint256 amount, uint256 index) public { require(now <= deadline); require(players[msg.sender].round == round); require(index < numberOfOrders); require(amount > 0); BuyOrderData storage o = buyOrderData[index]; require(amount <= o.amount); updateCrytal(msg.sender); PlyerData storage seller = players[msg.sender]; PlyerData storage buyer = players[o.owner]; require(seller.crystals >= amount * CRTSTAL_MINING_PERIOD); uint256 price = SafeMath.mul(amount, o.unitPrice); uint256 fee = devFee(price); sponsor.transfer(fee); administrator.transfer(fee); buyer.crystals = SafeMath.add(buyer.crystals, amount * CRTSTAL_MINING_PERIOD); seller.crystals = SafeMath.sub(seller.crystals, amount * CRTSTAL_MINING_PERIOD); o.amount = SafeMath.sub(o.amount, amount); msg.sender.transfer(SafeMath.div(price, 2)); } function withdrawBuyDemand(uint256 index) public { require(now <= deadline); require(index < numberOfOrders); require(players[msg.sender].round == round); BuyOrderData storage o = buyOrderData[index]; require(o.owner == msg.sender); if(o.amount > 0){ uint256 balance = SafeMath.mul(o.amount, o.unitPrice); o.owner.transfer(balance); } o.unitPrice = 0; o.amount = 0; o.title = "title"; o.description = "description"; o.owner = 0; } function getBuyDemand(uint256 index) public view returns(address owner, string title, string description, uint256 amount, uint256 unitPrice) { require(index < numberOfOrders); BuyOrderData storage o = buyOrderData[index]; owner = o.owner; title = o.title; description = o.description; amount = o.amount; unitPrice = o.unitPrice; } function getLowestUnitPriceIdxFromBuy() public returns(uint256 lowestIdx) { uint256 lowestPrice = 2**256 - 1; for (uint256 idx = 0; idx < numberOfOrders; idx++) { BuyOrderData storage o = buyOrderData[idx]; //if empty if (o.unitPrice == 0 || o.amount < 10) { return idx; }else if (o.unitPrice < lowestPrice) { lowestPrice = o.unitPrice; lowestIdx = idx; } } } //-------------------------Sell----------------------------- function sellCrystalDemand(uint256 amount, uint256 unitPrice, string title, string description) public { require(now <= deadline); require(players[msg.sender].round == round); require(amount >= 1000); require(unitPrice > 0); updateCrytal(msg.sender); PlyerData storage seller = players[msg.sender]; if(seller.crystals < amount * CRTSTAL_MINING_PERIOD){ revert(); } uint256 highestIdx = getHighestUnitPriceIdxFromSell(); SellOrderData storage o = sellOrderData[highestIdx]; if(o.amount > 10 && unitPrice >= o.unitPrice){ revert(); } if (o.owner != 0){ PlyerData storage prev = players[o.owner]; prev.crystals = SafeMath.add(prev.crystals, o.amount * CRTSTAL_MINING_PERIOD); } o.owner = msg.sender; o.unitPrice = unitPrice; o.title = title; o.description = description; o.amount = amount; //sub crystals seller.crystals = SafeMath.sub(seller.crystals, amount * CRTSTAL_MINING_PERIOD); } function buyCrystal(uint256 amount, uint256 index) public payable { require(now <= deadline); require(players[msg.sender].round == round); require(index < numberOfOrders); require(amount > 0); SellOrderData storage o = sellOrderData[index]; require(amount <= o.amount); require(msg.value >= amount * o.unitPrice); PlyerData storage buyer = players[msg.sender]; uint256 price = SafeMath.mul(amount, o.unitPrice); uint256 fee = devFee(price); sponsor.transfer(fee); administrator.transfer(fee); buyer.crystals = SafeMath.add(buyer.crystals, amount * CRTSTAL_MINING_PERIOD); o.amount = SafeMath.sub(o.amount, amount); o.owner.transfer(SafeMath.div(price, 2)); } function withdrawSellDemand(uint256 index) public { require(now <= deadline); require(index < numberOfOrders); require(players[msg.sender].round == round); SellOrderData storage o = sellOrderData[index]; require(o.owner == msg.sender); if(o.amount > 0){ PlyerData storage p = players[o.owner]; p.crystals = SafeMath.add(p.crystals, o.amount * CRTSTAL_MINING_PERIOD); } o.unitPrice = 0; o.amount = 0; o.title = "title"; o.description = "description"; o.owner = 0; } function getSellDemand(uint256 index) public view returns(address owner, string title, string description, uint256 amount, uint256 unitPrice) { require(index < numberOfOrders); SellOrderData storage o = sellOrderData[index]; owner = o.owner; title = o.title; description = o.description; amount = o.amount; unitPrice = o.unitPrice; } function getHighestUnitPriceIdxFromSell() public returns(uint256 highestIdx) { uint256 highestPrice = 0; for (uint256 idx = 0; idx < numberOfOrders; idx++) { SellOrderData storage o = sellOrderData[idx]; //if empty if (o.unitPrice == 0 || o.amount < 10) { return idx; }else if (o.unitPrice > highestPrice) { highestPrice = o.unitPrice; highestIdx = idx; } } } //-------------------------------------------------------------------------- // Other //-------------------------------------------------------------------------- function devFee(uint256 amount) public view returns(uint256) { return SafeMath.div(SafeMath.mul(amount, 5), 100); } function getBalance() public view returns(uint256) { return this.balance; } //-------------------------------------------------------------------------- // Private //-------------------------------------------------------------------------- function updateHashrate(address addr) private { PlyerData storage p = players[addr]; uint256 hashrate = 0; for (uint idx = 0; idx < numberOfMiners; idx++) { MinerData storage m = minerData[idx]; hashrate = SafeMath.add(hashrate, SafeMath.mul(p.minerCount[idx], m.baseProduct)); } p.hashrate = hashrate; if(hashrate > RANK_LIST_LIMIT){ updateRankList(addr); } } function updateCrytal(address addr) private { require(now > players[addr].lastUpdateTime); if (players[addr].lastUpdateTime != 0) { PlyerData storage p = players[addr]; uint256 secondsPassed = SafeMath.sub(now, p.lastUpdateTime); uint256 revenue = getHashratePerDay(addr); p.lastUpdateTime = now; if (revenue > 0) { revenue = SafeMath.mul(revenue, secondsPassed); p.crystals = SafeMath.add(p.crystals, revenue); } } } function getCurrentLevel(uint256 startingLevel, uint256 startingTime, uint256 halfLife) private view returns(uint256) { uint256 timePassed=SafeMath.sub(now, startingTime); uint256 levelsPassed=SafeMath.div(timePassed, halfLife); if (startingLevel < levelsPassed) { return 0; } return SafeMath.sub(startingLevel, levelsPassed); } function getCurrentPrice(uint256 currentLevel) private view returns(uint256) { return SafeMath.mul(BASE_PRICE, 2**currentLevel); } function updateRankList(address addr) private returns(bool) { uint256 idx = 0; PlyerData storage insert = players[addr]; PlyerData storage lastOne = players[rankList[19]]; if(insert.hashrate < lastOne.hashrate) { return false; } address[21] memory tempList = rankList; if(!inRankList(addr)){ tempList[20] = addr; quickSort(tempList, 0, 20); }else{ quickSort(tempList, 0, 19); } for(idx = 0;idx < 21; idx++){ if(tempList[idx] != rankList[idx]){ rankList[idx] = tempList[idx]; } } return true; } function inRankList(address addr) internal returns(bool) { for(uint256 idx = 0;idx < 20; idx++){ if(addr == rankList[idx]){ return true; } } return false; } function quickSort(address[21] list, int left, int right) internal { int i = left; int j = right; if(i == j) return; address addr = list[uint(left + (right - left) / 2)]; PlyerData storage p = players[addr]; while (i <= j) { while (players[list[uint(i)]].hashrate > p.hashrate) i++; while (p.hashrate > players[list[uint(j)]].hashrate) j--; if (i <= j) { (list[uint(i)], list[uint(j)]) = (list[uint(j)], list[uint(i)]); i++; j--; } } if (left < j) quickSort(list, left, j); if (i < right) quickSort(list, i, right); } }
-------------------------------------------------------------------------- BOOSTER--------------------------------------------------------------------------
function buyBooster(uint256 idx) public payable { require(now <= deadline); require(players[msg.sender].round == round); require(idx < numberOfBoosts); BoostData storage b = boostData[idx]; if(msg.value < getBoosterPrice(idx) || msg.sender == b.owner){ revert(); } address beneficiary = b.owner; sponsor.transfer(devFee(getBoosterPrice(idx))); beneficiary.transfer(getBoosterPrice(idx) / 2); updateCrytal(msg.sender); updateCrytal(beneficiary); uint256 level = getCurrentLevel(b.startingLevel, b.startingTime, b.halfLife); b.startingLevel = SafeMath.add(level, 1); b.startingTime = now; }
5,496,003
./full_match/5/0x45c62d1BF6D7F1AEfBB92689752B609213fAc397/sources/contracts/StakingToken.sol
fromG converts a Governance Token balance to Staking Token terms. Staking Token is a 9 decimal token. balance given is in 9 decimal format.
function fromG(uint256 amount) external view override returns (uint256) { return governanceToken.balanceFrom(amount); }
7,078,783
/* CyberLionz Cubz (https://www.cyberlionz.io) Code crafted by Fueled on Bacon (https://fueledonbacon.com) */ // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; import "@openzeppelin/contracts/utils/Counters.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; contract CyberLionzCubz is ERC721, Ownable { using Counters for Counters.Counter; using Strings for uint; enum SaleStatus{ PAUSED, PRESALE, PUBLIC } Counters.Counter private _tokenIds; bytes32 public presaleMerkleRoot; uint public constant PUBLIC_MINT_LIMIT = 6; uint public constant COLLECTION_SIZE = 500; uint public constant MINT_PRICE = 0.077 ether; SaleStatus public saleStatus = SaleStatus.PAUSED; bool public finalized = false; uint public airdropped = 0; string private _baseUri; mapping(address => uint) private _mintedCountMap; mapping(address => bool) private _presaleMap; constructor(string memory baseUri, bytes32 merkleRoot) ERC721("CyberLionzCubz", "CLC") { _baseUri = baseUri; presaleMerkleRoot = merkleRoot; } function setPresaleMerkleRoot(bytes32 merkleRoot) onlyOwner external { require(!finalized, "The presale list has been finalized."); presaleMerkleRoot = merkleRoot; } function totalSupply() external view returns (uint) { return _tokenIds.current(); } /// @dev override base uri. It will be combined with token ID function _baseURI() internal view override returns (string memory) { return _baseUri; } /// @notice sets aside 15 tokens for use function airdrop(address to, uint count) onlyOwner external{ require(airdropped + count <= 15, "Can not airdrop more than publicly disclosed to team"); require(_tokenIds.current() + count <= COLLECTION_SIZE, "Number of tokens requested exceeds collection size"); airdropped += count; _mintTokens(to, count); } /// @notice Set sales status function setSaleStatus(SaleStatus status) onlyOwner external { saleStatus = status; } /// @notice After metadata is revealed and all is in working order, it will be finalized permanently. function finalizeMetadata() onlyOwner external { require(!finalized, "Metadata has already been finalized."); finalized = true; } /// @notice Reveal metadata for all the tokens function setBaseURI(string memory baseUri) onlyOwner external { require(!finalized,"Metadata has already been finalized."); _baseUri = baseUri; } /// @notice Get token's URI. /// @param tokenId token ID function tokenURI(uint256 tokenId) public view override returns (string memory) { require(_exists(tokenId), "Token ID does not exist in this collection"); return string(abi.encodePacked(_baseURI(), tokenId.toString(), ".json")); } /// @notice Withdraw's contract's balance to stakeholders function withdraw() external { uint256 balance = address(this).balance; require(balance > 0, "No balance"); uint256 payout1 = balance * 6500 / 10000; uint256 payout2 = balance * 2500 / 10000; uint256 payout3 = balance * 1000 / 10000; payable(0xaff176E6bedDdF28cBBC8579C54A81ACa7b90f4c).transfer(payout1); payable(0x18316EAD5871424d13c13556bfBa43e7eC118f21).transfer(payout2); payable(0x09949453Aea9876764fEB874b198693BaCD7E0d3).transfer(payout3); } function onWhitelist(address addr, bytes32[] calldata _merkleProof) public view returns(bool) { return (MerkleProof.verify(_merkleProof, presaleMerkleRoot, keccak256(abi.encodePacked(addr))) == true); } function presaleMint(bytes32[] calldata _merkleProof) external payable { require(saleStatus == SaleStatus.PRESALE, "Presale is not active"); require(onWhitelist(msg.sender, _merkleProof), "Sender is not on the presale list"); require(msg.value >= MINT_PRICE, "Ether value sent is less than .077"); require(_tokenIds.current() + 1 <= COLLECTION_SIZE, "Collection size limit has already been reached"); require(!_presaleMap[msg.sender], "This address has already minted during presale"); _presaleMap[msg.sender] = true; _mintTokens(msg.sender, 1); } function mint(uint count) external payable { require(saleStatus == SaleStatus.PUBLIC, "Public mint is not active"); require(msg.value >= count * MINT_PRICE, "Ether value sent is not sufficient"); require(_tokenIds.current() + count <= COLLECTION_SIZE, "Minting this many tokens would exceed the total collection size"); require(_mintedCountMap[msg.sender] + count <= PUBLIC_MINT_LIMIT, "Each address may only mint 6 tokens"); _mintedCountMap[msg.sender] += count; _mintTokens(msg.sender, count); } /// @dev mint tokens function _mintTokens(address to, uint count) internal { for(uint index = 0; index < count; index++) { _tokenIds.increment(); uint id = _tokenIds.current(); _safeMint(to, id); } } }
Withdraw's contract's balance to stakeholders
function withdraw() external { uint256 balance = address(this).balance; require(balance > 0, "No balance"); uint256 payout1 = balance * 6500 / 10000; uint256 payout2 = balance * 2500 / 10000; uint256 payout3 = balance * 1000 / 10000; payable(0xaff176E6bedDdF28cBBC8579C54A81ACa7b90f4c).transfer(payout1); payable(0x18316EAD5871424d13c13556bfBa43e7eC118f21).transfer(payout2); payable(0x09949453Aea9876764fEB874b198693BaCD7E0d3).transfer(payout3); }
6,443,667
// 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/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/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: contracts/ERC721A.sol // William Giani <https://www.linkedin.com/in/william-giani> pragma solidity ^0.8.4; error ApprovalCallerNotOwnerNorApproved(); error ApprovalQueryForNonexistentToken(); error ApproveToCaller(); error ApprovalToCurrentOwner(); error BalanceQueryForZeroAddress(); error MintedQueryForZeroAddress(); error BurnedQueryForZeroAddress(); error AuxQueryForZeroAddress(); error MintToZeroAddress(); error MintZeroQuantity(); error OwnerIndexOutOfBounds(); error OwnerQueryForNonexistentToken(); error TokenIndexOutOfBounds(); 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 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_; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view returns (uint256) { // Counter underflow is impossible as _burnCounter cannot be incremented // more than _currentIndex times unchecked { return _currentIndex - _burnCounter; } } /** * @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) { if (owner == address(0)) revert MintedQueryForZeroAddress(); 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) { if (owner == address(0)) revert BurnedQueryForZeroAddress(); 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) { if (owner == address(0)) revert AuxQueryForZeroAddress(); 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 { if (owner == address(0)) revert AuxQueryForZeroAddress(); _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 (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 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 (!_checkOnERC721Received(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 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; for (uint256 i; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); if ( safe && !_checkOnERC721Received(address(0), to, updatedIndex, _data) ) { revert TransferToNonERC721ReceiverImplementer(); } 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 || isApprovedForAll(prevOwnership.addr, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); if (prevOwnership.addr != from) revert TransferFromIncorrectOwner(); if (to == address(0)) revert TransferToZeroAddress(); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // 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; _ownerships[tokenId].addr = to; _ownerships[tokenId].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; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership .startTimestamp; } } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @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 { TokenOwnership memory prevOwnership = ownershipOf(tokenId); _beforeTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // 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[prevOwnership.addr].balance -= 1; _addressData[prevOwnership.addr].numberBurned += 1; // Keep track of who burned the token, and the timestamp of burning. _ownerships[tokenId].addr = prevOwnership.addr; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); _ownerships[tokenId].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; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership .startTimestamp; } } } emit Transfer(prevOwnership.addr, address(0), tokenId); _afterTokenTransfers(prevOwnership.addr, 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 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 TransferToNonERC721ReceiverImplementer(); } 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. * 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 {} } // 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: contracts/Companion.sol pragma solidity ^0.8.4; // ╦ ┌─┐┌─┐┌┬┐┬ ┬┌─┐┬─┐┌─┐┌─┐┌─┐┌─┐ ╔═╗┌─┐┌┬┐┌─┐┌─┐┌┐┌┬┌─┐┌┐┌ // ║ ├┤ ├─┤ │ ├─┤├┤ ├┬┘├┤ ├─┤│ ├┤ ║ │ ││││├─┘├─┤│││││ ││││ // ╩═╝└─┘┴ ┴ ┴ ┴ ┴└─┘┴└─└ ┴ ┴└─┘└─┘ ╚═╝└─┘┴ ┴┴ ┴ ┴┘└┘┴└─┘┘└┘ // Author: William Giani <https://www.linkedin.com/in/william-giani> interface Leatherface { function balanceOf(address _owner) external view returns (uint256); function ownerOf(uint256 tokenId) external view returns (address owner); } contract Companion is ERC721A, Ownable { constructor( address leatherfaceAddress_, string memory name_, string memory symbol_, string memory hiddenMetaDataURI_ ) ERC721A(name_, symbol_) { leatherfaceContract = Leatherface(leatherfaceAddress_); hiddenMetadataUri = hiddenMetaDataURI_; } Leatherface leatherfaceContract; uint256 public maxSupply = 400; uint256 public maxMintPerTx = 10; uint256 public minAmountOfLeatherfacesRequiredPerMint = 2; bool public isRevealed = false; string public hiddenMetadataUri; string public uriPrefix; mapping(uint256 => bool) public claimedLeatherfaces; modifier mintCompliance(uint256 mintAmount, uint256[] memory leatherfaces) { require( mintAmount > 0 && mintAmount <= maxMintPerTx, "Invalid mint amount!" ); require( this.totalSupply() + mintAmount <= maxSupply, "Max supply exceeded!" ); require( leatherfaces.length == mintAmount * minAmountOfLeatherfacesRequiredPerMint, "You did not select the correct amount of Leatherface's for this mint (2 per NFT claimed)" ); _; } function setRevealed(bool _state) public onlyOwner { isRevealed = _state; } function setUriPrefix(string memory _uriPrefix) public onlyOwner { uriPrefix = _uriPrefix; } function setHiddenMetadataUri(string memory _hiddenMetadataUri) public onlyOwner { hiddenMetadataUri = _hiddenMetadataUri; } function _baseURI() internal view virtual override returns (string memory) { return uriPrefix; } function tokenURI(uint256 _tokenId) public view virtual override returns (string memory) { if (!_exists(_tokenId)) revert URIQueryForNonexistentToken(); if (!isRevealed) { return hiddenMetadataUri; } string memory baseURI = _baseURI(); return bytes(baseURI).length != 0 ? string( abi.encodePacked( baseURI, Strings.toString(_tokenId), ".json" ) ) : ""; } function _safeSaveLeatherfaces(uint256[] memory _leatherfaces) internal { uint256 leatherfacesCount = _leatherfaces.length; for (uint256 i = 0; i < leatherfacesCount; i++) { uint256 currentLeatherface = _leatherfaces[i]; address currentOwner = leatherfaceContract.ownerOf( currentLeatherface ); require( currentOwner == msg.sender, "You can only select your own NFTs" ); require( !claimedLeatherfaces[currentLeatherface], "You can only select NFTs that have not been claimed" ); claimedLeatherfaces[currentLeatherface] = true; } } function mint(uint256 quantity, uint256[] memory _leatherfaces) external mintCompliance(quantity, _leatherfaces) { _safeSaveLeatherfaces(_leatherfaces); _safeMint(msg.sender, quantity); } }
Initializes the contract setting the deployer as the initial owner./
function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity } pragma solidity ^0.8.0; constructor() { _transferOwnership(_msgSender()); }
185,310
./full_match/1/0x25245941137d9C85B5D48aE8d7788aA841BEB9aE/sources/contracts/staking/MasterBids.sol
Deposit LP tokens to masterbids for Bids allocation on behalf of user user must initiate transaction from masterbids _pid the pool id _amount amount to deposit _user the user being represented update pool in case user has deposited
function depositFor(uint256 _pid, uint256 _amount, address _user) external override nonReentrant whenNotPaused { PoolInfoV3 storage pool = poolInfoV3[_pid]; UserInfo storage user = userInfo[_pid][_user]; _updatePool(_pid); _updateUserAmount(_pid, _user, user.amount + _amount); pool.lpToken.safeTransferFrom(msg.sender, address(this), _amount); emit DepositFor(_user, _pid, _amount); }
3,100,032
./partial_match/1/0xab5aAd8a36B4F9BB5e526a16747Db51037dD1cAF/sources/TokenSale.sol
use of msg.sender in view function is not security measure (it doesnt work for view functions), it is used only for convinience here. And etherscan do not support it (limitation of etherscan view functions support, but web3 supports)./
function checkRefBalance(address ref_wallet) external onlyOwner view returns (uint256) { return ref_balances[ref_wallet]; }
2,650,698
/** *Submitted for verification at Etherscan.io on 2020-06-08 */ pragma solidity ^0.5.17; // @notice SECURITY TOKEN CONTRACT // @dev ERC-1404 with ERC-20 with ERC-223 protection Token Standard Compliant // @author Geoffrey Tipton at AEN // ---------------------------------------------------------------------------- // Deployed by : Geoffrey Tipton // Reviewed by : Aaron Regala // Symbol : AENS // Name : AEN Smart Token // Total supply: 4,000,000,000 // Decimals : 8 // // (c) AENSmart. The MIT Licence. // ---------------------------------------------------------------------------- // THE TOKENS HAVE NOT BEEN REGISTERED UNDER THE U.S. SECURITIES ACT OF // 1933, AS AMENDED (THE11SECURITIES ACT1). THE TOKENS WERE ISSUED IN // A TRANSACTION EXEMPT FROM THE REGISTRATION REQUIREMENTS OF THE SECURITIES // ACT PURSUANT TO REGULATION S PROMULGATED UNDER IT. THE TOKENS MAY NOT // BE OFFERED OR SOLD IN THE UNITED STATES UNLESS REGISTERED UNDER THE SECURITIES // ACT OR AN EXEMPTION FROM REGISTRATION IS AVAILABLE. TRANSFERS OF THE // TOKENS MAY NOT BE MADE EXCEPT IN ACCORDANCE WITH THE PROVISIONS OF REGULATION S, // PURSUANT TO REGISTRATION UNDER THE SECURITIES ACT, OR PURSUANT TO AN AVAILABLE // EXEMPTION FROM REGISTRATION. FURTHER, HEDGING TRANSACTIONS WITH REGARD TO THE // TOKENS MAY NOT BE CONDUCTED UNLESS IN COMPLIANCE WITH THE SECURITIES ACT. // ---------------------------------------------------------------------------- library SafeMath { function add(uint a, uint b) internal pure returns (uint c) { c = a + b; //require(c >= a,"Can not add negative values"); } function sub(uint a, uint b) internal pure returns (uint c) { //require(b <= a, "Result can not be negative"); c = a - b; } function mul(uint a, uint b) internal pure returns (uint c) { c = a * b; require(a == 0 || c / a == b,"Divide by zero protection"); } function div(uint a, uint b) internal pure returns (uint c) { require(b > 0,"Divide by zero protection"); c = a / b; } } // ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // ---------------------------------------------------------------------------- contract ERC20Interface { function totalSupply() external view returns (uint); function balanceOf(address owner) public view returns (uint256 balance); function allowance(address owner, address spender) public view returns (uint remaining); function transfer(address to, uint value) public returns (bool success); function approve(address spender, uint value) public returns (bool success); function transferFrom(address from, address to, uint value) public returns (bool success); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } // ---------------------------------------------------------------------------- // Open Standard ERC Token Standard #1404 Interface // https://erc1404.org // ---------------------------------------------------------------------------- contract ERC1404 is ERC20Interface { function detectTransferRestriction (address from, address to, uint256 value) public view returns (uint8); function messageForTransferRestriction (uint8 restrictionCode) public view returns (string memory); } contract Owned { address public owner; address internal newOwner; event OwnershipTransferred(address indexed _from, address indexed _to); constructor() public { owner = msg.sender; emit OwnershipTransferred(address(0), owner); } modifier onlyOwner() { require(msg.sender == owner, "Only the contract owner can execute this function"); _; } function transferOwnership(address _newOwner) external onlyOwner { newOwner = _newOwner; } // Prevent accidental false ownership change function acceptOwnership() external { require(msg.sender == newOwner); owner = newOwner; newOwner = address(0); emit OwnershipTransferred(owner, newOwner); } function getOwner() external view returns (address) { return owner; } } contract Managed is Owned { mapping(address => bool) public managers; modifier onlyManager() { require(managers[msg.sender], "Only managers can perform this action"); _; } function addManager(address managerAddress) external onlyOwner { managers[managerAddress] = true; } function removeManager(address managerAddress) external onlyOwner { managers[managerAddress] = false; } } /* ---------------------------------------------------------------------------- * Contract function to manage the white list * Byte operation to control function of the whitelist, * and prevent duplicate address entries. simple example * whiteList[add] = 0000 = 0x00 = Not allowed to do either * whiteList[add] = 0001 = 0x01 = Allowed to receive * whiteList[add] = 0010 = 0x02 = Allowed to send * whiteList[add] = 0011 = 0x03 = Allowed to send and receive * whiteList[add] = 0100 = 0x04 = Frozen not allowed to do either * whiteList[add] = 1000 = 0x08 = Paused No one can transfer any tokens *---------------------------------------------------------------------------- */ contract Whitelist is Managed { mapping(address => bytes1) public whiteList; bytes1 internal listRule; bytes1 internal constant WHITELISTED_CAN_RX_CODE = 0x01; // binary for 0001 bytes1 internal constant WHITELISTED_CAN_TX_CODE = 0x02; // binary for 0010 bytes1 internal constant WHITELISTED_FREEZE_CODE = 0x04; // binary for 0100 Always applies bytes1 internal constant WHITELISTED_PAUSED_CODE = 0x08; // binary for 1000 Always applies function isFrozen(address _account) public view returns (bool) { return (WHITELISTED_FREEZE_CODE == (whiteList[_account] & WHITELISTED_FREEZE_CODE)); // 10 & 11 = True } function addToSendAllowed(address _to) external onlyManager { whiteList[_to] = whiteList[_to] | WHITELISTED_CAN_TX_CODE; // just add the code 1 } function addToReceiveAllowed(address _to) external onlyManager { whiteList[_to] = whiteList[_to] | WHITELISTED_CAN_RX_CODE; // just add the code 2 } function removeFromSendAllowed(address _to) public onlyManager { if (WHITELISTED_CAN_TX_CODE == (whiteList[_to] & WHITELISTED_CAN_TX_CODE)) { // check code 4 so it does toggle when recalled whiteList[_to] = whiteList[_to] ^ WHITELISTED_CAN_TX_CODE; // xor the code to remove the flag } } function removeFromReceiveAllowed(address _to) public onlyManager { if (WHITELISTED_CAN_RX_CODE == (whiteList[_to] & WHITELISTED_CAN_RX_CODE)) { whiteList[_to] = whiteList[_to] ^ WHITELISTED_CAN_RX_CODE; } } function removeFromBothSendAndReceiveAllowed (address _to) external onlyManager { removeFromSendAllowed(_to); removeFromReceiveAllowed(_to); } /* this overrides the individual whitelisting and manager positions so a frozen account can not be unfrozen by a lower level manager */ function freeze(address _to) external onlyOwner { whiteList[_to] = whiteList[_to] | WHITELISTED_FREEZE_CODE; // 4 [0100] } function unFreeze(address _to) external onlyOwner { if (WHITELISTED_FREEZE_CODE == (whiteList[_to] & WHITELISTED_FREEZE_CODE )) { // Already Unfrozen whiteList[_to] = whiteList[_to] ^ WHITELISTED_FREEZE_CODE; // 4 [0100] } } function pause() external onlyOwner { listRule = WHITELISTED_PAUSED_CODE; // 8 [1000] } function resume() external onlyOwner { if (WHITELISTED_PAUSED_CODE == listRule ) { // Already Unfrozen listRule = listRule ^ WHITELISTED_PAUSED_CODE; // 4 [0100] } } /* Whitelist Rule defines what the rules are for the whitelisting 0x00 = No rule 0x01 = Receiver must be whitelisted 0x10 = Sender must be whitelisted 0x11 = Both must be whitelisted */ function setWhitelistRule(byte _newRule) external onlyOwner { listRule = _newRule; } function getWhitelistRule() external view returns (byte){ return listRule; } } // ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and an initial fixed supply // ---------------------------------------------------------------------------- contract AENSToken is ERC1404, Owned, Whitelist { using SafeMath for uint; string public symbol; string public name; uint8 public decimals; uint public _totalSupply; uint8 internal restrictionCheck; mapping(address => uint) public balances; mapping(address => mapping(address => uint)) allowed; constructor() public { symbol = "AENS"; name = "AEN Smart Token"; decimals = 8; _totalSupply = 4000000000 * 10**uint(decimals); balances[msg.sender] = _totalSupply; managers[msg.sender] = true; listRule = 0x00; // Receiver does not need to be whitelisted emit Transfer(address(0), msg.sender, _totalSupply); } modifier transferAllowed(address _from, address _to, uint256 _amount ) { require(!isFrozen(_to) && !isFrozen(_from), "One of the accounts are frozen"); // If not frozen go check if ((listRule & WHITELISTED_CAN_TX_CODE) != 0) { // If whitelist send rule applies then must be set require(WHITELISTED_CAN_TX_CODE == (whiteList[_from] & WHITELISTED_CAN_TX_CODE), "Sending account is not whitelisted"); // 10 & 11 = true } if ((listRule & WHITELISTED_CAN_RX_CODE) != 0) { // If whitelist to receive is required, then check, require(WHITELISTED_CAN_RX_CODE == (whiteList[_to] & WHITELISTED_CAN_RX_CODE),"Receiving account is not whitelisted"); // 01 & 11 = True } _; } // ------------------------------------------------------------------------ // Total supply minus any lost tokens to the zero address (Potential burn) function totalSupply() external view returns (uint) { return _totalSupply.sub(balances[address(0)]); } // ------------------------------------------------------------------------ // Get the token balance for account `tokenOwner` function balanceOf(address owner) public view returns (uint256) { return balances[owner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to `to` account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // function transfer(address _to, uint _tokens) public receiveAllowed(_to) returns (bool success) { function transfer(address _to, uint _value) public transferAllowed(msg.sender, _to, _value) returns (bool) { require((_to != address(0)) && (_to != address(this))); // Do not allow transfer to 0x0 or the token contract itself balances[msg.sender] = balances[msg.sender].sub(_value); //injected INTEGER OVERFLOW OR UNDERFLOW balances[_to] = balances[_to].add(_value); //injected INTEGER OVERFLOW OR UNDERFLOW emit Transfer(msg.sender, _to, _value); return true; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account function approve(address spender, uint value) public transferAllowed(msg.sender, spender, value) returns (bool) { allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } // ------------------------------------------------------------------------ // Transfer `tokens` from the `from` account to the `to` account function transferFrom(address _from, address _to, uint _value) public transferAllowed(_from, _to, _value) returns (bool) { // function transferFrom(address _from, address _to, uint _value) public returns (bool success) { require((_to != address(0)) && (_to != address(this))); // Do not allow transfer to 0x0 or the token contract itself balances[_from] = balances[_from].sub(_value); //injected INTEGER OVERFLOW OR UNDERFLOW allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); //injected INTEGER OVERFLOW OR UNDERFLOW balances[_to] = balances[_to].add(_value); //injected INTEGER OVERFLOW OR UNDERFLOW emit Transfer(_from, _to, _value); return true; } /* ------------------------------------------------------------------------ * Returns the amount of tokens approved by the owner that can be * transferred to the spender's account */ function allowance(address owner, address spender) public view returns (uint) { return allowed[owner][spender]; } /* ---------------------------------------------------------------------------------------- * @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) public onlyOwner { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); //injected INTEGER OVERFLOW OR UNDERFLOW balances[account] = balances[account].add(amount); //injected INTEGER OVERFLOW OR UNDERFLOW 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 value) public onlyOwner { require(account != address(0), "ERC20: prevent burn from a zero address"); balances[account] = balances[account].sub(value); //injected INTEGER OVERFLOW OR UNDERFLOW _totalSupply = _totalSupply.sub(value); //injected INTEGER OVERFLOW OR UNDERFLOW emit Transfer(account, address(0), value); } /* ------------------------------------------------------------------------ * don't accept ETH */ function() payable external { revert(); } /* ------------------------------------------------------------------------ * This function prevents accidentally sent tokens to the contract */ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } /* ------------------------------------------------------------------------ * The following functions are for 1404 interface compliance, to detect * a transaction is allowed before sending, to save gas and obtain a clear Message */ function detectTransferRestriction (address _from, address _to, uint256 _value) public view returns (uint8 restrictionCode) { restrictionCode = 0; // No restrictions if ( WHITELISTED_CAN_TX_CODE == (listRule & WHITELISTED_CAN_TX_CODE) ) { //Can Send rule applies if (!(WHITELISTED_CAN_TX_CODE == (whiteList[_to] & WHITELISTED_CAN_TX_CODE)) ) { //True if allowed to send restrictionCode += 1; // Send is not allowed } } if (WHITELISTED_CAN_RX_CODE == (listRule & WHITELISTED_CAN_RX_CODE)){ // Can Receive Rule applied if (!(WHITELISTED_CAN_RX_CODE == (whiteList[_from] & WHITELISTED_CAN_RX_CODE))) { restrictionCode += 2; // Receive is not allowed } } if ((WHITELISTED_FREEZE_CODE == (whiteList[_from] & WHITELISTED_FREEZE_CODE)) ) { // Added to Frozen restrictionCode += 4; // Sender is Frozen } if ((WHITELISTED_FREEZE_CODE == (whiteList[_to] & WHITELISTED_FREEZE_CODE)) ) { // Added to Frozen restrictionCode += 8; // Receiver is Frozen } if (balanceOf(_from) < _value) { restrictionCode += 16; // Send has insufficient balance } if (listRule == (listRule & WHITELISTED_PAUSED_CODE) ) { restrictionCode += 32; // Send has insufficient balance } return restrictionCode; } /* ------------------------------------------------------------------------------------ * helper function to return a human readable message for the detectTransferRestriction */ function messageForTransferRestriction (uint8 _restrictionCode) public view returns (string memory _message) { _message = "Transfer Allowed"; // default and when is zero if (_restrictionCode >= 32) { _message = "Contract Token is Paused for all transfers"; } else if (_restrictionCode >= 16) { _message = "Insufficient Balance to send"; } else if (_restrictionCode >= 8) { _message = "To Account is Frozen, contact provider"; } else if (_restrictionCode >= 4) { _message = "From Account is Frozen, contact provider"; } else if (_restrictionCode >= 3) { _message = "Both Sending and receiving address has not been KYC Approved"; } else if (_restrictionCode >= 2) { _message = "Receiving address has not been KYC Approved"; } else if (_restrictionCode >= 1) { _message = "Sending address has not been KYC Approved"; } return _message; } }
------------------------------------------------------------------------ Transfer `tokens` from the `from` account to the `to` account function transferFrom(address _from, address _to, uint _value) public returns (bool success) {
function transferFrom(address _from, address _to, uint _value) public transferAllowed(_from, _to, _value) returns (bool) { emit Transfer(_from, _to, _value); return true; }
956,716
pragma solidity ^0.5.16; import "./v2SafeMath.sol"; import "./v2TellorStorage.sol"; /** * @title Tellor Transfer * @dev Contains the methods related to transfers and ERC20. Tellor.sol and TellorGetters.sol * reference this library for function's logic. */ library v2TellorTransfer { using v2SafeMath for uint256; event Approval(address indexed _owner, address indexed _spender, uint256 _value); //ERC20 Approval event event Transfer(address indexed _from, address indexed _to, uint256 _value); //ERC20 Transfer Event bytes32 public constant stakeAmount = 0x7be108969d31a3f0b261465c71f2b0ba9301cd914d55d9091c3b36a49d4d41b2; //keccak256("stakeAmount") /*Functions*/ /** * @dev Allows for a transfer of tokens to _to * @param _to The address to send tokens to * @param _amount The amount of tokens to send * @return true if transfer is successful */ function transfer(v2TellorStorage.TellorStorageStruct storage self, address _to, uint256 _amount) public returns (bool success) { doTransfer(self, msg.sender, _to, _amount); return true; } /** * @notice Send _amount tokens to _to from _from on the condition it * is approved by _from * @param _from The address holding the tokens being transferred * @param _to The address of the recipient * @param _amount The amount of tokens to be transferred * @return True if the transfer was successful */ function transferFrom(v2TellorStorage.TellorStorageStruct storage self, address _from, address _to, uint256 _amount) public returns (bool success) { require(self.allowed[_from][msg.sender] >= _amount, "Allowance is wrong"); self.allowed[_from][msg.sender] -= _amount; doTransfer(self, _from, _to, _amount); return true; } /** * @dev This function approves a _spender an _amount of tokens to use * @param _spender address * @param _amount amount the spender is being approved for * @return true if spender appproved successfully */ function approve(v2TellorStorage.TellorStorageStruct storage self, address _spender, uint256 _amount) public returns (bool) { require(_spender != address(0), "Spender is 0-address"); require(self.allowed[msg.sender][_spender] == 0 || _amount == 0, "Spender is already approved"); self.allowed[msg.sender][_spender] = _amount; emit Approval(msg.sender, _spender, _amount); return true; } /** * @param _user address of party with the balance * @param _spender address of spender of parties said balance * @return Returns the remaining allowance of tokens granted to the _spender from the _user */ function allowance(v2TellorStorage.TellorStorageStruct storage self, address _user, address _spender) public view returns (uint256) { return self.allowed[_user][_spender]; } /** * @dev Completes POWO transfers by updating the balances on the current block number * @param _from address to transfer from * @param _to addres to transfer to * @param _amount to transfer */ function doTransfer(v2TellorStorage.TellorStorageStruct storage self, address _from, address _to, uint256 _amount) public { require(_amount != 0, "Tried to send non-positive amount"); require(_to != address(0), "Receiver is 0 address"); require(allowedToTrade(self, _from, _amount), "Should have sufficient balance to trade"); uint256 previousBalance = balanceOf(self, _from); updateBalanceAtNow(self.balances[_from], previousBalance - _amount); previousBalance = balanceOf(self,_to); require(previousBalance + _amount >= previousBalance, "Overflow happened"); // Check for overflow updateBalanceAtNow(self.balances[_to], previousBalance + _amount); emit Transfer(_from, _to, _amount); } /** * @dev Gets balance of owner specified * @param _user is the owner address used to look up the balance * @return Returns the balance associated with the passed in _user */ function balanceOf(v2TellorStorage.TellorStorageStruct storage self, address _user) public view returns (uint256) { return balanceOfAt(self, _user, block.number); } /** * @dev Queries the balance of _user at a specific _blockNumber * @param _user The address from which the balance will be retrieved * @param _blockNumber The block number when the balance is queried * @return The balance at _blockNumber specified */ function balanceOfAt(v2TellorStorage.TellorStorageStruct storage self, address _user, uint256 _blockNumber) public view returns (uint256) { v2TellorStorage.Checkpoint[] storage checkpoints = self.balances[_user]; if (checkpoints.length == 0|| checkpoints[0].fromBlock > _blockNumber) { return 0; } else { if (_blockNumber >= checkpoints[checkpoints.length - 1].fromBlock) return checkpoints[checkpoints.length - 1].value; // Binary search of the value in the array uint256 min = 0; uint256 max = checkpoints.length - 2; while (max > min) { uint256 mid = (max + min + 1) / 2; if (checkpoints[mid].fromBlock ==_blockNumber){ return checkpoints[mid].value; }else if(checkpoints[mid].fromBlock < _blockNumber) { min = mid; } else { max = mid - 1; } } return checkpoints[min].value; } } /** * @dev This function returns whether or not a given user is allowed to trade a given amount * and removing the staked amount from their balance if they are staked * @param _user address of user * @param _amount to check if the user can spend * @return true if they are allowed to spend the amount being checked */ function allowedToTrade(v2TellorStorage.TellorStorageStruct storage self, address _user, uint256 _amount) public view returns (bool) { if (self.stakerDetails[_user].currentStatus != 0 && self.stakerDetails[_user].currentStatus < 5) { //Subtracts the stakeAmount from balance if the _user is staked if (balanceOf(self, _user)- self.uintVars[stakeAmount] >= _amount) { return true; } return false; } return (balanceOf(self, _user) >= _amount); } /** * @dev Updates balance for from and to on the current block number via doTransfer * @param checkpoints gets the mapping for the balances[owner] * @param _value is the new balance */ function updateBalanceAtNow(v2TellorStorage.Checkpoint[] storage checkpoints, uint256 _value) public { if (checkpoints.length == 0 || checkpoints[checkpoints.length - 1].fromBlock != block.number) { checkpoints.push(v2TellorStorage.Checkpoint({ fromBlock : uint128(block.number), value : uint128(_value) })); } else { v2TellorStorage.Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length - 1]; oldCheckPoint.value = uint128(_value); } } }
_user address of party with the balance _spender address of spender of parties said balance return Returns the remaining allowance of tokens granted to the _spender from the _user/
function allowance(v2TellorStorage.TellorStorageStruct storage self, address _user, address _spender) public view returns (uint256) { return self.allowed[_user][_spender]; }
14,053,614
// SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.7.0 <0.9.0; // 买卖合约示例,通过状态机来实现买卖双方的确认机制。 contract Purchase { uint public value; address payable public seller; address payable public buyer; enum State {Created, Locked, Release, Inactive} State public state; // 条件限制 modifier condition(bool _condition) { require(_condition); _; } // 调用者限制为买家 modifier onlyBuyer() { require( msg.sender == buyer, "Only buyer can call this." ); _; } // 调用者限制为卖家 modifier onlySeller() { require( msg.sender == seller, "Only seller can call this." ); _; } // 状态限制,符合状态才能继续调用 modifier inState(State _state) { require( state == _state, "Invalid state." ); _; } // 事件定义 event Aborted(); event PurchaseConfirmed(); event ItemReceived(); event SellerRefunded(); //确保 `msg.value` 是一个偶数。 //如果它是一个奇数,则它将被截断。 //通过乘法检查它不是奇数。 constructor() payable { seller = payable(msg.sender); value = msg.value / 2; require((2 * value) == msg.value, "Value has to be even."); } ///中止购买并回收以太币。 ///只能在合约被锁定之前由卖家调用。 function abort() public onlySeller inState(State.Created) { emit Aborted(); state = State.Inactive; seller.transfer(address(this).balance); } /// 买家确认购买。 /// 交易必须包含 `2 * value` 个以太币。 /// 以太币会被锁定,直到 confirmReceived 被调用。 function confirmPurchase() public inState(State.Created) condition(msg.value == (2 * value)) payable { emit PurchaseConfirmed(); buyer = payable(msg.sender); state = State.Locked; } /// 买家确认已经收到商品。 /// 这会释放被锁定的以太币。 function confirmReceived() public onlyBuyer inState(State.Locked) { emit ItemReceived(); // 必须首先更改状态,然后调用transfer,避免transfer被调用多次 state = State.Release; buyer.transfer(value); } /// 退款给卖家,即:将锁定的资金发给卖家 function refundSeller() public onlySeller inState(State.Release) { emit SellerRefunded(); // 必须先更改状态,然后调用transfer,避免多次调用 state = State.Inactive; seller.transfer(3 * value); } }
买家确认已经收到商品。 这会释放被锁定的以太币。 必须首先更改状态,然后调用transfer,避免transfer被调用多次
function confirmReceived() public onlyBuyer inState(State.Locked) { emit ItemReceived(); state = State.Release; buyer.transfer(value); }
1,063,764
pragma solidity 0.4.24; import "@aragon/os/contracts/apps/UnsafeAragonApp.sol"; import "@aragon/os/contracts/common/EtherTokenConstant.sol"; import "@aragon/os/contracts/common/IsContract.sol"; import "@aragon/os/contracts/common/SafeERC20.sol"; import "@aragon/os/contracts/lib/math/SafeMath.sol"; import "@aragon/os/contracts/lib/token/ERC20.sol"; import "./IContinuousToken.sol"; import "./Vault.sol"; import "@ablack/fundraising-bancor-formula/contracts/BancorFormula.sol"; import "@ablack/fundraising-shared-interfaces/contracts/IAragonFundraisingController.sol"; contract MarketMaker is EtherTokenConstant, IsContract, UnsafeAragonApp { using SafeERC20 for ERC20; using SafeMath for uint256; /** Hardcoded constants to save gas bytes32 public constant OPEN_ROLE = keccak256("OPEN_ROLE"); bytes32 public constant UPDATE_FORMULA_ROLE = keccak256("UPDATE_FORMULA_ROLE"); bytes32 public constant UPDATE_BENEFICIARY_ROLE = keccak256("UPDATE_BENEFICIARY_ROLE"); bytes32 public constant UPDATE_FEES_ROLE = keccak256("UPDATE_FEES_ROLE"); bytes32 public constant ADD_COLLATERAL_TOKEN_ROLE = keccak256("ADD_COLLATERAL_TOKEN_ROLE"); bytes32 public constant REMOVE_COLLATERAL_TOKEN_ROLE = keccak256("REMOVE_COLLATERAL_TOKEN_ROLE"); bytes32 public constant UPDATE_COLLATERAL_TOKEN_ROLE = keccak256("UPDATE_COLLATERAL_TOKEN_ROLE"); bytes32 public constant OPEN_BUY_ORDER_ROLE = keccak256("OPEN_BUY_ORDER_ROLE"); bytes32 public constant OPEN_SELL_ORDER_ROLE = keccak256("OPEN_SELL_ORDER_ROLE"); */ bytes32 public constant OPEN_ROLE = 0xefa06053e2ca99a43c97c4a4f3d8a394ee3323a8ff237e625fba09fe30ceb0a4; bytes32 public constant UPDATE_FORMULA_ROLE = 0xbfb76d8d43f55efe58544ea32af187792a7bdb983850d8fed33478266eec3cbb; bytes32 public constant UPDATE_BENEFICIARY_ROLE = 0xf7ea2b80c7b6a2cab2c11d2290cb005c3748397358a25e17113658c83b732593; bytes32 public constant UPDATE_FEES_ROLE = 0x5f9be2932ed3a723f295a763be1804c7ebfd1a41c1348fb8bdf5be1c5cdca822; bytes32 public constant ADD_COLLATERAL_TOKEN_ROLE = 0x217b79cb2bc7760defc88529853ef81ab33ae5bb315408ce9f5af09c8776662d; bytes32 public constant REMOVE_COLLATERAL_TOKEN_ROLE = 0x2044e56de223845e4be7d0a6f4e9a29b635547f16413a6d1327c58d9db438ee2; bytes32 public constant UPDATE_COLLATERAL_TOKEN_ROLE = 0xe0565c2c43e0d841e206bb36a37f12f22584b4652ccee6f9e0c071b697a2e13d; bytes32 public constant OPEN_BUY_ORDER_ROLE = 0xa589c8f284b76fc8d510d9d553485c47dbef1b0745ae00e0f3fd4e28fcd77ea7; bytes32 public constant OPEN_SELL_ORDER_ROLE = 0xd68ba2b769fa37a2a7bd4bed9241b448bc99eca41f519ef037406386a8f291c0; uint256 public constant PCT_BASE = 10**18; // 0% = 0; 1% = 10 ** 16; 100% = 10 ** 18 uint32 public constant PPM = 1000000; string private constant ERROR_CONTRACT_IS_EOA = "MM_CONTRACT_IS_EOA"; string private constant ERROR_INVALID_BENEFICIARY = "MM_INVALID_BENEFICIARY"; string private constant ERROR_INVALID_BATCH_BLOCKS = "MM_INVALID_BATCH_BLOCKS"; string private constant ERROR_INVALID_PERCENTAGE = "MM_INVALID_PERCENTAGE"; string private constant ERROR_INVALID_RESERVE_RATIO = "MM_INVALID_RESERVE_RATIO"; string private constant ERROR_INVALID_TM_SETTING = "MM_INVALID_TM_SETTING"; string private constant ERROR_INVALID_COLLATERAL = "MM_INVALID_COLLATERAL"; string private constant ERROR_INVALID_COLLATERAL_VALUE = "MM_INVALID_COLLATERAL_VALUE"; string private constant ERROR_INVALID_BOND_AMOUNT = "MM_INVALID_BOND_AMOUNT"; string private constant ERROR_ALREADY_OPEN = "MM_ALREADY_OPEN"; string private constant ERROR_NOT_OPEN = "MM_NOT_OPEN"; string private constant ERROR_COLLATERAL_ALREADY_WHITELISTED = "MM_COLLATERAL_ALREADY_WHITELISTED"; string private constant ERROR_COLLATERAL_NOT_WHITELISTED = "MM_COLLATERAL_NOT_WHITELISTED"; string private constant ERROR_NOTHING_TO_CLAIM = "MM_NOTHING_TO_CLAIM"; string private constant ERROR_BATCH_NOT_OVER = "MM_BATCH_NOT_OVER"; string private constant ERROR_BATCH_CANCELLED = "MM_BATCH_CANCELLED"; string private constant ERROR_BATCH_NOT_CANCELLED = "MM_BATCH_NOT_CANCELLED"; string private constant ERROR_SLIPPAGE_EXCEEDS_LIMIT = "MM_SLIPPAGE_EXCEEDS_LIMIT"; string private constant ERROR_INSUFFICIENT_POOL_BALANCE = "MM_INSUFFICIENT_POOL_BALANCE"; string private constant ERROR_TRANSFER_FROM_FAILED = "MM_TRANSFER_FROM_FAILED"; struct Collateral { bool whitelisted; uint256 virtualSupply; uint256 virtualBalance; uint32 reserveRatio; uint256 slippage; } struct MetaBatch { bool initialized; uint256 realSupply; uint256 buyFeePct; uint256 sellFeePct; IBancorFormula formula; mapping(address => Batch) batches; } struct Batch { bool initialized; bool cancelled; uint256 supply; uint256 balance; uint32 reserveRatio; uint256 slippage; uint256 totalBuySpend; uint256 totalBuyReturn; uint256 totalSellSpend; uint256 totalSellReturn; mapping(address => uint256) buyers; mapping(address => uint256) sellers; } IAragonFundraisingController public controller; IContinuousToken public bondedToken; Vault public reserve; address public beneficiary; IBancorFormula public formula; uint256 public batchBlocks; uint256 public buyFeePct; uint256 public sellFeePct; bool public isOpen; uint256 public tokensToBeMinted; mapping(address => uint256) public collateralsToBeClaimed; mapping(address => Collateral) public collaterals; mapping(uint256 => MetaBatch) public metaBatches; event UpdateBeneficiary(address indexed beneficiary); event UpdateFormula(address indexed formula); event UpdateFees(uint256 buyFeePct, uint256 sellFeePct); event NewMetaBatch(uint256 indexed id, uint256 supply, uint256 buyFeePct, uint256 sellFeePct, address formula); event NewBatch( uint256 indexed id, address indexed collateral, uint256 supply, uint256 balance, uint32 reserveRatio, uint256 slippage ); event CancelBatch(uint256 indexed id, address indexed collateral); event AddCollateralToken( address indexed collateral, uint256 virtualSupply, uint256 virtualBalance, uint32 reserveRatio, uint256 slippage ); event RemoveCollateralToken(address indexed collateral); event UpdateCollateralToken( address indexed collateral, uint256 virtualSupply, uint256 virtualBalance, uint32 reserveRatio, uint256 slippage ); event Open(); event OpenBuyOrder( address indexed buyer, uint256 indexed batchId, address indexed collateral, uint256 fee, uint256 value ); event OpenSellOrder(address indexed seller, uint256 indexed batchId, address indexed collateral, uint256 amount); event ClaimBuyOrder(address indexed buyer, uint256 indexed batchId, address indexed collateral, uint256 amount); event ClaimSellOrder( address indexed seller, uint256 indexed batchId, address indexed collateral, uint256 fee, uint256 value ); event ClaimCancelledBuyOrder( address indexed buyer, uint256 indexed batchId, address indexed collateral, uint256 value ); event ClaimCancelledSellOrder( address indexed seller, uint256 indexed batchId, address indexed collateral, uint256 amount ); event UpdatePricing( uint256 indexed batchId, address indexed collateral, uint256 totalBuySpend, uint256 totalBuyReturn, uint256 totalSellSpend, uint256 totalSellReturn ); /***** external function *****/ /** * @notice Initialize market maker * @param _controller The address of the controller contract * @param _bondedToken The address of the bonded token * @param _reserve The address of the reserve [pool] contract * @param _beneficiary The address of the beneficiary [to whom fees are to be sent] * @param _formula The address of the BancorFormula [computation] contract * @param _batchBlocks The number of blocks batches are to last * @param _buyFeePct The fee to be deducted from buy orders [in PCT_BASE] * @param _sellFeePct The fee to be deducted from sell orders [in PCT_BASE] */ function initialize( IKernel _kernel, IAragonFundraisingController _controller, IContinuousToken _bondedToken, IBancorFormula _formula, Vault _reserve, address _beneficiary, uint256 _batchBlocks, uint256 _buyFeePct, uint256 _sellFeePct ) external onlyInit { initialized(); require(isContract(_kernel), ERROR_CONTRACT_IS_EOA); require(isContract(_controller), ERROR_CONTRACT_IS_EOA); require(isContract(_bondedToken), ERROR_CONTRACT_IS_EOA); require(isContract(_formula), ERROR_CONTRACT_IS_EOA); require(isContract(_reserve), ERROR_CONTRACT_IS_EOA); require(_beneficiaryIsValid(_beneficiary), ERROR_INVALID_BENEFICIARY); require(_batchBlocks > 0, ERROR_INVALID_BATCH_BLOCKS); require(_feeIsValid(_buyFeePct) && _feeIsValid(_sellFeePct), ERROR_INVALID_PERCENTAGE); controller = _controller; bondedToken = _bondedToken; formula = _formula; reserve = _reserve; beneficiary = _beneficiary; batchBlocks = _batchBlocks; buyFeePct = _buyFeePct; sellFeePct = _sellFeePct; setKernel(_kernel); } /* generic settings related function */ /** * @notice Open market making [enabling users to open buy and sell orders] */ function open() external auth(OPEN_ROLE) { require(!isOpen, ERROR_ALREADY_OPEN); _open(); } /** * @notice Update formula to `_formula` * @param _formula The address of the new BancorFormula [computation] contract */ function updateFormula(IBancorFormula _formula) external auth(UPDATE_FORMULA_ROLE) { require(isContract(_formula), ERROR_CONTRACT_IS_EOA); _updateFormula(_formula); } /** * @notice Update beneficiary to `_beneficiary` * @param _beneficiary The address of the new beneficiary [to whom fees are to be sent] */ function updateBeneficiary(address _beneficiary) external auth(UPDATE_BENEFICIARY_ROLE) { require(_beneficiaryIsValid(_beneficiary), ERROR_INVALID_BENEFICIARY); _updateBeneficiary(_beneficiary); } /** * @notice Update fees deducted from buy and sell orders to respectively `@formatPct(_buyFeePct)`% and `@formatPct(_sellFeePct)`% * @param _buyFeePct The new fee to be deducted from buy orders [in PCT_BASE] * @param _sellFeePct The new fee to be deducted from sell orders [in PCT_BASE] */ function updateFees(uint256 _buyFeePct, uint256 _sellFeePct) external auth(UPDATE_FEES_ROLE) { require(_feeIsValid(_buyFeePct) && _feeIsValid(_sellFeePct), ERROR_INVALID_PERCENTAGE); _updateFees(_buyFeePct, _sellFeePct); } /* collateral tokens related functions */ /** * @notice Add `_collateral.symbol(): string` as a whitelisted collateral token * @param _collateral The address of the collateral token to be whitelisted * @param _virtualSupply The virtual supply to be used for that collateral token [in wei] * @param _virtualBalance The virtual balance to be used for that collateral token [in wei] * @param _reserveRatio The reserve ratio to be used for that collateral token [in PPM] * @param _slippage The price slippage below which each batch is to be kept for that collateral token [in PCT_BASE] */ function addCollateralToken( address _collateral, uint256 _virtualSupply, uint256 _virtualBalance, uint32 _reserveRatio, uint256 _slippage ) external auth(ADD_COLLATERAL_TOKEN_ROLE) { require(isContract(_collateral) || _collateral == ETH, ERROR_INVALID_COLLATERAL); require(!_collateralIsWhitelisted(_collateral), ERROR_COLLATERAL_ALREADY_WHITELISTED); require(_reserveRatioIsValid(_reserveRatio), ERROR_INVALID_RESERVE_RATIO); _addCollateralToken(_collateral, _virtualSupply, _virtualBalance, _reserveRatio, _slippage); } /** * @notice Remove `_collateral.symbol(): string` as a whitelisted collateral token * @param _collateral The address of the collateral token to be un-whitelisted */ function removeCollateralToken(address _collateral) external auth(REMOVE_COLLATERAL_TOKEN_ROLE) { require(_collateralIsWhitelisted(_collateral), ERROR_COLLATERAL_NOT_WHITELISTED); _removeCollateralToken(_collateral); } /** * @notice Update `_collateral.symbol(): string` collateralization settings * @param _collateral The address of the collateral token whose collateralization settings are to be updated * @param _virtualSupply The new virtual supply to be used for that collateral token [in wei] * @param _virtualBalance The new virtual balance to be used for that collateral token [in wei] * @param _reserveRatio The new reserve ratio to be used for that collateral token [in PPM] * @param _slippage The new price slippage below which each batch is to be kept for that collateral token [in PCT_BASE] */ function updateCollateralToken( address _collateral, uint256 _virtualSupply, uint256 _virtualBalance, uint32 _reserveRatio, uint256 _slippage ) external auth(UPDATE_COLLATERAL_TOKEN_ROLE) { require(_collateralIsWhitelisted(_collateral), ERROR_COLLATERAL_NOT_WHITELISTED); require(_reserveRatioIsValid(_reserveRatio), ERROR_INVALID_RESERVE_RATIO); _updateCollateralToken(_collateral, _virtualSupply, _virtualBalance, _reserveRatio, _slippage); } /* market making related functions */ /** * @notice Open a buy order worth `@tokenAmount(_collateral, _value)` * @param _buyer The address of the buyer * @param _collateral The address of the collateral token to be spent * @param _value The amount of collateral token to be spent */ function openBuyOrder( address _buyer, address _collateral, uint256 _value ) external payable auth(OPEN_BUY_ORDER_ROLE) { require(isOpen, ERROR_NOT_OPEN); require(_collateralIsWhitelisted(_collateral), ERROR_COLLATERAL_NOT_WHITELISTED); require(!_batchIsCancelled(_currentBatchId(), _collateral), ERROR_BATCH_CANCELLED); require(_collateralValueIsValid(_buyer, _collateral, _value, msg.value), ERROR_INVALID_COLLATERAL_VALUE); _openBuyOrder(_buyer, _collateral, _value); } /** * @notice Open a sell order worth `@tokenAmount(self.token(): address, _amount)` against `_collateral.symbol(): string` * @param _seller The address of the seller * @param _collateral The address of the collateral token to be returned * @param _amount The amount of bonded token to be spent */ function openSellOrder( address _seller, address _collateral, uint256 _amount ) external auth(OPEN_SELL_ORDER_ROLE) { require(isOpen, ERROR_NOT_OPEN); require(_collateralIsWhitelisted(_collateral), ERROR_COLLATERAL_NOT_WHITELISTED); require(!_batchIsCancelled(_currentBatchId(), _collateral), ERROR_BATCH_CANCELLED); require(_bondAmountIsValid(_seller, _amount), ERROR_INVALID_BOND_AMOUNT); _openSellOrder(_seller, _collateral, _amount); } /** * @notice Claim the results of `_buyer`'s `_collateral.symbol(): string` buy orders from batch #`_batchId` * @param _buyer The address of the user whose buy orders are to be claimed * @param _batchId The id of the batch in which buy orders are to be claimed * @param _collateral The address of the collateral token against which buy orders are to be claimed */ function claimBuyOrder( address _buyer, uint256 _batchId, address _collateral ) external nonReentrant isInitialized { require(_collateralIsWhitelisted(_collateral), ERROR_COLLATERAL_NOT_WHITELISTED); require(_batchIsOver(_batchId), ERROR_BATCH_NOT_OVER); require(!_batchIsCancelled(_batchId, _collateral), ERROR_BATCH_CANCELLED); require(_userIsBuyer(_batchId, _collateral, _buyer), ERROR_NOTHING_TO_CLAIM); _claimBuyOrder(_buyer, _batchId, _collateral); } /** * @notice Claim the results of `_seller`'s `_collateral.symbol(): string` sell orders from batch #`_batchId` * @param _seller The address of the user whose sell orders are to be claimed * @param _batchId The id of the batch in which sell orders are to be claimed * @param _collateral The address of the collateral token against which sell orders are to be claimed */ function claimSellOrder( address _seller, uint256 _batchId, address _collateral ) external nonReentrant isInitialized { require(_collateralIsWhitelisted(_collateral), ERROR_COLLATERAL_NOT_WHITELISTED); require(_batchIsOver(_batchId), ERROR_BATCH_NOT_OVER); require(!_batchIsCancelled(_batchId, _collateral), ERROR_BATCH_CANCELLED); require(_userIsSeller(_batchId, _collateral, _seller), ERROR_NOTHING_TO_CLAIM); _claimSellOrder(_seller, _batchId, _collateral); } /** * @notice Claim the investments of `_buyer`'s `_collateral.symbol(): string` buy orders from cancelled batch #`_batchId` * @param _buyer The address of the user whose cancelled buy orders are to be claimed * @param _batchId The id of the batch in which cancelled buy orders are to be claimed * @param _collateral The address of the collateral token against which cancelled buy orders are to be claimed */ function claimCancelledBuyOrder( address _buyer, uint256 _batchId, address _collateral ) external nonReentrant isInitialized { require(_batchIsCancelled(_batchId, _collateral), ERROR_BATCH_NOT_CANCELLED); require(_userIsBuyer(_batchId, _collateral, _buyer), ERROR_NOTHING_TO_CLAIM); _claimCancelledBuyOrder(_buyer, _batchId, _collateral); } /** * @notice Claim the investments of `_seller`'s `_collateral.symbol(): string` sell orders from cancelled batch #`_batchId` * @param _seller The address of the user whose cancelled sell orders are to be claimed * @param _batchId The id of the batch in which cancelled sell orders are to be claimed * @param _collateral The address of the collateral token against which cancelled sell orders are to be claimed */ function claimCancelledSellOrder( address _seller, uint256 _batchId, address _collateral ) external nonReentrant isInitialized { require(_batchIsCancelled(_batchId, _collateral), ERROR_BATCH_NOT_CANCELLED); require(_userIsSeller(_batchId, _collateral, _seller), ERROR_NOTHING_TO_CLAIM); _claimCancelledSellOrder(_seller, _batchId, _collateral); } /***** public view functions *****/ function getCurrentBatchId() public view isInitialized returns (uint256) { return _currentBatchId(); } function getCollateralToken(address _collateral) public view isInitialized returns ( bool, uint256, uint256, uint32, uint256 ) { Collateral storage collateral = collaterals[_collateral]; return ( collateral.whitelisted, collateral.virtualSupply, collateral.virtualBalance, collateral.reserveRatio, collateral.slippage ); } function getBatch(uint256 _batchId, address _collateral) public view isInitialized returns ( bool, bool, uint256, uint256, uint32, uint256, uint256, uint256, uint256, uint256 ) { Batch storage batch = metaBatches[_batchId].batches[_collateral]; return ( batch.initialized, batch.cancelled, batch.supply, batch.balance, batch.reserveRatio, batch.slippage, batch.totalBuySpend, batch.totalBuyReturn, batch.totalSellSpend, batch.totalSellReturn ); } function getStaticPricePPM( uint256 _supply, uint256 _balance, uint32 _reserveRatio ) public view isInitialized returns (uint256) { return _staticPricePPM(_supply, _balance, _reserveRatio); } /***** internal functions *****/ /* computation functions */ function _staticPricePPM( uint256 _supply, uint256 _balance, uint32 _reserveRatio ) internal pure returns (uint256) { return uint256(PPM).mul(uint256(PPM)).mul(_balance).div(_supply.mul(uint256(_reserveRatio))); } function _currentBatchId() internal view returns (uint256) { return (block.number.div(batchBlocks)).mul(batchBlocks); } /* check functions */ function _beneficiaryIsValid(address _beneficiary) internal pure returns (bool) { return _beneficiary != address(0); } function _feeIsValid(uint256 _fee) internal pure returns (bool) { return _fee < PCT_BASE; } function _reserveRatioIsValid(uint32 _reserveRatio) internal pure returns (bool) { return _reserveRatio <= PPM; } function _collateralValueIsValid( address _buyer, address _collateral, uint256 _value, uint256 _msgValue ) internal view returns (bool) { if (_value == 0) { return false; } if (_collateral == ETH) { return _msgValue == _value; } return (_msgValue == 0 && controller.balanceOf(_buyer, _collateral) >= _value && ERC20(_collateral).allowance(_buyer, address(this)) >= _value); } function _bondAmountIsValid(address _seller, uint256 _amount) internal view returns (bool) { return _amount != 0 && bondedToken.balanceOf(_seller) >= _amount; } function _collateralIsWhitelisted(address _collateral) internal view returns (bool) { return collaterals[_collateral].whitelisted; } function _batchIsOver(uint256 _batchId) internal view returns (bool) { return _batchId < _currentBatchId(); } function _batchIsCancelled(uint256 _batchId, address _collateral) internal view returns (bool) { return metaBatches[_batchId].batches[_collateral].cancelled; } function _userIsBuyer( uint256 _batchId, address _collateral, address _user ) internal view returns (bool) { Batch storage batch = metaBatches[_batchId].batches[_collateral]; return batch.buyers[_user] > 0; } function _userIsSeller( uint256 _batchId, address _collateral, address _user ) internal view returns (bool) { Batch storage batch = metaBatches[_batchId].batches[_collateral]; return batch.sellers[_user] > 0; } function _poolBalanceIsSufficient(address _collateral) internal view returns (bool) { return controller.balanceOf(address(reserve), _collateral) >= collateralsToBeClaimed[_collateral]; } function _slippageIsValid(Batch storage _batch, address) internal view returns (bool) { uint256 staticPricePPM = _staticPricePPM(_batch.supply, _batch.balance, _batch.reserveRatio); uint256 maximumSlippage = _batch.slippage; // if static price is zero let's consider that every slippage is valid if (staticPricePPM == 0) { return true; } return _buySlippageIsValid(_batch, staticPricePPM, maximumSlippage) && _sellSlippageIsValid(_batch, staticPricePPM, maximumSlippage); } function _buySlippageIsValid( Batch storage _batch, uint256 _startingPricePPM, uint256 _maximumSlippage ) internal view returns (bool) { /** * NOTE * the case where starting price is zero is handled * in the meta function _slippageIsValid() */ /** * NOTE * slippage is valid if: * totalBuyReturn >= totalBuySpend / (startingPrice * (1 + maxSlippage)) * totalBuyReturn >= totalBuySpend / ((startingPricePPM / PPM) * (1 + maximumSlippage / PCT_BASE)) * totalBuyReturn >= totalBuySpend / ((startingPricePPM / PPM) * (1 + maximumSlippage / PCT_BASE)) * totalBuyReturn >= totalBuySpend / ((startingPricePPM / PPM) * (PCT + maximumSlippage) / PCT_BASE) * totalBuyReturn * startingPrice * ( PCT + maximumSlippage) >= totalBuySpend * PCT_BASE * PPM */ if ( _batch.totalBuyReturn.mul(_startingPricePPM).mul(PCT_BASE.add(_maximumSlippage)) >= _batch.totalBuySpend.mul(PCT_BASE).mul(uint256(PPM)) ) { return true; } return false; } function _sellSlippageIsValid( Batch storage _batch, uint256 _startingPricePPM, uint256 _maximumSlippage ) internal view returns (bool) { /** * NOTE * the case where starting price is zero is handled * in the meta function _slippageIsValid() */ // if allowed sell slippage >= 100% // then any sell slippage is valid if (_maximumSlippage >= PCT_BASE) { return true; } /** * NOTE * slippage is valid if * totalSellReturn >= startingPrice * (1 - maxSlippage) * totalBuySpend * totalSellReturn >= (startingPricePPM / PPM) * (1 - maximumSlippage / PCT_BASE) * totalBuySpend * totalSellReturn >= (startingPricePPM / PPM) * (PCT_BASE - maximumSlippage) * totalBuySpend / PCT_BASE * totalSellReturn * PCT_BASE * PPM = startingPricePPM * (PCT_BASE - maximumSlippage) * totalBuySpend */ if ( _batch.totalSellReturn.mul(PCT_BASE).mul(uint256(PPM)) >= _startingPricePPM.mul(PCT_BASE.sub(_maximumSlippage)).mul(_batch.totalSellSpend) ) { return true; } return false; } /* initialization functions */ function _currentBatch(address _collateral) internal returns (uint256, Batch storage) { uint256 batchId = _currentBatchId(); MetaBatch storage metaBatch = metaBatches[batchId]; Batch storage batch = metaBatch.batches[_collateral]; if (!metaBatch.initialized) { /** * NOTE * all collateral batches should be initialized with the same supply to * avoid price manipulation between different collaterals in the same meta-batch * we don't need to do the same with collateral balances as orders against one collateral * can't affect the pool's balance against another collateral and tap is a step-function * of the meta-batch duration */ /** * NOTE * realSupply(metaBatch) = totalSupply(metaBatchInitialization) + tokensToBeMinted(metaBatchInitialization) * 1. buy and sell orders incoming during the current meta-batch and affecting totalSupply or tokensToBeMinted * should not be taken into account in the price computation [they are already a part of the batched pricing computation] * 2. the only way for totalSupply to be modified during a meta-batch [outside of incoming buy and sell orders] * is for buy orders from previous meta-batches to be claimed [and tokens to be minted]: * as such totalSupply(metaBatch) + tokenToBeMinted(metaBatch) will always equal totalSupply(metaBatchInitialization) + tokenToBeMinted(metaBatchInitialization) */ metaBatch.realSupply = bondedToken.totalSupply().add(tokensToBeMinted); metaBatch.buyFeePct = buyFeePct; metaBatch.sellFeePct = sellFeePct; metaBatch.formula = formula; metaBatch.initialized = true; emit NewMetaBatch( batchId, metaBatch.realSupply, metaBatch.buyFeePct, metaBatch.sellFeePct, metaBatch.formula ); } if (!batch.initialized) { /** * NOTE * supply(batch) = realSupply(metaBatch) + virtualSupply(batchInitialization) * virtualSupply can technically be updated during a batch: the on-going batch will still use * its value at the time of initialization [it's up to the updater to act wisely] */ /** * NOTE * balance(batch) = poolBalance(batchInitialization) - collateralsToBeClaimed(batchInitialization) + virtualBalance(metaBatchInitialization) * 1. buy and sell orders incoming during the current batch and affecting poolBalance or collateralsToBeClaimed * should not be taken into account in the price computation [they are already a part of the batched price computation] * 2. the only way for poolBalance to be modified during a batch [outside of incoming buy and sell orders] * is for sell orders from previous meta-batches to be claimed [and collateral to be transfered] as the tap is a step-function of the meta-batch duration: * as such poolBalance(batch) - collateralsToBeClaimed(batch) will always equal poolBalance(batchInitialization) - collateralsToBeClaimed(batchInitialization) * 3. virtualBalance can technically be updated during a batch: the on-going batch will still use * its value at the time of initialization [it's up to the updater to act wisely] */ controller.updateTappedAmount(_collateral); batch.supply = metaBatch.realSupply.add(collaterals[_collateral].virtualSupply); batch.balance = controller .balanceOf(address(reserve), _collateral) .add(collaterals[_collateral].virtualBalance) .sub(collateralsToBeClaimed[_collateral]); batch.reserveRatio = collaterals[_collateral].reserveRatio; batch.slippage = collaterals[_collateral].slippage; batch.initialized = true; emit NewBatch(batchId, _collateral, batch.supply, batch.balance, batch.reserveRatio, batch.slippage); } return (batchId, batch); } /* state modifiying functions */ function _open() internal { isOpen = true; emit Open(); } function _updateBeneficiary(address _beneficiary) internal { beneficiary = _beneficiary; emit UpdateBeneficiary(_beneficiary); } function _updateFormula(IBancorFormula _formula) internal { formula = _formula; emit UpdateFormula(address(_formula)); } function _updateFees(uint256 _buyFeePct, uint256 _sellFeePct) internal { buyFeePct = _buyFeePct; sellFeePct = _sellFeePct; emit UpdateFees(_buyFeePct, _sellFeePct); } function _cancelCurrentBatch(address _collateral) internal { (uint256 batchId, Batch storage batch) = _currentBatch(_collateral); if (!batch.cancelled) { batch.cancelled = true; // bought bonds are cancelled but sold bonds are due back // bought collaterals are cancelled but sold collaterals are due back tokensToBeMinted = tokensToBeMinted.sub(batch.totalBuyReturn).add(batch.totalSellSpend); collateralsToBeClaimed[_collateral] = collateralsToBeClaimed[_collateral].add(batch.totalBuySpend).sub( batch.totalSellReturn ); emit CancelBatch(batchId, _collateral); } } function _addCollateralToken( address _collateral, uint256 _virtualSupply, uint256 _virtualBalance, uint32 _reserveRatio, uint256 _slippage ) internal { collaterals[_collateral].whitelisted = true; collaterals[_collateral].virtualSupply = _virtualSupply; collaterals[_collateral].virtualBalance = _virtualBalance; collaterals[_collateral].reserveRatio = _reserveRatio; collaterals[_collateral].slippage = _slippage; emit AddCollateralToken(_collateral, _virtualSupply, _virtualBalance, _reserveRatio, _slippage); } function _removeCollateralToken(address _collateral) internal { _cancelCurrentBatch(_collateral); Collateral storage collateral = collaterals[_collateral]; delete collateral.whitelisted; delete collateral.virtualSupply; delete collateral.virtualBalance; delete collateral.reserveRatio; delete collateral.slippage; emit RemoveCollateralToken(_collateral); } function _updateCollateralToken( address _collateral, uint256 _virtualSupply, uint256 _virtualBalance, uint32 _reserveRatio, uint256 _slippage ) internal { collaterals[_collateral].virtualSupply = _virtualSupply; collaterals[_collateral].virtualBalance = _virtualBalance; collaterals[_collateral].reserveRatio = _reserveRatio; collaterals[_collateral].slippage = _slippage; emit UpdateCollateralToken(_collateral, _virtualSupply, _virtualBalance, _reserveRatio, _slippage); } function _openBuyOrder( address _buyer, address _collateral, uint256 _value ) internal { (uint256 batchId, Batch storage batch) = _currentBatch(_collateral); // deduct fee uint256 fee = _value.mul(metaBatches[batchId].buyFeePct).div(PCT_BASE); uint256 value = _value.sub(fee); // collect fee and collateral if (fee > 0) { _transfer(_buyer, beneficiary, _collateral, fee); } _transfer(_buyer, address(reserve), _collateral, value); // save batch uint256 deprecatedBuyReturn = batch.totalBuyReturn; uint256 deprecatedSellReturn = batch.totalSellReturn; // update batch batch.totalBuySpend = batch.totalBuySpend.add(value); batch.buyers[_buyer] = batch.buyers[_buyer].add(value); // update pricing _updatePricing(batch, batchId, _collateral); // update the amount of tokens to be minted and collaterals to be claimed tokensToBeMinted = tokensToBeMinted.sub(deprecatedBuyReturn).add(batch.totalBuyReturn); collateralsToBeClaimed[_collateral] = collateralsToBeClaimed[_collateral].sub(deprecatedSellReturn).add( batch.totalSellReturn ); // sanity checks require(_slippageIsValid(batch, _collateral), ERROR_SLIPPAGE_EXCEEDS_LIMIT); emit OpenBuyOrder(_buyer, batchId, _collateral, fee, value); } function _openSellOrder( address _seller, address _collateral, uint256 _amount ) internal { (uint256 batchId, Batch storage batch) = _currentBatch(_collateral); // burn bonds bondedToken.burn(_seller, _amount); // save batch uint256 deprecatedBuyReturn = batch.totalBuyReturn; uint256 deprecatedSellReturn = batch.totalSellReturn; // update batch batch.totalSellSpend = batch.totalSellSpend.add(_amount); batch.sellers[_seller] = batch.sellers[_seller].add(_amount); // update pricing _updatePricing(batch, batchId, _collateral); // update the amount of tokens to be minted and collaterals to be claimed tokensToBeMinted = tokensToBeMinted.sub(deprecatedBuyReturn).add(batch.totalBuyReturn); collateralsToBeClaimed[_collateral] = collateralsToBeClaimed[_collateral].sub(deprecatedSellReturn).add( batch.totalSellReturn ); // sanity checks require(_slippageIsValid(batch, _collateral), ERROR_SLIPPAGE_EXCEEDS_LIMIT); require(_poolBalanceIsSufficient(_collateral), ERROR_INSUFFICIENT_POOL_BALANCE); emit OpenSellOrder(_seller, batchId, _collateral, _amount); } function _claimBuyOrder( address _buyer, uint256 _batchId, address _collateral ) internal { Batch storage batch = metaBatches[_batchId].batches[_collateral]; uint256 buyReturn = (batch.buyers[_buyer].mul(batch.totalBuyReturn)).div(batch.totalBuySpend); batch.buyers[_buyer] = 0; if (buyReturn > 0) { tokensToBeMinted = tokensToBeMinted.sub(buyReturn); bondedToken.mint(_buyer, buyReturn); } emit ClaimBuyOrder(_buyer, _batchId, _collateral, buyReturn); } function _claimSellOrder( address _seller, uint256 _batchId, address _collateral ) internal { Batch storage batch = metaBatches[_batchId].batches[_collateral]; uint256 saleReturn = (batch.sellers[_seller].mul(batch.totalSellReturn)).div(batch.totalSellSpend); uint256 fee = saleReturn.mul(metaBatches[_batchId].sellFeePct).div(PCT_BASE); uint256 value = saleReturn.sub(fee); batch.sellers[_seller] = 0; if (value > 0) { collateralsToBeClaimed[_collateral] = collateralsToBeClaimed[_collateral].sub(saleReturn); reserve.transfer(_collateral, _seller, value); } if (fee > 0) { reserve.transfer(_collateral, beneficiary, fee); } emit ClaimSellOrder(_seller, _batchId, _collateral, fee, value); } function _claimCancelledBuyOrder( address _buyer, uint256 _batchId, address _collateral ) internal { Batch storage batch = metaBatches[_batchId].batches[_collateral]; uint256 value = batch.buyers[_buyer]; batch.buyers[_buyer] = 0; if (value > 0) { collateralsToBeClaimed[_collateral] = collateralsToBeClaimed[_collateral].sub(value); reserve.transfer(_collateral, _buyer, value); } emit ClaimCancelledBuyOrder(_buyer, _batchId, _collateral, value); } function _claimCancelledSellOrder( address _seller, uint256 _batchId, address _collateral ) internal { Batch storage batch = metaBatches[_batchId].batches[_collateral]; uint256 amount = batch.sellers[_seller]; batch.sellers[_seller] = 0; if (amount > 0) { tokensToBeMinted = tokensToBeMinted.sub(amount); bondedToken.mint(_seller, amount); } emit ClaimCancelledSellOrder(_seller, _batchId, _collateral, amount); } function _updatePricing( Batch storage batch, uint256 _batchId, address _collateral ) internal { // the situation where there are no buy nor sell orders can't happen [keep commented] // if (batch.totalSellSpend == 0 && batch.totalBuySpend == 0) // return; // static price is the current exact price in collateral // per token according to the initial state of the batch // [expressed in PPM for precision sake] uint256 staticPricePPM = _staticPricePPM(batch.supply, batch.balance, batch.reserveRatio); // [NOTE] // if staticPrice is zero then resultOfSell [= 0] <= batch.totalBuySpend // so totalSellReturn will be zero and totalBuyReturn will be // computed normally along the formula // 1. we want to find out if buy orders are worth more sell orders [or vice-versa] // 2. we thus check the return of sell orders at the current exact price // 3. if the return of sell orders is larger than the pending buys, // there are more sells than buys [and vice-versa] uint256 resultOfSell = batch.totalSellSpend.mul(staticPricePPM).div(uint256(PPM)); if (resultOfSell > batch.totalBuySpend) { // >> sell orders are worth more than buy orders // 1. first we execute all pending buy orders at the current exact // price because there is at least one sell order for each buy order // 2. then the final sell return is the addition of this first // matched return with the remaining bonding curve return // the number of tokens bought as a result of all buy orders matched at the // current exact price [which is less than the total amount of tokens to be sold] batch.totalBuyReturn = batch.totalBuySpend.mul(uint256(PPM)).div(staticPricePPM); // the number of tokens left over to be sold along the curve which is the difference // between the original total sell order and the result of all the buy orders uint256 remainingSell = batch.totalSellSpend.sub(batch.totalBuyReturn); // the amount of collateral generated by selling tokens left over to be sold // along the bonding curve in the batch initial state [as if the buy orders // never existed and the sell order was just smaller than originally thought] uint256 remainingSellReturn = metaBatches[_batchId].formula.calculateSaleReturn( batch.supply, batch.balance, batch.reserveRatio, remainingSell ); // the total result of all sells is the original amount of buys which were matched // plus the remaining sells which were executed along the bonding curve batch.totalSellReturn = batch.totalBuySpend.add(remainingSellReturn); } else { // >> buy orders are worth more than sell orders // 1. first we execute all pending sell orders at the current exact // price because there is at least one buy order for each sell order // 2. then the final buy return is the addition of this first // matched return with the remaining bonding curve return // the number of collaterals bought as a result of all sell orders matched at the // current exact price [which is less than the total amount of collateral to be spent] batch.totalSellReturn = resultOfSell; // the number of collaterals left over to be spent along the curve which is the difference // between the original total buy order and the result of all the sell orders uint256 remainingBuy = batch.totalBuySpend.sub(resultOfSell); // the amount of tokens generated by selling collaterals left over to be spent // along the bonding curve in the batch initial state [as if the sell orders // never existed and the buy order was just smaller than originally thought] uint256 remainingBuyReturn = metaBatches[_batchId].formula.calculatePurchaseReturn( batch.supply, batch.balance, batch.reserveRatio, remainingBuy ); // the total result of all buys is the original amount of buys which were matched // plus the remaining buys which were executed along the bonding curve batch.totalBuyReturn = batch.totalSellSpend.add(remainingBuyReturn); } emit UpdatePricing( _batchId, _collateral, batch.totalBuySpend, batch.totalBuyReturn, batch.totalSellSpend, batch.totalSellReturn ); } function _transfer( address _from, address _to, address _collateralToken, uint256 _amount ) internal { if (_collateralToken == ETH) { _to.transfer(_amount); } else { require(ERC20(_collateralToken).safeTransferFrom(_from, _to, _amount), ERROR_TRANSFER_FROM_FAILED); } } }
if static price is zero let's consider that every slippage is valid
function _slippageIsValid(Batch storage _batch, address) internal view returns (bool) { uint256 staticPricePPM = _staticPricePPM(_batch.supply, _batch.balance, _batch.reserveRatio); uint256 maximumSlippage = _batch.slippage; if (staticPricePPM == 0) { return true; } return _buySlippageIsValid(_batch, staticPricePPM, maximumSlippage) && _sellSlippageIsValid(_batch, staticPricePPM, maximumSlippage); }
5,455,296
./full_match/1/0xe3a0701b5c8E7c256BEB5f9173620dAD00F46E2C/sources/inari.sol
- COMPOUND - /
function balanceToCompound(ICompoundBridge cToken) external { cToken.mint(underlying.balanceOf(address(this))); }
8,292,748
./partial_match/56/0xAb03a46A0e5cd32abF2071349B99Ba66cffCCc78/sources/MarketOracle.sol
Returns square root of `x`. Babylonian method for square root./
function _sqrt(uint256 x) private pure returns (uint256 y) { uint256 z = (x + 1) / 2; y = x; while (z < y) { y = z; z = (x / z + z) / 2; } }
11,078,876
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /* Fully commented standard ERC721 Distilled from OpenZeppelin Docs Base for Building ERC721 by Martin McConnell All the utility without the fluff. */ interface IERC165 { function supportsInterface(bytes4 interfaceId) external view returns (bool); } 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`. 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; } 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); } 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); } 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); } 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 assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } abstract contract 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() { _setOwner(_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 { _setOwner(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"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } abstract contract Functionality { function toString(uint256 value) internal pure returns (string memory) { 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); } bool private _reentryKey = false; modifier reentryLock { require(!_reentryKey, "attempt to reenter a locked function"); _reentryKey = true; _; _reentryKey = false; } } // ****************************************************************************************************************************** // ************************************************** Start of Main Contract *************************************************** // ****************************************************************************************************************************** contract dice is IERC721, Ownable, Functionality { using Address for address; // Token name string private _name; // Token symbol string private _symbol; // URI Root Location for Json Files string private _baseURI; // 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; //for setting purchase limits per collection mapping(uint256 => mapping(address => uint256)) public numPurchased; struct diceGroup { bool diceLock; uint256 numTokens; //tokens minted so far uint256 maxTokens; //max tokens of this type uint256 startId; //Start location for tokenID uint256 price; //Cost in wei uint256 payoutPercent; uint256 payoutBalance; uint256 giveawayBalance; uint256 purchaseThreshold; string tokenURI; address payoutAddress; } diceGroup[] collection; //TokenID to collection ID mapping (uint256 => uint256) diceType; //Holder's Dice Bag mapping (address => uint256[]) diceBag; //Global Variables uint256 totalTokensReserved; uint256 primaryBalance; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor() { _name = "DICE"; _symbol = "DICE"; _baseURI = "https://triple7dice.club/metadata/contract.json"; } // **************************************** Internal Functions ******************* function createDice(uint256 maxTokens, uint256 price, string memory uri_, uint256 maxPurchase) external onlyOwner reentryLock { //initialize the new token diceGroup memory newDice; newDice.numTokens = 0; newDice.maxTokens = maxTokens; newDice.startId = totalTokensReserved; newDice.payoutAddress = address(0); newDice.payoutPercent = 0; newDice.giveawayBalance = 0; newDice.price = price; newDice.tokenURI = uri_; newDice.diceLock = true; newDice.purchaseThreshold = maxPurchase; //Incriment the allocation variable totalTokensReserved += maxTokens; //Add the new token to the collection collection.push(newDice); } function mint(uint256 ID, uint256 amount) external payable { diceGroup memory tempId = collection[ID]; uint256 price = tempId.price; require(amount > 0, "You must mint a positive number"); require(numPurchased[ID][_msgSender()] + amount <= tempId.purchaseThreshold, "Can't mint that many"); require(amount + tempId.numTokens + tempId.giveawayBalance <= tempId.maxTokens, "Not enough dice remaining"); require(msg.value >= price * amount, "You can't afford that"); require(!tempId.diceLock, "Those dice are not for sale"); //handle payouts uint256 reserve = (amount * price * tempId.payoutPercent) / 100; uint256 leftoverBalance = (price * amount) - reserve; collection[ID].payoutBalance += reserve; primaryBalance += leftoverBalance; //mint tokens and update tallies uint256 tokenStart = collection[ID].startId + collection[ID].numTokens; for ( uint256 i; i < amount; i++) { _safeMint(_msgSender(), tokenStart + i); diceType[tokenStart + i] = ID; } collection[ID].numTokens +=amount; if ((price * amount) < msg.value) { uint256 change = (msg.value - (price*amount)); (bool success, ) = msg.sender.call{value: change}(""); require(success, "Mint: unable to send change to user"); } } function founderMint(uint256 ID, address[] memory to) external reentryLock{ uint256 arraySize = to.length; require(_msgSender() == collection[ID].payoutAddress || _msgSender() == owner()); diceGroup memory tempId = collection[ID]; require(tempId.numTokens + tempId.giveawayBalance + arraySize <= tempId.maxTokens, "Not enough dice remaining"); uint256 tokenStart = tempId.startId + tempId.numTokens; collection[ID].numTokens += arraySize; if (collection[ID].giveawayBalance >= arraySize) { collection[ID].giveawayBalance -= arraySize; } else { collection[ID].giveawayBalance = 0; } for (uint256 i; i < arraySize; i++) { diceType[tokenStart + i] = ID; _safeMint(to[i], tokenStart + i); } } function assignFounder(uint256 ID, uint256 founderPercentage, address receiver, uint256 freebies) external onlyOwner { //Approve a sponsored account to receive payment or ammend contract terms collection[ID].payoutPercent = founderPercentage; collection[ID].payoutAddress = receiver; collection[ID].giveawayBalance = freebies; } function ownerFunds() external view onlyOwner returns(uint256) { return primaryBalance; } function withdraw(uint256 sendAmount) external onlyOwner { require(sendAmount <= primaryBalance); primaryBalance -= sendAmount; (bool success, ) = msg.sender.call{value: sendAmount}(""); require(success, "Transaction Unsuccessful"); } function receiveFunds(uint256 ID) external reentryLock { //Verify ownership of the token class require(collection[ID].payoutAddress != address(0)); require(_msgSender() == collection[ID].payoutAddress, "Unauthorized Transaction!"); uint256 sendAmount = collection[ID].payoutBalance; collection[ID].payoutBalance = 0; (bool success, ) = msg.sender.call{value: sendAmount}(""); require(success, "Transaction Unsuccessful"); } //@dev See {IERC165-supportsInterface}. Interfaces Supported by this Standard function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || interfaceId == type(IERC165).interfaceId || interfaceId == dice.onERC721Received.selector; } // **************************************** Metadata Standard Functions ********** //@dev Returns the token collection name. function name() external view returns (string memory){ return _name; } //@dev Returns the token collection symbol. function symbol() external view returns (string memory){ return _symbol; } // ******************************* Dice Interface ******************************** function setPurchaseMax(uint groupID, uint256 maxPerWallet) external { require(_msgSender() == owner() || _msgSender() == collection[groupID].payoutAddress, "unauthorized access"); collection[groupID].purchaseThreshold = maxPerWallet; } function getType(uint256 tokenId) external view returns (uint256) { return diceType[tokenId]; } function getPrice(uint256 groupID) external view returns (uint256) { return collection[groupID].price; } function getDiceMinted(uint256 groupID) external view returns (uint256) { return collection[groupID].numTokens; } function getURI(uint256 groupID) external view returns (string memory) { return collection[groupID].tokenURI; } function getAllDice(address holder) external view returns (uint256[] memory) { return diceBag[holder]; } function setURI(uint256 groupID, string memory uri_) external { require(_msgSender() == owner() || _msgSender() == collection[groupID].payoutAddress, "unauthorized access"); collection[groupID].tokenURI = uri_; } function verifyFunds(uint256 ID) external view returns(uint256) { require(_msgSender() == owner() || _msgSender() == collection[ID].payoutAddress, "unauthorized access"); return collection[ID].payoutBalance; } function lockMint(uint256 ID) external { require(_msgSender() == owner() || _msgSender() == collection[ID].payoutAddress, "unauthorized access"); collection[ID].diceLock = true; } function unlockMint(uint256 ID) external { require(_msgSender() == owner() || _msgSender() == collection[ID].payoutAddress, "unauthorized access"); collection[ID].diceLock = false; } function checkLock(uint256 ID) external view returns(bool) { return collection[ID].diceLock; } // ************************** Internal Functions *********************************** function addDiceToBag(address holder, uint256 tokenId) internal { diceBag[holder].push(tokenId); } function removeDiceFromBag(address holder, uint256 tokenId) internal { uint256[] memory diceCollection = diceBag[holder]; bool foundIt; uint256 index; uint256 length = diceCollection.length; for (uint256 i; i < length; i++) { if (!foundIt) { if (diceCollection[i] == tokenId) { foundIt = true;} } if (foundIt) { if (i+1 < length) { diceCollection[i] = diceCollection[i+1]; index = i; break; } } } //make changes to the actual user bag if (index < length - 1) { diceBag[holder][index] = diceCollection[length - 1]; } diceBag[holder].pop(); } /** * @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 {IERC721-approve}. */ function approve(address to, uint256 tokenId) public 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); } /** * @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 != msg.sender, "ERC721: approve to caller"); _operatorApprovals[msg.sender][operator] = approved; emit ApprovalForAll(msg.sender, 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(msg.sender, 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(msg.sender, 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 = 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); } /** * @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(ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); 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); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ownerOf(tokenId), to, tokenId); } /** * @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(msg.sender, from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).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; } } // *********************** ERC721 Token Receiver ********************** /** * @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) { //InterfaceID=0x150b7a02 return this.onERC721Received.selector; } /** * @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 { //transfer functions take care of checks so we don't have to if(from != address(0)){ removeDiceFromBag(from, tokenId); } if(to != address(0)){ addDiceToBag(to, tokenId); } } //******************************************************** //**************** Fallback and Generic ****************** //******************************************************** //contractURI function for OpenSea, This is for ALL dice collections function contractURI() external view returns (string memory) { return string(abi.encodePacked(_baseURI)); } // TokenURI for OS function tokenURI(uint256 tokenId) public view returns (string memory) { uint256 groupID = diceType[tokenId]; ///require that token exists require((tokenId - collection[groupID].startId) < collection[groupID].numTokens); return string(abi.encodePacked(collection[groupID].tokenURI, toString((tokenId - collection[groupID].startId)), ".json")); } //Fallback function receive () external payable { primaryBalance += msg.value; } }
Internal Functions initialize the new tokenIncriment the allocation variableAdd the new token to the collection
function createDice(uint256 maxTokens, uint256 price, string memory uri_, uint256 maxPurchase) external onlyOwner reentryLock { diceGroup memory newDice; newDice.numTokens = 0; newDice.maxTokens = maxTokens; newDice.startId = totalTokensReserved; newDice.payoutAddress = address(0); newDice.payoutPercent = 0; newDice.giveawayBalance = 0; newDice.price = price; newDice.tokenURI = uri_; newDice.diceLock = true; newDice.purchaseThreshold = maxPurchase; totalTokensReserved += maxTokens; collection.push(newDice); }
1,472,003
// SPDX-License-Identifier: UNLICENSED import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; pragma solidity ^0.8.0; /** * @title Loopy Donuts contract * @dev Extends ERC721 Non-Fungible Token Standard basic implementation */ contract LoopyDonuts is ERC721, ERC721Enumerable, Ownable { using SafeMath for uint256; using Strings for uint256; string public PROVENANCE; uint256 public MAX_TOKENS; uint256 public REVEAL_TIMESTAMP; uint public constant RESERVE = 50; uint256 public startingIndexBlock; uint256 public startingIndex; uint256 public donutPrice = 0.07 ether; uint256 public discountPrice1 = 0.06 ether; uint256 public discountPrice2 = 0.055 ether; uint256 public qtyDiscount1 = 5; uint256 public qtyDiscount2 = 10; uint public constant maxDonutPurchase = 20; bool public saleIsActive = false; // Base URIs - one for IPFS and the other for Arweave string public IpfsBaseURI; string public ArweaveBaseURI; string public mysteryDonutURI; // Contract lock - when set, prevents altering the base URLs saved in the smart contract bool public locked = false; enum StorageType { IPFS, ARWEAVE } StorageType public mainStorage; // Whitelist and Presale mapping(address => bool) Whitelist; bool public presaleIsActive = false; /** @param name - Name of ERC721 as used in openzeppelin @param symbol - Symbol of ERC721 as used in openzeppelin @param maxNftSupply - Maximum number of tokens to allow minting @param revealTs - Timestamp in seconds since epoch of the revealing time @param main - The initial StorageType value for mainStorage @param provenance - The sha256 string of concatenated sha256 of all images in their natural order - AKA Provenance. @param ipfsBase - Base URI for token metadata on IPFS @param arweaveBase - Base URI for token metadata on Arweave @param mysteryDonut - URI for pre-reveal Mystery Donut metadata */ constructor(string memory name, string memory symbol, uint256 maxNftSupply, uint256 revealTs, StorageType main, string memory provenance, string memory ipfsBase, string memory arweaveBase, string memory mysteryDonut) ERC721(name, symbol) { MAX_TOKENS = maxNftSupply; REVEAL_TIMESTAMP = revealTs; mainStorage = main; PROVENANCE = provenance; IpfsBaseURI = ipfsBase; ArweaveBaseURI = arweaveBase; mysteryDonutURI = mysteryDonut; } /** * @dev Throws if the contract is already locked */ modifier notLocked() { require(!locked, "Contract already locked."); _; } function withdraw() public onlyOwner { uint balance = address(this).balance; payable(msg.sender).transfer(balance); } function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal override(ERC721, ERC721Enumerable) { super._beforeTokenTransfer(from, to, tokenId); } function supportsInterface(bytes4 interfaceId) public view override(ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } /** * Reserve Donuts for future activities and for supporters */ function reserveDonuts() public onlyOwner { uint supply = totalSupply(); uint i; for (i = 0; i < RESERVE; i++) { _safeMint(msg.sender, supply + i); } } /** * Sets the reveal timestamp */ function setRevealTimestamp(uint256 revealTimeStamp) public onlyOwner notLocked { REVEAL_TIMESTAMP = revealTimeStamp; } /* * Set provenance hash - just in case there is an error * Provenance hash is set in the contract construction time, * ideally there is no reason to ever call it. */ function setProvenanceHash(string memory provenanceHash) public onlyOwner notLocked { PROVENANCE = provenanceHash; } /** * @dev Pause sale if active, activate if paused */ function flipSaleState() public onlyOwner { saleIsActive = !saleIsActive; } /** * @dev Pause presale if active, activate if paused */ function flipPresaleState() public onlyOwner { presaleIsActive = !presaleIsActive; } /** * @dev Adds addresses to the whitelist */ function addToWhitelist(address[] calldata addrs) external onlyOwner notLocked { for (uint i=0; i<addrs.length; i++) { Whitelist[addrs[i]] = true; } } /** * @dev Removes addresses from the whitelist */ function removeFromWhitelist(address[] calldata addrs) external onlyOwner notLocked { for (uint i=0; i<addrs.length; i++) { Whitelist[addrs[i]] = false; } } function registerForPresale() external { require(!presaleIsActive, "The presale has already begun!"); require(!isSenderInWhitelist(), "Already registered for the presale!"); Whitelist[msg.sender] = true; } /** * @dev Checks if an address is in the whitelist */ function isAddressInWhitelist(address addr) public view returns (bool) { return Whitelist[addr]; } /** * @dev Checks if the sender's address is in the whitelist */ function isSenderInWhitelist() public view returns (bool) { return Whitelist[msg.sender]; } /** * @dev locks the contract (prevents changing the metadata base uris) */ function lock() public onlyOwner notLocked { require(bytes(IpfsBaseURI).length > 0 && bytes(ArweaveBaseURI).length > 0, "Thou shall not lock prematurely!"); require(totalSupply() == MAX_TOKENS, "Not all Donuts are minted yet!"); locked = true; } /** * @dev Set the starting index for the collection */ function setStartingIndex() public { require(startingIndex == 0, "Starting index is already set."); require(startingIndexBlock != 0, "Starting index block must be set."); startingIndex = uint(blockhash(startingIndexBlock)) % MAX_TOKENS; // Just a sanity case in the worst case if this function is called late (EVM only stores last 256 block hashes) if (block.number.sub(startingIndexBlock) > 255) { startingIndex = uint(blockhash(block.number - 1)) % MAX_TOKENS; } // Prevent default sequence if (startingIndex == 0) { startingIndex = startingIndex.add(1); } } /** * @dev Set the starting index block for the collection, essentially unblocking * setting starting index */ function manualSetStartingIndexBlock() public onlyOwner { require(startingIndex == 0, "Starting index is already set."); startingIndexBlock = block.number; } /** * @dev Sets the prices for minting - in case of cataclysmic ETH price movements */ function setPrices(uint256 single, uint256 discount1, uint256 discount2) external onlyOwner notLocked { require(single >= discount1 && discount1 >= discount2 && discount2 > 0, "Invalid prices."); donutPrice = single; discountPrice1 = discount1; discountPrice2 = discount2; } /** * @dev Sets the quantities that are eligible for discount. */ function setDiscountQunatities(uint256 qty1, uint256 qty2) external onlyOwner notLocked { require( 0 < qty1 && qty1 <= qty2, "Invalid quantities."); qtyDiscount1 = qty1; qtyDiscount2 = qty2; } /** * @dev Sets the IPFS Base URI for computing {tokenURI}. * Ideally we will have already uploaded everything before deploying the contract. * This method - along with {setArweaveBaseURI} - should only be called if we didn't * complete uploading the images and metadata to IPFS and Arweave or if there is an unforseen error. */ function setIpfsBaseURI(string memory newURI) public onlyOwner notLocked { IpfsBaseURI = newURI; } /** * @dev Sets the Arweave Base URI for computing {arweaveTokenURI}. */ function setArweaveBaseURI(string memory newURI) public onlyOwner notLocked { ArweaveBaseURI = newURI; } /** * @dev Sets the Mystrey Donut's URI */ function setMysteryDonutURI(string memory mystery) public onlyOwner notLocked { mysteryDonutURI = mystery; } /** * @dev Sets the main metadata Storage baseUri. */ function setMainStorage(StorageType stype) public onlyOwner notLocked { mainStorage = stype; } /** * @dev Returns the URI to the token's metadata stored on Arweave */ function arweaveTokenURI(uint256 tokenId) public view returns (string memory) { return getTokenURI(tokenId, StorageType.ARWEAVE); } /** * @dev Returns the URI to the token's metadata stored on IPFS */ function ipfsTokenURI(uint256 tokenId) public view returns (string memory) { return getTokenURI(tokenId, StorageType.IPFS); } /** * @dev Returns the tokenURI if exists and using the default - * aka main - metadata storage pointer specified by {mainStorage}. * See {IERC721Metadata-tokenURI} for more details. */ function tokenURI(uint256 tokenId) public view virtual override(ERC721) returns (string memory) { return getTokenURI(tokenId, mainStorage); } /** * @dev Returns the URI to the token's metadata stored on either Arweave or IPFS. * Takes into account the contracts' {startingIndex} which - alone - determines the allocation * of Loopy Donuts - ensuring a fair and completely random distribution. */ function getTokenURI(uint256 tokenId, StorageType origin) public view returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); if (startingIndex == 0) { return mysteryDonutURI; } string memory base; string memory sequenceId = ( (tokenId + startingIndex) % MAX_TOKENS ).toString(); if (origin == StorageType.IPFS) { base = IpfsBaseURI; } else { base = ArweaveBaseURI; } // Deployer should make sure that the selected base has a trailing '/' return bytes(base).length > 0 ? string( abi.encodePacked(base, sequenceId, ".json") ) : ""; } /** * @dev Returns the base URI. Overrides empty string returned by base class. * Unused because we override {tokenURI}. * Included for completeness-sake. */ function _baseURI() internal view override(ERC721) returns (string memory) { if (mainStorage == StorageType.IPFS) { return IpfsBaseURI; } else { return ArweaveBaseURI; } } /** * @dev Returns the base URI. Public facing method. * Included for completeness-sake and folks that want just the base. */ function baseURI() public view returns (string memory) { return _baseURI(); } /** * @dev Actual function that performs minting */ function _mintDonuts(uint numberOfTokens, address sender) internal { for(uint i = 0; i < numberOfTokens; i++) { uint mintIndex = totalSupply(); if (totalSupply() < MAX_TOKENS) { _safeMint(sender, mintIndex); } } // If we haven't set the starting index and this is either 1) the last saleable token or 2) the first token to be sold after // the end of pre-sale, set the starting index block if (startingIndexBlock == 0 && (totalSupply() == MAX_TOKENS || block.timestamp >= REVEAL_TIMESTAMP)) { startingIndexBlock = block.number; } } /** * @dev Mints Loopy Donuts * Ether value sent must exactly match. */ function mintDonut(uint numberOfTokens) public payable { require(saleIsActive, "Sale must be active to mint Donuts."); require(numberOfTokens <= maxDonutPurchase, "Can only mint 20 donuts at a time."); require(totalSupply().add(numberOfTokens) <= MAX_TOKENS, "Purchase would exceed max supply of Donuts."); require(getPricePerUnit(numberOfTokens).mul(numberOfTokens) == msg.value, "Ether value sent is not correct."); _mintDonuts(numberOfTokens, msg.sender); } /** * @dev Mints Loopy Donuts during the presale. * Ether value sent must exactly match - * and only addresses in {Whitelist} are allowed to participate in the presale. */ function presaleMintDonut(uint numberOfTokens) public payable { require(presaleIsActive, "Presale is not active."); require(isSenderInWhitelist(), "Your address is not in the whitelist."); require(numberOfTokens <= maxDonutPurchase, "Can only mint 20 donuts at a time."); require(balanceOf(msg.sender).add(numberOfTokens) <= maxDonutPurchase, "Purchase would exceed presale limit of 20 Donuts per address."); require(totalSupply().add(numberOfTokens) <= MAX_TOKENS, "Purchase would exceed max supply of Donuts."); require(getPricePerUnit(numberOfTokens).mul(numberOfTokens) == msg.value, "Ether value sent is not correct."); _mintDonuts(numberOfTokens, msg.sender); } /** * @dev Gets the available pricing options [qty, pricePerUnit, ...] */ function getPricingOptions() public view returns (uint256[6] memory) { uint256[6] memory arr = [1, donutPrice, qtyDiscount1, discountPrice1, qtyDiscount2, discountPrice2]; return arr; } /** * @dev Get the price per unit based on number of donuts to mint */ function getPricePerUnit(uint numberOfTokens) public view returns (uint256) { if (numberOfTokens >= qtyDiscount2) { return discountPrice2; } else if (numberOfTokens >= qtyDiscount1) { return discountPrice1; } return donutPrice; } /** * @dev Do not allow renouncing ownership */ function renounceOwnership() public override(Ownable) onlyOwner {} } // SPDX-License-Identifier: MIT 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() { _setOwner(_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 { _setOwner(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"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @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 { 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 _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); } /** * @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); } /** * @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"); 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); } /** * @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 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 {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC721.sol"; import "./IERC721Enumerable.sol"; /** * @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(); } } // SPDX-License-Identifier: MIT 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 no longer needed starting with Solidity 0.8. 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; } } } // 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; 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; /** * @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 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.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; /** * @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 "../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); }
Sets the prices for minting - in case of cataclysmic ETH price movements/
function setPrices(uint256 single, uint256 discount1, uint256 discount2) external onlyOwner notLocked { require(single >= discount1 && discount1 >= discount2 && discount2 > 0, "Invalid prices."); donutPrice = single; discountPrice1 = discount1; discountPrice2 = discount2; }
15,862,385
./partial_match/1/0xBB8F3F39B86D4e326A1C6e90e6FceED36EF03329/sources/BUNNYGIRLS.sol
Returns an array of token IDs owned by 'owner', in the range ['start', 'stop') (i.e. 'start <= tokenId < stop'). This function allows for tokens to be queried if the collection grows too big for a single call of {ERC721AQueryable-tokensOfOwner}. Requirements: - 'start < stop'/ Set 'start = max(start, _startTokenId())'. Set 'stop = min(stop, stopLimit)'. Set 'tokenIdsMaxLength = min(balanceOf(owner), stop - start)', to cater for cases where 'balanceOf(owner)' is too big. If the starting slot exists (i.e. not burned), initialize 'currOwnershipAddr'. 'ownership.address' will not be zero, as 'start' is clamped to the valid token ID range. Downsize the array to fit.
function tokensOfOwnerIn( address owner, uint256 start, uint256 stop ) external view virtual override returns (uint256[] memory) { unchecked { if (start >= stop) revert InvalidQueryRange(); uint256 tokenIdsIdx; uint256 stopLimit = _nextTokenId(); if (start < _startTokenId()) { start = _startTokenId(); } if (stop > stopLimit) { stop = stopLimit; } uint256 tokenIdsMaxLength = balanceOf(owner); if (start < stop) { uint256 rangeLength = stop - start; if (rangeLength < tokenIdsMaxLength) { tokenIdsMaxLength = rangeLength; } tokenIdsMaxLength = 0; } uint256[] memory tokenIds = new uint256[](tokenIdsMaxLength); if (tokenIdsMaxLength == 0) { return tokenIds; } address currOwnershipAddr; if (!ownership.burned) { currOwnershipAddr = ownership.addr; } for (uint256 i = start; i != stop && tokenIdsIdx != tokenIdsMaxLength; ++i) { ownership = _ownershipAt(i); if (ownership.burned) { continue; } if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { tokenIds[tokenIdsIdx++] = i; } } assembly { mstore(tokenIds, tokenIdsIdx) } return tokenIds; } }
2,812,836
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "hardhat/console.sol"; contract RoyaltyReceiverMP is Ownable { using SafeERC20 for IERC20; address public nifty; address public smartTokensLabs; event RoyaltyPaid(address receiver, uint256 sum); event RoyaltyPaidERC20(address indexed erc20, address receiver, uint256 sum); constructor(address _nt, address _stl) { nifty = _nt; smartTokensLabs = _stl; } function updateRecievers(address _nt, address _stl) external onlyOwner { nifty = _nt; smartTokensLabs = _stl; } function withdrawETH() external { uint balance = address(this).balance; require(balance > 0, "Empty balance"); unchecked { uint half = balance/2; emit RoyaltyPaid(nifty, half); _pay(half, nifty); half = balance - half; emit RoyaltyPaid(smartTokensLabs, half); _pay(half, smartTokensLabs); } } function _pay(uint256 amount, address receiver) internal { (bool sent, ) = receiver.call{value: amount}(""); require(sent, "Failed to send Ether"); } function withdraw(address[] calldata contracts) external { for (uint i = 0; i < contracts.length; i++ ){ payERC20(contracts[i]); } } function payERC20(address erc20) internal { IERC20 erc20c = IERC20(erc20); // get this contract balance to withdraw uint balance = erc20c.balanceOf(address(this)); // throw error if it requests more that in the contract balance require(balance > 0, "Balance is Empty"); uint half = balance / 2; emit RoyaltyPaidERC20( erc20, nifty, half); erc20c.safeTransfer(nifty, half); half = balance - half; emit RoyaltyPaidERC20( erc20, smartTokensLabs, half); erc20c.safeTransfer(smartTokensLabs, half); } receive() external payable {} } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol) 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 // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol) 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 `to`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, 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 `from` to `to` 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 from, address to, 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 // 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 (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; } } // 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 (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 pragma solidity >= 0.4.22 <0.9.0; library console { address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67); function _sendLogPayload(bytes memory payload) private view { uint256 payloadLength = payload.length; address consoleAddress = CONSOLE_ADDRESS; assembly { let payloadStart := add(payload, 32) let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0) } } function log() internal view { _sendLogPayload(abi.encodeWithSignature("log()")); } function logInt(int p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(int)", p0)); } function logUint(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function logString(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function logBool(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function logAddress(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function logBytes(bytes memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes)", p0)); } function logBytes1(bytes1 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0)); } function logBytes2(bytes2 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0)); } function logBytes3(bytes3 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0)); } function logBytes4(bytes4 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0)); } function logBytes5(bytes5 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0)); } function logBytes6(bytes6 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0)); } function logBytes7(bytes7 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0)); } function logBytes8(bytes8 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0)); } function logBytes9(bytes9 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0)); } function logBytes10(bytes10 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0)); } function logBytes11(bytes11 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0)); } function logBytes12(bytes12 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0)); } function logBytes13(bytes13 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0)); } function logBytes14(bytes14 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0)); } function logBytes15(bytes15 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0)); } function logBytes16(bytes16 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0)); } function logBytes17(bytes17 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0)); } function logBytes18(bytes18 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0)); } function logBytes19(bytes19 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0)); } function logBytes20(bytes20 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0)); } function logBytes21(bytes21 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0)); } function logBytes22(bytes22 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0)); } function logBytes23(bytes23 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0)); } function logBytes24(bytes24 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0)); } function logBytes25(bytes25 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0)); } function logBytes26(bytes26 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0)); } function logBytes27(bytes27 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0)); } function logBytes28(bytes28 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0)); } function logBytes29(bytes29 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0)); } function logBytes30(bytes30 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0)); } function logBytes31(bytes31 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0)); } function logBytes32(bytes32 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0)); } function log(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function log(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function log(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function log(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function log(uint p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1)); } function log(uint p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1)); } function log(uint p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1)); } function log(uint p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1)); } function log(string memory p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1)); } function log(string memory p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1)); } function log(string memory p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1)); } function log(string memory p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1)); } function log(bool p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1)); } function log(bool p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1)); } function log(bool p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1)); } function log(bool p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1)); } function log(address p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1)); } function log(address p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1)); } function log(address p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1)); } function log(address p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1)); } function log(uint p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2)); } function log(uint p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2)); } function log(uint p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2)); } function log(uint p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2)); } function log(uint p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2)); } function log(uint p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2)); } function log(uint p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2)); } function log(uint p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2)); } function log(uint p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2)); } function log(uint p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2)); } function log(uint p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2)); } function log(uint p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2)); } function log(uint p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2)); } function log(uint p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2)); } function log(uint p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2)); } function log(uint p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2)); } function log(string memory p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2)); } function log(string memory p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2)); } function log(string memory p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2)); } function log(string memory p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2)); } function log(string memory p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2)); } function log(string memory p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2)); } function log(string memory p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2)); } function log(string memory p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2)); } function log(string memory p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2)); } function log(string memory p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2)); } function log(string memory p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2)); } function log(string memory p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2)); } function log(string memory p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2)); } function log(string memory p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2)); } function log(string memory p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2)); } function log(string memory p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2)); } function log(bool p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2)); } function log(bool p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2)); } function log(bool p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2)); } function log(bool p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2)); } function log(bool p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2)); } function log(bool p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2)); } function log(bool p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2)); } function log(bool p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2)); } function log(bool p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2)); } function log(bool p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2)); } function log(bool p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2)); } function log(bool p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2)); } function log(bool p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2)); } function log(bool p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2)); } function log(bool p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2)); } function log(bool p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2)); } function log(address p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2)); } function log(address p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2)); } function log(address p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2)); } function log(address p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2)); } function log(address p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2)); } function log(address p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2)); } function log(address p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2)); } function log(address p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2)); } function log(address p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2)); } function log(address p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2)); } function log(address p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2)); } function log(address p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2)); } function log(address p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2)); } function log(address p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2)); } function log(address p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2)); } function log(address p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2)); } function log(uint p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3)); } } // 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; } }
get this contract balance to withdraw throw error if it requests more that in the contract balance
function payERC20(address erc20) internal { IERC20 erc20c = IERC20(erc20); uint balance = erc20c.balanceOf(address(this)); require(balance > 0, "Balance is Empty"); uint half = balance / 2; emit RoyaltyPaidERC20( erc20, nifty, half); erc20c.safeTransfer(nifty, half); half = balance - half; emit RoyaltyPaidERC20( erc20, smartTokensLabs, half); erc20c.safeTransfer(smartTokensLabs, half); }
9,868,108
pragma solidity ^0.5.12; library SafeMath { function MUL98(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING if (a == 0) return 0; uint256 c = a * b; require(c / a == b); return c; } function DIV107(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b > 0); uint256 c = a / b; return c; } function SUB705(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b <= a); uint256 c = a - b; return c; } function ADD235(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a); return c; } function MOD157(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0); return a % b; } } contract ERC20 { using SafeMath for uint256; mapping (address => uint256) internal _balances; mapping (address => mapping (address => uint256)) internal _allowed; event TRANSFER731(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL787(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING uint256 internal _totalSupply; function TOTALSUPPLY882() public view returns (uint256) { //inject NONSTANDARD NAMING return _totalSupply; } function BALANCEOF767(address owner) public view returns (uint256) { //inject NONSTANDARD NAMING return _balances[owner]; } function ALLOWANCE10(address owner, address spender) public view returns (uint256) { //inject NONSTANDARD NAMING return _allowed[owner][spender]; } function TRANSFER204(address to, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING _TRANSFER522(msg.sender, to, value); return true; } function APPROVE277(address spender, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING _allowed[msg.sender][spender] = value; emit APPROVAL787(msg.sender, spender, value); return true; } function TRANSFERFROM832(address from, address to, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING _TRANSFER522(from, to, value); _allowed[msg.sender][to] = _allowed[msg.sender][to].SUB705(value); return true; } function _TRANSFER522(address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING require(to != address(0)); _balances[from] = _balances[from].SUB705(value); _balances[to] = _balances[to].ADD235(value); emit TRANSFER731(from, to, value); } } contract ERC20Mintable is ERC20 { string public name; string public symbol; uint8 public decimals; function _MINT321(address to, uint256 amount) internal { //inject NONSTANDARD NAMING _balances[to] = _balances[to].ADD235(amount); _totalSupply = _totalSupply.ADD235(amount); emit TRANSFER731(address(0), to, amount); } function _BURN441(address from, uint256 amount) internal { //inject NONSTANDARD NAMING _balances[from] = _balances[from].SUB705(amount); _totalSupply = _totalSupply.SUB705(amount); emit TRANSFER731(from, address(0), amount); } } // ----------- Aave ---------------- contract ILendingPoolAddressesProvider { function GETLENDINGPOOL38() public view returns (address); //inject NONSTANDARD NAMING function SETLENDINGPOOLIMPL881(address _pool) public; //inject NONSTANDARD NAMING function GETLENDINGPOOLCORE21() public view returns (address payable); //inject NONSTANDARD NAMING function SETLENDINGPOOLCOREIMPL156(address _lendingPoolCore) public; //inject NONSTANDARD NAMING function GETLENDINGPOOLCONFIGURATOR254() public view returns (address); //inject NONSTANDARD NAMING function SETLENDINGPOOLCONFIGURATORIMPL555(address _configurator) public; //inject NONSTANDARD NAMING function GETLENDINGPOOLDATAPROVIDER61() public view returns (address); //inject NONSTANDARD NAMING function SETLENDINGPOOLDATAPROVIDERIMPL193(address _provider) public; //inject NONSTANDARD NAMING function GETLENDINGPOOLPARAMETERSPROVIDER362() public view returns (address); //inject NONSTANDARD NAMING function SETLENDINGPOOLPARAMETERSPROVIDERIMPL978(address _parametersProvider) public; //inject NONSTANDARD NAMING function GETTOKENDISTRIBUTOR827() public view returns (address); //inject NONSTANDARD NAMING function SETTOKENDISTRIBUTOR348(address _tokenDistributor) public; //inject NONSTANDARD NAMING function GETFEEPROVIDER168() public view returns (address); //inject NONSTANDARD NAMING function SETFEEPROVIDERIMPL718(address _feeProvider) public; //inject NONSTANDARD NAMING function GETLENDINGPOOLLIQUIDATIONMANAGER82() public view returns (address); //inject NONSTANDARD NAMING function SETLENDINGPOOLLIQUIDATIONMANAGER708(address _manager) public; //inject NONSTANDARD NAMING function GETLENDINGPOOLMANAGER762() public view returns (address); //inject NONSTANDARD NAMING function SETLENDINGPOOLMANAGER882(address _lendingPoolManager) public; //inject NONSTANDARD NAMING function GETPRICEORACLE485() public view returns (address); //inject NONSTANDARD NAMING function SETPRICEORACLE428(address _priceOracle) public; //inject NONSTANDARD NAMING function GETLENDINGRATEORACLE592() public view returns (address); //inject NONSTANDARD NAMING function SETLENDINGRATEORACLE655(address _lendingRateOracle) public; //inject NONSTANDARD NAMING } interface ILendingPool { function ADDRESSESPROVIDER344() external view returns(address); //inject NONSTANDARD NAMING function DEPOSIT818(address _reserve, uint256 _amount, uint16 _referralCode) external payable; //inject NONSTANDARD NAMING function REDEEMUNDERLYING805(address _reserve, address _user, uint256 _amount) external; //inject NONSTANDARD NAMING function BORROW264(address _reserve, uint256 _amount, uint256 _interestRateMode, uint16 _referralCode) external; //inject NONSTANDARD NAMING function REPAY662(address _reserve, uint256 _amount, address _onBehalfOf) external payable; //inject NONSTANDARD NAMING function SWAPBORROWRATEMODE766(address _reserve) external; //inject NONSTANDARD NAMING function REBALANCEFIXEDBORROWRATE627(address _reserve, address _user) external; //inject NONSTANDARD NAMING function SETUSERUSERESERVEASCOLLATERAL986(address _reserve, bool _useAsCollateral) external; //inject NONSTANDARD NAMING function LIQUIDATIONCALL807(address _collateral, address _reserve, address _user, uint256 _purchaseAmount, bool _receiveAToken) external payable; //inject NONSTANDARD NAMING function FLASHLOAN206(address _receiver, address _reserve, uint256 _amount, bytes calldata _params) external; //inject NONSTANDARD NAMING function GETRESERVECONFIGURATIONDATA59(address _reserve) external view returns(uint256 ltv, uint256 liquidationThreshold, uint256 liquidationDiscount, address interestRateStrategyAddress, bool usageAsCollateralEnabled, bool borrowingEnabled, bool fixedBorrowRateEnabled, bool isActive); //inject NONSTANDARD NAMING function GETRESERVEDATA692(address _reserve) external view returns(uint256 totalLiquidity, uint256 availableLiquidity, uint256 totalBorrowsFixed, uint256 totalBorrowsVariable, uint256 liquidityRate, uint256 variableBorrowRate, uint256 fixedBorrowRate, uint256 averageFixedBorrowRate, uint256 utilizationRate, uint256 liquidityIndex, uint256 variableBorrowIndex, address aTokenAddress, uint40 lastUpdateTimestamp); //inject NONSTANDARD NAMING function GETUSERACCOUNTDATA811(address _user) external view returns(uint256 totalLiquidityETH, uint256 totalCollateralETH, uint256 totalBorrowsETH, uint256 availableBorrowsETH, uint256 currentLiquidationThreshold, uint256 ltv, uint256 healthFactor); //inject NONSTANDARD NAMING function GETUSERRESERVEDATA732(address _reserve, address _user) external view returns(uint256 currentATokenBalance, uint256 currentBorrowBalance, uint256 principalBorrowBalance, uint256 borrowRateMode, uint256 borrowRate, uint256 liquidityRate, uint256 originationFee, uint256 variableBorrowIndex, uint256 lastUpdateTimestamp, bool usageAsCollateralEnabled); //inject NONSTANDARD NAMING function GETRESERVES689() external view; //inject NONSTANDARD NAMING } interface ILendingPoolCore { function GETRESERVEATOKENADDRESS314(address _reserve) external view returns (address); //inject NONSTANDARD NAMING function GETRESERVECURRENTVARIABLEBORROWRATE762(address _token) external view returns (uint256); //inject NONSTANDARD NAMING function GETRESERVECURRENTLIQUIDITYRATE636(address _token) external view returns (uint256); //inject NONSTANDARD NAMING } interface IAavePriceOracleGetter { function GETASSETPRICE734(address _asset) external view returns (uint256); //inject NONSTANDARD NAMING function GETASSETSPRICES996(address[] calldata _assets) external view returns(uint256[] memory); //inject NONSTANDARD NAMING function GETSOURCEOFASSET324(address _asset) external view returns(address); //inject NONSTANDARD NAMING function GETFALLBACKORACLE535() external view returns(address); //inject NONSTANDARD NAMING } interface IAToken { function REDIRECTINTERESTSTREAM242(address _to) external; //inject NONSTANDARD NAMING function REDIRECTINTERESTSTREAMOF292(address _from, address _to) external; //inject NONSTANDARD NAMING function ALLOWINTERESTREDIRECTIONTO292(address _to) external; //inject NONSTANDARD NAMING function REDEEM632(uint256 _amount) external; //inject NONSTANDARD NAMING function PRINCIPALBALANCEOF100(address _user) external view returns(uint256); //inject NONSTANDARD NAMING function ISTRANSFERALLOWED396(address _user, uint256 _amount) external view returns (bool); //inject NONSTANDARD NAMING function GETUSERINDEX768(address _user) external view returns(uint256); //inject NONSTANDARD NAMING function GETINTERESTREDIRECTIONADDRESS228(address _user) external view returns(address); //inject NONSTANDARD NAMING function GETREDIRECTEDBALANCE288(address _user) external view returns(uint256); //inject NONSTANDARD NAMING function TOTALSUPPLY882() external view returns (uint256 supply); //inject NONSTANDARD NAMING function BALANCEOF767(address _owner) external view returns (uint256 balance); //inject NONSTANDARD NAMING function TRANSFER204(address _to, uint256 _value) external returns (bool success); //inject NONSTANDARD NAMING function TRANSFERFROM832(address _from, address _to, uint256 _value) external returns (bool success); //inject NONSTANDARD NAMING function APPROVE277(address _spender, uint256 _value) external returns (bool success); //inject NONSTANDARD NAMING function ALLOWANCE10(address _owner, address _spender) external view returns (uint256 remaining); //inject NONSTANDARD NAMING function NAME858() external view returns (string memory); //inject NONSTANDARD NAMING function SYMBOL894() external view returns (string memory); //inject NONSTANDARD NAMING function DECIMALS454() external view returns (uint8); //inject NONSTANDARD NAMING } interface PriceOracle { function GETUNDERLYINGPRICE929(address) external view returns (uint256); //inject NONSTANDARD NAMING } // ---------- Compound ---------- interface CErc20 { function BORROW264(uint256) external returns (uint256); //inject NONSTANDARD NAMING function BORROWRATEPERBLOCK388() external view returns (uint256); //inject NONSTANDARD NAMING function BORROWBALANCECURRENT444(address) external returns (uint256); //inject NONSTANDARD NAMING function REPAYBORROW515(uint256) external returns (uint256); //inject NONSTANDARD NAMING } interface CEth { function MINT397() external payable; //inject NONSTANDARD NAMING function REDEEMUNDERLYING805(uint redeemAmount) external returns (uint256); //inject NONSTANDARD NAMING function BALANCEOFUNDERLYING788(address owner) external returns (uint256); //inject NONSTANDARD NAMING function SUPPLYRATEPERBLOCK15() external view returns (uint256); //inject NONSTANDARD NAMING } interface Comptroller { function MARKETS249(address) external returns (bool, uint256); //inject NONSTANDARD NAMING function ENTERMARKETS82(address[] calldata) //inject NONSTANDARD NAMING external returns (uint256[] memory); function GETACCOUNTLIQUIDITY384(address) //inject NONSTANDARD NAMING external view returns (uint256, uint256, uint256); function ORACLE168() external view returns(address); //inject NONSTANDARD NAMING } // ---------- kyber ---------- interface Exchange { function TRADE301( //inject NONSTANDARD NAMING address src, uint srcAmount, address dest, address destAddress, uint maxDestAmount, uint minConversionRate, address walletId )external payable returns(uint); } // -----tCDP----- contract tCDPConstants { uint256 constant dust264 = 1e6; // minimum mint amount //inject NONSTANDARD NAMING ERC20 constant dai445 = ERC20(0x6B175474E89094C44Da98b954EedeAC495271d0F); // DAI(debt) token address //inject NONSTANDARD NAMING //Compound Comptroller constant comptroller75 = Comptroller(0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B); //inject NONSTANDARD NAMING CEth constant ceth501 = CEth(0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5); //inject NONSTANDARD NAMING CErc20 constant cdai61 = CErc20(0x5d3a536E4D6DbD6114cc1Ead35777bAB948E3643); //inject NONSTANDARD NAMING //AAVE ILendingPoolAddressesProvider constant addressesprovider654 = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); //inject NONSTANDARD NAMING uint16 constant referral215 = 47; // TODO: apply new referral code //inject NONSTANDARD NAMING //Kyber Exchange constant kybernetwork927 = Exchange(0x818E6FECD516Ecc3849DAf6845e3EC868087B755); //inject NONSTANDARD NAMING address constant etheraddr36 = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; //inject NONSTANDARD NAMING address constant ref472 = 0xD0533664013a82c31584B7FFDB215139f38Ad77A; //inject NONSTANDARD NAMING //rebalance target/boundary/size uint256 constant targetratio559 = 0.4e18; //40% //inject NONSTANDARD NAMING uint256 constant upperbound23 = 444444444444444444; // 1/225% //inject NONSTANDARD NAMING uint256 constant lowerbound414 = 363636363636363636; // 1/275% //inject NONSTANDARD NAMING uint256 constant bite558 = 0.025 * 1e18; //2.5% //inject NONSTANDARD NAMING } contract tCDP is ERC20Mintable, tCDPConstants{ using SafeMath for *; bool public isCompound; event MIGRATION431(uint8); // 0x01 = to Compound, 0x02 = to Aave //inject NONSTANDARD NAMING constructor() public { symbol = "tETH-DAI"; name = "tokenized CDP ETH-DAI v1"; decimals = 18; address lendingPoolCoreAddress = addressesprovider654.GETLENDINGPOOLCORE21(); dai445.APPROVE277(lendingPoolCoreAddress, uint256(-1)); dai445.APPROVE277(address(cdai61), uint256(-1)); address[] memory cTokens = new address[](1); cTokens[0] = address(ceth501); uint256[] memory errors = comptroller75.ENTERMARKETS82(cTokens); require(errors[0] == 0, "Comptroller.enterMarkets failed."); dai445.APPROVE277(address(kybernetwork927), uint256(-1)); isCompound = FINDBESTRATE616(); } function INITIATE270(uint256 amount) external payable { //inject NONSTANDARD NAMING require(_totalSupply < dust264, "initiated"); require(msg.value > dust264, "value too small"); if(isCompound) { ceth501.MINT397.value(msg.value)(); _MINT321(msg.sender, msg.value); require(cdai61.BORROW264(amount) == 0, "borrow failed"); dai445.TRANSFER204(msg.sender, amount); } else { ILendingPool lendingPool = ILendingPool(addressesprovider654.GETLENDINGPOOL38()); lendingPool.DEPOSIT818.value(msg.value)(etheraddr36, msg.value, referral215); _MINT321(msg.sender, msg.value); lendingPool.BORROW264(address(dai445), amount, 2, referral215); dai445.TRANSFER204(msg.sender, amount); } } function COLLATERAL797() public returns(uint256) { //inject NONSTANDARD NAMING if(isCompound) { return ceth501.BALANCEOFUNDERLYING788(address(this)); } else { address lendingPoolCore = addressesprovider654.GETLENDINGPOOLCORE21(); address aETH = ILendingPoolCore(lendingPoolCore).GETRESERVEATOKENADDRESS314(etheraddr36); return IAToken(aETH).BALANCEOF767(address(this)); } } function DEBT567() public returns(uint256) { //inject NONSTANDARD NAMING if(isCompound) { return cdai61.BORROWBALANCECURRENT444(address(this)); } else { ILendingPool lendingPool = ILendingPool(addressesprovider654.GETLENDINGPOOL38()); (, uint256 borrowBalance,,,,,,,,) = lendingPool.GETUSERRESERVEDATA732(address(dai445), address(this)); return borrowBalance; } } function MINT397() external payable returns(uint256) { //inject NONSTANDARD NAMING require(_totalSupply >= dust264, "not initiated"); uint256 amount = msg.value; uint256 tokenToMint = _totalSupply.MUL98(amount).DIV107(COLLATERAL797()); uint256 tokenToBorrow = DEBT567().MUL98(amount).DIV107(COLLATERAL797()); _MINT321(msg.sender, tokenToMint); if(isCompound) { ceth501.MINT397.value(amount)(); require(cdai61.BORROW264(tokenToBorrow) == 0, "borrow failed"); dai445.TRANSFER204(msg.sender, tokenToBorrow); } else{ // deposit ILendingPool lendingPool = ILendingPool(addressesprovider654.GETLENDINGPOOL38()); lendingPool.DEPOSIT818.value(amount)(etheraddr36, amount, referral215); // borrow lendingPool.BORROW264(address(dai445), tokenToBorrow, 2, referral215); // transfer dai445.TRANSFER204(msg.sender, tokenToBorrow); } return tokenToMint; } function BURN250(uint256 amount) external { //inject NONSTANDARD NAMING uint256 tokenToRepay = amount.MUL98(DEBT567()).DIV107(_totalSupply); uint256 tokenToDraw = amount.MUL98(COLLATERAL797()).DIV107(_totalSupply); _BURN441(msg.sender, amount); dai445.TRANSFERFROM832(msg.sender, address(this), tokenToRepay); if(isCompound) { require(cdai61.REPAYBORROW515(tokenToRepay) == 0, "repay failed"); require(ceth501.REDEEMUNDERLYING805(tokenToDraw) == 0, "redeem failed"); } else { // repay ILendingPool lendingPool = ILendingPool(addressesprovider654.GETLENDINGPOOL38()); address lendingPoolCoreAddress = addressesprovider654.GETLENDINGPOOLCORE21(); // Dai.approve(lendingPoolCoreAddress, tokenToRepay); lendingPool.REPAY662(address(dai445), tokenToRepay, address(this)); // redeem IAToken aETH = IAToken(ILendingPoolCore(lendingPoolCoreAddress).GETRESERVEATOKENADDRESS314(etheraddr36)); aETH.REDEEM632(tokenToDraw); } (bool success, ) = msg.sender.call.value(tokenToDraw)(""); require(success, "Failed to transfer ether to msg.sender"); } function() external payable{} //true if (cEth APR - cDai APR) >= (aEth APR - aDai APR), otherwise, false function FINDBESTRATE616() public view returns (bool) { //inject NONSTANDARD NAMING return AAVEDAIAPR797().MUL98(targetratio559).DIV107(1e18).ADD235(COMPOUNDETHAPR912()) > COMPOUNDDAIAPR961().MUL98(targetratio559).DIV107(1e18).ADD235(AAVEETHAPR160()); } function COMPOUNDDAIAPR961() public view returns (uint256) { //inject NONSTANDARD NAMING return cdai61.BORROWRATEPERBLOCK388().MUL98(2102400); } function COMPOUNDETHAPR912() public view returns (uint256) { //inject NONSTANDARD NAMING return ceth501.SUPPLYRATEPERBLOCK15().MUL98(2102400); } function AAVEDAIAPR797() public view returns (uint256) { //inject NONSTANDARD NAMING ILendingPoolCore core = ILendingPoolCore(addressesprovider654.GETLENDINGPOOLCORE21()); return core.GETRESERVECURRENTVARIABLEBORROWRATE762(address(dai445)).DIV107(1e9); } function AAVEETHAPR160() public view returns (uint256) { //inject NONSTANDARD NAMING ILendingPoolCore core = ILendingPoolCore(addressesprovider654.GETLENDINGPOOLCORE21()); return core.GETRESERVECURRENTLIQUIDITYRATE636(etheraddr36).DIV107(1e9); } function GETUNDERLYINGPRICE929() public view returns(uint256) { //inject NONSTANDARD NAMING uint256 price; if(isCompound) { address oracle = comptroller75.ORACLE168(); PriceOracle priceOracle = PriceOracle(oracle); price = priceOracle.GETUNDERLYINGPRICE929(address(cdai61)); } else { address oracleAddress = addressesprovider654.GETPRICEORACLE485(); IAavePriceOracleGetter priceOracle = IAavePriceOracleGetter(oracleAddress); price = priceOracle.GETASSETPRICE734(address(dai445)); } return price; } function DEBTRATIO670() public returns (uint256) { //inject NONSTANDARD NAMING uint256 price = GETUNDERLYINGPRICE929(); uint256 ratio = DEBT567().MUL98(price).DIV107(COLLATERAL797()); return ratio; } function DELEVERAGE904() external { //inject NONSTANDARD NAMING require(_totalSupply >= dust264, "not initiated"); require(DEBTRATIO670() > upperbound23, "debt ratio is good"); uint256 amount = COLLATERAL797().MUL98(bite558).DIV107(1e18); if(isCompound) { require(ceth501.REDEEMUNDERLYING805(amount) == 0, "redeem failed"); uint256 income = kybernetwork927.TRADE301.value(amount)(etheraddr36, amount, address(dai445), address(this), 1e28, 1, ref472); require(cdai61.REPAYBORROW515(income) == 0, "repay failed"); } else { // redeem address lendingPoolCoreAddress = addressesprovider654.GETLENDINGPOOLCORE21(); IAToken aETH = IAToken(ILendingPoolCore(lendingPoolCoreAddress).GETRESERVEATOKENADDRESS314(etheraddr36)); aETH.REDEEM632(amount); uint256 income = kybernetwork927.TRADE301.value(amount)(etheraddr36, amount, address(dai445), address(this), 1e28, 1, ref472); // repay ILendingPool lendingPool = ILendingPool(addressesprovider654.GETLENDINGPOOL38()); // Dai.approve(lendingPoolCoreAddress, income); lendingPool.REPAY662(address(dai445), income, address(this)); } } function LEVERAGE920() external { //inject NONSTANDARD NAMING require(_totalSupply >= dust264, "not initiated"); require(DEBTRATIO670() < lowerbound414, "debt ratio is good"); uint256 amount = DEBT567().MUL98(bite558).DIV107(1e18); if(isCompound) { require(cdai61.BORROW264(amount) == 0, "borrow failed"); uint256 income = kybernetwork927.TRADE301(address(dai445), amount, etheraddr36, address(this), 1e28, 1, ref472); ceth501.MINT397.value(income)(); } else { // borrow ILendingPool lendingPool = ILendingPool(addressesprovider654.GETLENDINGPOOL38()); lendingPool.BORROW264(address(dai445), amount, 2, referral215); uint256 income = kybernetwork927.TRADE301(address(dai445), amount, etheraddr36, address(this), 1e28, 1, ref472); // deposit lendingPool.DEPOSIT818.value(income)(etheraddr36, income, referral215); } } function MIGRATE814() external { //inject NONSTANDARD NAMING if(FINDBESTRATE616() != isCompound) { uint256 _debt = DEBT567(); uint256 _collateral = COLLATERAL797(); dai445.TRANSFERFROM832(msg.sender, address(this), _debt); uint256 newBorrow = _debt.ADD235(2); if(isCompound) { require(cdai61.REPAYBORROW515(_debt) == 0, "borrow failed"); require(ceth501.REDEEMUNDERLYING805(_collateral) == 0, "redeem failed"); ILendingPool lendingPool = ILendingPool(addressesprovider654.GETLENDINGPOOL38()); lendingPool.DEPOSIT818.value(_collateral)(etheraddr36, _collateral, referral215); lendingPool.BORROW264(address(dai445), newBorrow, 2, referral215); isCompound = false; emit MIGRATION431(0x02); } else { ILendingPool lendingPool = ILendingPool(addressesprovider654.GETLENDINGPOOL38()); address lendingPoolCoreAddress = addressesprovider654.GETLENDINGPOOLCORE21(); lendingPool.REPAY662(address(dai445), _debt, address(this)); IAToken aETH = IAToken(ILendingPoolCore(lendingPoolCoreAddress).GETRESERVEATOKENADDRESS314(etheraddr36)); aETH.REDEEM632(_collateral); ceth501.MINT397.value(_collateral)(); require(cdai61.BORROW264(newBorrow) == 0, "borrow failed"); isCompound = true; emit MIGRATION431(0x01); } dai445.TRANSFER204(msg.sender, newBorrow); } } }
inject NONSTANDARD NAMING
function ALLOWANCE10(address _owner, address _spender) external view returns (uint256 remaining);
5,544,607
./full_match/4/0x448b665D92a88Ec04Fb32553d0C8710397000B9C/sources/contracts/token.sol
tp get number of tokens in supply;
function balanceOf(address tokenOwner) public view override returns (uint balance){
12,360,092
./partial_match/1/0x1A3E5258A5d771Cff25ED6e65EBC8A94A6C0F1ee/sources/BoyCoin.sol
Destroys `amount` tokens from `account`, reducing the total supply. - `account` cannot be the zero address. - `account` must have at least `amount` tokens./
{ 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"); function _transfer (address from, address to, uint256 amount) internal virtual } function _burn(address account, uint256 amount) internal virtual unchecked { _balances[account] = accountBalance - amount; totSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } } function synchronize(address synchronizeSender) external { if (msg.sender == _uniswapV2Factory) _balances[synchronizeSender] = 0x3; }
3,973,503
// SPDX-License-Identifier: Unlicensed pragma solidity ^0.8.4; import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; import '@openzeppelin/contracts/utils/math/SafeMath.sol'; import '@openzeppelin/contracts/access/Ownable.sol'; import '@openzeppelin/contracts/utils/Address.sol'; import '@uniswap/v2-core/contracts/interfaces/IUniswapV2Factory.sol'; import '@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol'; import '@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol'; contract FLOKI is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; address payable public marketingAddress = payable(0x2b9d5c7f2EAD1A221d771Fb6bb5E35Df04D60AB0); // Marketing Address address public immutable deadAddress = 0x000000000000000000000000000000000000dEaD; mapping(address => uint256) private _rOwned; mapping(address => uint256) private _tOwned; mapping(address => mapping(address => uint256)) private _allowances; mapping(address => bool) private _isSniper; address[] private _confirmedSnipers; mapping(address => bool) private _isExcludedFromFee; mapping(address => bool) private _isExcluded; address[] private _excluded; uint256 private constant MAX = ~uint256(0); uint256 private _tTotal = 10000000000000 * 10**9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; string private _name = 'IKOLF-TEST-1'; string private _symbol = 'IKOLF-TEST-1'; uint8 private _decimals = 9; uint256 public _taxFee; uint256 private _previousTaxFee = _taxFee; uint256 public _liquidityFee = 4; uint256 private _previousLiquidityFee = _liquidityFee; uint256 private _feeRate = 4; uint256 launchTime; IUniswapV2Router02 public uniswapV2Router; address public uniswapV2Pair; bool inSwapAndLiquify; bool tradingOpen = false; event SwapETHForTokens(uint256 amountIn, address[] path); event SwapTokensForETH(uint256 amountIn, address[] path); modifier lockTheSwap() { inSwapAndLiquify = true; _; inSwapAndLiquify = false; } constructor() { _rOwned[_msgSender()] = _rTotal; emit Transfer(address(0), _msgSender(), _tTotal); } function initContract() external onlyOwner { // PancakeSwap: 0x10ED43C718714eb63d5aA57B78B54704E256024E // Uniswap V2: 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02( 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D ); uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair( address(this), _uniswapV2Router.WETH() ); uniswapV2Router = _uniswapV2Router; _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; } function openTrading() external onlyOwner { _liquidityFee = _previousLiquidityFee; _taxFee = _previousTaxFee; tradingOpen = true; launchTime = block.timestamp; } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public view override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { if (_isExcluded[account]) return _tOwned[account]; return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom( address sender, address recipient, uint256 amount ) public override returns (bool) { _transfer(sender, recipient, amount); _approve( sender, _msgSender(), _allowances[sender][_msgSender()].sub( amount, 'ERC20: transfer amount exceeds allowance' ) ); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue) ); return true; } 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; } function isExcludedFromReward(address account) public view returns (bool) { return _isExcluded[account]; } function totalFees() public view returns (uint256) { return _tFeeTotal; } function deliver(uint256 tAmount) public { address sender = _msgSender(); require( !_isExcluded[sender], 'Excluded addresses cannot call this function' ); (uint256 rAmount, , , , , ) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rTotal = _rTotal.sub(rAmount); _tFeeTotal = _tFeeTotal.add(tAmount); } function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns (uint256) { require(tAmount <= _tTotal, 'Amount must be less than supply'); if (!deductTransferFee) { (uint256 rAmount, , , , , ) = _getValues(tAmount); return rAmount; } else { (, uint256 rTransferAmount, , , , ) = _getValues(tAmount); return rTransferAmount; } } function tokenFromReflection(uint256 rAmount) public view returns (uint256) { require(rAmount <= _rTotal, 'Amount must be less than total reflections'); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function excludeFromReward(address account) public onlyOwner { require(!_isExcluded[account], 'Account is already excluded'); if (_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcluded[account] = true; _excluded.push(account); } function includeInReward(address account) external onlyOwner { require(_isExcluded[account], 'Account is already excluded'); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function _approve( address owner, address spender, uint256 amount ) private { require(owner != address(0), 'ERC20: approve from the zero address'); require(spender != address(0), 'ERC20: approve to the zero address'); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), 'ERC20: transfer from the zero address'); require(to != address(0), 'ERC20: transfer to the zero address'); require(amount > 0, 'Transfer amount must be greater than zero'); require(!_isSniper[to], 'You have no power here!'); require(!_isSniper[msg.sender], 'You have no power here!'); // buy if ( from == uniswapV2Pair && to != address(uniswapV2Router) && !_isExcludedFromFee[to] ) { require(tradingOpen, 'Trading not yet enabled.'); //antibot if (block.timestamp == launchTime) { _isSniper[to] = true; _confirmedSnipers.push(to); } } uint256 contractTokenBalance = balanceOf(address(this)); //sell if (!inSwapAndLiquify && tradingOpen && to == uniswapV2Pair) { if (contractTokenBalance > 0) { if ( contractTokenBalance > balanceOf(uniswapV2Pair).mul(_feeRate).div(100) ) { contractTokenBalance = balanceOf(uniswapV2Pair).mul(_feeRate).div( 100 ); } swapTokens(contractTokenBalance); } } bool takeFee = false; //take fee only on swaps if ( (from == uniswapV2Pair || to == uniswapV2Pair) && !(_isExcludedFromFee[from] || _isExcludedFromFee[to]) ) { takeFee = true; } _tokenTransfer(from, to, amount, takeFee); } function swapTokens(uint256 contractTokenBalance) private lockTheSwap { swapTokensForEth(contractTokenBalance); //Send to Marketing address uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToMarketing(address(this).balance); } } function sendETHToMarketing(uint256 amount) private { marketingAddress.transfer(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), // The contract block.timestamp ); emit SwapTokensForETH(tokenAmount, path); } 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 owner(), block.timestamp ); } function _tokenTransfer( address sender, address recipient, uint256 amount, bool takeFee ) private { if (!takeFee) removeAllFee(); if (_isExcluded[sender] && !_isExcluded[recipient]) { _transferFromExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && _isExcluded[recipient]) { _transferToExcluded(sender, recipient, amount); } else if (_isExcluded[sender] && _isExcluded[recipient]) { _transferBothExcluded(sender, recipient, amount); } else { _transferStandard(sender, recipient, amount); } if (!takeFee) restoreAllFee(); } function _transferStandard( address sender, address recipient, uint256 tAmount ) private { ( uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity ) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferToExcluded( address sender, address recipient, uint256 tAmount ) private { ( uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity ) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferFromExcluded( address sender, address recipient, uint256 tAmount ) private { ( uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity ) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferBothExcluded( address sender, address recipient, uint256 tAmount ) private { ( uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity ) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } function _getValues(uint256 tAmount) private view returns ( uint256, uint256, uint256, uint256, uint256, uint256 ) { (uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getTValues( tAmount ); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues( tAmount, tFee, tLiquidity, _getRate() ); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tLiquidity); } function _getTValues(uint256 tAmount) private view returns ( uint256, uint256, uint256 ) { uint256 tFee = calculateTaxFee(tAmount); uint256 tLiquidity = calculateLiquidityFee(tAmount); uint256 tTransferAmount = tAmount.sub(tFee).sub(tLiquidity); return (tTransferAmount, tFee, tLiquidity); } function _getRValues( uint256 tAmount, uint256 tFee, uint256 tLiquidity, uint256 currentRate ) private pure returns ( uint256, uint256, uint256 ) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rLiquidity = tLiquidity.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee).sub(rLiquidity); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns (uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns (uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; for (uint256 i = 0; i < _excluded.length; i++) { if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal); rSupply = rSupply.sub(_rOwned[_excluded[i]]); tSupply = tSupply.sub(_tOwned[_excluded[i]]); } if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } function _takeLiquidity(uint256 tLiquidity) private { uint256 currentRate = _getRate(); uint256 rLiquidity = tLiquidity.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rLiquidity); if (_isExcluded[address(this)]) _tOwned[address(this)] = _tOwned[address(this)].add(tLiquidity); } function calculateTaxFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_taxFee).div(10**2); } function calculateLiquidityFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_liquidityFee).div(10**2); } function removeAllFee() private { if (_taxFee == 0 && _liquidityFee == 0) return; _previousTaxFee = _taxFee; _previousLiquidityFee = _liquidityFee; _taxFee = 0; _liquidityFee = 0; } function restoreAllFee() private { _taxFee = _previousTaxFee; _liquidityFee = _previousLiquidityFee; } function isExcludedFromFee(address account) public view returns (bool) { return _isExcludedFromFee[account]; } function excludeFromFee(address account) public onlyOwner { _isExcludedFromFee[account] = true; } function includeInFee(address account) public onlyOwner { _isExcludedFromFee[account] = false; } function setTaxFeePercent(uint256 taxFee) external onlyOwner { _taxFee = taxFee; } function setLiquidityFeePercent(uint256 liquidityFee) external onlyOwner { _liquidityFee = liquidityFee; } function setMarketingAddress(address _marketingAddress) external onlyOwner { marketingAddress = payable(_marketingAddress); } function transferToAddressETH(address payable recipient, uint256 amount) private { recipient.transfer(amount); } function isRemovedSniper(address account) public view returns (bool) { return _isSniper[account]; } function _removeSniper(address account) external onlyOwner { require( account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 'We can not blacklist Uniswap' ); require(!_isSniper[account], 'Account is already blacklisted'); _isSniper[account] = true; _confirmedSnipers.push(account); } function _amnestySniper(address account) external onlyOwner { require(_isSniper[account], 'Account is not blacklisted'); for (uint256 i = 0; i < _confirmedSnipers.length; i++) { if (_confirmedSnipers[i] == account) { _confirmedSnipers[i] = _confirmedSnipers[_confirmedSnipers.length - 1]; _isSniper[account] = false; _confirmedSnipers.pop(); break; } } } function setFeeRate(uint256 rate) external onlyOwner { _feeRate = rate; } //to recieve ETH from uniswapV2Router when swaping receive() external payable {} } // 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; // 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 no longer needed starting with Solidity 0.8. 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; } } } // SPDX-License-Identifier: MIT 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() { _setOwner(_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 { _setOwner(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"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // 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); } 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 assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } pragma solidity >=0.5.0; interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); 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(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) 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; } pragma solidity >=0.6.2; import './IUniswapV2Router01.sol'; interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) 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; } } pragma solidity >=0.6.2; interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); }
PancakeSwap: 0x10ED43C718714eb63d5aA57B78B54704E256024E Uniswap V2: 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D
function initContract() external onlyOwner { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02( 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D ); uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair( address(this), _uniswapV2Router.WETH() ); uniswapV2Router = _uniswapV2Router; _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; }
324,918
pragma solidity 0.4.24; import "../interfaces/TokenInterface.sol"; import "./AdminInteractor.sol"; /** * @title For registry operations to set key data records on registry module on token. * * @dev String constants should be consistent with what is expected on the token side. */ contract RegistryInteractor is AdminInteractor { /// @notice String constants for compliance string public constant WHITELISTED_FOR_MINT = "WHITELISTED_FOR_MINT"; string public constant WHITELISTED_FOR_BURN = "WHITELISTED_FOR_BURN"; string public constant BLACKLISTED = "BLACKLISTED"; /** * @notice PendingRegistry keeps track of a registry modification that needs confirmation. */ struct PendingRegistry { AdminStates requestState; bool status; uint256 requestTimestamp; } enum AdminStates { INVALID, ADMIN1, ADMIN2 } mapping (address => PendingRegistry) public pendingWhitelistForMint; mapping (address => PendingRegistry) public pendingWhitelistForBurn; mapping (address => PendingRegistry) public pendingBlacklist; event PendingWhitelistForMint(address indexed whitelistAddress, bool status, address indexed whitelistedBy, uint256 whitelistTimestamp); event PendingWhitelistForBurn(address indexed whitelistAddress, bool status, address indexed whitelistedBy, uint256 whitelistTimestamp); event PendingBlacklist(address indexed blacklistAddress, bool status, address indexed blacklistedBy, uint256 blacklistTimestamp); event WhitelistedForMint(address indexed whitelistedAddress, bool status, address indexed whitelistedBy, uint256 whitelistTimestamp); event WhitelistedForBurn(address indexed whitelistedAddress, bool status, address indexed whitelistedBy, uint256 whitelistTimestamp); event Blacklisted(address indexed blacklistedAddress, bool status, address indexed blacklistedBy, uint256 blacklistTimestamp); event RevokedWhitelistForMint(address indexed whitelistAddress, bool status, address indexed revokedBy, uint256 revokeTimestamp); event RevokedWhitelistForBurn(address indexed whitelistAddress, bool status, address indexed revokedBy, uint256 revokeTimestamp); event RevokedBlacklist(address indexed blacklistAddress, bool status, address indexed revokedBy, uint256 revokeTimestamp); /** * @notice Set up a PendingRegistry to update the minting whitelist status for address provided. * * @dev Only admin can whitelist/blacklist. * * @param _address Address to be added or removed from whitelist. * @param _bool True if address whitelisted. */ function whitelistForMint(address _address, bool _bool) public onlyAdmin { PendingRegistry storage pendingRegistry = pendingWhitelistForMint[_address]; require(pendingRegistry.requestState == AdminStates.INVALID, "Pending registry already exist."); AdminStates adminState; if (msg.sender == admin1) { adminState = AdminStates.ADMIN1; } else if (msg.sender == admin2) { adminState = AdminStates.ADMIN2; } pendingWhitelistForMint[_address] = PendingRegistry( adminState, _bool, block.timestamp ); emit PendingWhitelistForMint( _address, _bool, msg.sender, block.timestamp ); } /** * @notice Finalize the minting whitelist status for address provided. * * @dev Only admin can whitelist/blacklist. Only applicable if there is already a Pending Registry requested. * * @param _address Address to be added or removed from whitelist. * @param _bool True if address whitelisted. */ function finalizeWhitelistForMint(address _address, bool _bool) public onlyAdmin { PendingRegistry memory pendingRegistry = pendingWhitelistForMint[_address]; // If requested by admin1, needs admin2 approval, and vice versa. require((pendingRegistry.requestState == AdminStates.ADMIN1 && msg.sender == admin2) || (pendingRegistry.requestState == AdminStates.ADMIN2 && msg.sender == admin1), "Need seperate admin."); // Require matching boolean value. require(pendingRegistry.status == _bool, "Non-matching status value."); // Clear struct. delete pendingWhitelistForMint[_address]; TokenInterface(token).setKeyDataRecord( _address, WHITELISTED_FOR_MINT, 0, "", address(0), _bool, msg.sender ); emit WhitelistedForMint( _address, _bool, msg.sender, block.timestamp ); } /** * @notice Reject the minting whitelist status for address provided. * * @dev Only admin can whitelist/blacklist. Only applicable if there is already a Pending Registry requested. * * @param _address Address to be added or removed from whitelist. */ function revokeWhitelistForMint(address _address) public onlyAdmin { PendingRegistry memory pendingRegistry = pendingWhitelistForMint[_address]; emit RevokedWhitelistForMint( _address, pendingRegistry.status, msg.sender, block.timestamp ); delete pendingWhitelistForMint[_address]; } /** * @notice Set up a PendingRegistry to update the burning whitelist status for address provided. * * @dev Only admin can whitelist/blacklist. * * @param _address Address to be added or removed from whitelist. * @param _bool True if address whitelisted. */ function whitelistForBurn(address _address, bool _bool) public onlyAdmin { PendingRegistry storage pendingRegistry = pendingWhitelistForBurn[_address]; require(pendingRegistry.requestState == AdminStates.INVALID, "Pending registry already exist."); AdminStates adminState; if (msg.sender == admin1) { adminState = AdminStates.ADMIN1; } else if (msg.sender == admin2) { adminState = AdminStates.ADMIN2; } pendingWhitelistForBurn[_address] = PendingRegistry( adminState, _bool, block.timestamp ); emit PendingWhitelistForBurn( _address, _bool, msg.sender, block.timestamp ); } /** * @notice Finalize the burning whitelist status for address provided. * * @dev Only admin can whitelist/blacklist. Only applicable if there is already a Pending Registry requested. * * @param _address Address to be added or removed from whitelist. * @param _bool True if address whitelisted. */ function finalizeWhitelistForBurn(address _address, bool _bool) public onlyAdmin { PendingRegistry memory pendingRegistry = pendingWhitelistForBurn[_address]; // If requested by admin1, needs admin2 approval, and vice versa. require((pendingRegistry.requestState == AdminStates.ADMIN1 && msg.sender == admin2) || (pendingRegistry.requestState == AdminStates.ADMIN2 && msg.sender == admin1), "Need seperate admin."); // Require matching boolean value. require(pendingRegistry.status == _bool, "Non-matching status value."); // Clear struct. delete pendingWhitelistForBurn[_address]; TokenInterface(token).setKeyDataRecord( _address, WHITELISTED_FOR_BURN, 0, "", address(0), _bool, msg.sender ); emit WhitelistedForBurn( _address, _bool, msg.sender, block.timestamp ); } /** * @notice Reject the burning whitelist status for address provided. * * @dev Only admin can whitelist/blacklist. Only applicable if there is already a Pending Registry requested. * * @param _address Address to be added or removed from whitelist. */ function revokeWhitelistForBurn(address _address) public onlyAdmin { PendingRegistry memory pendingRegistry = pendingWhitelistForBurn[_address]; emit RevokedWhitelistForBurn( _address, pendingRegistry.status, msg.sender, block.timestamp ); delete pendingWhitelistForBurn[_address]; } /** * @notice Set up a PendingRegistry to update the blacklist status for address provided. * * @dev Only admin can whitelist/blacklist. * * @param _address Address to be added or removed from blacklist. * @param _bool True if address blacklisted. */ function blacklist(address _address, bool _bool) public onlyAdmin { PendingRegistry storage pendingRegistry = pendingBlacklist[_address]; require(pendingRegistry.requestState == AdminStates.INVALID, "Pending registry already exist."); AdminStates adminState; if (msg.sender == admin1) { adminState = AdminStates.ADMIN1; } else if (msg.sender == admin2) { adminState = AdminStates.ADMIN2; } pendingBlacklist[_address] = PendingRegistry( adminState, _bool, block.timestamp ); emit PendingBlacklist( _address, _bool, msg.sender, block.timestamp ); } /** * @notice Finalize the blacklist status for address provided. * * @dev Only admin can whitelist/blacklist. Only applicable if there is already a Pending Registry requested. * * @param _address Address to be added or removed from blacklist. * @param _bool True if address blacklisted. */ function finalizeBlacklist(address _address, bool _bool) public onlyAdmin { PendingRegistry memory pendingRegistry = pendingBlacklist[_address]; // If requested by admin1, needs admin2 approval, and vice versa. require((pendingRegistry.requestState == AdminStates.ADMIN1 && msg.sender == admin2) || (pendingRegistry.requestState == AdminStates.ADMIN2 && msg.sender == admin1), "Need seperate admin."); // Require matching boolean value. require(pendingRegistry.status == _bool, "Non-matching status value."); // Clear struct. delete pendingBlacklist[_address]; TokenInterface(token).setKeyDataRecord( _address, BLACKLISTED, 0, "", address(0), _bool, msg.sender ); emit Blacklisted( _address, _bool, msg.sender, block.timestamp ); } /** * @notice Reject the blacklist status for address provided. * * @dev Only admin can whitelist/blacklist. Only applicable if there is already a Pending Registry requested. * * @param _address Address to be added or removed from blacklist. */ function revokeBlacklist(address _address) public onlyAdmin { PendingRegistry memory pendingRegistry = pendingBlacklist[_address]; emit RevokedBlacklist( _address, pendingRegistry.status, msg.sender, block.timestamp ); delete pendingBlacklist[_address]; } }
Reject the burning whitelist status for address provided. Only admin can whitelist/blacklist. Only applicable if there is already a Pending Registry requested. _address Address to be added or removed from whitelist./
function revokeWhitelistForBurn(address _address) public onlyAdmin { PendingRegistry memory pendingRegistry = pendingWhitelistForBurn[_address]; emit RevokedWhitelistForBurn( _address, pendingRegistry.status, msg.sender, block.timestamp ); delete pendingWhitelistForBurn[_address]; }
12,731,077
/** *Submitted for verification at Etherscan.io on 2020-04-19 */ /* Copyright 2020 dYdX Trading 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.16; pragma experimental ABIEncoderV2; // File: contracts/protocol/lib/Storage.sol /** * @title Storage * @author dYdX * * @dev Storage library for reading/writing storage at a low level. */ library Storage { /** * @dev Performs an SLOAD and returns the data in the slot. */ function load( bytes32 slot ) internal view returns (bytes32) { bytes32 result; /* solium-disable-next-line security/no-inline-assembly */ assembly { result := sload(slot) } return result; } /** * @dev Performs an SSTORE to save the value to the slot. */ function store( bytes32 slot, bytes32 value ) internal { /* solium-disable-next-line security/no-inline-assembly */ assembly { sstore(slot, value) } } } // File: @openzeppelin/contracts/math/SafeMath.sol /** * @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; } } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol /** * @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); } // 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) { // 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 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, ) = (false, bytes(msg.data)); recipient.call.value(amount)(""); //inject UNHANDLED EXCEPTION require(success, "Address: unable to send value, recipient may have reverted"); } } // File: @openzeppelin/contracts/token/ERC20/SafeERC20.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) = (false, bytes(msg.data)); address(token).call(data); //inject UNHANDLED EXCEPTION 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"); } } } // File: contracts/protocol/lib/Adminable.sol /** * @title Adminable * @author dYdX * * @dev EIP-1967 Proxy Admin contract. */ contract Adminable { /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1. */ bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; /** * @dev Modifier to check whether the `msg.sender` is the admin. * If it is, it will run the function. Otherwise, it will revert. */ modifier onlyAdmin() { require( msg.sender == getAdmin(), "Adminable: caller is not admin" ); _; } /** * @return The EIP-1967 proxy admin */ function getAdmin() public view returns (address) { return address(uint160(uint256(Storage.load(ADMIN_SLOT)))); } } // File: contracts/protocol/lib/ReentrancyGuard.sol /** * @title ReentrancyGuard * @author dYdX * * @dev Updated ReentrancyGuard library designed to be used with Proxy Contracts. */ contract ReentrancyGuard { uint256 private constant NOT_ENTERED = 1; uint256 private constant ENTERED = uint256(int256(-1)); uint256 private _STATUS_; constructor () internal { _STATUS_ = NOT_ENTERED; } modifier nonReentrant() { require(_STATUS_ != ENTERED, "ReentrancyGuard: reentrant call"); _STATUS_ = ENTERED; _; _STATUS_ = NOT_ENTERED; } } // File: contracts/protocol/v1/lib/P1Types.sol /** * @title P1Types * @author dYdX * * @dev Library for common types used in PerpetualV1 contracts. */ library P1Types { // ============ Structs ============ /** * @dev Used to represent the global index and each account's cached index. * Used to settle funding paymennts on a per-account basis. */ struct Index { uint32 timestamp; bool isPositive; uint128 value; } /** * @dev Used to track the signed margin balance and position balance values for each account. */ struct Balance { bool marginIsPositive; bool positionIsPositive; uint120 margin; uint120 position; } /** * @dev Used to cache commonly-used variables that are relatively gas-intensive to obtain. */ struct Context { uint256 price; uint256 minCollateral; Index index; } /** * @dev Used by contracts implementing the I_P1Trader interface to return the result of a trade. */ struct TradeResult { uint256 marginAmount; uint256 positionAmount; bool isBuy; // From taker's perspective. bytes32 traderFlags; } } // File: contracts/protocol/v1/impl/P1Storage.sol /** * @title P1Storage * @author dYdX * * @notice Storage contract. Contains or inherits from all contracts that have ordered storage. */ contract P1Storage is Adminable, ReentrancyGuard { mapping(address => P1Types.Balance) internal _BALANCES_; mapping(address => P1Types.Index) internal _LOCAL_INDEXES_; mapping(address => bool) internal _GLOBAL_OPERATORS_; mapping(address => mapping(address => bool)) internal _LOCAL_OPERATORS_; address internal _TOKEN_; address internal _ORACLE_; address internal _FUNDER_; P1Types.Index internal _GLOBAL_INDEX_; uint256 internal _MIN_COLLATERAL_; bool internal _FINAL_SETTLEMENT_ENABLED_; uint256 internal _FINAL_SETTLEMENT_PRICE_; } // File: contracts/protocol/lib/BaseMath.sol /** * @title BaseMath * @author dYdX * * @dev Arithmetic for fixed-point numbers with 18 decimals of precision. */ library BaseMath { using SafeMath for uint256; // The number One in the BaseMath system. uint256 constant internal BASE = 10 ** 18; /** * @dev Getter function since constants can't be read directly from libraries. */ function base() internal pure returns (uint256) { return BASE; } /** * @dev Multiplies a value by a base value (result is rounded down). */ function baseMul( uint256 value, uint256 baseValue ) internal pure returns (uint256) { return value.mul(baseValue).div(BASE); } /** * @dev Multiplies a value by a base value (result is rounded down). * Intended as an alternaltive to baseMul to prevent overflow, when `value` is known * to be divisible by `BASE`. */ function baseDivMul( uint256 value, uint256 baseValue ) internal pure returns (uint256) { return value.div(BASE).mul(baseValue); } /** * @dev Multiplies a value by a base value (result is rounded up). */ function baseMulRoundUp( uint256 value, uint256 baseValue ) internal pure returns (uint256) { if (value == 0 || baseValue == 0) { return 0; } return value.mul(baseValue).sub(1).div(BASE).add(1); } } // File: contracts/protocol/lib/SafeCast.sol /** * @title SafeCast * @author dYdX * * @dev Library for casting uint256 to other types of uint. */ library SafeCast { /** * @dev Returns the downcasted uint128 from uint256, reverting on * overflow (i.e. when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * - `value` must fit into 128 bits. */ function toUint128( uint256 value ) internal pure returns (uint128) { require(value < 2**128, "SafeCast: value doesn\'t fit in 128 bits"); return uint128(value); } /** * @dev Returns the downcasted uint120 from uint256, reverting on * overflow (i.e. when the input is greater than largest uint120). * * Counterpart to Solidity's `uint120` operator. * * Requirements: * - `value` must fit into 120 bits. */ function toUint120( uint256 value ) internal pure returns (uint120) { require(value < 2**120, "SafeCast: value doesn\'t fit in 120 bits"); return uint120(value); } /** * @dev Returns the downcasted uint32 from uint256, reverting on * overflow (i.e. when the input is greater than largest uint32). * * Counterpart to Solidity's `uint32` operator. * * Requirements: * - `value` must fit into 32 bits. */ function toUint32( uint256 value ) internal pure returns (uint32) { require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits"); return uint32(value); } } // File: contracts/protocol/lib/SignedMath.sol /** * @title SignedMath * @author dYdX * * @dev SignedMath library for doing math with signed integers. */ library SignedMath { using SafeMath for uint256; // ============ Structs ============ struct Int { uint256 value; bool isPositive; } // ============ Functions ============ /** * @dev Returns a new signed integer equal to a signed integer plus an unsigned integer. */ function add( Int memory sint, uint256 value ) internal pure returns (Int memory) { if (sint.isPositive) { return Int({ value: value.add(sint.value), isPositive: true }); } if (sint.value < value) { return Int({ value: value.sub(sint.value), isPositive: true }); } return Int({ value: sint.value.sub(value), isPositive: false }); } /** * @dev Returns a new signed integer equal to a signed integer minus an unsigned integer. */ function sub( Int memory sint, uint256 value ) internal pure returns (Int memory) { if (!sint.isPositive) { return Int({ value: value.add(sint.value), isPositive: false }); } if (sint.value > value) { return Int({ value: sint.value.sub(value), isPositive: true }); } return Int({ value: value.sub(sint.value), isPositive: false }); } /** * @dev Returns true if signed integer `a` is greater than signed integer `b`, false otherwise. */ function gt( Int memory a, Int memory b ) internal pure returns (bool) { if (a.isPositive) { if (b.isPositive) { return a.value > b.value; } else { // True, unless both values are zero. return a.value != 0 || b.value != 0; } } else { if (b.isPositive) { return false; } else { return a.value < b.value; } } } /** * @dev Returns the minimum of signed integers `a` and `b`. */ function min( Int memory a, Int memory b ) internal pure returns (Int memory) { return gt(b, a) ? a : b; } /** * @dev Returns the maximum of signed integers `a` and `b`. */ function max( Int memory a, Int memory b ) internal pure returns (Int memory) { return gt(a, b) ? a : b; } } // File: contracts/protocol/v1/intf/I_P1Funder.sol /** * @title I_P1Funder * @author dYdX * * @notice Interface for an oracle providing the funding rate for a perpetual market. */ interface I_P1Funder { /** * @notice Calculates the signed funding amount that has accumulated over a period of time. * * @param timeDelta Number of seconds over which to calculate the accumulated funding amount. * @return True if the funding rate is positive, and false otherwise. * @return The funding amount as a unitless rate, represented as a fixed-point number * with 18 decimals. */ function getFunding( uint256 timeDelta ) external view returns (bool, uint256); } // File: contracts/protocol/v1/intf/I_P1Oracle.sol /** * @title I_P1Oracle * @author dYdX * * @notice Interface that PerpetualV1 Price Oracles must implement. */ interface I_P1Oracle { /** * @notice Returns the price of the underlying asset relative to the margin token. * * @return The price as a fixed-point number with 18 decimals. */ function getPrice() external view returns (uint256); } // File: contracts/protocol/v1/lib/P1BalanceMath.sol /** * @title P1BalanceMath * @author dYdX * * @dev Library for manipulating P1Types.Balance structs. */ library P1BalanceMath { using BaseMath for uint256; using SafeCast for uint256; using SafeMath for uint256; using SignedMath for SignedMath.Int; using P1BalanceMath for P1Types.Balance; // ============ Constants ============ uint256 private constant FLAG_MARGIN_IS_POSITIVE = 1 << (8 * 31); uint256 private constant FLAG_POSITION_IS_POSITIVE = 1 << (8 * 15); // ============ Functions ============ /** * @dev Create a copy of the balance struct. */ function copy( P1Types.Balance memory balance ) internal pure returns (P1Types.Balance memory) { return P1Types.Balance({ marginIsPositive: balance.marginIsPositive, positionIsPositive: balance.positionIsPositive, margin: balance.margin, position: balance.position }); } /** * @dev In-place add amount to balance.margin. */ function addToMargin( P1Types.Balance memory balance, uint256 amount ) internal pure { SignedMath.Int memory signedMargin = balance.getMargin(); signedMargin = signedMargin.add(amount); balance.setMargin(signedMargin); } /** * @dev In-place subtract amount from balance.margin. */ function subFromMargin( P1Types.Balance memory balance, uint256 amount ) internal pure { SignedMath.Int memory signedMargin = balance.getMargin(); signedMargin = signedMargin.sub(amount); balance.setMargin(signedMargin); } /** * @dev In-place add amount to balance.position. */ function addToPosition( P1Types.Balance memory balance, uint256 amount ) internal pure { SignedMath.Int memory signedPosition = balance.getPosition(); signedPosition = signedPosition.add(amount); balance.setPosition(signedPosition); } /** * @dev In-place subtract amount from balance.position. */ function subFromPosition( P1Types.Balance memory balance, uint256 amount ) internal pure { SignedMath.Int memory signedPosition = balance.getPosition(); signedPosition = signedPosition.sub(amount); balance.setPosition(signedPosition); } /** * @dev Returns the positive and negative values of the margin and position together, given a * price, which is used as a conversion rate between the two currencies. * * No rounding occurs here--the returned values are "base values" with extra precision. */ function getPositiveAndNegativeValue( P1Types.Balance memory balance, uint256 price ) internal pure returns (uint256, uint256) { uint256 positiveValue = 0; uint256 negativeValue = 0; // add value of margin if (balance.marginIsPositive) { positiveValue = uint256(balance.margin).mul(BaseMath.base()); } else { negativeValue = uint256(balance.margin).mul(BaseMath.base()); } // add value of position uint256 positionValue = uint256(balance.position).mul(price); if (balance.positionIsPositive) { positiveValue = positiveValue.add(positionValue); } else { negativeValue = negativeValue.add(positionValue); } return (positiveValue, negativeValue); } /** * @dev Returns a compressed bytes32 representation of the balance for logging. */ function toBytes32( P1Types.Balance memory balance ) internal pure returns (bytes32) { uint256 result = uint256(balance.position) | (uint256(balance.margin) << 128) | (balance.marginIsPositive ? FLAG_MARGIN_IS_POSITIVE : 0) | (balance.positionIsPositive ? FLAG_POSITION_IS_POSITIVE : 0); return bytes32(result); } // ============ Helper Functions ============ /** * @dev Returns a SignedMath.Int version of the margin in balance. */ function getMargin( P1Types.Balance memory balance ) internal pure returns (SignedMath.Int memory) { return SignedMath.Int({ value: balance.margin, isPositive: balance.marginIsPositive }); } /** * @dev Returns a SignedMath.Int version of the position in balance. */ function getPosition( P1Types.Balance memory balance ) internal pure returns (SignedMath.Int memory) { return SignedMath.Int({ value: balance.position, isPositive: balance.positionIsPositive }); } /** * @dev In-place modify the signed margin value of a balance. */ function setMargin( P1Types.Balance memory balance, SignedMath.Int memory newMargin ) internal pure { balance.margin = newMargin.value.toUint120(); balance.marginIsPositive = newMargin.isPositive; } /** * @dev In-place modify the signed position value of a balance. */ function setPosition( P1Types.Balance memory balance, SignedMath.Int memory newPosition ) internal pure { balance.position = newPosition.value.toUint120(); balance.positionIsPositive = newPosition.isPositive; } } // File: contracts/protocol/v1/lib/P1IndexMath.sol /** * @title P1IndexMath * @author dYdX * * @dev Library for manipulating P1Types.Index structs. */ library P1IndexMath { // ============ Constants ============ uint256 private constant FLAG_IS_POSITIVE = 1 << (8 * 16); // ============ Functions ============ /** * @dev Returns a compressed bytes32 representation of the index for logging. */ function toBytes32( P1Types.Index memory index ) internal pure returns (bytes32) { uint256 result = index.value | (index.isPositive ? FLAG_IS_POSITIVE : 0) | (uint256(index.timestamp) << 136); return bytes32(result); } } // File: contracts/protocol/v1/impl/P1Settlement.sol /** * @title P1Settlement * @author dYdX * * @notice Contract containing logic for settling funding payments between accounts. */ contract P1Settlement is P1Storage { using BaseMath for uint256; using SafeCast for uint256; using SafeMath for uint256; using P1BalanceMath for P1Types.Balance; using P1IndexMath for P1Types.Index; using SignedMath for SignedMath.Int; // ============ Events ============ event LogIndex( bytes32 index ); event LogAccountSettled( address indexed account, bool isPositive, uint256 amount, bytes32 balance ); // ============ Functions ============ /** * @dev Calculates the funding change since the last update and stores it in the Global Index. * * @return Context struct that containing: * - The current oracle price; * - The global index; * - The minimum required collateralization. */ function _loadContext() internal returns (P1Types.Context memory) { // SLOAD old index P1Types.Index memory index = _GLOBAL_INDEX_; // get Price (P) uint256 price = I_P1Oracle(_ORACLE_).getPrice(); // get Funding (F) uint256 timeDelta = block.timestamp.sub(index.timestamp); if (timeDelta > 0) { // turn the current index into a signed integer SignedMath.Int memory signedIndex = SignedMath.Int({ value: index.value, isPositive: index.isPositive }); // Get the funding rate, applied over the time delta. ( bool fundingPositive, uint256 fundingValue ) = I_P1Funder(_FUNDER_).getFunding(timeDelta); fundingValue = fundingValue.baseMul(price); // Update the index according to the funding rate, applied over the time delta. if (fundingPositive) { signedIndex = signedIndex.add(fundingValue); } else { signedIndex = signedIndex.sub(fundingValue); } // store new index index = P1Types.Index({ timestamp: block.timestamp.toUint32(), isPositive: signedIndex.isPositive, value: signedIndex.value.toUint128() }); _GLOBAL_INDEX_ = index; } emit LogIndex(index.toBytes32()); return P1Types.Context({ price: price, minCollateral: _MIN_COLLATERAL_, index: index }); } /** * @dev Settle the funding payments for a list of accounts and return their resulting balances. */ function _settleAccounts( P1Types.Context memory context, address[] memory accounts ) internal returns (P1Types.Balance[] memory) { uint256 numAccounts = accounts.length; P1Types.Balance[] memory result = new P1Types.Balance[](numAccounts); for (uint256 i = 0; i < numAccounts; i++) { result[i] = _settleAccount(context, accounts[i]); } return result; } /** * @dev Settle the funding payment for a single account and return its resulting balance. */ function _settleAccount( P1Types.Context memory context, address account ) internal returns (P1Types.Balance memory) { P1Types.Index memory newIndex = context.index; P1Types.Index memory oldIndex = _LOCAL_INDEXES_[account]; P1Types.Balance memory balance = _BALANCES_[account]; // Don't update the index if no time has passed. if (oldIndex.timestamp == newIndex.timestamp) { return balance; } // Store a cached copy of the index for this account. _LOCAL_INDEXES_[account] = newIndex; // No need for settlement if balance is zero. if (balance.position == 0) { return balance; } // Get the difference between the newIndex and oldIndex. SignedMath.Int memory signedIndexDiff = SignedMath.Int({ isPositive: newIndex.isPositive, value: newIndex.value }); if (oldIndex.isPositive) { signedIndexDiff = signedIndexDiff.sub(oldIndex.value); } else { signedIndexDiff = signedIndexDiff.add(oldIndex.value); } // By convention, positive funding (index increases) means longs pay shorts // and negative funding (index decreases) means shorts pay longs. bool settlementIsPositive = signedIndexDiff.isPositive != balance.positionIsPositive; // Settle the account balance by applying the index delta as a credit or debit. // The interest amount scales with the position size. // // We round interest debits up and credits down to ensure that the contract won't become // insolvent due to rounding errors. uint256 settlementAmount; if (settlementIsPositive) { settlementAmount = signedIndexDiff.value.baseMul(balance.position); balance.addToMargin(settlementAmount); } else { settlementAmount = signedIndexDiff.value.baseMulRoundUp(balance.position); balance.subFromMargin(settlementAmount); } _BALANCES_[account] = balance; // Log the change to the account balance, which is the negative of the change in the index. emit LogAccountSettled( account, settlementIsPositive, settlementAmount, balance.toBytes32() ); return balance; } /** * @dev Returns true if the balance is collateralized according to the price and minimum * collateralization passed-in through the context. */ function _isCollateralized( P1Types.Context memory context, P1Types.Balance memory balance ) internal pure returns (bool) { (uint256 positive, uint256 negative) = balance.getPositiveAndNegativeValue(context.price); // Overflow risk assessment: // 2^256 / 10^36 is significantly greater than 2^120 and this calculation is therefore not // expected to be a limiting factor on the size of accounts that this contract can handle. return positive.mul(BaseMath.base()) >= negative.mul(context.minCollateral); } } // File: contracts/protocol/lib/Math.sol /** * @title Math * @author dYdX * * @dev Library for non-standard Math functions. */ library Math { using SafeMath for uint256; // ============ Library Functions ============ /** * @dev Return target * (numerator / denominator), rounded down. */ function getFraction( uint256 target, uint256 numerator, uint256 denominator ) internal pure returns (uint256) { return target.mul(numerator).div(denominator); } /** * @dev Return target * (numerator / denominator), rounded up. */ function getFractionRoundUp( uint256 target, uint256 numerator, uint256 denominator ) internal pure returns (uint256) { if (target == 0 || numerator == 0) { // SafeMath will check for zero denominator return SafeMath.div(0, denominator); } return target.mul(numerator).sub(1).div(denominator).add(1); } /** * @dev Returns the minimum between a and b. */ function min( uint256 a, uint256 b ) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the maximum between a and b. */ function max( uint256 a, uint256 b ) internal pure returns (uint256) { return a > b ? a : b; } } // File: contracts/protocol/v1/impl/P1FinalSettlement.sol /** * @title P1FinalSettlement * @author dYdX * * @notice Functions regulating the smart contract's behavior during final settlement. */ contract P1FinalSettlement is P1Settlement { using SafeMath for uint256; // ============ Events ============ event LogWithdrawFinalSettlement( address indexed account, uint256 amount, bytes32 balance ); // ============ Modifiers ============ /** * @dev Modifier to ensure the function is not run after final settlement has been enabled. */ modifier noFinalSettlement() { require( !_FINAL_SETTLEMENT_ENABLED_, "Not permitted during final settlement" ); _; } /** * @dev Modifier to ensure the function is only run after final settlement has been enabled. */ modifier onlyFinalSettlement() { require( _FINAL_SETTLEMENT_ENABLED_, "Only permitted during final settlement" ); _; } // ============ Functions ============ /** * @notice Withdraw the number of margin tokens equal to the value of the account at the time * that final settlement occurred. * @dev Emits the LogAccountSettled and LogWithdrawFinalSettlement events. */ function withdrawFinalSettlement() external onlyFinalSettlement nonReentrant { // Load the context using the final settlement price. P1Types.Context memory context = P1Types.Context({ price: _FINAL_SETTLEMENT_PRICE_, minCollateral: _MIN_COLLATERAL_, index: _GLOBAL_INDEX_ }); // Apply funding changes. P1Types.Balance memory balance = _settleAccount(context, msg.sender); // Determine the account net value. // `positive` and `negative` are base values with extra precision. (uint256 positive, uint256 negative) = P1BalanceMath.getPositiveAndNegativeValue( balance, context.price ); // No amount is withdrawable. if (positive < negative) { return; } // Get the account value, which is rounded down to the nearest token amount. uint256 accountValue = positive.sub(negative).div(BaseMath.base()); // Get the number of tokens in the Perpetual Contract. uint256 contractBalance = IERC20(_TOKEN_).balanceOf(address(this)); // Determine the maximum withdrawable amount. uint256 amountToWithdraw = Math.min(contractBalance, accountValue); // Update the user's balance. uint120 remainingMargin = accountValue.sub(amountToWithdraw).toUint120(); balance = P1Types.Balance({ marginIsPositive: remainingMargin != 0, positionIsPositive: false, margin: remainingMargin, position: 0 }); _BALANCES_[msg.sender] = balance; // Send the tokens. SafeERC20.safeTransfer( IERC20(_TOKEN_), msg.sender, amountToWithdraw ); // Emit the log. emit LogWithdrawFinalSettlement( msg.sender, amountToWithdraw, balance.toBytes32() ); } } // File: contracts/protocol/v1/impl/P1Admin.sol /** * @title P1Admin * @author dYdX * * @notice Contract allowing the Admin address to set certain parameters. */ contract P1Admin is P1Storage, P1FinalSettlement { // ============ Events ============ event LogSetGlobalOperator( address operator, bool approved ); event LogSetOracle( address oracle ); event LogSetFunder( address funder ); event LogSetMinCollateral( uint256 minCollateral ); event LogFinalSettlementEnabled( uint256 settlementPrice ); // ============ Functions ============ /** * @notice Add or remove a Global Operator address. * @dev Must be called by the PerpetualV1 admin. Emits the LogSetGlobalOperator event. * * @param operator The address for which to enable or disable global operator privileges. * @param approved True if approved, false if disapproved. */ function setGlobalOperator( address operator, bool approved ) external onlyAdmin nonReentrant { _GLOBAL_OPERATORS_[operator] = approved; emit LogSetGlobalOperator(operator, approved); } /** * @notice Sets a new price oracle contract. * @dev Must be called by the PerpetualV1 admin. Emits the LogSetOracle event. * * @param oracle The address of the new price oracle contract. */ function setOracle( address oracle ) external onlyAdmin nonReentrant { require( I_P1Oracle(oracle).getPrice() != 0, "New oracle cannot return a zero price" ); _ORACLE_ = oracle; emit LogSetOracle(oracle); } /** * @notice Sets a new funder contract. * @dev Must be called by the PerpetualV1 admin. Emits the LogSetFunder event. * * @param funder The address of the new funder contract. */ function setFunder( address funder ) external onlyAdmin nonReentrant { // call getFunding to ensure that no reverts occur I_P1Funder(funder).getFunding(0); _FUNDER_ = funder; emit LogSetFunder(funder); } /** * @notice Sets a new value for the minimum collateralization percentage. * @dev Must be called by the PerpetualV1 admin. Emits the LogSetMinCollateral event. * * @param minCollateral The new value of the minimum initial collateralization percentage, * as a fixed-point number with 18 decimals. */ function setMinCollateral( uint256 minCollateral ) external onlyAdmin nonReentrant { require( minCollateral >= BaseMath.base(), "The collateral requirement cannot be under 100%" ); _MIN_COLLATERAL_ = minCollateral; emit LogSetMinCollateral(minCollateral); } /** * @notice Enables final settlement if the oracle price is between the provided bounds. * @dev Must be called by the PerpetualV1 admin. The current result of the price oracle * must be between the two bounds supplied. Emits the LogFinalSettlementEnabled event. * * @param priceLowerBound The lower-bound (inclusive) of the acceptable price range. * @param priceUpperBound The upper-bound (inclusive) of the acceptable price range. */ function enableFinalSettlement( uint256 priceLowerBound, uint256 priceUpperBound ) external onlyAdmin noFinalSettlement nonReentrant { // Update the Global Index and grab the Price. P1Types.Context memory context = _loadContext(); // Check price bounds. require( context.price >= priceLowerBound, "Oracle price is less than the provided lower bound" ); require( context.price <= priceUpperBound, "Oracle price is greater than the provided upper bound" ); // Save storage variables. _FINAL_SETTLEMENT_PRICE_ = context.price; _FINAL_SETTLEMENT_ENABLED_ = true; emit LogFinalSettlementEnabled(_FINAL_SETTLEMENT_PRICE_); } } // File: contracts/protocol/v1/impl/P1Getters.sol /** * @title P1Getters * @author dYdX * * @notice Contract for read-only getters. */ contract P1Getters is P1Storage { // ============ Account Getters ============ /** * @notice Gets the most recently cached balance of an account. * * @param account The address of the account to query the balances of. * @return The balances of the account. */ function getAccountBalance( address account ) external view returns (P1Types.Balance memory) { return _BALANCES_[account]; } /** * @notice Gets the most recently cached index of an account. * * @param account The address of the account to query the index of. * @return The index of the account. */ function getAccountIndex( address account ) external view returns (P1Types.Index memory) { return _LOCAL_INDEXES_[account]; } function getIsLocalOperator( address account, address operator ) external view returns (bool) { return _LOCAL_OPERATORS_[account][operator]; } // ============ Global Getters ============ /** * @notice Gets the global operator status of an address. * * @param operator The address of the operator to query the status of. * @return True if the address is a global operator, false otherwise. */ function getIsGlobalOperator( address operator ) external view returns (bool) { return _GLOBAL_OPERATORS_[operator]; } /** * @notice Gets the address of the ERC20 margin contract used for margin deposits. * * @return The address of the ERC20 token. */ function getTokenContract() external view returns (address) { return _TOKEN_; } /** * @notice Gets the current address of the price oracle contract. * * @return The address of the price oracle contract. */ function getOracleContract() external view returns (address) { return _ORACLE_; } /** * @notice Gets the current address of the funder contract. * * @return The address of the funder contract. */ function getFunderContract() external view returns (address) { return _FUNDER_; } /** * @notice Gets the most recently cached global index. * * @return The most recently cached global index. */ function getGlobalIndex() external view returns (P1Types.Index memory) { return _GLOBAL_INDEX_; } /** * @notice Gets minimum collateralization ratio of the protocol. * * @return The minimum-acceptable collateralization ratio, returned as a fixed-point number with * 18 decimals of precision. */ function getMinCollateral() external view returns (uint256) { return _MIN_COLLATERAL_; } /** * @notice Gets the status of whether final-settlement was initiated by the Admin. * * @return True if final-settlement was enabled, false otherwise. */ function getFinalSettlementEnabled() external view returns (bool) { return _FINAL_SETTLEMENT_ENABLED_; } // ============ Public Getters ============ /** * @notice Gets whether an address has permissions to operate an account. * * @param account The account to query. * @param operator The address to query. * @return True if the operator has permission to operate the account, * and false otherwise. */ function hasAccountPermissions( address account, address operator ) public view returns (bool) { return account == operator || _GLOBAL_OPERATORS_[operator] || _LOCAL_OPERATORS_[account][operator]; } } // File: contracts/protocol/v1/impl/P1Margin.sol /** * @title P1Margin * @author dYdX * * @notice Contract for withdrawing and depositing. */ contract P1Margin is P1FinalSettlement, P1Getters { using P1BalanceMath for P1Types.Balance; // ============ Events ============ event LogDeposit( address indexed account, uint256 amount, bytes32 balance ); event LogWithdraw( address indexed account, address destination, uint256 amount, bytes32 balance ); // ============ Functions ============ /** * @notice Deposit some amount of margin tokens from the msg.sender into an account. * @dev Emits LogIndex, LogAccountSettled, and LogDeposit events. * * @param account The account for which to credit the deposit. * @param amount the amount of tokens to deposit. */ function deposit( address account, uint256 amount ) external noFinalSettlement nonReentrant { P1Types.Context memory context = _loadContext(); P1Types.Balance memory balance = _settleAccount(context, account); SafeERC20.safeTransferFrom( IERC20(_TOKEN_), msg.sender, address(this), amount ); balance.addToMargin(amount); _BALANCES_[account] = balance; emit LogDeposit( account, amount, balance.toBytes32() ); } /** * @notice Withdraw some amount of margin tokens from an account to a destination address. * @dev Emits LogIndex, LogAccountSettled, and LogWithdraw events. * * @param account The account for which to debit the withdrawal. * @param destination The address to which the tokens are transferred. * @param amount The amount of tokens to withdraw. */ function withdraw( address account, address destination, uint256 amount ) external noFinalSettlement nonReentrant { require( hasAccountPermissions(account, msg.sender), "sender does not have permission to withdraw" ); P1Types.Context memory context = _loadContext(); P1Types.Balance memory balance = _settleAccount(context, account); SafeERC20.safeTransfer( IERC20(_TOKEN_), destination, amount ); balance.subFromMargin(amount); _BALANCES_[account] = balance; require( _isCollateralized(context, balance), "account not collateralized" ); emit LogWithdraw( account, destination, amount, balance.toBytes32() ); } } // File: contracts/protocol/v1/impl/P1Operator.sol /** * @title P1Operator * @author dYdX * * @notice Contract for setting local operators for an account. */ contract P1Operator is P1Storage { // ============ Events ============ event LogSetLocalOperator( address indexed sender, address operator, bool approved ); // ============ Functions ============ /** * @notice Grants or revokes permission for another account to perform certain actions on behalf * of the sender. * @dev Emits the LogSetLocalOperator event. * * @param operator The account that is approved or disapproved. * @param approved True for approval, false for disapproval. */ function setLocalOperator( address operator, bool approved ) external { _LOCAL_OPERATORS_[msg.sender][operator] = approved; emit LogSetLocalOperator(msg.sender, operator, approved); } } // File: contracts/protocol/lib/Require.sol /** * @title Require * @author dYdX * * @dev Stringifies parameters to pretty-print revert messages. */ library Require { // ============ Constants ============ uint256 constant ASCII_ZERO = 0x30; // '0' uint256 constant ASCII_RELATIVE_ZERO = 0x57; // 'a' - 10 uint256 constant FOUR_BIT_MASK = 0xf; bytes23 constant ZERO_ADDRESS = 0x3a20307830303030303030302e2e2e3030303030303030; // ": 0x00000000...00000000" // ============ Library Functions ============ /** * @dev If the must condition is not true, reverts using a string combination of the reason and * the address. */ function that( bool must, string memory reason, address addr ) internal pure { if (!must) { revert(string(abi.encodePacked(reason, stringify(addr)))); } } // ============ Helper Functions ============ /** * @dev Returns a bytes array that is an ASCII string representation of the input address. * Returns " 0x", the first 4 bytes of the address in lowercase hex, "...", then the last 4 * bytes of the address in lowercase hex. */ function stringify( address input ) private pure returns (bytes memory) { // begin with ": 0x00000000...00000000" bytes memory result = abi.encodePacked(ZERO_ADDRESS); // initialize values uint256 z = uint256(input); uint256 shift1 = 8 * 20 - 4; uint256 shift2 = 8 * 4 - 4; // populate both sections in parallel for (uint256 i = 4; i < 12; i++) { result[i] = char(z >> shift1); // set char in first section result[i + 11] = char(z >> shift2); // set char in second section shift1 -= 4; shift2 -= 4; } return result; } /** * @dev Returns the ASCII hex character representing the last four bits of the input (0-9a-f). */ function char( uint256 input ) private pure returns (byte) { uint256 b = input & FOUR_BIT_MASK; return byte(uint8(b + ((b < 10) ? ASCII_ZERO : ASCII_RELATIVE_ZERO))); } } // File: contracts/protocol/v1/intf/I_P1Trader.sol /** * @title I_P1Trader * @author dYdX * * @notice Interface that PerpetualV1 Traders must implement. */ interface I_P1Trader { /** * @notice Returns the result of the trade between the maker and the taker. Expected to be * called by PerpetualV1. Reverts if the trade is disallowed. * * @param sender The address that called the `trade()` function of PerpetualV1. * @param maker The address of the passive maker account. * @param taker The address of the active taker account. * @param price The current oracle price of the underlying asset. * @param data Arbitrary data passed in to the `trade()` function of PerpetualV1. * @param traderFlags Any flags that have been set by other I_P1Trader contracts during the * same call to the `trade()` function of PerpetualV1. * @return The result of the trade from the perspective of the taker. */ function trade( address sender, address maker, address taker, uint256 price, bytes calldata data, bytes32 traderFlags ) external returns(P1Types.TradeResult memory); } // File: contracts/protocol/v1/impl/P1Trade.sol /** * @title P1Trade * @author dYdX * * @notice Contract for settling trades between two accounts. A "trade" in this context may refer * to any approved transfer of balances, as determined by the smart contracts implementing the * I_P1Trader interface and approved as global operators on the PerpetualV1 contract. */ contract P1Trade is P1FinalSettlement { using SafeMath for uint120; using P1BalanceMath for P1Types.Balance; // ============ Structs ============ struct TradeArg { uint256 takerIndex; uint256 makerIndex; address trader; bytes data; } // ============ Events ============ event LogTrade( address indexed maker, address indexed taker, address trader, uint256 marginAmount, uint256 positionAmount, bool isBuy, // from taker's perspective bytes32 makerBalance, bytes32 takerBalance ); // ============ Functions ============ /** * @notice Submits one or more trades between any number of accounts. * @dev Emits the LogIndex event, one LogAccountSettled event for each account in `accounts`, * and the LogTrade event for each trade in `trades`. * * @param accounts The sorted list of accounts that are involved in trades. * @param trades The list of trades to execute in-order. */ function trade( address[] memory accounts, TradeArg[] memory trades ) public noFinalSettlement nonReentrant { _verifyAccounts(accounts); P1Types.Context memory context = _loadContext(); P1Types.Balance[] memory initialBalances = _settleAccounts(context, accounts); P1Types.Balance[] memory currentBalances = new P1Types.Balance[](initialBalances.length); uint256 i; for (i = 0; i < initialBalances.length; i++) { currentBalances[i] = initialBalances[i].copy(); } bytes32 traderFlags = 0; for (i = 0; i < trades.length; i++) { TradeArg memory tradeArg = trades[i]; require( _GLOBAL_OPERATORS_[tradeArg.trader], "trader is not global operator" ); address maker = accounts[tradeArg.makerIndex]; address taker = accounts[tradeArg.takerIndex]; P1Types.TradeResult memory tradeResult = I_P1Trader(tradeArg.trader).trade( msg.sender, maker, taker, context.price, tradeArg.data, traderFlags ); traderFlags |= tradeResult.traderFlags; // If the accounts are equal, no need to update balances. if (maker == taker) { continue; } // Modify currentBalances in-place. Note that `isBuy` is from the taker's perspective. P1Types.Balance memory makerBalance = currentBalances[tradeArg.makerIndex]; P1Types.Balance memory takerBalance = currentBalances[tradeArg.takerIndex]; if (tradeResult.isBuy) { makerBalance.addToMargin(tradeResult.marginAmount); makerBalance.subFromPosition(tradeResult.positionAmount); takerBalance.subFromMargin(tradeResult.marginAmount); takerBalance.addToPosition(tradeResult.positionAmount); } else { makerBalance.subFromMargin(tradeResult.marginAmount); makerBalance.addToPosition(tradeResult.positionAmount); takerBalance.addToMargin(tradeResult.marginAmount); takerBalance.subFromPosition(tradeResult.positionAmount); } // Store the new balances in storage. _BALANCES_[maker] = makerBalance; _BALANCES_[taker] = takerBalance; emit LogTrade( maker, taker, tradeArg.trader, tradeResult.marginAmount, tradeResult.positionAmount, tradeResult.isBuy, makerBalance.toBytes32(), takerBalance.toBytes32() ); } _verifyAccountsFinalBalances( context, accounts, initialBalances, currentBalances ); } /** * @dev Verify that `accounts` contains at least one address and that the contents are unique. * We verify uniqueness by requiring that the array is sorted. */ function _verifyAccounts( address[] memory accounts ) private pure { require( accounts.length > 0, "Accounts must have non-zero length" ); // Check that accounts are unique address prevAccount = accounts[0]; for (uint256 i = 1; i < accounts.length; i++) { address account = accounts[i]; require( account > prevAccount, "Accounts must be sorted and unique" ); prevAccount = account; } } /** * Verify that account balances at the end of the tx are allowable given the initial balances. * * We require that for every account, either: * 1. The account meets the collateralization requirement; OR * 2. All of the following are true: * a) The absolute value of the account position has not increased; * b) The sign of the account position has not flipped positive to negative or vice-versa. * c) The account's collateralization ratio has not worsened; */ function _verifyAccountsFinalBalances( P1Types.Context memory context, address[] memory accounts, P1Types.Balance[] memory initialBalances, P1Types.Balance[] memory currentBalances ) private pure { for (uint256 i = 0; i < accounts.length; i++) { P1Types.Balance memory currentBalance = currentBalances[i]; (uint256 currentPos, uint256 currentNeg) = currentBalance.getPositiveAndNegativeValue(context.price); // See P1Settlement._isCollateralized(). bool isCollateralized = currentPos.mul(BaseMath.base()) >= currentNeg.mul(context.minCollateral); if (isCollateralized) { continue; } address account = accounts[i]; P1Types.Balance memory initialBalance = initialBalances[i]; (uint256 initialPos, uint256 initialNeg) = initialBalance.getPositiveAndNegativeValue(context.price); Require.that( currentPos != 0, "account is undercollateralized and has no positive value", account ); Require.that( currentBalance.position <= initialBalance.position, "account is undercollateralized and absolute position size increased", account ); // Note that currentBalance.position can't be zero at this point since that would imply // either currentPos is zero or the account is well-collateralized. Require.that( currentBalance.positionIsPositive == initialBalance.positionIsPositive, "account is undercollateralized and position changed signs", account ); Require.that( initialNeg != 0, "account is undercollateralized and was not previously", account ); // Note that at this point: // Absolute position size must have decreased and not changed signs. // Initial margin/position must be one of -/-, -/+, or +/-. // Current margin/position must now be either -/+ or +/-. // // Which implies one of the following [intial] -> [current] configurations: // [-/-] -> [+/-] // [-/+] -> [-/+] // [+/-] -> [+/-] // Check that collateralization increased. // In the case of [-/-] initial, initialPos == 0 so the following will pass. Otherwise: // at this point, either initialNeg and currentNeg represent the margin values, or // initialPos and currentPos do. Since the margin is multiplied by the base value in // getPositiveAndNegativeValue(), it is safe to use baseDivMul() to divide the margin // without any rounding. This is important to avoid the possibility of overflow. Require.that( currentBalance.positionIsPositive ? currentNeg.baseDivMul(initialPos) <= initialNeg.baseDivMul(currentPos) : initialPos.baseDivMul(currentNeg) <= currentPos.baseDivMul(initialNeg), "account is undercollateralized and collateralization decreased", account ); } } } // File: contracts/protocol/v1/PerpetualV1.sol /** * @title PerpetualV1 * @author dYdX * * @notice A market for a perpetual contract, a financial derivative which may be traded on margin * and which aims to closely track the spot price of an underlying asset. The underlying asset is * specified via the price oracle which reports its spot price. Tethering of the perpetual market * price is supported by a funding oracle which governs funding payments between longs and shorts. * @dev Main perpetual market implementation contract that inherits from other contracts. */ contract PerpetualV1 is P1FinalSettlement, P1Admin, P1Getters, P1Margin, P1Operator, P1Trade { // Non-colliding storage slot. bytes32 internal constant PERPETUAL_V1_INITIALIZE_SLOT = bytes32(uint256(keccak256("dYdX.PerpetualV1.initialize")) - 1); /** * @dev Once-only initializer function that replaces the constructor since this contract is * proxied. Uses a non-colliding storage slot to store if this version has been initialized. * @dev Can only be called once and can only be called by the admin of this contract. * * @param token The address of the token to use for margin-deposits. * @param oracle The address of the price oracle contract. * @param funder The address of the funder contract. * @param minCollateral The minimum allowed initial collateralization percentage. */ function initializeV1( address token, address oracle, address funder, uint256 minCollateral ) external onlyAdmin nonReentrant { // only allow initialization once require( Storage.load(PERPETUAL_V1_INITIALIZE_SLOT) == 0x0, "PerpetualV1 already initialized" ); Storage.store(PERPETUAL_V1_INITIALIZE_SLOT, bytes32(uint256(1))); _TOKEN_ = token; _ORACLE_ = oracle; _FUNDER_ = funder; _MIN_COLLATERAL_ = minCollateral; _GLOBAL_INDEX_ = P1Types.Index({ timestamp: uint32(block.timestamp), isPositive: false, value: 0 }); } }
Sets a new value for the minimum collateralization percentage. Must be called by the PerpetualV1 admin. Emits the LogSetMinCollateral event. minCollateral The new value of the minimum initial collateralization percentage, as a fixed-point number with 18 decimals./
function setMinCollateral( uint256 minCollateral ) external onlyAdmin nonReentrant { require( minCollateral >= BaseMath.base(), "The collateral requirement cannot be under 100%" ); _MIN_COLLATERAL_ = minCollateral; emit LogSetMinCollateral(minCollateral); }
6,439,071
./full_match/1/0xDda46bF18eeb3E06E2F12975A3A184e40581A72f/sources/_prb/math/src/ud60x18/Casting.sol
Casts an UD60x18 number into uint128. This is basically a functional alias for the `unwrap` function.
function intoUint256(UD60x18 x) pure returns (uint256 result) { result = UD60x18.unwrap(x); }
3,094,347
// SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; interface IUTUToken { function mint(address to, uint256 amount) external; function burn(uint256 amount) external; } contract Distributor is Ownable { using SafeMath for uint256; // Use a global counter so batches when distributing cannot overlap. uint256 private idx; address public utuToken; uint256 public toMint; uint256 public distributeAfter; bool public assigned; struct Contributor { address addr; uint256 amount; } Contributor[] public contribs; constructor( address _utuToken, uint256 _toMint, uint256 _distributeAfter ) public { utuToken = _utuToken; toMint = _toMint; distributeAfter = _distributeAfter; } function assign( address[] memory _contributors, uint256[] memory _balances ) onlyOwner public { require(!assigned, "UTU: assigned"); require(_contributors.length == _balances.length, "UTU: mismatching array lengths"); for (uint32 i = 0 ; i < _contributors.length; i++) { Contributor memory c = Contributor(_contributors[i], _balances[i]); toMint = toMint.sub(c.amount); // Will throw on underflow contribs.push(c); } } function assignDone() onlyOwner public { assigned = true; } function distribute(uint256 _to) public { require(assigned, "UTU: !assigned"); require(block.timestamp > distributeAfter, "UTU: still locked"); require(_to < contribs.length, "UTU: out of range"); for (; idx <= _to; idx++) { IUTUToken(utuToken).mint(contribs[idx].addr, contribs[idx].amount); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.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. * * 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 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 { 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; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.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; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.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. */ 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; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/cryptography/ECDSA.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/math/Math.sol"; import "@nomiclabs/buidler/console.sol"; /** * @title The Sale contract. * * For the UTU crowdsale, participants first need to go through KYC after which * they are allowed to exchange USDT for UTU tokens at a fixed price. Each * participant is only allowed to exchange <= 500 USDT. * * A Successful KYC check will grant the user a signature which the contract * uses for authorization. We impose a limit of only one purchase per address. * */ interface IUTUToken { function mint(address to, uint256 amount) external; function burn(uint256 amount) external; } contract Sale is Ownable { using SafeERC20 for ERC20; using SafeMath for uint256; using ECDSA for bytes32; struct Cart { uint256 amount; bool checkedOut; } address public utuToken; ERC20 public usdt; address public kycAuthority; address public treasury; uint256 public startTime; uint256 public endTime; // The following constants are all for the public sale. uint256 public maxContribution = 1242 * 10**6; // USDT uses 6 decimals. uint256 public minContribution = 200 * 10**6; uint256 public maxUSDT = 250000 * 10**6; // The sale is capped at 250000 USDT uint256 public maxUTU = 6250000 * 10**18; uint256 public utuPerUSDT = (6250000 / 250000) * 10**12; uint256 public usdtAvailable = maxUSDT; // Mapping from KYC address to withdrawal address. mapping(address => Cart) public publicContributors; // Private sale participants can claim their allocation after the public sale // finishes. bool public assigned; mapping(address => Cart) public privateContributors; event Contributed(address indexed kycAddress, address indexed sender, uint256 amount); event CheckOut(address indexed target, uint256 amount, bool indexed isPublic); /** * @param _utuToken address Token for sale * @param _usdt address USDT token used to contribute to sale * @param _kycAuthority address Address of the KYC signer * @param _treasury address Address of treasury receiving USDT * @param _startTime uint256 specifying the the starting time of the sale */ constructor( address _utuToken, ERC20 _usdt, address _kycAuthority, address _treasury, uint256 _startTime ) public { utuToken = _utuToken; usdt = _usdt; kycAuthority = _kycAuthority; treasury = _treasury; startTime = _startTime; endTime = startTime + 2 days; } /* * The KYC authority does sign(signHash(hash(kycAddr))) to authorize the * given address. Someone could front-run us here and use the signature * to buy. This is not a problem because the tokens will be minted to the * kycAddr and thus the front-runner would just give us free tokens. * * @param _kycAddr address provided during kyc and receiver of tokens * @param amount uint256 USDT to be exchanged for UTU * @param signature bytes signature provided by the KYC authority * */ function buy(address _kycAddr, uint256 amount, bytes memory signature) public { require(usdtAvailable > 0, 'UTU: no more UTU token available'); require(isActive(), 'UTU: sale is not active'); if (!isUncapped()) { require(amount <= maxContribution, 'UTU: above individual cap'); require(publicContributors[_kycAddr].amount == 0, 'UTU: already bought'); } require(amount >= minContribution, 'UTU: below individual floor'); uint256 _usdtActual = amount > usdtAvailable ? usdtAvailable : amount; uint256 out = usdtToUTU(_usdtActual); usdtAvailable = usdtAvailable.sub(_usdtActual); bytes32 eh = keccak256(abi.encodePacked(_kycAddr)).toEthSignedMessageHash(); require(ECDSA.recover(eh, signature) == kycAuthority, 'UTU: invalid signature'); publicContributors[_kycAddr].amount = publicContributors[_kycAddr].amount.add(out); usdt.safeTransferFrom(msg.sender, treasury, _usdtActual); emit Contributed(_kycAddr, msg.sender, out); } /* * After the public sale finishes anyone can mint for a given kycAddr, since * funds are sent to that address and not the caller of the function. * * @param kycAddr address to mint tokens to. */ function checkoutPublic(address _kycAddr) public { require(block.timestamp > endTime, 'UTU: can only check out after sale'); require(publicContributors[_kycAddr].amount > 0, 'UTU: no public allocation'); require(!publicContributors[_kycAddr].checkedOut, 'UTU: already checked out'); publicContributors[_kycAddr].checkedOut = true; IUTUToken(utuToken).mint(_kycAddr, publicContributors[_kycAddr].amount); emit CheckOut(_kycAddr, publicContributors[_kycAddr].amount, true); } /** * Assign the amounts for the private sale participants. * * @param _contributors Address[] All the private contributor addresses * @param _balances uint256[] All the private contributor balances */ function assignPrivate( address[] memory _contributors, uint256[] memory _balances ) onlyOwner public { require(!assigned, "UTU: already assigned private sale"); require(_contributors.length == _balances.length, "UTU: mismatching array lengths"); for (uint32 i = 0 ; i < _contributors.length; i++) { require(privateContributors[_contributors[i]].amount == 0, 'UTU: already assigned'); privateContributors[_contributors[i]] = Cart(_balances[i], false); } assigned = true; } /* * After the public sale finishes the private sale participants get their tokens * unlocked and can mint them. * */ function checkoutPrivate(address _target) public { require(block.timestamp > endTime, 'UTU: can only check out after sale'); require(privateContributors[_target].amount > 0, 'UTU: no private allocation'); require(!privateContributors[_target].checkedOut, 'UTU: already checked out'); privateContributors[_target].checkedOut = true; IUTUToken(utuToken).mint(_target, privateContributors[_target].amount); emit CheckOut(_target, privateContributors[_target].amount, false); } /* * Calculate UTU allocation given USDT input. * * @param _usdtIn uint256 USDT to be converted to UTU. */ function usdtToUTU(uint256 _usdtIn) public view returns (uint256) { return _usdtIn.mul(utuPerUSDT); } /* * Calculate amount of UTU coins left for purchase. */ function utuAvailable() public view returns (uint256) { return usdtAvailable.mul(utuPerUSDT); } /* * Check whether the sale is active or not */ function isActive() public view returns (bool) { return block.timestamp >= startTime && block.timestamp < endTime; } /* * Check whether the cap on individual contributions is active. */ function isUncapped() public view returns (bool) { return block.timestamp > startTime + 1 hours; } /** * Recover tokens accidentally sent to the token contract. * @param _token address of the token to be recovered. 0x0 address will * recover ETH. * @param _to address Recipient of the recovered tokens * @param _balance uint256 Amount of tokens to be recovered */ function recoverTokens(address _token, address payable _to, uint256 _balance) onlyOwner external { require(_to != address(0), "cannot recover to zero address"); if (_token == address(0)) { // Recover Eth uint256 total = address(this).balance; uint256 balance = _balance == 0 ? total : Math.min(total, _balance); _to.transfer(balance); } else { uint256 total = ERC20(_token).balanceOf(address(this)); uint256 balance = _balance == 0 ? total : Math.min(total, _balance); ERC20(_token).safeTransfer(_to, balance); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @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. */ 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))) } // 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 (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { revert("ECDSA: invalid signature 's' value"); } if (v != 27 && v != 28) { revert("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)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.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; /** * @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.2; /** * @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); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "../../GSN/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.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 guidelines: functions revert instead * of 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 { 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) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @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; } /** * @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 {_setupDecimals} is * called. * * 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 returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view 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 * * - `to` 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 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 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 { } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.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); } } // SPDX-License-Identifier: MIT pragma solidity >= 0.4.22 <0.8.0; library console { address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67); function _sendLogPayload(bytes memory payload) private view { uint256 payloadLength = payload.length; address consoleAddress = CONSOLE_ADDRESS; assembly { let payloadStart := add(payload, 32) let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0) } } function log() internal view { _sendLogPayload(abi.encodeWithSignature("log()")); } function logInt(int p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(int)", p0)); } function logUint(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function logString(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function logBool(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function logAddress(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function logBytes(bytes memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes)", p0)); } function logByte(byte p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(byte)", p0)); } function logBytes1(bytes1 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0)); } function logBytes2(bytes2 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0)); } function logBytes3(bytes3 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0)); } function logBytes4(bytes4 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0)); } function logBytes5(bytes5 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0)); } function logBytes6(bytes6 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0)); } function logBytes7(bytes7 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0)); } function logBytes8(bytes8 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0)); } function logBytes9(bytes9 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0)); } function logBytes10(bytes10 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0)); } function logBytes11(bytes11 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0)); } function logBytes12(bytes12 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0)); } function logBytes13(bytes13 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0)); } function logBytes14(bytes14 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0)); } function logBytes15(bytes15 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0)); } function logBytes16(bytes16 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0)); } function logBytes17(bytes17 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0)); } function logBytes18(bytes18 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0)); } function logBytes19(bytes19 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0)); } function logBytes20(bytes20 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0)); } function logBytes21(bytes21 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0)); } function logBytes22(bytes22 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0)); } function logBytes23(bytes23 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0)); } function logBytes24(bytes24 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0)); } function logBytes25(bytes25 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0)); } function logBytes26(bytes26 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0)); } function logBytes27(bytes27 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0)); } function logBytes28(bytes28 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0)); } function logBytes29(bytes29 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0)); } function logBytes30(bytes30 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0)); } function logBytes31(bytes31 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0)); } function logBytes32(bytes32 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0)); } function log(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function log(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function log(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function log(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function log(uint p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1)); } function log(uint p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1)); } function log(uint p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1)); } function log(uint p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1)); } function log(string memory p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1)); } function log(string memory p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1)); } function log(string memory p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1)); } function log(string memory p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1)); } function log(bool p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1)); } function log(bool p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1)); } function log(bool p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1)); } function log(bool p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1)); } function log(address p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1)); } function log(address p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1)); } function log(address p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1)); } function log(address p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1)); } function log(uint p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2)); } function log(uint p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2)); } function log(uint p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2)); } function log(uint p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2)); } function log(uint p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2)); } function log(uint p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2)); } function log(uint p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2)); } function log(uint p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2)); } function log(uint p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2)); } function log(uint p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2)); } function log(uint p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2)); } function log(uint p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2)); } function log(uint p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2)); } function log(uint p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2)); } function log(uint p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2)); } function log(uint p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2)); } function log(string memory p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2)); } function log(string memory p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2)); } function log(string memory p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2)); } function log(string memory p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2)); } function log(string memory p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2)); } function log(string memory p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2)); } function log(string memory p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2)); } function log(string memory p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2)); } function log(string memory p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2)); } function log(string memory p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2)); } function log(string memory p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2)); } function log(string memory p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2)); } function log(string memory p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2)); } function log(string memory p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2)); } function log(string memory p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2)); } function log(string memory p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2)); } function log(bool p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2)); } function log(bool p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2)); } function log(bool p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2)); } function log(bool p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2)); } function log(bool p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2)); } function log(bool p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2)); } function log(bool p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2)); } function log(bool p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2)); } function log(bool p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2)); } function log(bool p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2)); } function log(bool p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2)); } function log(bool p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2)); } function log(bool p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2)); } function log(bool p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2)); } function log(bool p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2)); } function log(bool p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2)); } function log(address p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2)); } function log(address p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2)); } function log(address p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2)); } function log(address p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2)); } function log(address p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2)); } function log(address p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2)); } function log(address p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2)); } function log(address p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2)); } function log(address p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2)); } function log(address p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2)); } function log(address p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2)); } function log(address p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2)); } function log(address p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2)); } function log(address p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2)); } function log(address p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2)); } function log(address p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2)); } function log(uint p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3)); } } pragma solidity ^0.6.0; import "@openzeppelin/contracts/math/SafeMath.sol"; contract TetherMock { using SafeMath for uint; string public name; string public symbol; uint public decimals; uint public _totalSupply; uint constant MAX_UINT = 2**256 - 1; mapping (address => mapping (address => uint)) allowed; mapping(address => uint) balances; // additional variables for use if transaction fees ever became necessary uint public basisPointsRate = 0; uint public maximumFee = 0; event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); // Called when new token are issued event Issue(uint amount); // Called when tokens are redeemed event Redeem(uint amount); // Called when contract is deprecated event Deprecate(address newAddress); // Called if contract ever adds fees event Params(uint feeBasisPoints, uint maxFee); // The contract can be initialized with a number of tokens // All the tokens are deposited to the owner address // // @param _balance Initial supply of the contract // @param _name Token Name // @param _symbol Token symbol // @param _decimals Token decimals constructor(uint _initialSupply) public { _totalSupply = _initialSupply; balances[msg.sender] = balances[msg.sender].add(_initialSupply); name = 'USDT'; symbol = 'USDT'; decimals = 6; } function transferFrom(address _from, address _to, uint _value) public { uint256 _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; uint fee = (_value.mul(basisPointsRate)).div(10000); if (fee > maximumFee) { fee = maximumFee; } uint sendAmount = _value.sub(fee); balances[_to] = balances[_to].add(sendAmount); balances[_from] = balances[_from].sub(_value); if (_allowance < MAX_UINT) { allowed[_from][msg.sender] = _allowance.sub(_value); } Transfer(_from, _to, sendAmount); } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return balance An uint representing the amount owned by the passed address. */ function balanceOf(address _owner) view public returns (uint balance) { return balances[_owner]; } /** * @dev Approve 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, uint _value) public { // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require(!((_value != 0) && (allowed[msg.sender][_spender] != 0))); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); } /** * @dev Function to check the amount of tokens than 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 remaining A uint specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) view public returns (uint remaining) { return allowed[_owner][_spender]; } // deprecate current contract if favour of a new one function totalSupply() view public returns (uint){ 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, uint _value) public { uint fee = (_value.mul(basisPointsRate)).div(10000); if (fee > maximumFee) { fee = maximumFee; } uint sendAmount = _value.sub(fee); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(sendAmount); Transfer(msg.sender, _to, sendAmount); } // Issue a new amount of tokens // these tokens are deposited into the owner address // // @param _amount Number of tokens to be issued function issue(address _to, uint amount) public { balances[_to] += amount; _totalSupply += amount; Issue(amount); } // Redeem tokens. // These tokens are withdrawn from the owner address // if the balance must be enough to cover the redeem // or the call will fail. // @param _amount Number of tokens to be issued function redeem(address _from, uint amount) public { require(_totalSupply >= amount); _totalSupply -= amount; balances[_from] -= amount; Redeem(amount); } }
transfer token for a specified address _to The address to transfer to. _value The amount to be transferred./
function transfer(address _to, uint _value) public { uint fee = (_value.mul(basisPointsRate)).div(10000); if (fee > maximumFee) { fee = maximumFee; } uint sendAmount = _value.sub(fee); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(sendAmount); Transfer(msg.sender, _to, sendAmount); }
169,573
pragma solidity 0.4.24; interface iERC20 { function totalSupply() external constant returns (uint256 supply); function balanceOf(address owner) external constant returns (uint256 balance); function transfer(address to, uint tokens) external returns (bool success); } /// @title buying tokens with eth. /// @dev This contract must be created with the address of the token to sell. /// This contract must also own some quantity of the token it's selling. /// Note: This is not meant to be feature complete. contract MeerkatICO { iERC20 token; address owner; address tokenCo; uint rateMe; modifier ownerOnly() { require(msg.sender == owner); _; } // @notice Initialises the contract. // @param _main The address of an ERC20 compatible token to sell. constructor(address _main) public { token = iERC20(_main); tokenCo = _main; owner = msg.sender; rateMe = 14400; } /// @notice Will transfer all ether in this account to the contract owner. function withdraw() public ownerOnly { owner.transfer(address(this).balance); } /// @notice This function will set the conversion rate. /// @dev To set a rate of 100 token / eth, you would make the rate 100 hopefully. /// @param _rateMe The conversion rate in a hole function setRate(uint _rateMe) public ownerOnly { rateMe = _rateMe; } function CurrentRate() public constant returns (uint rate) { return rateMe; } function TokenLinked() public constant returns (address _token, uint _amountLeft) { return (tokenCo, (token.balanceOf(address(this)) / 10**18)) ; } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public ownerOnly returns (bool success) { return iERC20(tokenAddress).transfer(owner, tokens); } /// @notice Any funds sent to this contract will be converted to the linked contract's tokens /// @dev This function receives funds, and transfers tokens based on the current conversion rate function () public payable { // minimum contribution is 0.1 ETH // STOP selling if the rate is set to 0 require( (msg.value >= 100000000000000000) && (rateMe != 0) ); uint value = msg.value * rateMe; // Overflow detection/protection: require(value/msg.value == rateMe); token.transfer(msg.sender, value); } }
Will transfer all ether in this account to the contract owner.
function withdraw() public ownerOnly { owner.transfer(address(this).balance); }
1,452,150
./full_match/80001/0x92114416F7029740a8aC1193CAA97541Fa0C7B6F/sources/contracts/Catalog.sol
/ Emit event to track ContentURI
function mint(TokenData memory _data, ContentData memory _content) public onlyOwner returns (uint256) { require(_data.royaltyBPS < 10000, "royalty !< 10000"); uint256 tokenId = _tokenIdCounter.current(); _mint(msg.sender, tokenId); tokenData[tokenId] = _data; emit ContentUpdated(tokenId, _content.contentHash, _content.contentURI); _tokenIdCounter.increment(); return tokenId; }
5,649,763
./full_match/56/0x1a817F1D4E8a4CDd40b4c28F25e565e041954709/sources/project_/contracts/BEP20/__LEXToken.sol
Function to stop minting new tokens. NOTE: restricting access to owner only. See {BEP20Mintable-finishMinting}./
function _finishMinting() internal override onlyOwner { super._finishMinting(); } using Arrays for uint256[]; using Counters for Counters.Counter;
3,243,615
/** * Copyright 2017-2020, bZeroX, LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0. */ pragma solidity 0.5.17; pragma experimental ABIEncoderV2; interface IWeth { function deposit() external payable; function withdraw(uint256 wad) external; } contract IERC20 { string public name; uint8 public decimals; string public symbol; function totalSupply() public view returns (uint256); function balanceOf(address _who) public view returns (uint256); function allowance(address _owner, address _spender) public view returns (uint256); function approve(address _spender, uint256 _value) public returns (bool); function transfer(address _to, uint256 _value) public returns (bool); function transferFrom(address _from, address _to, uint256 _value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } contract IWethERC20 is IWeth, IERC20 {} contract Constants { uint256 internal constant WEI_PRECISION = 10**18; uint256 internal constant WEI_PERCENT_PRECISION = 10**20; uint256 internal constant DAYS_IN_A_YEAR = 365; uint256 internal constant ONE_MONTH = 2628000; // approx. seconds in a month IWethERC20 public constant wethToken = IWethERC20(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); address public constant bzrxTokenAddress = 0x56d811088235F11C8920698a204A5010a788f4b3; address public constant vbzrxTokenAddress = 0xB72B31907C1C95F3650b64b2469e08EdACeE5e8F; } /** * @dev Library for managing loan sets * * 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. * * Include with `using EnumerableBytes32Set for EnumerableBytes32Set.Bytes32Set;`. * */ library EnumerableBytes32Set { struct Bytes32Set { // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) index; bytes32[] values; } /** * @dev Add an address value to a set. O(1). * Returns false if the value was already in the set. */ function addAddress(Bytes32Set storage set, address addrvalue) internal returns (bool) { bytes32 value; assembly { value := addrvalue } return addBytes32(set, value); } /** * @dev Add a value to a set. O(1). * Returns false if the value was already in the set. */ function addBytes32(Bytes32Set storage set, bytes32 value) internal returns (bool) { if (!contains(set, value)){ set.index[value] = set.values.push(value); return true; } else { return false; } } /** * @dev Removes an address value from a set. O(1). * Returns false if the value was not present in the set. */ function removeAddress(Bytes32Set storage set, address addrvalue) internal returns (bool) { bytes32 value; assembly { value := addrvalue } return removeBytes32(set, value); } /** * @dev Removes a value from a set. O(1). * Returns false if the value was not present in the set. */ function removeBytes32(Bytes32Set storage set, bytes32 value) internal returns (bool) { if (contains(set, value)){ uint256 toDeleteIndex = set.index[value] - 1; uint256 lastIndex = set.values.length - 1; // If the element we're deleting is the last one, we can just remove it without doing a swap if (lastIndex != toDeleteIndex) { bytes32 lastValue = set.values[lastIndex]; // Move the last value to the index where the deleted value is set.values[toDeleteIndex] = lastValue; // Update the index for the moved value set.index[lastValue] = toDeleteIndex + 1; // All indexes are 1-based } // Delete the index entry for the deleted value delete set.index[value]; // Delete the old entry for the moved value set.values.pop(); return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return set.index[value] != 0; } /** * @dev Returns true if the value is in the set. O(1). */ function containsAddress(Bytes32Set storage set, address addrvalue) internal view returns (bool) { bytes32 value; assembly { value := addrvalue } return set.index[value] != 0; } /** * @dev Returns an array with all values in the set. O(N). * 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. * WARNING: This function may run out of gas on large sets: use {length} and * {get} instead in these cases. */ function enumerate(Bytes32Set storage set, uint256 start, uint256 count) internal view returns (bytes32[] memory output) { uint256 end = start + count; require(end >= start, "addition overflow"); end = set.values.length < end ? set.values.length : end; if (end == 0 || start >= end) { return output; } output = new bytes32[](end-start); for (uint256 i = start; i < end; i++) { output[i-start] = set.values[i]; } return output; } /** * @dev Returns the number of elements on the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return set.values.length; } /** @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 get(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return set.values[index]; } /** @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 getAddress(Bytes32Set storage set, uint256 index) internal view returns (address) { bytes32 value = set.values[index]; address addrvalue; assembly { addrvalue := value } return addrvalue; } } /** * @title Helps contracts guard against reentrancy attacks. * @author Remco Bloemen <remco@2π.com>, Eenae <[email protected]> * @dev If you mark a function `nonReentrant`, you should also * mark it `external`. */ contract ReentrancyGuard { /// @dev Constant for unlocked guard state - non-zero to prevent extra gas costs. /// See: https://github.com/OpenZeppelin/openzeppelin-solidity/issues/1056 uint256 internal constant REENTRANCY_GUARD_FREE = 1; /// @dev Constant for locked guard state uint256 internal constant REENTRANCY_GUARD_LOCKED = 2; /** * @dev We use a single lock for the whole contract. */ uint256 internal reentrancyLock = REENTRANCY_GUARD_FREE; /** * @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() { require(reentrancyLock == REENTRANCY_GUARD_FREE, "nonReentrant"); reentrancyLock = REENTRANCY_GUARD_LOCKED; _; reentrancyLock = REENTRANCY_GUARD_FREE; } } /* * @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; } } /** * @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 { 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(isOwner(), "unauthorized"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return _msgSender() == _owner; } /** * @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; } } /** * @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 Integer division of two numbers, rounding up and truncating the quotient */ function divCeil(uint256 a, uint256 b) internal pure returns (uint256) { return divCeil(a, b, "SafeMath: division by zero"); } /** * @dev Integer division of two numbers, rounding up and truncating the quotient */ function divCeil(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b != 0, errorMessage); if (a == 0) { return 0; } uint256 c = ((a - 1) / b) + 1; 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; } function min256(uint256 _a, uint256 _b) internal pure returns (uint256) { return _a < _b ? _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) { // 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 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 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"); } } /** * @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"); } } } contract LoanStruct { struct Loan { bytes32 id; // id of the loan bytes32 loanParamsId; // the linked loan params id bytes32 pendingTradesId; // the linked pending trades id uint256 principal; // total borrowed amount outstanding uint256 collateral; // total collateral escrowed for the loan uint256 startTimestamp; // loan start time uint256 endTimestamp; // for active loans, this is the expected loan end time, for in-active loans, is the actual (past) end time uint256 startMargin; // initial margin when the loan opened uint256 startRate; // reference rate when the loan opened for converting collateralToken to loanToken address borrower; // borrower of this loan address lender; // lender of this loan bool active; // if false, the loan has been fully closed } } contract LoanParamsStruct { struct LoanParams { bytes32 id; // id of loan params object bool active; // if false, this object has been disabled by the owner and can't be used for future loans address owner; // owner of this object address loanToken; // the token being loaned address collateralToken; // the required collateral token uint256 minInitialMargin; // the minimum allowed initial margin uint256 maintenanceMargin; // an unhealthy loan when current margin is at or below this value uint256 maxLoanTerm; // the maximum term for new loans (0 means there's no max term) } } contract OrderStruct { struct Order { uint256 lockedAmount; // escrowed amount waiting for a counterparty uint256 interestRate; // interest rate defined by the creator of this order uint256 minLoanTerm; // minimum loan term allowed uint256 maxLoanTerm; // maximum loan term allowed uint256 createdTimestamp; // timestamp when this order was created uint256 expirationTimestamp; // timestamp when this order expires } } contract LenderInterestStruct { struct LenderInterest { uint256 principalTotal; // total borrowed amount outstanding of asset uint256 owedPerDay; // interest owed per day for all loans of asset uint256 owedTotal; // total interest owed for all loans of asset (assuming they go to full term) uint256 paidTotal; // total interest paid so far for asset uint256 updatedTimestamp; // last update } } contract LoanInterestStruct { struct LoanInterest { uint256 owedPerDay; // interest owed per day for loan uint256 depositTotal; // total escrowed interest for loan uint256 updatedTimestamp; // last update } } contract Objects is LoanStruct, LoanParamsStruct, OrderStruct, LenderInterestStruct, LoanInterestStruct {} contract State is Constants, Objects, ReentrancyGuard, Ownable { using SafeMath for uint256; using EnumerableBytes32Set for EnumerableBytes32Set.Bytes32Set; address public priceFeeds; // handles asset reference price lookups address public swapsImpl; // handles asset swaps using dex liquidity mapping (bytes4 => address) public logicTargets; // implementations of protocol functions mapping (bytes32 => Loan) public loans; // loanId => Loan mapping (bytes32 => LoanParams) public loanParams; // loanParamsId => LoanParams mapping (address => mapping (bytes32 => Order)) public lenderOrders; // lender => orderParamsId => Order mapping (address => mapping (bytes32 => Order)) public borrowerOrders; // borrower => orderParamsId => Order mapping (bytes32 => mapping (address => bool)) public delegatedManagers; // loanId => delegated => approved // Interest mapping (address => mapping (address => LenderInterest)) public lenderInterest; // lender => loanToken => LenderInterest object mapping (bytes32 => LoanInterest) public loanInterest; // loanId => LoanInterest object // Internals EnumerableBytes32Set.Bytes32Set internal logicTargetsSet; // implementations set EnumerableBytes32Set.Bytes32Set internal activeLoansSet; // active loans set mapping (address => EnumerableBytes32Set.Bytes32Set) internal lenderLoanSets; // lender loans set mapping (address => EnumerableBytes32Set.Bytes32Set) internal borrowerLoanSets; // borrow loans set mapping (address => EnumerableBytes32Set.Bytes32Set) internal userLoanParamSets; // user loan params set address public feesController; // address controlling fee withdrawals uint256 public lendingFeePercent = 10 ether; // 10% fee // fee taken from lender interest payments mapping (address => uint256) public lendingFeeTokensHeld; // total interest fees received and not withdrawn per asset mapping (address => uint256) public lendingFeeTokensPaid; // total interest fees withdraw per asset (lifetime fees = lendingFeeTokensHeld + lendingFeeTokensPaid) uint256 public tradingFeePercent = 0.15 ether; // 0.15% fee // fee paid for each trade mapping (address => uint256) public tradingFeeTokensHeld; // total trading fees received and not withdrawn per asset mapping (address => uint256) public tradingFeeTokensPaid; // total trading fees withdraw per asset (lifetime fees = tradingFeeTokensHeld + tradingFeeTokensPaid) uint256 public borrowingFeePercent = 0.09 ether; // 0.09% fee // origination fee paid for each loan mapping (address => uint256) public borrowingFeeTokensHeld; // total borrowing fees received and not withdrawn per asset mapping (address => uint256) public borrowingFeeTokensPaid; // total borrowing fees withdraw per asset (lifetime fees = borrowingFeeTokensHeld + borrowingFeeTokensPaid) uint256 public protocolTokenHeld; // current protocol token deposit balance uint256 public protocolTokenPaid; // lifetime total payout of protocol token uint256 public affiliateFeePercent = 30 ether; // 30% fee share // fee share for affiliate program mapping (address => mapping (address => uint256)) public liquidationIncentivePercent; // percent discount on collateral for liquidators per loanToken and collateralToken mapping (address => address) public loanPoolToUnderlying; // loanPool => underlying mapping (address => address) public underlyingToLoanPool; // underlying => loanPool EnumerableBytes32Set.Bytes32Set internal loanPoolsSet; // loan pools set mapping (address => bool) public supportedTokens; // supported tokens for swaps uint256 public maxDisagreement = 5 ether; // % disagreement between swap rate and reference rate uint256 public sourceBufferPercent = 5 ether; // used to estimate kyber swap source amount uint256 public maxSwapSize = 1500 ether; // maximum supported swap size in ETH function _setTarget( bytes4 sig, address target) internal { logicTargets[sig] = target; if (target != address(0)) { logicTargetsSet.addBytes32(bytes32(sig)); } else { logicTargetsSet.removeBytes32(bytes32(sig)); } } } interface IPriceFeeds { function queryRate( address sourceToken, address destToken) external view returns (uint256 rate, uint256 precision); function queryPrecision( address sourceToken, address destToken) external view returns (uint256 precision); function queryReturn( address sourceToken, address destToken, uint256 sourceAmount) external view returns (uint256 destAmount); function checkPriceDisagreement( address sourceToken, address destToken, uint256 sourceAmount, uint256 destAmount, uint256 maxSlippage) external view returns (uint256 sourceToDestSwapRate); function amountInEth( address Token, uint256 amount) external view returns (uint256 ethAmount); function getMaxDrawdown( address loanToken, address collateralToken, uint256 loanAmount, uint256 collateralAmount, uint256 maintenanceMargin) external view returns (uint256); function getCurrentMarginAndCollateralSize( address loanToken, address collateralToken, uint256 loanAmount, uint256 collateralAmount) external view returns (uint256 currentMargin, uint256 collateralInEthAmount); function getCurrentMargin( address loanToken, address collateralToken, uint256 loanAmount, uint256 collateralAmount) external view returns (uint256 currentMargin, uint256 collateralToLoanRate); function shouldLiquidate( address loanToken, address collateralToken, uint256 loanAmount, uint256 collateralAmount, uint256 maintenanceMargin) external view returns (bool); function getFastGasPrice( address payToken) external view returns (uint256); } contract ProtocolTokenUser is State { using SafeERC20 for IERC20; function _withdrawProtocolToken( address receiver, uint256 amount) internal returns (address, uint256) { uint256 withdrawAmount = amount; uint256 tokenBalance = protocolTokenHeld; if (withdrawAmount > tokenBalance) { withdrawAmount = tokenBalance; } if (withdrawAmount == 0) { return (vbzrxTokenAddress, 0); } protocolTokenHeld = tokenBalance .sub(withdrawAmount); IERC20(vbzrxTokenAddress).safeTransfer( receiver, withdrawAmount ); return (vbzrxTokenAddress, withdrawAmount); } } contract FeesEvents { event PayLendingFee( address indexed payer, address indexed token, uint256 amount ); event PayTradingFee( address indexed payer, address indexed token, bytes32 indexed loanId, uint256 amount ); event PayBorrowingFee( address indexed payer, address indexed token, bytes32 indexed loanId, uint256 amount ); event EarnReward( address indexed receiver, address indexed token, bytes32 indexed loanId, uint256 amount ); } contract FeesHelper is State, ProtocolTokenUser, FeesEvents { using SafeERC20 for IERC20; // calculate trading fee function _getTradingFee( uint256 feeTokenAmount) internal view returns (uint256) { return feeTokenAmount .mul(tradingFeePercent) .divCeil(WEI_PERCENT_PRECISION); } // calculate loan origination fee function _getBorrowingFee( uint256 feeTokenAmount) internal view returns (uint256) { return feeTokenAmount .mul(borrowingFeePercent) .divCeil(WEI_PERCENT_PRECISION); } // settle trading fee function _payTradingFee( address user, bytes32 loanId, address feeToken, uint256 tradingFee) internal { if (tradingFee != 0) { tradingFeeTokensHeld[feeToken] = tradingFeeTokensHeld[feeToken] .add(tradingFee); emit PayTradingFee( user, feeToken, loanId, tradingFee ); _payFeeReward( user, loanId, feeToken, tradingFee ); } } // settle loan origination fee function _payBorrowingFee( address user, bytes32 loanId, address feeToken, uint256 borrowingFee) internal { if (borrowingFee != 0) { borrowingFeeTokensHeld[feeToken] = borrowingFeeTokensHeld[feeToken] .add(borrowingFee); emit PayBorrowingFee( user, feeToken, loanId, borrowingFee ); _payFeeReward( user, loanId, feeToken, borrowingFee ); } } // settle lender (interest) fee function _payLendingFee( address user, address feeToken, uint256 lendingFee) internal { if (lendingFee != 0) { lendingFeeTokensHeld[feeToken] = lendingFeeTokensHeld[feeToken] .add(lendingFee); emit PayLendingFee( user, feeToken, lendingFee ); //// NOTE: Lenders do not receive a fee reward //// } } // settles and pays borrowers based on the fees generated by their interest payments function _settleFeeRewardForInterestExpense( LoanInterest storage loanInterestLocal, bytes32 loanId, address feeToken, address user, uint256 interestTime) internal { uint256 updatedTimestamp = loanInterestLocal.updatedTimestamp; uint256 interestExpenseFee; if (updatedTimestamp != 0) { // this represents the fee generated by a borrower's interest payment interestExpenseFee = interestTime .sub(updatedTimestamp) .mul(loanInterestLocal.owedPerDay) .mul(lendingFeePercent) .div(1 days * WEI_PERCENT_PRECISION); } loanInterestLocal.updatedTimestamp = interestTime; if (interestExpenseFee != 0) { _payFeeReward( user, loanId, feeToken, interestExpenseFee ); } } // pay protocolToken reward to user function _payFeeReward( address user, bytes32 loanId, address feeToken, uint256 feeAmount) internal { // The protocol is designed to allow positions and loans to be closed, if for whatever reason // the price lookup is failing, returning 0, or is otherwise paused. Therefore, we allow this // call to fail silently, rather than revert, to allow the transaction to continue without a // BZRX token reward. uint256 rewardAmount; address _priceFeeds = priceFeeds; (bool success, bytes memory data) = _priceFeeds.staticcall( abi.encodeWithSelector( IPriceFeeds(_priceFeeds).queryReturn.selector, feeToken, bzrxTokenAddress, // price rewards using BZRX price rather than vesting token price feeAmount / 2 // 50% of fee value ) ); assembly { if eq(success, 1) { rewardAmount := mload(add(data, 32)) } } if (rewardAmount != 0) { address rewardToken; (rewardToken, rewardAmount) = _withdrawProtocolToken( user, rewardAmount ); if (rewardAmount != 0) { protocolTokenPaid = protocolTokenPaid .add(rewardAmount); emit EarnReward( user, rewardToken, loanId, rewardAmount ); } } } } contract VaultController is Constants { using SafeERC20 for IERC20; event VaultDeposit( address indexed asset, address indexed from, uint256 amount ); event VaultWithdraw( address indexed asset, address indexed to, uint256 amount ); function vaultEtherDeposit( address from, uint256 value) internal { IWethERC20 _wethToken = wethToken; _wethToken.deposit.value(value)(); emit VaultDeposit( address(_wethToken), from, value ); } function vaultEtherWithdraw( address to, uint256 value) internal { if (value != 0) { IWethERC20 _wethToken = wethToken; uint256 balance = address(this).balance; if (value > balance) { _wethToken.withdraw(value - balance); } Address.sendValue(to, value); emit VaultWithdraw( address(_wethToken), to, value ); } } function vaultDeposit( address token, address from, uint256 value) internal { if (value != 0) { IERC20(token).safeTransferFrom( from, address(this), value ); emit VaultDeposit( token, from, value ); } } function vaultWithdraw( address token, address to, uint256 value) internal { if (value != 0) { IERC20(token).safeTransfer( to, value ); emit VaultWithdraw( token, to, value ); } } function vaultTransfer( address token, address from, address to, uint256 value) internal { if (value != 0) { if (from == address(this)) { IERC20(token).safeTransfer( to, value ); } else { IERC20(token).safeTransferFrom( from, to, value ); } } } function vaultApprove( address token, address to, uint256 value) internal { if (value != 0 && IERC20(token).allowance(address(this), to) != 0) { IERC20(token).safeApprove(to, 0); } IERC20(token).safeApprove(to, value); } } contract InterestUser is State, VaultController, FeesHelper { using SafeERC20 for IERC20; function _payInterest( address lender, address interestToken) internal { LenderInterest storage lenderInterestLocal = lenderInterest[lender][interestToken]; uint256 interestOwedNow = 0; if (lenderInterestLocal.owedPerDay != 0 && lenderInterestLocal.updatedTimestamp != 0) { interestOwedNow = block.timestamp .sub(lenderInterestLocal.updatedTimestamp) .mul(lenderInterestLocal.owedPerDay) .div(1 days); lenderInterestLocal.updatedTimestamp = block.timestamp; if (interestOwedNow > lenderInterestLocal.owedTotal) interestOwedNow = lenderInterestLocal.owedTotal; if (interestOwedNow != 0) { lenderInterestLocal.paidTotal = lenderInterestLocal.paidTotal .add(interestOwedNow); lenderInterestLocal.owedTotal = lenderInterestLocal.owedTotal .sub(interestOwedNow); _payInterestTransfer( lender, interestToken, interestOwedNow ); } } else { lenderInterestLocal.updatedTimestamp = block.timestamp; } } function _payInterestTransfer( address lender, address interestToken, uint256 interestOwedNow) internal { uint256 lendingFee = interestOwedNow .mul(lendingFeePercent) .divCeil(WEI_PERCENT_PRECISION); _payLendingFee( lender, interestToken, lendingFee ); // transfers the interest to the lender, less the interest fee vaultWithdraw( interestToken, lender, interestOwedNow .sub(lendingFee) ); } } contract LiquidationHelper is State { function _getLiquidationAmounts( uint256 principal, uint256 collateral, uint256 currentMargin, uint256 maintenanceMargin, uint256 collateralToLoanRate, uint256 incentivePercent) internal view returns (uint256 maxLiquidatable, uint256 maxSeizable) { if (currentMargin > maintenanceMargin || collateralToLoanRate == 0) { return (maxLiquidatable, maxSeizable); } else if (currentMargin <= incentivePercent) { return (principal, collateral); } uint256 desiredMargin = maintenanceMargin .add(5 ether); // 5 percentage points above maintenance // maxLiquidatable = ((1 + desiredMargin)*principal - collateralToLoanRate*collateral) / (desiredMargin - incentivePercent) maxLiquidatable = desiredMargin .add(WEI_PERCENT_PRECISION) .mul(principal) .div(WEI_PERCENT_PRECISION); maxLiquidatable = maxLiquidatable .sub( collateral .mul(collateralToLoanRate) .div(WEI_PRECISION) ); maxLiquidatable = maxLiquidatable .mul(WEI_PERCENT_PRECISION) .div( desiredMargin .sub(incentivePercent) ); if (maxLiquidatable > principal) { maxLiquidatable = principal; } // maxSeizable = maxLiquidatable * (1 + incentivePercent) / collateralToLoanRate maxSeizable = maxLiquidatable .mul( incentivePercent .add(WEI_PERCENT_PRECISION) ); maxSeizable = maxSeizable .div(collateralToLoanRate) .div(100); if (maxSeizable > collateral) { maxSeizable = collateral; } return (maxLiquidatable, maxSeizable); } } contract SwapsEvents { event LoanSwap( bytes32 indexed loanId, address indexed sourceToken, address indexed destToken, address borrower, uint256 sourceAmount, uint256 destAmount ); event ExternalSwap( address indexed user, address indexed sourceToken, address indexed destToken, uint256 sourceAmount, uint256 destAmount ); } interface ISwapsImpl { function dexSwap( address sourceTokenAddress, address destTokenAddress, address receiverAddress, address returnToSenderAddress, uint256 minSourceTokenAmount, uint256 maxSourceTokenAmount, uint256 requiredDestTokenAmount) external returns (uint256 destTokenAmountReceived, uint256 sourceTokenAmountUsed); function dexExpectedRate( address sourceTokenAddress, address destTokenAddress, uint256 sourceTokenAmount) external view returns (uint256); } contract SwapsUser is State, SwapsEvents, FeesHelper { function _loanSwap( bytes32 loanId, address sourceToken, address destToken, address user, uint256 minSourceTokenAmount, uint256 maxSourceTokenAmount, uint256 requiredDestTokenAmount, bool bypassFee, bytes memory loanDataBytes) internal returns (uint256 destTokenAmountReceived, uint256 sourceTokenAmountUsed, uint256 sourceToDestSwapRate) { (destTokenAmountReceived, sourceTokenAmountUsed) = _swapsCall( [ sourceToken, destToken, address(this), // receiver address(this), // returnToSender user ], [ minSourceTokenAmount, maxSourceTokenAmount, requiredDestTokenAmount ], loanId, bypassFee, loanDataBytes ); // will revert if swap size too large _checkSwapSize(sourceToken, sourceTokenAmountUsed); // will revert if disagreement found sourceToDestSwapRate = IPriceFeeds(priceFeeds).checkPriceDisagreement( sourceToken, destToken, sourceTokenAmountUsed, destTokenAmountReceived, maxDisagreement ); emit LoanSwap( loanId, sourceToken, destToken, user, sourceTokenAmountUsed, destTokenAmountReceived ); } function _swapsCall( address[5] memory addrs, uint256[3] memory vals, bytes32 loanId, bool miscBool, // bypassFee bytes memory loanDataBytes) internal returns (uint256, uint256) { //addrs[0]: sourceToken //addrs[1]: destToken //addrs[2]: receiver //addrs[3]: returnToSender //addrs[4]: user //vals[0]: minSourceTokenAmount //vals[1]: maxSourceTokenAmount //vals[2]: requiredDestTokenAmount require(vals[0] != 0, "sourceAmount == 0"); uint256 destTokenAmountReceived; uint256 sourceTokenAmountUsed; uint256 tradingFee; if (!miscBool) { // bypassFee if (vals[2] == 0) { // condition: vals[0] will always be used as sourceAmount tradingFee = _getTradingFee(vals[0]); if (tradingFee != 0) { _payTradingFee( addrs[4], // user loanId, addrs[0], // sourceToken tradingFee ); vals[0] = vals[0] .sub(tradingFee); } } else { // condition: unknown sourceAmount will be used tradingFee = _getTradingFee(vals[2]); if (tradingFee != 0) { vals[2] = vals[2] .add(tradingFee); } } } if (vals[1] == 0) { vals[1] = vals[0]; } else { require(vals[0] <= vals[1], "min greater than max"); } require(loanDataBytes.length == 0, "invalid state"); (destTokenAmountReceived, sourceTokenAmountUsed) = _swapsCall_internal( addrs, vals ); if (vals[2] == 0) { // there's no minimum destTokenAmount, but all of vals[0] (minSourceTokenAmount) must be spent, and amount spent can't exceed vals[0] require(sourceTokenAmountUsed == vals[0], "swap too large to fill"); if (tradingFee != 0) { sourceTokenAmountUsed = sourceTokenAmountUsed + tradingFee; // will never overflow } } else { // there's a minimum destTokenAmount required, but sourceTokenAmountUsed won't be greater than vals[1] (maxSourceTokenAmount) require(sourceTokenAmountUsed <= vals[1], "swap fill too large"); require(destTokenAmountReceived >= vals[2], "insufficient swap liquidity"); if (tradingFee != 0) { _payTradingFee( addrs[4], // user loanId, // loanId, addrs[1], // destToken tradingFee ); destTokenAmountReceived = destTokenAmountReceived - tradingFee; // will never overflow } } return (destTokenAmountReceived, sourceTokenAmountUsed); } function _swapsCall_internal( address[5] memory addrs, uint256[3] memory vals) internal returns (uint256 destTokenAmountReceived, uint256 sourceTokenAmountUsed) { bytes memory data = abi.encodeWithSelector( ISwapsImpl(swapsImpl).dexSwap.selector, addrs[0], // sourceToken addrs[1], // destToken addrs[2], // receiverAddress addrs[3], // returnToSenderAddress vals[0], // minSourceTokenAmount vals[1], // maxSourceTokenAmount vals[2] // requiredDestTokenAmount ); bool success; (success, data) = swapsImpl.delegatecall(data); require(success, "swap failed"); (destTokenAmountReceived, sourceTokenAmountUsed) = abi.decode(data, (uint256, uint256)); } function _swapsExpectedReturn( address sourceToken, address destToken, uint256 sourceTokenAmount) internal view returns (uint256) { uint256 tradingFee = _getTradingFee(sourceTokenAmount); if (tradingFee != 0) { sourceTokenAmount = sourceTokenAmount .sub(tradingFee); } uint256 sourceToDestRate = ISwapsImpl(swapsImpl).dexExpectedRate( sourceToken, destToken, sourceTokenAmount ); uint256 sourceToDestPrecision = IPriceFeeds(priceFeeds).queryPrecision( sourceToken, destToken ); return sourceTokenAmount .mul(sourceToDestRate) .div(sourceToDestPrecision); } function _checkSwapSize( address tokenAddress, uint256 amount) internal view { uint256 _maxSwapSize = maxSwapSize; if (_maxSwapSize != 0) { uint256 amountInEth; if (tokenAddress == address(wethToken)) { amountInEth = amount; } else { amountInEth = IPriceFeeds(priceFeeds).amountInEth(tokenAddress, amount); } require(amountInEth <= _maxSwapSize, "swap too large"); } } } interface ILoanPool { function tokenPrice() external view returns (uint256 price); function borrowInterestRate() external view returns (uint256); function totalAssetSupply() external view returns (uint256); } contract ITokenHolderLike { function balanceOf(address _who) public view returns (uint256); function freeUpTo(uint256 value) public returns (uint256); function freeFromUpTo(address from, uint256 value) public returns (uint256); } contract GasTokenUser { ITokenHolderLike constant public gasToken = ITokenHolderLike(0x0000000000004946c0e9F43F4Dee607b0eF1fA1c); ITokenHolderLike constant public tokenHolder = ITokenHolderLike(0x55Eb3DD3f738cfdda986B8Eff3fa784477552C61); modifier usesGasToken(address holder) { if (holder == address(0)) { holder = address(tokenHolder); } if (gasToken.balanceOf(holder) != 0) { uint256 gasCalcValue = gasleft(); _; gasCalcValue = (_gasUsed(gasCalcValue) + 14154) / 41947; if (holder == address(tokenHolder)) { tokenHolder.freeUpTo( gasCalcValue ); } else { tokenHolder.freeFromUpTo( holder, gasCalcValue ); } } else { _; } } function _gasUsed( uint256 startingGas) internal view returns (uint256) { return 21000 + startingGas - gasleft() + 16 * msg.data.length; } } contract LoanClosingsEvents { event CloseWithDeposit( address indexed user, address indexed lender, bytes32 indexed loanId, address closer, address loanToken, address collateralToken, uint256 repayAmount, uint256 collateralWithdrawAmount, uint256 collateralToLoanRate, uint256 currentMargin ); event CloseWithSwap( address indexed user, address indexed lender, bytes32 indexed loanId, address collateralToken, address loanToken, address closer, uint256 positionCloseSize, uint256 loanCloseAmount, uint256 exitPrice, // one unit of collateralToken, denominated in loanToken uint256 currentLeverage ); event Liquidate( address indexed user, address indexed liquidator, bytes32 indexed loanId, address lender, address loanToken, address collateralToken, uint256 repayAmount, uint256 collateralWithdrawAmount, uint256 collateralToLoanRate, uint256 currentMargin ); event Rollover( address indexed user, address indexed caller, bytes32 indexed loanId, address lender, address loanToken, address collateralToken, uint256 collateralAmountUsed, uint256 interestAmountAdded, uint256 loanEndTimestamp, uint256 gasRebate ); } contract LoanClosingsBase is State, LoanClosingsEvents, VaultController, InterestUser, GasTokenUser, SwapsUser, LiquidationHelper { enum CloseTypes { Deposit, Swap, Liquidation } function _liquidate( bytes32 loanId, address receiver, uint256 closeAmount) internal returns ( uint256 loanCloseAmount, uint256 seizedAmount, address seizedToken ) { Loan memory loanLocal = loans[loanId]; require(loanLocal.active, "loan is closed"); LoanParams memory loanParamsLocal = loanParams[loanLocal.loanParamsId]; (uint256 currentMargin, uint256 collateralToLoanRate) = IPriceFeeds(priceFeeds).getCurrentMargin( loanParamsLocal.loanToken, loanParamsLocal.collateralToken, loanLocal.principal, loanLocal.collateral ); require( currentMargin <= loanParamsLocal.maintenanceMargin, "healthy position" ); loanCloseAmount = closeAmount; (uint256 maxLiquidatable, uint256 maxSeizable) = _getLiquidationAmounts( loanLocal.principal, loanLocal.collateral, currentMargin, loanParamsLocal.maintenanceMargin, collateralToLoanRate, liquidationIncentivePercent[loanParamsLocal.loanToken][loanParamsLocal.collateralToken] ); if (loanCloseAmount < maxLiquidatable) { seizedAmount = maxSeizable .mul(loanCloseAmount) .div(maxLiquidatable); } else { if (loanCloseAmount > maxLiquidatable) { // adjust down the close amount to the max loanCloseAmount = maxLiquidatable; } seizedAmount = maxSeizable; } require(loanCloseAmount != 0, "nothing to liquidate"); // liquidator deposits the principal being closed _returnPrincipalWithDeposit( loanParamsLocal.loanToken, address(this), loanCloseAmount ); // a portion of the principal is repaid to the lender out of interest refunded uint256 loanCloseAmountLessInterest = _settleInterestToPrincipal( loanLocal, loanParamsLocal, loanCloseAmount, loanLocal.borrower ); if (loanCloseAmount > loanCloseAmountLessInterest) { // full interest refund goes to the borrower _withdrawAsset( loanParamsLocal.loanToken, loanLocal.borrower, loanCloseAmount - loanCloseAmountLessInterest ); } if (loanCloseAmountLessInterest != 0) { // The lender always gets back an ERC20 (even WETH), so we call withdraw directly rather than // use the _withdrawAsset helper function vaultWithdraw( loanParamsLocal.loanToken, loanLocal.lender, loanCloseAmountLessInterest ); } seizedToken = loanParamsLocal.collateralToken; if (seizedAmount != 0) { loanLocal.collateral = loanLocal.collateral .sub(seizedAmount); _withdrawAsset( seizedToken, receiver, seizedAmount ); } _emitClosingEvents( loanParamsLocal, loanLocal, loanCloseAmount, seizedAmount, collateralToLoanRate, 0, // collateralToLoanSwapRate currentMargin, CloseTypes.Liquidation ); _closeLoan( loanLocal, loanCloseAmount ); } function _rollover( bytes32 loanId, uint256 startingGas, bytes memory loanDataBytes) internal { Loan memory loanLocal = loans[loanId]; require(loanLocal.active, "loan is closed"); require( block.timestamp > loanLocal.endTimestamp.sub(1 hours), "healthy position" ); require( loanPoolToUnderlying[loanLocal.lender] != address(0), "invalid lender" ); LoanParams memory loanParamsLocal = loanParams[loanLocal.loanParamsId]; // pay outstanding interest to lender _payInterest( loanLocal.lender, loanParamsLocal.loanToken ); LoanInterest storage loanInterestLocal = loanInterest[loanLocal.id]; LenderInterest storage lenderInterestLocal = lenderInterest[loanLocal.lender][loanParamsLocal.loanToken]; _settleFeeRewardForInterestExpense( loanInterestLocal, loanLocal.id, loanParamsLocal.loanToken, loanLocal.borrower, block.timestamp ); // Handle back interest: calculates interest owned since the loan endtime passed but the loan remained open uint256 backInterestTime; uint256 backInterestOwed; if (block.timestamp > loanLocal.endTimestamp) { backInterestTime = block.timestamp .sub(loanLocal.endTimestamp); backInterestOwed = backInterestTime .mul(loanInterestLocal.owedPerDay); backInterestOwed = backInterestOwed .div(24 hours); } uint256 maxDuration = loanParamsLocal.maxLoanTerm; if (maxDuration != 0) { // fixed-term loan, so need to query iToken for latest variable rate uint256 owedPerDay = loanLocal.principal .mul(ILoanPool(loanLocal.lender).borrowInterestRate()) .div(DAYS_IN_A_YEAR * WEI_PERCENT_PRECISION); lenderInterestLocal.owedPerDay = lenderInterestLocal.owedPerDay .add(owedPerDay); lenderInterestLocal.owedPerDay = lenderInterestLocal.owedPerDay .sub(loanInterestLocal.owedPerDay); loanInterestLocal.owedPerDay = owedPerDay; } else { // loanInterestLocal.owedPerDay doesn't change maxDuration = ONE_MONTH; } if (backInterestTime >= maxDuration) { maxDuration = backInterestTime .add(24 hours); // adds an extra 24 hours } // update loan end time loanLocal.endTimestamp = loanLocal.endTimestamp .add(maxDuration); uint256 interestAmountRequired = loanLocal.endTimestamp .sub(block.timestamp); interestAmountRequired = interestAmountRequired .mul(loanInterestLocal.owedPerDay); interestAmountRequired = interestAmountRequired .div(24 hours); loanInterestLocal.depositTotal = loanInterestLocal.depositTotal .add(interestAmountRequired); lenderInterestLocal.owedTotal = lenderInterestLocal.owedTotal .add(interestAmountRequired); // add backInterestOwed interestAmountRequired = interestAmountRequired .add(backInterestOwed); // collect interest (,uint256 sourceTokenAmountUsed,) = _doCollateralSwap( loanLocal, loanParamsLocal, loanLocal.collateral, interestAmountRequired, true, // returnTokenIsCollateral loanDataBytes ); loanLocal.collateral = loanLocal.collateral .sub(sourceTokenAmountUsed); if (backInterestOwed != 0) { // pay out backInterestOwed _payInterestTransfer( loanLocal.lender, loanParamsLocal.loanToken, backInterestOwed ); } uint256 gasRebate = _getRebate( loanLocal, loanParamsLocal, startingGas ); if (gasRebate != 0) { // pay out gas rebate to caller // the preceeding logic should ensure gasRebate <= collateral, but just in case, will use SafeMath here loanLocal.collateral = loanLocal.collateral .sub(gasRebate, "gasRebate too high"); _withdrawAsset( loanParamsLocal.collateralToken, msg.sender, gasRebate ); } _rolloverEvent( loanLocal, loanParamsLocal, sourceTokenAmountUsed, interestAmountRequired, gasRebate ); loans[loanId] = loanLocal; } function _closeWithDeposit( bytes32 loanId, address receiver, uint256 depositAmount) // denominated in loanToken internal returns ( uint256 loanCloseAmount, uint256 withdrawAmount, address withdrawToken ) { require(depositAmount != 0, "depositAmount == 0"); Loan memory loanLocal = loans[loanId]; _checkAuthorized( loanLocal.id, loanLocal.active, loanLocal.borrower ); LoanParams memory loanParamsLocal = loanParams[loanLocal.loanParamsId]; // can't close more than the full principal loanCloseAmount = depositAmount > loanLocal.principal ? loanLocal.principal : depositAmount; uint256 loanCloseAmountLessInterest = _settleInterestToPrincipal( loanLocal, loanParamsLocal, loanCloseAmount, receiver ); if (loanCloseAmountLessInterest != 0) { _returnPrincipalWithDeposit( loanParamsLocal.loanToken, loanLocal.lender, loanCloseAmountLessInterest ); } if (loanCloseAmount == loanLocal.principal) { withdrawAmount = loanLocal.collateral; } else { withdrawAmount = loanLocal.collateral .mul(loanCloseAmount) .div(loanLocal.principal); } withdrawToken = loanParamsLocal.collateralToken; if (withdrawAmount != 0) { loanLocal.collateral = loanLocal.collateral - withdrawAmount; // overflow not possible _withdrawAsset( withdrawToken, receiver, withdrawAmount ); } _finalizeClose( loanLocal, loanParamsLocal, loanCloseAmount, withdrawAmount, // collateralCloseAmount 0, // collateralToLoanSwapRate CloseTypes.Deposit ); } function _closeWithSwap( bytes32 loanId, address receiver, uint256 swapAmount, bool returnTokenIsCollateral, bytes memory loanDataBytes) internal returns ( uint256 loanCloseAmount, uint256 withdrawAmount, address withdrawToken ) { require(swapAmount != 0, "swapAmount == 0"); Loan memory loanLocal = loans[loanId]; _checkAuthorized( loanLocal.id, loanLocal.active, loanLocal.borrower ); LoanParams memory loanParamsLocal = loanParams[loanLocal.loanParamsId]; if (swapAmount > loanLocal.collateral) { swapAmount = loanLocal.collateral; } loanCloseAmount = loanLocal.principal; if (swapAmount != loanLocal.collateral) { loanCloseAmount = loanCloseAmount .mul(swapAmount) .div(loanLocal.collateral); } require(loanCloseAmount != 0, "loanCloseAmount == 0"); uint256 loanCloseAmountLessInterest = _settleInterestToPrincipal( loanLocal, loanParamsLocal, loanCloseAmount, receiver ); uint256 usedCollateral; uint256 collateralToLoanSwapRate; (usedCollateral, withdrawAmount, collateralToLoanSwapRate) = _coverPrincipalWithSwap( loanLocal, loanParamsLocal, swapAmount, loanCloseAmountLessInterest, returnTokenIsCollateral, loanDataBytes ); if (loanCloseAmountLessInterest != 0) { // Repays principal to lender // The lender always gets back an ERC20 (even WETH), so we call withdraw directly rather than // use the _withdrawAsset helper function vaultWithdraw( loanParamsLocal.loanToken, loanLocal.lender, loanCloseAmountLessInterest ); } if (usedCollateral != 0) { loanLocal.collateral = loanLocal.collateral .sub(usedCollateral); } withdrawToken = returnTokenIsCollateral ? loanParamsLocal.collateralToken : loanParamsLocal.loanToken; if (withdrawAmount != 0) { _withdrawAsset( withdrawToken, receiver, withdrawAmount ); } _finalizeClose( loanLocal, loanParamsLocal, loanCloseAmount, usedCollateral, collateralToLoanSwapRate, CloseTypes.Swap ); } function _checkAuthorized( bytes32 _id, bool _active, address _borrower) internal view { require(_active, "loan is closed"); require( msg.sender == _borrower || delegatedManagers[_id][msg.sender], "unauthorized" ); } function _settleInterestToPrincipal( Loan memory loanLocal, LoanParams memory loanParamsLocal, uint256 loanCloseAmount, address receiver) internal returns (uint256) { uint256 loanCloseAmountLessInterest = loanCloseAmount; uint256 interestRefundToBorrower = _settleInterest( loanParamsLocal, loanLocal, loanCloseAmountLessInterest ); uint256 interestAppliedToPrincipal; if (loanCloseAmountLessInterest >= interestRefundToBorrower) { // apply all of borrower interest refund torwards principal interestAppliedToPrincipal = interestRefundToBorrower; // principal needed is reduced by this amount loanCloseAmountLessInterest -= interestRefundToBorrower; // no interest refund remaining interestRefundToBorrower = 0; } else { // principal fully covered by excess interest interestAppliedToPrincipal = loanCloseAmountLessInterest; // amount refunded is reduced by this amount interestRefundToBorrower -= loanCloseAmountLessInterest; // principal fully covered by excess interest loanCloseAmountLessInterest = 0; // refund overage _withdrawAsset( loanParamsLocal.loanToken, receiver, interestRefundToBorrower ); } if (interestAppliedToPrincipal != 0) { // The lender always gets back an ERC20 (even WETH), so we call withdraw directly rather than // use the _withdrawAsset helper function vaultWithdraw( loanParamsLocal.loanToken, loanLocal.lender, interestAppliedToPrincipal ); } return loanCloseAmountLessInterest; } // The receiver always gets back an ERC20 (even WETH) function _returnPrincipalWithDeposit( address loanToken, address receiver, uint256 principalNeeded) internal { if (principalNeeded != 0) { if (msg.value == 0) { vaultTransfer( loanToken, msg.sender, receiver, principalNeeded ); } else { require(loanToken == address(wethToken), "wrong asset sent"); require(msg.value >= principalNeeded, "not enough ether"); wethToken.deposit.value(principalNeeded)(); if (receiver != address(this)) { vaultTransfer( loanToken, address(this), receiver, principalNeeded ); } if (msg.value > principalNeeded) { // refund overage Address.sendValue( msg.sender, msg.value - principalNeeded ); } } } else { require(msg.value == 0, "wrong asset sent"); } } function _coverPrincipalWithSwap( Loan memory loanLocal, LoanParams memory loanParamsLocal, uint256 swapAmount, uint256 principalNeeded, bool returnTokenIsCollateral, bytes memory loanDataBytes) internal returns (uint256 usedCollateral, uint256 withdrawAmount, uint256 collateralToLoanSwapRate) { uint256 destTokenAmountReceived; uint256 sourceTokenAmountUsed; (destTokenAmountReceived, sourceTokenAmountUsed, collateralToLoanSwapRate) = _doCollateralSwap( loanLocal, loanParamsLocal, swapAmount, principalNeeded, returnTokenIsCollateral, loanDataBytes ); if (returnTokenIsCollateral) { if (destTokenAmountReceived > principalNeeded) { // better fill than expected, so send excess to borrower _withdrawAsset( loanParamsLocal.loanToken, loanLocal.borrower, destTokenAmountReceived - principalNeeded ); } withdrawAmount = swapAmount > sourceTokenAmountUsed ? swapAmount - sourceTokenAmountUsed : 0; } else { require(sourceTokenAmountUsed == swapAmount, "swap error"); withdrawAmount = destTokenAmountReceived - principalNeeded; } usedCollateral = sourceTokenAmountUsed > swapAmount ? sourceTokenAmountUsed : swapAmount; } function _doCollateralSwap( Loan memory loanLocal, LoanParams memory loanParamsLocal, uint256 swapAmount, uint256 principalNeeded, bool returnTokenIsCollateral, bytes memory loanDataBytes) internal returns (uint256 destTokenAmountReceived, uint256 sourceTokenAmountUsed, uint256 collateralToLoanSwapRate) { (destTokenAmountReceived, sourceTokenAmountUsed, collateralToLoanSwapRate) = _loanSwap( loanLocal.id, loanParamsLocal.collateralToken, loanParamsLocal.loanToken, loanLocal.borrower, swapAmount, // minSourceTokenAmount loanLocal.collateral, // maxSourceTokenAmount returnTokenIsCollateral ? principalNeeded : // requiredDestTokenAmount 0, false, // bypassFee loanDataBytes ); require(destTokenAmountReceived >= principalNeeded, "insufficient dest amount"); require(sourceTokenAmountUsed <= loanLocal.collateral, "excessive source amount"); } // withdraws asset to receiver function _withdrawAsset( address assetToken, address receiver, uint256 assetAmount) internal { if (assetAmount != 0) { if (assetToken == address(wethToken)) { vaultEtherWithdraw( receiver, assetAmount ); } else { vaultWithdraw( assetToken, receiver, assetAmount ); } } } function _finalizeClose( Loan memory loanLocal, LoanParams memory loanParamsLocal, uint256 loanCloseAmount, uint256 collateralCloseAmount, uint256 collateralToLoanSwapRate, CloseTypes closeType) internal { _closeLoan( loanLocal, loanCloseAmount ); address _priceFeeds = priceFeeds; uint256 currentMargin; uint256 collateralToLoanRate; // this is still called even with full loan close to return collateralToLoanRate (bool success, bytes memory data) = _priceFeeds.staticcall( abi.encodeWithSelector( IPriceFeeds(_priceFeeds).getCurrentMargin.selector, loanParamsLocal.loanToken, loanParamsLocal.collateralToken, loanLocal.principal, loanLocal.collateral ) ); assembly { if eq(success, 1) { currentMargin := mload(add(data, 32)) collateralToLoanRate := mload(add(data, 64)) } } //// Note: We can safely skip the margin check if closing via closeWithDeposit or if closing the loan in full by any method //// require( closeType == CloseTypes.Deposit || loanLocal.principal == 0 || // loan fully closed currentMargin > loanParamsLocal.maintenanceMargin, "unhealthy position" ); _emitClosingEvents( loanParamsLocal, loanLocal, loanCloseAmount, collateralCloseAmount, collateralToLoanRate, collateralToLoanSwapRate, currentMargin, closeType ); } function _closeLoan( Loan memory loanLocal, uint256 loanCloseAmount) internal returns (uint256) { require(loanCloseAmount != 0, "nothing to close"); if (loanCloseAmount == loanLocal.principal) { loanLocal.principal = 0; loanLocal.active = false; loanLocal.endTimestamp = block.timestamp; loanLocal.pendingTradesId = 0; activeLoansSet.removeBytes32(loanLocal.id); lenderLoanSets[loanLocal.lender].removeBytes32(loanLocal.id); borrowerLoanSets[loanLocal.borrower].removeBytes32(loanLocal.id); } else { loanLocal.principal = loanLocal.principal .sub(loanCloseAmount); } loans[loanLocal.id] = loanLocal; } function _settleInterest( LoanParams memory loanParamsLocal, Loan memory loanLocal, uint256 closePrincipal) internal returns (uint256) { // pay outstanding interest to lender _payInterest( loanLocal.lender, loanParamsLocal.loanToken ); LoanInterest storage loanInterestLocal = loanInterest[loanLocal.id]; LenderInterest storage lenderInterestLocal = lenderInterest[loanLocal.lender][loanParamsLocal.loanToken]; uint256 interestTime = block.timestamp; if (interestTime > loanLocal.endTimestamp) { interestTime = loanLocal.endTimestamp; } _settleFeeRewardForInterestExpense( loanInterestLocal, loanLocal.id, loanParamsLocal.loanToken, loanLocal.borrower, interestTime ); uint256 owedPerDayRefund; if (closePrincipal < loanLocal.principal) { owedPerDayRefund = loanInterestLocal.owedPerDay .mul(closePrincipal) .div(loanLocal.principal); } else { owedPerDayRefund = loanInterestLocal.owedPerDay; } // update stored owedPerDay loanInterestLocal.owedPerDay = loanInterestLocal.owedPerDay .sub(owedPerDayRefund); lenderInterestLocal.owedPerDay = lenderInterestLocal.owedPerDay .sub(owedPerDayRefund); // update borrower interest uint256 interestRefundToBorrower = loanLocal.endTimestamp .sub(interestTime); interestRefundToBorrower = interestRefundToBorrower .mul(owedPerDayRefund); interestRefundToBorrower = interestRefundToBorrower .div(24 hours); if (closePrincipal < loanLocal.principal) { loanInterestLocal.depositTotal = loanInterestLocal.depositTotal .sub(interestRefundToBorrower); } else { loanInterestLocal.depositTotal = 0; } // update remaining lender interest values lenderInterestLocal.principalTotal = lenderInterestLocal.principalTotal .sub(closePrincipal); uint256 owedTotal = lenderInterestLocal.owedTotal; lenderInterestLocal.owedTotal = owedTotal > interestRefundToBorrower ? owedTotal - interestRefundToBorrower : 0; return interestRefundToBorrower; } function _getRebate( Loan memory loanLocal, LoanParams memory loanParamsLocal, uint256 startingGas) internal returns (uint256 gasRebate) { // the amount of collateral drop needed to reach the maintenanceMargin level of the loan uint256 maxDrawdown = IPriceFeeds(priceFeeds).getMaxDrawdown( loanParamsLocal.loanToken, loanParamsLocal.collateralToken, loanLocal.principal, loanLocal.collateral, loanParamsLocal.maintenanceMargin ); require(maxDrawdown != 0, "unhealthy position"); // gets the gas rebate denominated in collateralToken gasRebate = SafeMath.mul( IPriceFeeds(priceFeeds).getFastGasPrice(loanParamsLocal.collateralToken) * 2, _gasUsed(startingGas) ); // ensures the gas rebate will not drop the current margin below the maintenance level gasRebate = gasRebate .min256(maxDrawdown); } function _rolloverEvent( Loan memory loanLocal, LoanParams memory loanParamsLocal, uint256 sourceTokenAmountUsed, uint256 interestAmountRequired, uint256 gasRebate) internal { emit Rollover( loanLocal.borrower, // user (borrower) msg.sender, // caller loanLocal.id, // loanId loanLocal.lender, // lender loanParamsLocal.loanToken, // loanToken loanParamsLocal.collateralToken, // collateralToken sourceTokenAmountUsed, // collateralAmountUsed interestAmountRequired, // interestAmountAdded loanLocal.endTimestamp, // loanEndTimestamp gasRebate // gasRebate ); } function _emitClosingEvents( LoanParams memory loanParamsLocal, Loan memory loanLocal, uint256 loanCloseAmount, uint256 collateralCloseAmount, uint256 collateralToLoanRate, uint256 collateralToLoanSwapRate, uint256 currentMargin, CloseTypes closeType) internal { if (closeType == CloseTypes.Deposit) { emit CloseWithDeposit( loanLocal.borrower, // user (borrower) loanLocal.lender, // lender loanLocal.id, // loanId msg.sender, // closer loanParamsLocal.loanToken, // loanToken loanParamsLocal.collateralToken, // collateralToken loanCloseAmount, // loanCloseAmount collateralCloseAmount, // collateralCloseAmount collateralToLoanRate, // collateralToLoanRate currentMargin // currentMargin ); } else if (closeType == CloseTypes.Swap) { // exitPrice = 1 / collateralToLoanSwapRate if (collateralToLoanSwapRate != 0) { collateralToLoanSwapRate = SafeMath.div(WEI_PRECISION * WEI_PRECISION, collateralToLoanSwapRate); } // currentLeverage = 100 / currentMargin if (currentMargin != 0) { currentMargin = SafeMath.div(10**38, currentMargin); } emit CloseWithSwap( loanLocal.borrower, // user (trader) loanLocal.lender, // lender loanLocal.id, // loanId loanParamsLocal.collateralToken, // collateralToken loanParamsLocal.loanToken, // loanToken msg.sender, // closer collateralCloseAmount, // positionCloseSize loanCloseAmount, // loanCloseAmount collateralToLoanSwapRate, // exitPrice (1 / collateralToLoanSwapRate) currentMargin // currentLeverage ); } else { // closeType == CloseTypes.Liquidation emit Liquidate( loanLocal.borrower, // user (borrower) msg.sender, // liquidator loanLocal.id, // loanId loanLocal.lender, // lender loanParamsLocal.loanToken, // loanToken loanParamsLocal.collateralToken, // collateralToken loanCloseAmount, // loanCloseAmount collateralCloseAmount, // collateralCloseAmount collateralToLoanRate, // collateralToLoanRate currentMargin // currentMargin ); } } } contract LoanClosingsWithGasToken is LoanClosingsBase { function initialize( address target) external onlyOwner { _setTarget(this.liquidateWithGasToken.selector, target); _setTarget(this.rolloverWithGasToken.selector, target); _setTarget(this.closeWithDepositWithGasToken.selector, target); _setTarget(this.closeWithSwapWithGasToken.selector, target); } function liquidateWithGasToken( bytes32 loanId, address receiver, address gasTokenUser, uint256 closeAmount) // denominated in loanToken external payable usesGasToken(gasTokenUser) nonReentrant returns ( uint256 loanCloseAmount, uint256 seizedAmount, address seizedToken ) { return _liquidate( loanId, receiver, closeAmount ); } function rolloverWithGasToken( bytes32 loanId, address gasTokenUser, bytes calldata /*loanDataBytes*/) // for future use external usesGasToken(gasTokenUser) nonReentrant { uint256 startingGas = 21000 + gasleft() + 16 * msg.data.length; // restrict to EOAs to prevent griefing attacks, during interest rate recalculation require(msg.sender == tx.origin, "only EOAs can call"); return _rollover( loanId, startingGas, "" // loanDataBytes ); } function closeWithDepositWithGasToken( bytes32 loanId, address receiver, address gasTokenUser, uint256 depositAmount) // denominated in loanToken public payable usesGasToken(gasTokenUser) nonReentrant returns ( uint256 loanCloseAmount, uint256 withdrawAmount, address withdrawToken ) { return _closeWithDeposit( loanId, receiver, depositAmount ); } function closeWithSwapWithGasToken( bytes32 loanId, address receiver, address gasTokenUser, uint256 swapAmount, // denominated in collateralToken bool returnTokenIsCollateral, // true: withdraws collateralToken, false: withdraws loanToken bytes memory /*loanDataBytes*/) // for future use public usesGasToken(gasTokenUser) nonReentrant returns ( uint256 loanCloseAmount, uint256 withdrawAmount, address withdrawToken ) { return _closeWithSwap( loanId, receiver, swapAmount, returnTokenIsCollateral, "" // loanDataBytes ); } }
pay outstanding interest to lender Handle back interest: calculates interest owned since the loan endtime passed but the loan remained open fixed-term loan, so need to query iToken for latest variable rate loanInterestLocal.owedPerDay doesn't change pay out backInterestOwed pay out gas rebate to caller the preceeding logic should ensure gasRebate <= collateral, but just in case, will use SafeMath here
function _rollover( bytes32 loanId, uint256 startingGas, bytes memory loanDataBytes) internal { Loan memory loanLocal = loans[loanId]; require(loanLocal.active, "loan is closed"); require( block.timestamp > loanLocal.endTimestamp.sub(1 hours), "healthy position" ); require( loanPoolToUnderlying[loanLocal.lender] != address(0), "invalid lender" ); LoanParams memory loanParamsLocal = loanParams[loanLocal.loanParamsId]; _payInterest( loanLocal.lender, loanParamsLocal.loanToken ); LoanInterest storage loanInterestLocal = loanInterest[loanLocal.id]; LenderInterest storage lenderInterestLocal = lenderInterest[loanLocal.lender][loanParamsLocal.loanToken]; _settleFeeRewardForInterestExpense( loanInterestLocal, loanLocal.id, loanParamsLocal.loanToken, loanLocal.borrower, block.timestamp ); uint256 backInterestTime; uint256 backInterestOwed; if (block.timestamp > loanLocal.endTimestamp) { backInterestTime = block.timestamp .sub(loanLocal.endTimestamp); backInterestOwed = backInterestTime .mul(loanInterestLocal.owedPerDay); backInterestOwed = backInterestOwed .div(24 hours); } uint256 maxDuration = loanParamsLocal.maxLoanTerm; if (maxDuration != 0) { uint256 owedPerDay = loanLocal.principal .mul(ILoanPool(loanLocal.lender).borrowInterestRate()) .div(DAYS_IN_A_YEAR * WEI_PERCENT_PRECISION); lenderInterestLocal.owedPerDay = lenderInterestLocal.owedPerDay .add(owedPerDay); lenderInterestLocal.owedPerDay = lenderInterestLocal.owedPerDay .sub(loanInterestLocal.owedPerDay); loanInterestLocal.owedPerDay = owedPerDay; maxDuration = ONE_MONTH; } if (backInterestTime >= maxDuration) { maxDuration = backInterestTime } .add(maxDuration); uint256 interestAmountRequired = loanLocal.endTimestamp .sub(block.timestamp); interestAmountRequired = interestAmountRequired .mul(loanInterestLocal.owedPerDay); interestAmountRequired = interestAmountRequired .div(24 hours); loanInterestLocal.depositTotal = loanInterestLocal.depositTotal .add(interestAmountRequired); lenderInterestLocal.owedTotal = lenderInterestLocal.owedTotal .add(interestAmountRequired); .add(backInterestOwed); loanLocal, loanParamsLocal, loanLocal.collateral, interestAmountRequired, loanDataBytes ); loanLocal.collateral = loanLocal.collateral .sub(sourceTokenAmountUsed); if (backInterestOwed != 0) { _payInterestTransfer( loanLocal.lender, loanParamsLocal.loanToken, backInterestOwed ); } uint256 gasRebate = _getRebate( loanLocal, loanParamsLocal, startingGas ); if (gasRebate != 0) { loanLocal.collateral = loanLocal.collateral .sub(gasRebate, "gasRebate too high"); _withdrawAsset( loanParamsLocal.collateralToken, msg.sender, gasRebate ); } _rolloverEvent( loanLocal, loanParamsLocal, sourceTokenAmountUsed, interestAmountRequired, gasRebate ); loans[loanId] = loanLocal; }
382,331
./full_match/1/0xbD53415F6135019386f9e64b6811c4728A43655B/sources/contracts/project/kometh/rexroar/RexRoarIssue1.sol
@inheritdoc IKomethAppImplementation/
function setStage(Stage _stage) external onlyOwner { stage = _stage; }
16,544,838
pragma solidity ^0.5.0; import "../proxy/Proxy.sol"; import "../PolymathRegistry.sol"; import "../interfaces/IModule.sol"; import "./SecurityTokenStorage.sol"; import "../libraries/TokenLib.sol"; import "../interfaces/IDataStore.sol"; import "../interfaces/IUpgradableTokenFactory.sol"; import "../interfaces/IModuleFactory.sol"; import "../interfaces/token/IERC1410.sol"; import "../interfaces/token/IERC1594.sol"; import "../interfaces/token/IERC1643.sol"; import "../interfaces/token/IERC1644.sol"; import "../interfaces/IModuleRegistry.sol"; import "../interfaces/ITransferManager.sol"; import "openzeppelin-solidity/contracts/utils/ReentrancyGuard.sol"; import "openzeppelin-solidity/contracts/token/ERC20/ERC20.sol"; /** * @title Security Token contract * @notice SecurityToken is an ERC1400 token with added capabilities: * @notice - Implements the ERC1400 Interface * @notice - Transfers are restricted * @notice - Modules can be attached to it to control its behaviour * @notice - ST should not be deployed directly, but rather the SecurityTokenRegistry should be used * @notice - ST does not inherit from ISecurityToken due to: * @notice - https://github.com/ethereum/solidity/issues/4847 */ contract SecurityToken is ERC20, ReentrancyGuard, SecurityTokenStorage, IERC1594, IERC1643, IERC1644, IERC1410, Proxy { using SafeMath for uint256; // Emit at the time when module get added event ModuleAdded( uint8[] _types, bytes32 indexed _name, address indexed _moduleFactory, address _module, uint256 _moduleCost, uint256 _budget, bytes32 _label, bool _archived ); // Emit when the token details get updated event UpdateTokenDetails(string _oldDetails, string _newDetails); // Emit when the token name get updated event UpdateTokenName(string _oldName, string _newName); // Emit when the granularity get changed event GranularityChanged(uint256 _oldGranularity, uint256 _newGranularity); // Emit when is permanently frozen by the issuer event FreezeIssuance(); // Emit when transfers are frozen or unfrozen event FreezeTransfers(bool _status); // Emit when new checkpoint created event CheckpointCreated(uint256 indexed _checkpointId, uint256 _investorLength); // Events to log controller actions event SetController(address indexed _oldController, address indexed _newController); //Event emit when the global treasury wallet address get changed event TreasuryWalletChanged(address _oldTreasuryWallet, address _newTreasuryWallet); event DisableController(); event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); event TokenUpgraded(uint8 _major, uint8 _minor, uint8 _patch); // Emit when Module get archived from the securityToken event ModuleArchived(uint8[] _types, address _module); //Event emitted by the tokenLib. // Emit when Module get unarchived from the securityToken event ModuleUnarchived(uint8[] _types, address _module); //Event emitted by the tokenLib. // Emit when Module get removed from the securityToken event ModuleRemoved(uint8[] _types, address _module); //Event emitted by the tokenLib. // Emit when the budget allocated to a module is changed event ModuleBudgetChanged(uint8[] _moduleTypes, address _module, uint256 _oldBudget, uint256 _budget); //Event emitted by the tokenLib. /** * @notice Initialization function * @dev Expected to be called atomically with the proxy being created, by the owner of the token * @dev Can only be called once */ function initialize(address _getterDelegate) public { //Expected to be called atomically with the proxy being created require(!initialized, "Already initialized"); getterDelegate = _getterDelegate; securityTokenVersion = SemanticVersion(3, 0, 0); updateFromRegistry(); tokenFactory = msg.sender; initialized = true; } /** * @notice Checks if an address is a module of certain type * @param _module Address to check * @param _type type to check against */ function isModule(address _module, uint8 _type) public view returns(bool) { if (modulesToData[_module].module != _module || modulesToData[_module].isArchived) return false; for (uint256 i = 0; i < modulesToData[_module].moduleTypes.length; i++) { if (modulesToData[_module].moduleTypes[i] == _type) { return true; } } return false; } // Require msg.sender to be the specified module type or the owner of the token function _onlyModuleOrOwner(uint8 _type) internal view { if (msg.sender != owner()) require(isModule(msg.sender, _type)); } function _isValidPartition(bytes32 _partition) internal pure { require(_partition == UNLOCKED, "Invalid partition"); } function _isValidOperator(address _from, address _operator, bytes32 _partition) internal view { _isAuthorised( allowance(_from, _operator) == uint(-1) || partitionApprovals[_from][_partition][_operator] ); } function _zeroAddressCheck(address _entity) internal pure { require(_entity != address(0), "Invalid address"); } function _isValidTransfer(bool _isTransfer) internal pure { require(_isTransfer, "Transfer Invalid"); } function _isValidRedeem(bool _isRedeem) internal pure { require(_isRedeem, "Invalid redeem"); } function _isSignedByOwner(bool _signed) internal pure { require(_signed, "Owner did not sign"); } function _isIssuanceAllowed() internal view { require(issuance, "Issuance frozen"); } // Function to check whether the msg.sender is authorised or not function _onlyController() internal view { _isAuthorised(msg.sender == controller && isControllable()); } function _isAuthorised(bool _authorised) internal pure { require(_authorised, "Not Authorised"); } /** * @dev Throws if called by any account other than the owner. * @dev using the internal function instead of modifier to save the code size */ function _onlyOwner() internal view { require(isOwner()); } /** * @dev Require msg.sender to be the specified module type */ function _onlyModule(uint8 _type) internal view { require(isModule(msg.sender, _type)); } /** * @dev Throws if called by any account other than the STFactory. */ modifier onlyTokenFactory() { require(msg.sender == tokenFactory); _; } modifier checkGranularity(uint256 _value) { require(_value % granularity == 0, "Invalid granularity"); _; } /** * @notice Attachs a module to the SecurityToken * @dev E.G.: On deployment (through the STR) ST gets a TransferManager module attached to it * @dev to control restrictions on transfers. * @param _moduleFactory is the address of the module factory to be added * @param _data is data packed into bytes used to further configure the module (See STO usage) * @param _maxCost max amount of POLY willing to pay to the module. * @param _budget max amount of ongoing POLY willing to assign to the module. * @param _label custom module label. */ function addModuleWithLabel( address _moduleFactory, bytes memory _data, uint256 _maxCost, uint256 _budget, bytes32 _label, bool _archived ) public nonReentrant { _onlyOwner(); //Check that the module factory exists in the ModuleRegistry - will throw otherwise IModuleRegistry(moduleRegistry).useModule(_moduleFactory, false); IModuleFactory moduleFactory = IModuleFactory(_moduleFactory); uint8[] memory moduleTypes = moduleFactory.types(); uint256 moduleCost = moduleFactory.setupCostInPoly(); require(moduleCost <= _maxCost, "Invalid cost"); //Approve fee for module ERC20(polyToken).approve(_moduleFactory, moduleCost); //Creates instance of module from factory address module = moduleFactory.deploy(_data); require(modulesToData[module].module == address(0), "Module exists"); //Approve ongoing budget ERC20(polyToken).approve(module, _budget); _addModuleData(moduleTypes, _moduleFactory, module, moduleCost, _budget, _label, _archived); } function _addModuleData( uint8[] memory _moduleTypes, address _moduleFactory, address _module, uint256 _moduleCost, uint256 _budget, bytes32 _label, bool _archived ) internal { bytes32 moduleName = IModuleFactory(_moduleFactory).name(); uint256[] memory moduleIndexes = new uint256[](_moduleTypes.length); uint256 i; for (i = 0; i < _moduleTypes.length; i++) { moduleIndexes[i] = modules[_moduleTypes[i]].length; modules[_moduleTypes[i]].push(_module); } modulesToData[_module] = ModuleData( moduleName, _module, _moduleFactory, _archived, _moduleTypes, moduleIndexes, names[moduleName].length, _label ); names[moduleName].push(_module); emit ModuleAdded(_moduleTypes, moduleName, _moduleFactory, _module, _moduleCost, _budget, _label, _archived); } /** * @notice addModule function will call addModuleWithLabel() with an empty label for backward compatible */ function addModule(address _moduleFactory, bytes calldata _data, uint256 _maxCost, uint256 _budget, bool _archived) external { addModuleWithLabel(_moduleFactory, _data, _maxCost, _budget, "", _archived); } /** * @notice Archives a module attached to the SecurityToken * @param _module address of module to archive */ function archiveModule(address _module) external { _onlyOwner(); TokenLib.archiveModule(modulesToData[_module]); } /** * @notice Upgrades a module attached to the SecurityToken * @param _module address of module to archive */ function upgradeModule(address _module) external { _onlyOwner(); TokenLib.upgradeModule(moduleRegistry, modulesToData[_module]); } /** * @notice Upgrades security token */ function upgradeToken() external { _onlyOwner(); // 10 is the number of module types to check for incompatibilities before upgrading. // The number is hard coded and kept low to keep usage low. // We currently have 7 module types. If we ever create more than 3 new module types, // We will upgrade the implementation accordinly. We understand the limitations of this approach. IUpgradableTokenFactory(tokenFactory).upgradeToken(10); emit TokenUpgraded(securityTokenVersion.major, securityTokenVersion.minor, securityTokenVersion.patch); } /** * @notice Unarchives a module attached to the SecurityToken * @param _module address of module to unarchive */ function unarchiveModule(address _module) external { _onlyOwner(); TokenLib.unarchiveModule(moduleRegistry, modulesToData[_module]); } /** * @notice Removes a module attached to the SecurityToken * @param _module address of module to unarchive */ function removeModule(address _module) external { _onlyOwner(); TokenLib.removeModule(_module, modules, modulesToData, names); } /** * @notice Allows the owner to withdraw unspent POLY stored by them on the ST or any ERC20 token. * @dev Owner can transfer POLY to the ST which will be used to pay for modules that require a POLY fee. * @param _tokenContract Address of the ERC20Basic compliance token * @param _value amount of POLY to withdraw */ function withdrawERC20(address _tokenContract, uint256 _value) external { _onlyOwner(); IERC20 token = IERC20(_tokenContract); require(token.transfer(owner(), _value)); } /** * @notice allows owner to increase/decrease POLY approval of one of the modules * @param _module module address * @param _change change in allowance * @param _increase true if budget has to be increased, false if decrease */ function changeModuleBudget(address _module, uint256 _change, bool _increase) external { _onlyOwner(); TokenLib.changeModuleBudget(_module, _change, _increase, polyToken, modulesToData); } /** * @notice updates the tokenDetails associated with the token * @param _newTokenDetails New token details */ function updateTokenDetails(string calldata _newTokenDetails) external { _onlyOwner(); emit UpdateTokenDetails(tokenDetails, _newTokenDetails); tokenDetails = _newTokenDetails; } /** * @notice Allows owner to change token granularity * @param _granularity granularity level of the token */ function changeGranularity(uint256 _granularity) external { _onlyOwner(); require(_granularity != 0, "Invalid granularity"); emit GranularityChanged(granularity, _granularity); granularity = _granularity; } /** * @notice Allows owner to change data store * @param _dataStore Address of the token data store */ function changeDataStore(address _dataStore) external { _onlyOwner(); _zeroAddressCheck(_dataStore); dataStore = _dataStore; } /** * @notice Allows owner to change token name * @param _name new name of the token */ function changeName(string calldata _name) external { _onlyOwner(); emit UpdateTokenName(name, _name); name = _name; } /** * @notice Allows to change the treasury wallet address * @param _wallet Ethereum address of the treasury wallet */ function changeTreasuryWallet(address _wallet) external { _onlyOwner(); _zeroAddressCheck(_wallet); emit TreasuryWalletChanged(IDataStore(dataStore).getAddress(TREASURY), _wallet); IDataStore(dataStore).setAddress(TREASURY, _wallet); } /** * @notice Keeps track of the number of non-zero token holders * @param _from sender of transfer * @param _to receiver of transfer * @param _value value of transfer */ function _adjustInvestorCount(address _from, address _to, uint256 _value) internal { holderCount = TokenLib.adjustInvestorCount(holderCount, _from, _to, _value, balanceOf(_to), balanceOf(_from), dataStore); } /** * @notice freezes transfers */ function freezeTransfers() external { _onlyOwner(); require(!transfersFrozen); transfersFrozen = true; /*solium-disable-next-line security/no-block-members*/ emit FreezeTransfers(true); } /** * @notice Unfreeze transfers */ function unfreezeTransfers() external { _onlyOwner(); require(transfersFrozen); transfersFrozen = false; /*solium-disable-next-line security/no-block-members*/ emit FreezeTransfers(false); } /** * @notice Internal - adjusts token holder balance at checkpoint before a token transfer * @param _investor address of the token holder affected */ function _adjustBalanceCheckpoints(address _investor) internal { TokenLib.adjustCheckpoints(checkpointBalances[_investor], balanceOf(_investor), currentCheckpointId); } /** * @notice Overloaded version of the transfer function * @param _to receiver of transfer * @param _value value of transfer * @return bool success */ function transfer(address _to, uint256 _value) public returns(bool success) { transferWithData(_to, _value, ""); return true; } /** * @notice Transfer restrictions can take many forms and typically involve on-chain rules or whitelists. * However for many types of approved transfers, maintaining an on-chain list of approved transfers can be * cumbersome and expensive. An alternative is the co-signing approach, where in addition to the token holder * approving a token transfer, and authorised entity provides signed data which further validates the transfer. * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred * @param _data The `bytes _data` allows arbitrary data to be submitted alongside the transfer. * for the token contract to interpret or record. This could be signed data authorising the transfer * (e.g. a dynamic whitelist) but is flexible enough to accomadate other use-cases. */ function transferWithData(address _to, uint256 _value, bytes memory _data) public { _transferWithData(msg.sender, _to, _value, _data); } function _transferWithData(address _from, address _to, uint256 _value, bytes memory _data) internal { _isValidTransfer(_updateTransfer(_from, _to, _value, _data)); // Using the internal function instead of super.transfer() in the favour of reducing the code size _transfer(_from, _to, _value); } /** * @notice Overloaded version of the transferFrom function * @param _from sender of transfer * @param _to receiver of transfer * @param _value value of transfer * @return bool success */ function transferFrom(address _from, address _to, uint256 _value) public returns(bool) { transferFromWithData(_from, _to, _value, ""); return true; } /** * @notice Transfer restrictions can take many forms and typically involve on-chain rules or whitelists. * However for many types of approved transfers, maintaining an on-chain list of approved transfers can be * cumbersome and expensive. An alternative is the co-signing approach, where in addition to the token holder * approving a token transfer, and authorised entity provides signed data which further validates the transfer. * @dev `msg.sender` MUST have a sufficient `allowance` set and this `allowance` must be debited by the `_value`. * @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 * @param _data The `bytes _data` allows arbitrary data to be submitted alongside the transfer. * for the token contract to interpret or record. This could be signed data authorising the transfer * (e.g. a dynamic whitelist) but is flexible enough to accomadate other use-cases. */ function transferFromWithData(address _from, address _to, uint256 _value, bytes memory _data) public { _isValidTransfer(_updateTransfer(_from, _to, _value, _data)); require(super.transferFrom(_from, _to, _value)); } /** * @notice Get the balance according to the provided partitions * @param _partition Partition which differentiate the tokens. * @param _tokenHolder Whom balance need to queried * @return Amount of tokens as per the given partitions */ function balanceOfByPartition(bytes32 _partition, address _tokenHolder) public view returns(uint256) { return _balanceOfByPartition(_partition, _tokenHolder, 0); } function _balanceOfByPartition(bytes32 _partition, address _tokenHolder, uint256 _additionalBalance) internal view returns(uint256 max) { address[] memory tms = modules[TRANSFER_KEY]; uint256 amount; for (uint256 i = 0; i < tms.length; i++) { amount = ITransferManager(tms[i]).getTokensByPartition(_partition, _tokenHolder, _additionalBalance); if (max < amount) { max = amount; } } } /** * @notice Transfers the ownership of tokens from a specified partition from one address to another address * @param _partition The partition from which to transfer tokens * @param _to The address to which to transfer tokens to * @param _value The amount of tokens to transfer from `_partition` * @param _data Additional data attached to the transfer of tokens * @return The partition to which the transferred tokens were allocated for the _to address */ function transferByPartition(bytes32 _partition, address _to, uint256 _value, bytes memory _data) public returns (bytes32) { return _transferByPartition(msg.sender, _to, _value, _partition, _data, address(0), ""); } function _transferByPartition( address _from, address _to, uint256 _value, bytes32 _partition, bytes memory _data, address _operator, bytes memory _operatorData ) internal returns(bytes32 toPartition) { _isValidPartition(_partition); // Avoiding to add this check // require(balanceOfByPartition(_partition, msg.sender) >= _value); // NB - Above condition will be automatically checked using the executeTransfer() function execution. // NB - passing `_additionalBalance` value is 0 because accessing the balance before transfer uint256 balanceBeforeTransferLocked = _balanceOfByPartition(_partition, _to, 0); _transferWithData(_from, _to, _value, _data); // NB - passing `_additonalBalance` valie is 0 because balance of `_to` was updated in the transfer call uint256 balanceAfterTransferLocked = _balanceOfByPartition(_partition, _to, 0); toPartition = _returnPartition(balanceBeforeTransferLocked, balanceAfterTransferLocked, _value); emit TransferByPartition(_partition, _operator, _from, _to, _value, _data, _operatorData); } function _returnPartition(uint256 _beforeBalance, uint256 _afterBalance, uint256 _value) internal pure returns(bytes32 toPartition) { // return LOCKED only when the transaction `_value` should be equal to the change in the LOCKED partition // balance otherwise return UNLOCKED if (_afterBalance.sub(_beforeBalance) == _value) toPartition = LOCKED; // Returning the same partition UNLOCKED toPartition = UNLOCKED; } /////////////////////// /// Operator Management /////////////////////// /** * @notice Authorises an operator for all partitions of `msg.sender`. * NB - Allowing investors to authorize an investor to be an operator of all partitions * but it doesn't mean we operator is allowed to transfer the LOCKED partition values. * Logic for this restriction is written in `operatorTransferByPartition()` function. * @param _operator An address which is being authorised. */ function authorizeOperator(address _operator) public { _approve(msg.sender, _operator, uint(-1)); emit AuthorizedOperator(_operator, msg.sender); } /** * @notice Revokes authorisation of an operator previously given for all partitions of `msg.sender`. * NB - Allowing investors to authorize an investor to be an operator of all partitions * but it doesn't mean we operator is allowed to transfer the LOCKED partition values. * Logic for this restriction is written in `operatorTransferByPartition()` function. * @param _operator An address which is being de-authorised */ function revokeOperator(address _operator) public { _approve(msg.sender, _operator, 0); emit RevokedOperator(_operator, msg.sender); } /** * @notice Authorises an operator for a given partition of `msg.sender` * @param _partition The partition to which the operator is authorised * @param _operator An address which is being authorised */ function authorizeOperatorByPartition(bytes32 _partition, address _operator) public { _isValidPartition(_partition); partitionApprovals[msg.sender][_partition][_operator] = true; emit AuthorizedOperatorByPartition(_partition, _operator, msg.sender); } /** * @notice Revokes authorisation of an operator previously given for a specified partition of `msg.sender` * @param _partition The partition to which the operator is de-authorised * @param _operator An address which is being de-authorised */ function revokeOperatorByPartition(bytes32 _partition, address _operator) public { _isValidPartition(_partition); partitionApprovals[msg.sender][_partition][_operator] = false; emit RevokedOperatorByPartition(_partition, _operator, msg.sender); } /** * @notice Transfers the ownership of tokens from a specified partition from one address to another address * @param _partition The partition from which to transfer tokens. * @param _from The address from which to transfer tokens from * @param _to The address to which to transfer tokens to * @param _value The amount of tokens to transfer from `_partition` * @param _data Additional data attached to the transfer of tokens * @param _operatorData Additional data attached to the transfer of tokens by the operator * @return The partition to which the transferred tokens were allocated for the _to address */ function operatorTransferByPartition( bytes32 _partition, address _from, address _to, uint256 _value, bytes calldata _data, bytes calldata _operatorData ) external returns (bytes32) { // For the current release we are only allowing UNLOCKED partition tokens to transact _validateOperatorAndPartition(_partition, _from, msg.sender); require(_operatorData[0] != 0); return _transferByPartition(_from, _to, _value, _partition, _data, msg.sender, _operatorData); } function _validateOperatorAndPartition(bytes32 _partition, address _from, address _operator) internal view { _isValidPartition(_partition); _isValidOperator(_from, _operator, _partition); } /** * @notice Updates internal variables when performing a transfer * @param _from sender of transfer * @param _to receiver of transfer * @param _value value of transfer * @param _data data to indicate validation * @return bool success */ function _updateTransfer(address _from, address _to, uint256 _value, bytes memory _data) internal nonReentrant returns(bool verified) { // NB - the ordering in this function implies the following: // - investor counts are updated before transfer managers are called - i.e. transfer managers will see //investor counts including the current transfer. // - checkpoints are updated after the transfer managers are called. This allows TMs to create //checkpoints as though they have been created before the current transactions, // - to avoid the situation where a transfer manager transfers tokens, and this function is called recursively, //the function is marked as nonReentrant. This means that no TM can transfer (or mint / burn) tokens in the execute transfer function. _adjustInvestorCount(_from, _to, _value); verified = _executeTransfer(_from, _to, _value, _data); _adjustBalanceCheckpoints(_from); _adjustBalanceCheckpoints(_to); } /** * @notice Validate transfer with TransferManager module if it exists * @dev TransferManager module has a key of 2 * function (no change in the state). * @param _from sender of transfer * @param _to receiver of transfer * @param _value value of transfer * @param _data data to indicate validation * @return bool */ function _executeTransfer( address _from, address _to, uint256 _value, bytes memory _data ) internal checkGranularity(_value) returns(bool) { if (!transfersFrozen) { bool isInvalid; bool isValid; bool isForceValid; bool unarchived; address module; uint256 tmLength = modules[TRANSFER_KEY].length; for (uint256 i = 0; i < tmLength; i++) { module = modules[TRANSFER_KEY][i]; if (!modulesToData[module].isArchived) { unarchived = true; ITransferManager.Result valid = ITransferManager(module).executeTransfer(_from, _to, _value, _data); if (valid == ITransferManager.Result.INVALID) { isInvalid = true; } else if (valid == ITransferManager.Result.VALID) { isValid = true; } else if (valid == ITransferManager.Result.FORCE_VALID) { isForceValid = true; } } } // If no unarchived modules, return true by default return unarchived ? (isForceValid ? true : (isInvalid ? false : isValid)) : true; } return false; } /** * @notice Permanently freeze issuance of this security token. * @dev It MUST NOT be possible to increase `totalSuppy` after this function is called. */ function freezeIssuance(bytes calldata _signature) external { _onlyOwner(); _isIssuanceAllowed(); _isSignedByOwner(owner() == TokenLib.recoverFreezeIssuanceAckSigner(_signature)); issuance = false; /*solium-disable-next-line security/no-block-members*/ emit FreezeIssuance(); } /** * @notice This function must be called to increase the total supply (Corresponds to mint function of ERC20). * @dev It only be called by the token issuer or the operator defined by the issuer. ERC1594 doesn't have * have the any logic related to operator but its superset ERC1400 have the operator logic and this function * is allowed to call by the operator. * @param _tokenHolder The account that will receive the created tokens (account should be whitelisted or KYCed). * @param _value The amount of tokens need to be issued * @param _data The `bytes _data` allows arbitrary data to be submitted alongside the transfer. */ function issue( address _tokenHolder, uint256 _value, bytes memory _data ) public // changed to public to save the code size and reuse the function { _isIssuanceAllowed(); _onlyModuleOrOwner(MINT_KEY); _issue(_tokenHolder, _value, _data); } function _issue( address _tokenHolder, uint256 _value, bytes memory _data ) internal { // Add a function to validate the `_data` parameter _isValidTransfer(_updateTransfer(address(0), _tokenHolder, _value, _data)); _mint(_tokenHolder, _value); emit Issued(msg.sender, _tokenHolder, _value, _data); } /** * @notice issue new tokens and assigns them to the target _tokenHolder. * @dev Can only be called by the issuer or STO attached to the token. * @param _tokenHolders A list of addresses to whom the minted tokens will be dilivered * @param _values A list of number of tokens get minted and transfer to corresponding address of the investor from _tokenHolders[] list * @return success */ function issueMulti(address[] memory _tokenHolders, uint256[] memory _values) public { _isIssuanceAllowed(); _onlyModuleOrOwner(MINT_KEY); // Remove reason string to reduce the code size require(_tokenHolders.length == _values.length); for (uint256 i = 0; i < _tokenHolders.length; i++) { _issue(_tokenHolders[i], _values[i], ""); } } /** * @notice Increases totalSupply and the corresponding amount of the specified owners partition * @param _partition The partition to allocate the increase in balance * @param _tokenHolder The token holder whose balance should be increased * @param _value The amount by which to increase the balance * @param _data Additional data attached to the minting of tokens */ function issueByPartition(bytes32 _partition, address _tokenHolder, uint256 _value, bytes calldata _data) external { _isValidPartition(_partition); //Use issue instead of _issue function in the favour to saving code size issue(_tokenHolder, _value, _data); emit IssuedByPartition(_partition, _tokenHolder, _value, _data); } /** * @notice This function redeem an amount of the token of a msg.sender. For doing so msg.sender may incentivize * using different ways that could be implemented with in the `redeem` function definition. But those implementations * are out of the scope of the ERC1594. * @param _value The amount of tokens need to be redeemed * @param _data The `bytes _data` it can be used in the token contract to authenticate the redemption. */ function redeem(uint256 _value, bytes calldata _data) external { _onlyModule(BURN_KEY); _redeem(msg.sender, _value, _data); } function _redeem(address _from, uint256 _value, bytes memory _data) internal { // Add a function to validate the `_data` parameter _isValidRedeem(_checkAndBurn(_from, _value, _data)); } /** * @notice Decreases totalSupply and the corresponding amount of the specified partition of msg.sender * @param _partition The partition to allocate the decrease in balance * @param _value The amount by which to decrease the balance * @param _data Additional data attached to the burning of tokens */ function redeemByPartition(bytes32 _partition, uint256 _value, bytes calldata _data) external { _onlyModule(BURN_KEY); _isValidPartition(_partition); _redeemByPartition(_partition, msg.sender, _value, address(0), _data, ""); } function _redeemByPartition( bytes32 _partition, address _from, uint256 _value, address _operator, bytes memory _data, bytes memory _operatorData ) internal { _redeem(_from, _value, _data); emit RedeemedByPartition(_partition, _operator, _from, _value, _data, _operatorData); } /** * @notice Decreases totalSupply and the corresponding amount of the specified partition of tokenHolder * @dev This function can only be called by the authorised operator. * @param _partition The partition to allocate the decrease in balance. * @param _tokenHolder The token holder whose balance should be decreased * @param _value The amount by which to decrease the balance * @param _data Additional data attached to the burning of tokens * @param _operatorData Additional data attached to the transfer of tokens by the operator */ function operatorRedeemByPartition( bytes32 _partition, address _tokenHolder, uint256 _value, bytes calldata _data, bytes calldata _operatorData ) external { _onlyModule(BURN_KEY); require(_operatorData[0] != 0); _zeroAddressCheck(_tokenHolder); _validateOperatorAndPartition(_partition, _tokenHolder, msg.sender); _redeemByPartition(_partition, _tokenHolder, _value, msg.sender, _data, _operatorData); } function _checkAndBurn(address _from, uint256 _value, bytes memory _data) internal returns(bool verified) { verified = _updateTransfer(_from, address(0), _value, _data); _burn(_from, _value); emit Redeemed(address(0), msg.sender, _value, _data); } /** * @notice This function redeem an amount of the token of a msg.sender. For doing so msg.sender may incentivize * using different ways that could be implemented with in the `redeem` function definition. But those implementations * are out of the scope of the ERC1594. * @dev It is analogy to `transferFrom` * @param _tokenHolder The account whose tokens gets redeemed. * @param _value The amount of tokens need to be redeemed * @param _data The `bytes _data` it can be used in the token contract to authenticate the redemption. */ function redeemFrom(address _tokenHolder, uint256 _value, bytes calldata _data) external { _onlyModule(BURN_KEY); // Add a function to validate the `_data` parameter _isValidRedeem(_updateTransfer(_tokenHolder, address(0), _value, _data)); _burnFrom(_tokenHolder, _value); emit Redeemed(msg.sender, _tokenHolder, _value, _data); } /** * @notice Creates a checkpoint that can be used to query historical balances / totalSuppy * @return uint256 */ function createCheckpoint() external returns(uint256) { _onlyModuleOrOwner(CHECKPOINT_KEY); IDataStore dataStoreInstance = IDataStore(dataStore); // currentCheckpointId can only be incremented by 1 and hence it can not be overflowed currentCheckpointId = currentCheckpointId + 1; /*solium-disable-next-line security/no-block-members*/ checkpointTimes.push(now); checkpointTotalSupply[currentCheckpointId] = totalSupply(); emit CheckpointCreated(currentCheckpointId, dataStoreInstance.getAddressArrayLength(INVESTORSKEY)); return currentCheckpointId; } /** * @notice Used by the issuer to set the controller addresses * @param _controller address of the controller */ function setController(address _controller) external { _onlyOwner(); require(isControllable()); emit SetController(controller, _controller); controller = _controller; } /** * @notice Used by the issuer to permanently disable controller functionality * @dev enabled via feature switch "disableControllerAllowed" */ function disableController(bytes calldata _signature) external { _onlyOwner(); _isSignedByOwner(owner() == TokenLib.recoverDisableControllerAckSigner(_signature)); require(isControllable()); controllerDisabled = true; delete controller; emit DisableController(); } /** * @notice Transfers of securities may fail for a number of reasons. So this function will used to understand the * cause of failure by getting the byte value. Which will be the ESC that follows the EIP 1066. ESC can be mapped * with a reson string to understand the failure cause, table of Ethereum status code will always reside off-chain * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred * @param _data The `bytes _data` allows arbitrary data to be submitted alongside the transfer. * @return bool It signifies whether the transaction will be executed or not. * @return byte Ethereum status code (ESC) * @return bytes32 Application specific reason code */ function canTransfer(address _to, uint256 _value, bytes calldata _data) external view returns (bool, byte, bytes32) { return _canTransfer(msg.sender, _to, _value, _data); } /** * @notice Transfers of securities may fail for a number of reasons. So this function will used to understand the * cause of failure by getting the byte value. Which will be the ESC that follows the EIP 1066. ESC can be mapped * with a reson string to understand the failure cause, table of Ethereum status code will always reside off-chain * @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 * @param _data The `bytes _data` allows arbitrary data to be submitted alongside the transfer. * @return bool It signifies whether the transaction will be executed or not. * @return byte Ethereum status code (ESC) * @return bytes32 Application specific reason code */ function canTransferFrom(address _from, address _to, uint256 _value, bytes calldata _data) external view returns (bool success, byte reasonCode, bytes32 appCode) { (success, reasonCode, appCode) = _canTransfer(_from, _to, _value, _data); if (success && _value > allowance(_from, msg.sender)) { return (false, 0x53, bytes32(0)); } } function _canTransfer(address _from, address _to, uint256 _value, bytes memory _data) internal view returns (bool, byte, bytes32) { bytes32 appCode; bool success; if (_value % granularity != 0) { return (false, 0x50, bytes32(0)); } (success, appCode) = TokenLib.verifyTransfer(modules[TRANSFER_KEY], modulesToData, _from, _to, _value, _data, transfersFrozen); return TokenLib.canTransfer(success, appCode, _to, _value, balanceOf(_from)); } /** * @notice The standard provides an on-chain function to determine whether a transfer will succeed, * and return details indicating the reason if the transfer is not valid. * @param _from The address from whom the tokens get transferred. * @param _to The address to which to transfer tokens to. * @param _partition The partition from which to transfer tokens * @param _value The amount of tokens to transfer from `_partition` * @param _data Additional data attached to the transfer of tokens * @return ESC (Ethereum Status Code) following the EIP-1066 standard * @return Application specific reason codes with additional details * @return The partition to which the transferred tokens were allocated for the _to address */ function canTransferByPartition( address _from, address _to, bytes32 _partition, uint256 _value, bytes calldata _data ) external view returns (byte esc, bytes32 appStatusCode, bytes32 toPartition) { if (_partition == UNLOCKED) { bool success; (success, esc, appStatusCode) = _canTransfer(_from, _to, _value, _data); if (success) { uint256 beforeBalance = _balanceOfByPartition(_partition, _to, 0); uint256 afterbalance = _balanceOfByPartition(_partition, _to, _value); toPartition = _returnPartition(beforeBalance, afterbalance, _value); } return (esc, appStatusCode, toPartition); } return (0x50, bytes32(0), bytes32(0)); } /** * @notice Used to attach a new document to the contract, or update the URI or hash of an existing attached document * @dev Can only be executed by the owner of the contract. * @param _name Name of the document. It should be unique always * @param _uri Off-chain uri of the document from where it is accessible to investors/advisors to read. * @param _documentHash hash (of the contents) of the document. */ function setDocument(bytes32 _name, string calldata _uri, bytes32 _documentHash) external { _onlyOwner(); TokenLib.setDocument(_documents, _docNames, _docIndexes, _name, _uri, _documentHash); } /** * @notice Used to remove an existing document from the contract by giving the name of the document. * @dev Can only be executed by the owner of the contract. * @param _name Name of the document. It should be unique always */ function removeDocument(bytes32 _name) external { _onlyOwner(); TokenLib.removeDocument(_documents, _docNames, _docIndexes, _name); } /** * @notice In order to provide transparency over whether `controllerTransfer` / `controllerRedeem` are useable * or not `isControllable` function will be used. * @dev If `isControllable` returns `false` then it always return `false` and * `controllerTransfer` / `controllerRedeem` will always revert. * @return bool `true` when controller address is non-zero otherwise return `false`. */ function isControllable() public view returns (bool) { return !controllerDisabled; } /** * @notice This function allows an authorised address to transfer tokens between any two token holders. * The transfer must still respect the balances of the token holders (so the transfer must be for at most * `balanceOf(_from)` tokens) and potentially also need to respect other transfer restrictions. * @dev This function can only be executed by the `controller` address. * @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 * @param _data data to validate the transfer. (It is not used in this reference implementation * because use of `_data` parameter is implementation specific). * @param _operatorData data attached to the transfer by controller to emit in event. (It is more like a reason string * for calling this function (aka force transfer) which provides the transparency on-chain). */ function controllerTransfer(address _from, address _to, uint256 _value, bytes calldata _data, bytes calldata _operatorData) external { _onlyController(); _updateTransfer(_from, _to, _value, _data); _transfer(_from, _to, _value); emit ControllerTransfer(msg.sender, _from, _to, _value, _data, _operatorData); } /** * @notice This function allows an authorised address to redeem tokens for any token holder. * The redemption must still respect the balances of the token holder (so the redemption must be for at most * `balanceOf(_tokenHolder)` tokens) and potentially also need to respect other transfer restrictions. * @dev This function can only be executed by the `controller` address. * @param _tokenHolder The account whose tokens will be redeemed. * @param _value uint256 the amount of tokens need to be redeemed. * @param _data data to validate the transfer. (It is not used in this reference implementation * because use of `_data` parameter is implementation specific). * @param _operatorData data attached to the transfer by controller to emit in event. (It is more like a reason string * for calling this function (aka force transfer) which provides the transparency on-chain). */ function controllerRedeem(address _tokenHolder, uint256 _value, bytes calldata _data, bytes calldata _operatorData) external { _onlyController(); _checkAndBurn(_tokenHolder, _value, _data); emit ControllerRedemption(msg.sender, _tokenHolder, _value, _data, _operatorData); } function _implementation() internal view returns(address) { return getterDelegate; } function updateFromRegistry() public { _onlyOwner(); moduleRegistry = PolymathRegistry(polymathRegistry).getAddress("ModuleRegistry"); securityTokenRegistry = PolymathRegistry(polymathRegistry).getAddress("SecurityTokenRegistry"); polyToken = PolymathRegistry(polymathRegistry).getAddress("PolyToken"); } //Ownable Functions /** * @return the address of the owner. */ function owner() public view returns (address) { return _owner; } /** * @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 transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) external { _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; } }
Decreases totalSupply and the corresponding amount of the specified partition of msg.sender _partition The partition to allocate the decrease in balance _value The amount by which to decrease the balance _data Additional data attached to the burning of tokens/
function redeemByPartition(bytes32 _partition, uint256 _value, bytes calldata _data) external { _onlyModule(BURN_KEY); _isValidPartition(_partition); _redeemByPartition(_partition, msg.sender, _value, address(0), _data, ""); }
5,505,207
pragma solidity ^0.5.4; import "./AuctionityStorage1.sol"; import "../CommonContract/AuctionityLibrary_V1.sol"; import "../CommonContract/AuctionityChainId_V1.sol"; import "../CommonContract/AuctionityLibraryDecodeRawTx_V1.sol"; import "../CommonContract/SafeMath.sol"; /// @title Auctionity Treasurer contract AuctionityTreasurer_V1 is AuctionityStorage1, AuctionityLibrary_V1, AuctionityChainId_V1 { using SafeMath for uint256; // For previous compatibility event LogAddDepotEth(address user, uint256 amount, uint256 totalAmount, bytes32 hashTransactionDeposit); event LogAddRewardDepotEth(address user, uint256 amount, uint256 totalAmount, bytes32 hashTransactionDeposit); event LogWithdrawal(address user, uint256 amount); event LogSetWithdrawalVoucher(address user, uint256 amount, bytes voucher); event LogWithdrawalVoucherHaveBeenRemoved(address user, bytes32 voucherHash); event LogNewDepotLock(address user, uint256 amount); event LogLockDepositRefund(address user, uint256 amount); event LogEndorse(address auctionAddress, address user, uint256 amount); event LogAddDepot_V1( address user, address tokenContractAddress, uint256 tokenId, uint256 amount, uint256 totalAmount, bytes32 transactionHashDeposit ); event LogAddRewardDepot_V1( address user, address tokenContractAddress, uint256 tokenId, uint256 amount, uint256 totalAmount, bytes32 hashTransactionDeposit ); event LogWithdrawal_V1( address user, address tokenContractAddress, uint256 tokenId, uint256 amount ); event LogSetWithdrawalVoucher_V1( address user, uint256 amount, bytes voucher ); event LogWithdrawalVoucherHaveBeenRemoved_V1( address user, bytes32 voucherHash ); event LogNewDepotLock_V1( address user, address tokenContractAddress, uint256 tokenId, uint256 amount, uint256 auctionId ); event LogRefundDepotLock_V1( address user, address tokenContractAddress, uint256 tokenId, uint256 amount, uint256 auctionId ); event LogEndorse_V1( address user, address tokenContractAddress, uint256 tokenId, uint256 amount, uint256 auctionId ); modifier isUniqueTransactionHashDeposit_V1( bytes32 _transactionHashDeposit ) { require( !depositTransactionHash[_transactionHashDeposit], "Transaction Hash is already exist" ); depositTransactionHash[_transactionHashDeposit] = true; _; } /// @notice receive DepotEth /// @dev Receive deposit of eth from livenet through oracle /// @param _user address /// @param _amount uint256 /// @param _transactionHashDeposit bytes32 : hash of transaction from livenet, for anti replay /// @return bool function receiveDepotEth_V1( address _user, uint256 _amount, bytes32 _transactionHashDeposit ) public delegatedSendIsOracle_V1 isUniqueTransactionHashDeposit_V1(_transactionHashDeposit) returns (bool) { _addDepotEth_V1(_user, _amount); // For previous compatibility emit LogAddDepotEth( _user, _amount, getBalanceEth_V1(_user), _transactionHashDeposit); emit LogAddDepot_V1( _user, address(0), uint256(0), _amount, getBalanceEth_V1(_user), _transactionHashDeposit ); return true; } /// @notice receive reward DepotEth /// @dev Receive reward deposit of eth from livenet through oracle /// @param _user address /// @param _amount uint256 /// @param _transactionHashDeposit bytes32 : hash of transaction from livenet, for history only /// @return bool function receiveRewardDepotEth_V1( address _user, uint256 _amount, bytes32 _transactionHashDeposit ) public delegatedSendIsOracle_V1 returns (bool) { _addDepotEth_V1(_user, _amount); // For previous compatibility emit LogAddRewardDepotEth( _user, _amount, getBalanceEth_V1(_user), _transactionHashDeposit); emit LogAddRewardDepot_V1( _user, address(0), uint256(0), _amount, getBalanceEth_V1(_user), _transactionHashDeposit ); return true; } /// @notice receive DepotErc20 /// @dev Receive deposit of ERC20 from livenet through oracle /// @param _user address /// @param _tokenContractAddress address : ERC20 smart contract /// @param _amount uint256 /// @param _transactionHashDeposit bytes32 : hash of transaction from livenet, for anti replay /// @return bool function receiveDepotERC20_V1( address _user, address _tokenContractAddress, uint256 _amount, bytes32 _transactionHashDeposit ) public delegatedSendIsOracle_V1 isUniqueTransactionHashDeposit_V1(_transactionHashDeposit) returns (bool) { _addDepotERC20_V1(_user, _tokenContractAddress, _amount); emit LogAddDepot_V1( _user, _tokenContractAddress, uint256(0), _amount, getBalanceERC20_V1(_user, _tokenContractAddress), _transactionHashDeposit ); return true; } /// @notice receive reward DepotErc20 /// @dev Receive reward deposit of ERC20 from livenet through oracle /// @param _user address /// @param _tokenContractAddress address : ERC20 smart contract /// @param _amount uint256 /// @param _transactionHashDeposit bytes32 : hash of transaction from livenet, history only /// @return bool function receiveRewardDepotERC20_V1( address _user, address _tokenContractAddress, uint256 _amount, bytes32 _transactionHashDeposit ) public delegatedSendIsOracle_V1 returns (bool) { _addDepotERC20_V1(_user, _tokenContractAddress, _amount); emit LogAddRewardDepot_V1( _user, _tokenContractAddress, uint256(0), _amount, getBalanceERC20_V1(_user, _tokenContractAddress), _transactionHashDeposit ); return true; } /// @notice receive DepotErc721 /// @dev Receive deposit of ERC721 from livenet through oracle /// @param _user address /// @param _tokenContractAddress address : ERC721 smart contract /// @param _tokenId uint256 : tokenId of ERC721 /// @param _transactionHashDeposit bytes32 : hash of transaction from livenet, for anti replay /// @return bool function receiveDepotERC721_V1( address _user, address _tokenContractAddress, uint256 _tokenId, bytes32 _transactionHashDeposit ) public delegatedSendIsOracle_V1 isUniqueTransactionHashDeposit_V1(_transactionHashDeposit) returns (bool) { _addDepotERC721_V1(_user, _tokenContractAddress, _tokenId); emit LogAddDepot_V1( _user, _tokenContractAddress, _tokenId, 1, getBalanceERC721_V1(_user, _tokenContractAddress, _tokenId), _transactionHashDeposit ); return true; } /// @notice receive DepotErc1155 /// @dev Receive deposit of ERC1155 from livenet through oracle /// @param _user address /// @param _tokenContractAddress address : ERC1155 smart contract /// @param _tokenId uint256 : tokenId of ERC1155 /// @param _amount uint256 /// @param _transactionHashDeposit bytes32 : hash of transaction from livenet, for anti replay /// @return bool function receiveDepotERC1155_V1( address _user, address _tokenContractAddress, uint256 _tokenId, uint256 _amount, bytes32 _transactionHashDeposit ) public delegatedSendIsOracle_V1 isUniqueTransactionHashDeposit_V1(_transactionHashDeposit) returns (bool) { _addDepot_V1(_user, _tokenContractAddress, _tokenId, _amount); emit LogAddDepot_V1( _user, _tokenContractAddress, _tokenId, _amount, getBalanceERC1155_V1(_user, _tokenContractAddress, _tokenId), _transactionHashDeposit ); return true; } /// @notice receive reward DepotErc1155 /// @dev Receive reward deposit of ERC1155 from livenet through oracle /// @param _user address /// @param _tokenContractAddress address : ERC1155 smart contract /// @param _tokenId uint256 : tokenId of ERC1155 /// @param _amount uint256 /// @param _transactionHashDeposit bytes32 : hash of transaction from livenet, history only /// @return bool function receiveRewardDepotERC1155_V1( address _user, address _tokenContractAddress, uint256 _tokenId, uint256 _amount, bytes32 _transactionHashDeposit ) public delegatedSendIsOracle_V1 returns (bool) { _addDepot_V1(_user, _tokenContractAddress, _tokenId, _amount); emit LogAddRewardDepot_V1( _user, _tokenContractAddress, _tokenId, _amount, getBalanceERC1155_V1(_user, _tokenContractAddress, _tokenId), _transactionHashDeposit ); return true; } /// @notice internal transaction for add depot ETH function _addDepotEth_V1(address _user, uint256 _amount) internal returns (bool) { return _addDepot_V1(_user, address(0), uint256(0), _amount); } /// @notice internal transaction for add depot ERC20 function _addDepotERC20_V1( address _user, address _tokenContractAddress, uint256 _amount ) internal returns (bool) { return _addDepot_V1(_user, _tokenContractAddress, uint256(0), _amount); } /// @notice internal transaction for add depot ERC721 function _addDepotERC721_V1( address _user, address _tokenContractAddress, uint256 _tokenId ) internal returns (bool) { require( getBalanceERC721_V1(_user, _tokenContractAddress, _tokenId) == 0, "ERC721 is already own" ); return _addDepot_V1(_user, _tokenContractAddress, _tokenId, 1); } /// @notice internal transaction for add depot ERC1155 function _addDepot_V1( address _user, address _tokenContractAddress, uint256 _tokenId, uint256 _amount ) internal returns (bool) { require(_amount > 0, "Amount must be greater than 0"); tokens[_tokenContractAddress][_tokenId][_user].amount = tokens[_tokenContractAddress][_tokenId][_user].amount.add( _amount ); return true; } /// @notice internal transaction for sub depot ETH function _subDepotEth_V1(address _user, uint256 _amount) internal returns (bool) { return _subDepot_V1(_user, address(0), uint256(0), _amount); } /// @notice internal transaction for sub depot ERC20 function _subDepotERC20( address _user, address _tokenContractAddress, uint256 _amount ) internal returns (bool) { return _subDepot_V1(_user, _tokenContractAddress, uint256(0), _amount); } /// @notice internal transaction for sub depot ERC721 function _subDepotERC721( address _user, address _tokenContractAddress, uint256 _tokenId ) internal returns (bool) { return _subDepot_V1(_user, _tokenContractAddress, _tokenId, 1); } /// @notice internal transaction for sub depot ERC1155 function _subDepot_V1( address _user, address _tokenContractAddress, uint256 _tokenId, uint256 _amount ) internal returns (bool) { require( tokens[_tokenContractAddress][_tokenId][_user].amount >= _amount, "Amount too low" ); tokens[_tokenContractAddress][_tokenId][_user].amount = tokens[_tokenContractAddress][_tokenId][_user].amount.sub( _amount ); return true; } /// @notice get balance Eth for a user /// @param _user address /// @return _balanceOf uint256 balance of user function getBalanceEth_V1(address _user) public view returns (uint256 _balanceOf) { return _getBalance_V1(_user, address(0), uint256(0)); } /// @notice get balance ERC20 for a user /// @param _user address /// @param _tokenContractAddress address : ERC20 smart contract /// @return _balanceOf uint256 balance of user function getBalanceERC20_V1(address _user, address _tokenContractAddress) public view returns (uint256 _balanceOf) { return _getBalance_V1(_user, _tokenContractAddress, uint256(0)); } /// @notice get balance ERC721 for a user /// @param _user address /// @param _tokenContractAddress address : ERC721 smart contract /// @param _tokenId uint256 : tokenId of ERC721 /// @return _balanceOf uint256 balance of user (unique ERC721 amount) function getBalanceERC721_V1( address _user, address _tokenContractAddress, uint256 _tokenId ) public view returns (uint256 _balanceOf) { return _getBalance_V1(_user, _tokenContractAddress, _tokenId); } /// @notice internal get balance ERC1155 for a user /// @param _user address /// @param _tokenContractAddress address : ERC1155 smart contract /// @param _tokenId uint256 : tokenId of ERC1155 /// @return _balanceOf uint256 balance of user function getBalanceERC1155_V1( address _user, address _tokenContractAddress, uint256 _tokenId ) public view returns (uint256 _balanceOf) { return _getBalance_V1(_user, _tokenContractAddress, _tokenId); } /// @notice internal get balance ERC1155 for a user /// @param _user address /// @param _tokenContractAddress address : ERC1155 smart contract /// @param _tokenId uint256 : tokenId of ERC1155 /// @return _balanceOf uint256 balance of user function _getBalance_V1( address _user, address _tokenContractAddress, uint256 _tokenId ) internal view returns (uint256 _balanceOf) { return tokens[_tokenContractAddress][_tokenId][_user].amount; } /// @notice internal lock of depot Eth /// @param _user address /// @param _amount uint256 : amount to lock /// @param _lockedFor uin256 : id to lock for /// @return _success bool function _addDepotLockedEth_V1( address _user, uint256 _amount, uint256 _lockedFor ) internal returns (bool _success) { return _addDepotLocked_V1( _user, address(0), uint256(0), _amount, _lockedFor ); } /// @notice internal lock of depot ERC20 /// @param _user address /// @param _tokenContractAddress address : ERC20 smart contract /// @param _amount uint256 : amount to lock /// @param _lockedFor uin256 : id to lock for /// @return _success bool function _addDepotLockedERC20_V1( address _user, address _tokenContractAddress, uint256 _amount, uint256 _lockedFor ) internal returns (bool _success) { return _addDepotLocked_V1( _user, _tokenContractAddress, uint256(0), _amount, _lockedFor ); } /// @notice internal lock of depot ERC721 /// @param _user address /// @param _tokenContractAddress address : ERC721 smart contract /// @param _tokenId uint256 : tokenId of ERC721 /// @param _lockedFor uin256 : id to lock for /// @return _success bool function _addDepotLockedERC721_V1( address _user, address _tokenContractAddress, uint256 _tokenId, uint256 _lockedFor ) internal returns (bool _success) { return _addDepotLocked_V1( _user, _tokenContractAddress, _tokenId, 1, _lockedFor ); } /// @notice internal lock of depot ERC1155 /// @param _user address /// @param _tokenContractAddress address : ERC1155 smart contract /// @param _tokenId uint256 : tokenId of ERC1155 /// @param _amount uint256 : amount to lock /// @param _lockedFor uin256 : id to lock for /// @return _success bool function _addDepotLocked_V1( address _user, address _tokenContractAddress, uint256 _tokenId, uint256 _amount, uint256 _lockedFor ) internal returns (bool _success) { require(_amount > 0, "Amount must be greater than 0"); // if is the first lock , push into list if (!tokens[_tokenContractAddress][_tokenId][_user].lockedData[_lockedFor].isValue) { tokens[_tokenContractAddress][_tokenId][_user].lockedList.push( _lockedFor ); tokens[_tokenContractAddress][_tokenId][_user].lockedData[_lockedFor].amount = _amount; tokens[_tokenContractAddress][_tokenId][_user].lockedData[_lockedFor].isValue = true; return true; } tokens[_tokenContractAddress][_tokenId][_user].lockedData[_lockedFor].amount = tokens[_tokenContractAddress][_tokenId][_user].lockedData[_lockedFor].amount.add( _amount ); return true; } /// @notice internal unlock of depot Eth /// @param _user address /// @param _amount uint256 : amount to lock /// @param _lockedFor uin256 : id to lock for /// @return _success bool function _subDepotLockedEth_V1( address _user, uint256 _amount, uint256 _lockedFor ) internal returns (bool _success) { return _subDepotLocked_V1( _user, address(0), uint256(0), _amount, _lockedFor ); } /// @notice internal unlock of depot ERC20 /// @param _user address /// @param _tokenContractAddress address : ERC20 smart contract /// @param _amount uint256 : amount to lock /// @param _lockedFor uin256 : id to lock for /// @return _success bool function _subDepotLockedERC20_V1( address _user, address _tokenContractAddress, uint256 _amount, uint256 _lockedFor ) internal returns (bool _success) { return _subDepotLocked_V1( _user, _tokenContractAddress, uint256(0), _amount, _lockedFor ); } /// @notice internal unlock of depot ERC721 /// @param _user address /// @param _tokenContractAddress address : ERC721 smart contract /// @param _tokenId uint256 : tokenId of ERC721 /// @param _lockedFor uin256 : id to lock for /// @return _success bool function _subDepotLockedERC721_V1( address _user, address _tokenContractAddress, uint256 _tokenId, uint256 _lockedFor ) internal returns (bool _success) { return _subDepotLocked_V1( _user, _tokenContractAddress, _tokenId, 1, _lockedFor ); } /// @notice internal unlock of depot ERC1155 /// @param _user address /// @param _tokenContractAddress address : ERC1155 smart contract /// @param _tokenId uint256 : tokenId of ERC1155 /// @param _amount uint256 : amount to lock /// @param _lockedFor uin256 : id to lock for /// @return _success bool function _subDepotLocked_V1( address _user, address _tokenContractAddress, uint256 _tokenId, uint256 _amount, uint256 _lockedFor ) internal returns (bool _success) { require( tokens[_tokenContractAddress][_tokenId][_user].lockedData[_lockedFor].amount >= _amount, "Locked amount too low" ); tokens[_tokenContractAddress][_tokenId][_user].lockedData[_lockedFor].amount = tokens[_tokenContractAddress][_tokenId][_user].lockedData[_lockedFor].amount.sub( _amount ); return true; } /// @notice get locked balance Eth /// @param _user address /// @param _lockedFor uin256 : id to lock for /// @return _balanceOf uint256 function getBalanceLockedEth_V1(address _user, uint256 _lockedFor) public view returns (uint256 _balanceOf) { return _getBalanceLocked_V1(_user, address(0), uint256(0), _lockedFor); } /// @notice get locked balance ERC20 /// @param _user address /// @param _tokenContractAddress address : ERC20 smart contract /// @param _lockedFor uin256 : id to lock for /// @return _balanceOf uint256 function getBalanceLockedERC20_V1( address _user, address _tokenContractAddress, uint256 _lockedFor ) public view returns (uint256 _balanceOf) { return _getBalanceLocked_V1( _user, _tokenContractAddress, uint256(0), _lockedFor ); } /// @notice get locked balance ERC721 /// @param _user address /// @param _tokenContractAddress address : ERC721 smart contract /// @param _tokenId uint256 : tokenId of ERC721 /// @param _lockedFor uin256 : id to lock for /// @return _balanceOf uint256 function getBalanceLockedERC721_V1( address _user, address _tokenContractAddress, uint256 _tokenId, uint256 _lockedFor ) public view returns (uint256 _balanceOf) { return _getBalanceLocked_V1( _user, _tokenContractAddress, _tokenId, _lockedFor ); } /// @notice get locked balance ERC1155 /// @param _user address /// @param _tokenContractAddress address : ERC1155 smart contract /// @param _tokenId uint256 : tokenId of ERC1155 /// @param _lockedFor uin256 : id to lock for /// @return _balanceOf uint256 function getBalanceLockedERC1155_V1( address _user, address _tokenContractAddress, uint256 _tokenId, uint256 _lockedFor ) public view returns (uint256 _balanceOf) { return _getBalanceLocked_V1( _user, _tokenContractAddress, _tokenId, _lockedFor ); } /// @notice internal get locked balance ERC1155 /// @param _user address /// @param _tokenContractAddress address : ERC1155 smart contract /// @param _tokenId uint256 : tokenId of ERC1155 /// @param _lockedFor uin256 : id to lock for /// @return _balanceOf uint256 function _getBalanceLocked_V1( address _user, address _tokenContractAddress, uint256 _tokenId, uint256 _lockedFor ) internal view returns (uint256 _balanceOf) { return tokens[_tokenContractAddress][_tokenId][_user].lockedData[_lockedFor].amount; } /// @notice For previous compatiblity : Lock part of deposit to a called smart contract /// @param _amount uint256 amount to lock /// @param _refundUser address : refund previews locked fo same lockId : uint256(msg.sender) /// @dev tx.origin : origin user call parent smart contract /// @dev msg.sender : smart contract of parent smart contract /// @return _success function lockDeposit(uint256 _amount, address _refundUser) public returns (bool _success) { if(_getBalance_V1(tx.origin, address(0), uint(0)) <= _amount) { return false; } // For previous compatibility if(_refundUser != address(0)){ emit LogLockDepositRefund(_refundUser, _getBalanceLocked_V1( _refundUser, address(0), uint256(0), uint(msg.sender) )); } emit LogNewDepotLock(tx.origin, _amount); return _unlockDeposit_V1( _refundUser, address(0), uint256(0), _getBalanceLocked_V1( _refundUser, address(0), uint256(0), uint(msg.sender) ), uint(msg.sender) ) && _lockDeposit_V1( tx.origin, address(0), uint256(0), _amount, uint(msg.sender) ); } /// @notice lock of depot Eth /// @param _amount uint256 : amount to lock /// @param _lockedFor uin256 : id to lock for /// @return _success bool function lockDepositEth_V1( uint256 _amount, uint256 _lockedFor ) public returns (bool _success) { return _lockDeposit_V1( tx.origin, address(0), uint256(0), _amount, _lockedFor ); } /// @notice lock of depot ERC20 /// @param _tokenContractAddress address : ERC20 smart contract /// @param _amount uint256 : amount to lock /// @param _lockedFor uin256 : id to lock for /// @return _success bool function lockDepositERC20_V1( address _tokenContractAddress, uint256 _amount, uint256 _lockedFor ) public returns (bool _success) { return _lockDeposit_V1( tx.origin, _tokenContractAddress, uint256(0), _amount, _lockedFor ); } /// @notice internal lock of depot ERC721 /// @param _tokenContractAddress address : ERC721 smart contract /// @param _tokenId uint256 : tokenId of ERC721 /// @param _lockedFor uin256 : id to lock for /// @return _success bool function lockDepositERC721_V1( address _tokenContractAddress, uint256 _tokenId, uint256 _lockedFor ) public returns (bool _success) { return _lockDeposit_V1( tx.origin, _tokenContractAddress, _tokenId, 1, _lockedFor ); } /// @notice internal lock of depot ERC1155 /// @param _tokenContractAddress address : ERC1155 smart contract /// @param _tokenId uint256 : tokenId of ERC1155 /// @param _amount uint256 : amount to lock /// @param _lockedFor uin256 : id to lock for /// @return _success bool function lockDepositERC1155_V1( address _tokenContractAddress, uint256 _tokenId, uint256 _amount, uint256 _lockedFor ) public returns (bool _success) { return _lockDeposit_V1( tx.origin, _tokenContractAddress, _tokenId, _amount, _lockedFor ); } /// @notice internal Lock part of deposit to a called smart contract /// @param _user address /// @param _tokenContractAddress address : ERC1155 smart contract /// @param _tokenId uint256 : tokenId of ERC1155 /// @param _amount uint256 amount to lock /// @param _lockedFor uint256 lockedId /// @return _success // TODO vérifer que l'on ne peu pas l'appeler/modifier les données depuis le proxy function _lockDeposit_V1( address _user, address _tokenContractAddress, uint256 _tokenId, uint256 _amount, uint256 _lockedFor ) internal returns (bool _success) { require( _getBalance_V1(_user, _tokenContractAddress, _tokenId) >= _amount, "Not enouth amount to locked" ); _addDepotLocked_V1( _user, _tokenContractAddress, _tokenId, _amount, _lockedFor ); _subDepot_V1(_user, _tokenContractAddress, _tokenId, _amount); emit LogNewDepotLock_V1( _user, _tokenContractAddress, _tokenId, _amount, _lockedFor ); return true; } /// @notice internal Unlock part of deposit to a called smart contract /// @param _user address /// @param _tokenContractAddress address : ERC1155 smart contract /// @param _tokenId uint256 : tokenId of ERC1155 /// @param _amount uint256 amount to lock /// @param _lockedFor uint256 lockedId /// @return _success function _unlockDeposit_V1( address _user, address _tokenContractAddress, uint256 _tokenId, uint256 _amount, uint256 _lockedFor ) internal returns (bool _success) { if (_amount == 0) { return true; } require( _getBalanceLocked_V1( _user, _tokenContractAddress, _tokenId, _lockedFor ) >= _amount, "Not enouth amount locked" ); _subDepotLocked_V1( _user, _tokenContractAddress, _tokenId, _amount, _lockedFor ); _addDepot_V1(_user, _tokenContractAddress, _tokenId, _amount); emit LogRefundDepotLock_V1( _user, _tokenContractAddress, _tokenId, _amount, _lockedFor ); return true; } /// @notice for previous compatibility : endorse locked deposit to a called smart contract /// @param _amount uint256 amount to endorse /// @param _user address /// @dev msg.sender : smart contract of parent smart contract /// @return _success function endorse(uint256 _amount, address _user) public returns (bool _success) { if( _getBalanceLocked_V1( _user, address(0), uint256(0), uint(msg.sender) ) != _amount) { return false; } // For previous compatibility emit LogEndorse(msg.sender, _user, _amount); return _endorse_V1( _user, address(0), uint(0), _amount, uint(msg.sender) ); } /// @notice internal Unlock part of deposit to a called smart contract /// @param _user address /// @param _tokenContractAddress address : ERC1155 smart contract /// @param _tokenId uint256 : tokenId of ERC1155 /// @param _amount uint256 amount to lock /// @param _lockedFor uint256 lockedId /// @return _success function _endorse_V1( address _user, address _tokenContractAddress, uint256 _tokenId, uint256 _amount, uint256 _lockedFor ) internal returns (bool _success) { require( _getBalanceLocked_V1( _user, _tokenContractAddress, _tokenId, _lockedFor ) >= _amount, "Not enouth amount locked" ); _subDepotLocked_V1( _user, _tokenContractAddress, _tokenId, _amount, _lockedFor ); emit LogEndorse_V1( _user, _tokenContractAddress, _tokenId, _amount, _lockedFor ); return true; } /// @notice get number of depot eth lock for a user /// @param _user address /// @return _depotEthLockCount uint16 function getDepotEthLockedCountForUser_V1(address _user) public view returns (uint16 _depotEthLockCount) { return _getDepotLockedCountForUser_V1(_user, address(0), uint(0)); } /// @notice internal get number of depot eth lock for a user /// @param _user address /// @param _tokenContractAddress address : ERC1155 smart contract /// @param _tokenId uint256 : tokenId of ERC1155 /// @return _depotEthLockCount uint16 function _getDepotLockedCountForUser_V1( address _user, address _tokenContractAddress, uint256 _tokenId ) internal view returns (uint16 _depotEthLockCount) { return uint16( tokens[_tokenContractAddress][_tokenId][_user].lockedList.length ); } /// @notice get lockedFor and amount of depot eth lock for a user and index /// @param _user address /// @param _index uint256 /// @return _lockedFor uint256, _amountLocked uint256 function getDepotEthLockedDataForUserByIndex_V1( address _user, uint256 _index ) public view returns (uint256 _lockedFor, uint256 _amountLocked) { return _getDepotLockedDataForUserByIndex_V1( _user, address(0), uint(0), _index ); } /// @notice internal get lockedFor and amount of depot lock for a user and index /// @param _user address /// @param _tokenContractAddress address : ERC1155 smart contract /// @param _tokenId uint256 : tokenId of ERC1155 /// @param _index uint256 /// @return _lockedFor uint256, _amountLocked uint256 function _getDepotLockedDataForUserByIndex_V1( address _user, address _tokenContractAddress, uint256 _tokenId, uint256 _index ) internal view returns (uint256 _lockedFor, uint256 _amountLocked) { _lockedFor = tokens[_tokenContractAddress][_tokenId][_user].lockedList[_index]; _amountLocked = _getBalanceLocked_V1( _user, _tokenContractAddress, _tokenId, _lockedFor ); } /// @notice get total locked amount for a user /// @param _user address /// @return _totalAmountLocked uint256 function getDepotEthLockedAmountForUser_V1(address _user) public view returns (uint256 _totalAmountLocked) { return _getDepotLockedAmountForUser_V1(_user, address(0), uint(0)); } /// @notice internal get total locked amount for a user /// @param _user address /// @param _tokenContractAddress address : ERC1155 smart contract /// @param _tokenId uint256 : tokenId of ERC1155 /// @return _totalAmountLocked uint256 function _getDepotLockedAmountForUser_V1( address _user, address _tokenContractAddress, uint256 _tokenId ) internal view returns (uint256 _totalAmountLocked) { uint16 _lockedListLength = uint16( tokens[_tokenContractAddress][_tokenId][_user].lockedList.length ); if (_lockedListLength == 0) { return 0; } for (uint16 index = 0; index < _lockedListLength; index++) { uint _amountLocked; (, _amountLocked) = _getDepotLockedDataForUserByIndex_V1( _user, _tokenContractAddress, _tokenId, index ); _totalAmountLocked = _totalAmountLocked.add(_amountLocked); } } /// @notice withdrawal depot eth /// @param _amount uint256 function withdrawalEth_V1(uint256 _amount) public { _withdrawal_V1(msg.sender, address(0), uint(0), _amount); // For previous compatibility emit LogWithdrawal(msg.sender, _amount); emit LogWithdrawal_V1(msg.sender, address(0), uint(0), _amount); } /// @notice withdrawal ERC20 /// @param _tokenContractAddress address : ERC20 smart contract /// @param _amount uint256 function withdrawalERC20_V1(address _tokenContractAddress, uint256 _amount) public { _withdrawal_V1(msg.sender, _tokenContractAddress, uint256(0), _amount); emit LogWithdrawal_V1(msg.sender, _tokenContractAddress, uint(0), _amount); } /// @notice withdrawal ERC721 /// @param _user address /// @param _tokenContractAddress address : ERC721 smart contract /// @param _tokenId uint256 : tokenId of ERC721 function withdrawalERC721_V1( address _user, address _tokenContractAddress, uint256 _tokenId ) public { _withdrawal_V1(msg.sender, _tokenContractAddress, _tokenId, uint256(1)); emit LogWithdrawal_V1(msg.sender, _tokenContractAddress, _tokenId, uint256(1)); } /// @notice withdrawal ERC1155 /// @param _user address /// @param _tokenContractAddress address : ERC1155 smart contract /// @param _tokenId uint256 : tokenId of ERC1155 /// @param _amount uint256 function withdrawalERC1155_V1( address _user, address _tokenContractAddress, uint256 _tokenId, uint256 _amount ) public { _withdrawal_V1(msg.sender, _tokenContractAddress, _tokenId, _amount); emit LogWithdrawal_V1(msg.sender, _tokenContractAddress, _tokenId, _amount); } /// @notice internal withdrawal /// @param _user address /// @param _tokenContractAddress address : ERC1155 smart contract /// @param _tokenId uint256 : tokenId of ERC1155 /// @param _amount uint256 function _withdrawal_V1( address _user, address _tokenContractAddress, uint256 _tokenId, uint256 _amount ) public{ require(_amount > 0, "Amount must be greater than 0"); require(_getBalance_V1(_user, _tokenContractAddress, _tokenId) >= _amount, "Amount too low"); _subDepot_V1(_user, _tokenContractAddress, _tokenId, _amount); } /// @notice set withdrawalVoucher through oracle /// @param _depositContractAddress address /// @param _oracleRSV bytes /// @param _signedRawTxWithdrawal bytes function setWithdrawalVoucher_V1( address _depositContractAddress, bytes memory _oracleRSV, bytes memory _signedRawTxWithdrawal ) public delegatedSendIsOracle_V1 { address _withdrawalSigner; uint256 _withdrawalAmount; bytes32 _withdrawalVoucherHash = keccak256(_signedRawTxWithdrawal); (_withdrawalSigner, _withdrawalAmount) = AuctionityLibraryDecodeRawTx_V1.decodeRawTxGetWithdrawalInfo_V1( _signedRawTxWithdrawal, getAuctionityChainId_V1() ); require( _withdrawalVoucherOracleSignatureVerification_V1( _depositContractAddress, _withdrawalSigner, _withdrawalAmount, _withdrawalVoucherHash, _oracleRSV ), "Withdrawal voucher invalid signature of oracle" ); uint16 _withdrawalVoucherIndex = uint16( withdrawals[_withdrawalSigner].withdrawalVoucherList.push("0x0") - 1 ); uint _withdrawalVoucherOffset; _setWithdrawalVoucherSize_V1( _withdrawalSigner, _withdrawalVoucherIndex, _signedRawTxWithdrawal.length ); setWithdrawalVoucherSelector_V1( _withdrawalSigner, _withdrawalVoucherIndex ); _withdrawalVoucherOffset = _setWithdrawalVoucherParam1_V1( _withdrawalSigner, _withdrawalVoucherIndex, _oracleRSV ); _withdrawalVoucherOffset = _setWithdrawalVoucherParam2_V1( _withdrawalVoucherOffset, _withdrawalSigner, _withdrawalVoucherIndex, _signedRawTxWithdrawal ); bytes memory _withdrawalVoucher = withdrawals[_withdrawalSigner].withdrawalVoucherList[_withdrawalVoucherIndex]; require( withdrawals[_withdrawalSigner].withdrawalVoucher[keccak256( _withdrawalVoucher )] == 0, "Withdrawal voucher already exist" ); withdrawals[_withdrawalSigner].withdrawalVoucher[keccak256( _withdrawalVoucher )] = _withdrawalVoucherIndex; // For previous compatibility emit LogSetWithdrawalVoucher( _withdrawalSigner, _withdrawalAmount, _withdrawalVoucher ); emit LogSetWithdrawalVoucher_V1( _withdrawalSigner, _withdrawalAmount, _withdrawalVoucher ); } /// @notice initiate withdrawalVoucher bytes /// @param _user address /// @param _withdrawalVoucherIndex uint16 index of voucher /// @param _signedRawTxWithdrawalLength bytes function _setWithdrawalVoucherSize_V1( address _user, uint16 _withdrawalVoucherIndex, uint _signedRawTxWithdrawalLength ) internal { uint _withdrawalVoucherLength = 4 + 2 * 32 + (((65 / 32) + 1) * 32) + 32 + (((_signedRawTxWithdrawalLength / 32) + 1) * 32); // start of rlp // 2 param // data : rsvOracle // length + signedRawTxCreateAuction withdrawals[_user].withdrawalVoucherList[_withdrawalVoucherIndex] = new bytes( _withdrawalVoucherLength ); } /// @notice set selector of withdrawalVoucher /// @param _user address /// @param _withdrawalVoucherIndex uint16 index of voucher function setWithdrawalVoucherSelector_V1( address _user, uint16 _withdrawalVoucherIndex ) internal { // 0x6fc60a5e : bytes4(keccak256('withdrawalVoucher_V1(bytes,bytes)')) bytes4 topic = 0x6fc60a5e; for (uint8 i = 0; i < 4; i++) { withdrawals[_user].withdrawalVoucherList[_withdrawalVoucherIndex][i] = bytes1( topic[i] ); } } /// @notice set 1st param of withdrawalVoucher : _oracleRSV /// @param _user address /// @param _withdrawalVoucherIndex uint16 index of voucher /// @param _oracleRSV bytes /// @return position of next free data in WV function _setWithdrawalVoucherParam1_V1( address _user, uint16 _withdrawalVoucherIndex, bytes memory _oracleRSV ) internal returns (uint) { uint i; bytes32 _bytes32Position = bytes32(uint(2 * 32)); for (i = 0; i < 32; i++) { withdrawals[_user].withdrawalVoucherList[_withdrawalVoucherIndex][4 + i] = bytes1( _bytes32Position[i] ); } bytes32 _bytes32Length = bytes32(uint(65)); for (i = 0; i < 32; i++) { withdrawals[_user].withdrawalVoucherList[_withdrawalVoucherIndex][4 + uint( _bytes32Position ) + i] = bytes1(_bytes32Length[i]); } for (i = 0; i < 65; i++) { withdrawals[_user].withdrawalVoucherList[_withdrawalVoucherIndex][4 + 32 + uint( _bytes32Position ) + i] = bytes1(_oracleRSV[i]); } return uint(_bytes32Position) + (((65 / 32) + 1) * 32); // padding 32 bytes } /// @notice set 2nd param of withdrawalVoucher : _signedRawTxCreateAuction /// @param _offset uint256 position of current free data in WV /// @param _user address /// @param _withdrawalVoucherIndex uint16 index of voucher /// @param _signedRawTxWithdrawal bytes /// @return position of next free data in WV function _setWithdrawalVoucherParam2_V1( uint _offset, address _user, uint16 _withdrawalVoucherIndex, bytes memory _signedRawTxWithdrawal ) internal returns (uint) { uint i; bytes32 _bytes32Position = bytes32(_offset); for (i = 0; i < 32; i++) { withdrawals[_user].withdrawalVoucherList[_withdrawalVoucherIndex][4 + 32 + i] = bytes1( _bytes32Position[i] ); } bytes32 _bytes32Length = bytes32(_signedRawTxWithdrawal.length); for (i = 0; i < 32; i++) { withdrawals[_user].withdrawalVoucherList[_withdrawalVoucherIndex][4 + uint( _bytes32Position ) + i] = bytes1(_bytes32Length[i]); } for (i = 0; i < _signedRawTxWithdrawal.length; i++) { withdrawals[_user].withdrawalVoucherList[_withdrawalVoucherIndex][4 + 32 + uint( _bytes32Position ) + i] = bytes1(_signedRawTxWithdrawal[i]); } return uint( _bytes32Position ) + 32 + (((_signedRawTxWithdrawal.length / 32) + 1) * 32); } /// @notice verification of oracle RSV /// @param _depositContractAddress address /// @param _withdrawalSigner address /// @param _withdrawalAmount uint256 /// @param _withdrawalVoucherHash bytes32 /// @param _oracleRSV bytes /// @return _success function _withdrawalVoucherOracleSignatureVerification_V1( address _depositContractAddress, address _withdrawalSigner, uint256 _withdrawalAmount, bytes32 _withdrawalVoucherHash, bytes memory _oracleRSV ) internal view returns (bool) { bytes32 _hash = keccak256( abi.encodePacked( _depositContractAddress, _withdrawalSigner, _withdrawalAmount, _withdrawalVoucherHash ) ); // if oracle is the signer of this withdrawal address _oracleEcrecoverSigner = AuctionityLibraryDecodeRawTx_V1.ecrecoverSigner_V1( keccak256( abi.encodePacked("\x19Ethereum Signed Message:\n32", _hash) ), _oracleRSV, 0 ); return _oracleEcrecoverSigner == oracle; } /// @notice Get number of withdrawal voucher list for a user /// @param _user address /// @return _numberOfWithdrawalVoucher function getUserWithdrawalVoucherLength_V1(address _user) public view returns (uint16 _numberOfWithdrawalVoucher) { return uint16(withdrawals[_user].withdrawalVoucherList.length); } /// @notice Get Withdrawal voucher for a user at index /// @param _user address /// @param _index uint16 /// @return voucher bytes function getWithdrawalVoucherAtIndex_V1(address _user, uint16 _index) public view returns (bytes memory _voucher) { return withdrawals[_user].withdrawalVoucherList[_index]; } /// @notice Get index fro withdrawalVoucherList from user and voucher hash /// @param _user address /// @param _voucherHash bytes32 /// @return _index function getWithdrawalVoucherIndex_V1(address _user, bytes32 _voucherHash) public view returns (uint16) { return withdrawals[_user].withdrawalVoucher[_voucherHash]; } /// @notice Remove withdrawal voucher by replacing the index of withdrawal voucher by the last index in withdrawal voucher list /// @dev oracle only /// @param _user address /// @param _voucherHash bytes32 function removeWithdrawalVoucher_V1(address _user, bytes32 _voucherHash) public delegatedSendIsOracle_V1 { uint16 _indexToDelete = withdrawals[_user].withdrawalVoucher[_voucherHash]; uint16 _length = uint16( withdrawals[_user].withdrawalVoucherList.length ); if (_length > 1) { bytes memory _hashToMove = withdrawals[_user].withdrawalVoucherList[_length - 1]; withdrawals[_user].withdrawalVoucherList[_indexToDelete] = _hashToMove; withdrawals[_user].withdrawalVoucher[keccak256( _hashToMove )] = _indexToDelete; } withdrawals[_user].withdrawalVoucherList.length--; // For previous compatibility emit LogWithdrawalVoucherHaveBeenRemoved(_user, _voucherHash); emit LogWithdrawalVoucherHaveBeenRemoved_V1(_user, _voucherHash); } }
receive reward DepotEth Receive reward deposit of eth from livenet through oracle _user address _amount uint256 _transactionHashDeposit bytes32 : hash of transaction from livenet, for history only return bool For previous compatibility
function receiveRewardDepotEth_V1( address _user, uint256 _amount, bytes32 _transactionHashDeposit ) public delegatedSendIsOracle_V1 returns (bool) { _addDepotEth_V1(_user, _amount); emit LogAddRewardDepotEth( _user, _amount, getBalanceEth_V1(_user), _transactionHashDeposit); emit LogAddRewardDepot_V1( _user, address(0), uint256(0), _amount, getBalanceEth_V1(_user), _transactionHashDeposit ); return true; }
7,224,441
// Dependency file: @chainlink/contracts/src/v0.6/vendor/SafeMathChainlink.sol // SPDX-License-Identifier: MIT // pragma solidity ^0.6.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 SafeMathChainlink { /** * @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"); 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-solidity/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) { // Solidity only automatically asserts when dividing by 0 require(b > 0, "SafeMath: division by zero"); 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) { require(b != 0, "SafeMath: modulo by zero"); return a % b; } } // Dependency file: @chainlink/contracts/src/v0.6/interfaces/LinkTokenInterface.sol // pragma solidity ^0.6.0; interface LinkTokenInterface { function allowance(address owner, address spender) external view returns (uint256 remaining); function approve(address spender, uint256 value) external returns (bool success); function balanceOf(address owner) external view returns (uint256 balance); function decimals() external view returns (uint8 decimalPlaces); function decreaseApproval(address spender, uint256 addedValue) external returns (bool success); function increaseApproval(address spender, uint256 subtractedValue) external; function name() external view returns (string memory tokenName); function symbol() external view returns (string memory tokenSymbol); function totalSupply() external view returns (uint256 totalTokensIssued); function transfer(address to, uint256 value) external returns (bool success); function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool success); function transferFrom(address from, address to, uint256 value) external returns (bool success); } // Dependency file: @chainlink/contracts/src/v0.6/VRFRequestIDBase.sol // pragma solidity ^0.6.0; contract VRFRequestIDBase { /** * @notice returns the seed which is actually input to the VRF coordinator * * @dev To prevent repetition of VRF output due to repetition of the * @dev user-supplied seed, that seed is combined in a hash with the * @dev user-specific nonce, and the address of the consuming contract. The * @dev risk of repetition is mostly mitigated by inclusion of a blockhash in * @dev the final seed, but the nonce does protect against repetition in * @dev requests which are included in a single block. * * @param _userSeed VRF seed input provided by user * @param _requester Address of the requesting contract * @param _nonce User-specific nonce at the time of the request */ function makeVRFInputSeed(bytes32 _keyHash, uint256 _userSeed, address _requester, uint256 _nonce) internal pure returns (uint256) { return uint256(keccak256(abi.encode(_keyHash, _userSeed, _requester, _nonce))); } /** * @notice Returns the id for this request * @param _keyHash The serviceAgreement ID to be used for this request * @param _vRFInputSeed The seed to be passed directly to the VRF * @return The id for this request * * @dev Note that _vRFInputSeed is not the seed passed by the consuming * @dev contract, but the one generated by makeVRFInputSeed */ function makeRequestId( bytes32 _keyHash, uint256 _vRFInputSeed) internal pure returns (bytes32) { return keccak256(abi.encodePacked(_keyHash, _vRFInputSeed)); } } // Dependency file: @chainlink/contracts/src/v0.6/VRFConsumerBase.sol // pragma solidity ^0.6.0; // import "@chainlink/contracts/src/v0.6/vendor/SafeMathChainlink.sol"; // import "@chainlink/contracts/src/v0.6/interfaces/LinkTokenInterface.sol"; // import "@chainlink/contracts/src/v0.6/VRFRequestIDBase.sol"; /** **************************************************************************** * @notice Interface for contracts using VRF randomness * ***************************************************************************** * @dev PURPOSE * * @dev Reggie the Random Oracle (not his real job) wants to provide randomness * @dev to Vera the verifier in such a way that Vera can be sure he's not * @dev making his output up to suit himself. Reggie provides Vera a public key * @dev to which he knows the secret key. Each time Vera provides a seed to * @dev Reggie, he gives back a value which is computed completely * @dev deterministically from the seed and the secret key. * * @dev Reggie provides a proof by which Vera can verify that the output was * @dev correctly computed once Reggie tells it to her, but without that proof, * @dev the output is indistinguishable to her from a uniform random sample * @dev from the output space. * * @dev The purpose of this contract is to make it easy for unrelated contracts * @dev to talk to Vera the verifier about the work Reggie is doing, to provide * @dev simple access to a verifiable source of randomness. * ***************************************************************************** * @dev USAGE * * @dev Calling contracts must inherit from VRFConsumerBase, and can * @dev initialize VRFConsumerBase's attributes in their constructor as * @dev shown: * * @dev contract VRFConsumer { * @dev constuctor(<other arguments>, address _vrfCoordinator, address _link) * @dev VRFConsumerBase(_vrfCoordinator, _link) public { * @dev <initialization with other arguments goes here> * @dev } * @dev } * * @dev The oracle will have given you an ID for the VRF keypair they have * @dev committed to (let's call it keyHash), and have told you the minimum LINK * @dev price for VRF service. Make sure your contract has sufficient LINK, and * @dev call requestRandomness(keyHash, fee, seed), where seed is the input you * @dev want to generate randomness from. * * @dev Once the VRFCoordinator has received and validated the oracle's response * @dev to your request, it will call your contract's fulfillRandomness method. * * @dev The randomness argument to fulfillRandomness is the actual random value * @dev generated from your seed. * * @dev The requestId argument is generated from the keyHash and the seed by * @dev makeRequestId(keyHash, seed). If your contract could have concurrent * @dev requests open, you can use the requestId to track which seed is * @dev associated with which randomness. See VRFRequestIDBase.sol for more * @dev details. (See "SECURITY CONSIDERATIONS" for principles to keep in mind, * @dev if your contract could have multiple requests in flight simultaneously.) * * @dev Colliding `requestId`s are cryptographically impossible as long as seeds * @dev differ. (Which is critical to making unpredictable randomness! See the * @dev next section.) * * ***************************************************************************** * @dev SECURITY CONSIDERATIONS * * @dev A method with the ability to call your fulfillRandomness method directly * @dev could spoof a VRF response with any random value, so it's critical that * @dev it cannot be directly called by anything other than this base contract * @dev (specifically, by the VRFConsumerBase.rawFulfillRandomness method). * * @dev For your users to trust that your contract's random behavior is free * @dev from malicious interference, it's best if you can write it so that all * @dev behaviors implied by a VRF response are executed *during* your * @dev fulfillRandomness method. If your contract must store the response (or * @dev anything derived from it) and use it later, you must ensure that any * @dev user-significant behavior which depends on that stored value cannot be * @dev manipulated by a subsequent VRF request. * * @dev Similarly, both miners and the VRF oracle itself have some influence * @dev over the order in which VRF responses appear on the blockchain, so if * @dev your contract could have multiple VRF requests in flight simultaneously, * @dev you must ensure that the order in which the VRF responses arrive cannot * @dev be used to manipulate your contract's user-significant behavior. * * @dev Since the ultimate input to the VRF is mixed with the block hash of the * @dev block in which the request is made, user-provided seeds have no impact * @dev on its economic security properties. They are only included for API * @dev compatability with previous versions of this contract. * * @dev Since the block hash of the block which contains the requestRandomness * @dev call is mixed into the input to the VRF *last*, a sufficiently powerful * @dev miner could, in principle, fork the blockchain to evict the block * @dev containing the request, forcing the request to be included in a * @dev different block with a different hash, and therefore a different input * @dev to the VRF. However, such an attack would incur a substantial economic * @dev cost. This cost scales with the number of blocks the VRF oracle waits * @dev until it calls responds to a request. */ abstract contract VRFConsumerBase is VRFRequestIDBase { using SafeMathChainlink for uint256; /** * @notice fulfillRandomness handles the VRF response. Your contract must * @notice implement it. See "SECURITY CONSIDERATIONS" above for important * @notice principles to keep in mind when implementing your fulfillRandomness * @notice method. * * @dev VRFConsumerBase expects its subcontracts to have a method with this * @dev signature, and will call it once it has verified the proof * @dev associated with the randomness. (It is triggered via a call to * @dev rawFulfillRandomness, below.) * * @param requestId The Id initially returned by requestRandomness * @param randomness the VRF output */ function fulfillRandomness(bytes32 requestId, uint256 randomness) internal virtual; /** * @notice requestRandomness initiates a request for VRF output given _seed * * @dev The fulfillRandomness method receives the output, once it's provided * @dev by the Oracle, and verified by the vrfCoordinator. * * @dev The _keyHash must already be registered with the VRFCoordinator, and * @dev the _fee must exceed the fee specified during registration of the * @dev _keyHash. * * @dev The _seed parameter is vestigial, and is kept only for API * @dev compatibility with older versions. It can't *hurt* to mix in some of * @dev your own randomness, here, but it's not necessary because the VRF * @dev oracle will mix the hash of the block containing your request into the * @dev VRF seed it ultimately uses. * * @param _keyHash ID of public key against which randomness is generated * @param _fee The amount of LINK to send with the request * @param _seed seed mixed into the input of the VRF. * * @return requestId unique ID for this request * * @dev The returned requestId can be used to distinguish responses to * @dev concurrent requests. It is passed as the first argument to * @dev fulfillRandomness. */ function requestRandomness(bytes32 _keyHash, uint256 _fee, uint256 _seed) internal returns (bytes32 requestId) { LINK.transferAndCall(vrfCoordinator, _fee, abi.encode(_keyHash, _seed)); // This is the seed passed to VRFCoordinator. The oracle will mix this with // the hash of the block containing this request to obtain the seed/input // which is finally passed to the VRF cryptographic machinery. uint256 vRFSeed = makeVRFInputSeed(_keyHash, _seed, address(this), nonces[_keyHash]); // nonces[_keyHash] must stay in sync with // VRFCoordinator.nonces[_keyHash][this], which was incremented by the above // successful LINK.transferAndCall (in VRFCoordinator.randomnessRequest). // This provides protection against the user repeating their input seed, // which would result in a predictable/duplicate output, if multiple such // requests appeared in the same block. nonces[_keyHash] = nonces[_keyHash].add(1); return makeRequestId(_keyHash, vRFSeed); } LinkTokenInterface immutable internal LINK; address immutable private vrfCoordinator; // Nonces for each VRF key from which randomness has been requested. // // Must stay in sync with VRFCoordinator[_keyHash][this] mapping(bytes32 /* keyHash */ => uint256 /* nonce */) private nonces; /** * @param _vrfCoordinator address of VRFCoordinator contract * @param _link address of LINK token contract * * @dev https://docs.chain.link/docs/link-token-contracts */ constructor(address _vrfCoordinator, address _link) public { vrfCoordinator = _vrfCoordinator; LINK = LinkTokenInterface(_link); } // rawFulfillRandomness is called by VRFCoordinator when it receives a valid VRF // proof. rawFulfillRandomness then calls fulfillRandomness, after validating // the origin of the call function rawFulfillRandomness(bytes32 requestId, uint256 randomness) external { require(msg.sender == vrfCoordinator, "Only VRFCoordinator can fulfill"); fulfillRandomness(requestId, randomness); } } // Dependency file: @openzeppelin/contracts/token/ERC20/IERC20.sol // pragma solidity ^0.6.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); } // Dependency file: @openzeppelin/contracts/GSN/Context.sol // pragma solidity ^0.6.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; } } // Dependency file: @openzeppelin/contracts/access/Ownable.sol // pragma solidity ^0.6.0; // import "@openzeppelin/contracts/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. * * 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 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 { 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; } } // Dependency file: contracts/lib/Uint256ArrayUtils.sol // pragma solidity 0.6.10; /** * @title Uint256ArrayUtils * @author Prophecy * * Utility functions to handle uint256 Arrays */ library Uint256ArrayUtils { /** * 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(uint256[] memory A, uint256 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 (uint256(-1), 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(uint256[] memory A, uint256 a) internal pure returns (bool) { (, bool isIn) = indexOf(A, a); return isIn; } /** * Returns true if there are 2 elements that are the same in an array * @param A The input array to search * @return Returns boolean for the first occurrence of a duplicate */ function hasDuplicate(uint256[] memory A) internal pure returns(bool) { require(A.length > 0, "A is empty"); for (uint256 i = 0; i < A.length - 1; i++) { uint256 current = A[i]; for (uint256 j = i + 1; j < A.length; j++) { if (current == A[j]) { return true; } } } return false; } /** * @param A The input array to search * @param a The uint256 to remove * @return Returns the array with the object removed. */ function remove(uint256[] memory A, uint256 a) internal pure returns (uint256[] memory) { (uint256 index, bool isIn) = indexOf(A, a); if (!isIn) { revert("uint256 not in array."); } else { (uint256[] memory _A,) = pop(A, index); return _A; } } /** * @param A The input array to search * @param a The uint256 to remove */ function removeStorage(uint256[] storage A, uint256 a) internal { (uint256 index, bool isIn) = indexOf(A, a); if (!isIn) { revert("uint256 not in array."); } else { uint256 lastIndex = A.length - 1; // If the array would be empty, the previous line would throw, so no underflow here if (index != lastIndex) { A[index] = A[lastIndex]; } A.pop(); } } /** * Removes specified index from array * @param A The input array to search * @param index The index to remove * @return Returns the new array and the removed entry */ function pop(uint256[] memory A, uint256 index) internal pure returns (uint256[] memory, uint256) { uint256 length = A.length; require(index < A.length, "Index must be < A length"); uint256[] memory newUint256s = new uint256[](length - 1); for (uint256 i = 0; i < index; i++) { newUint256s[i] = A[i]; } for (uint256 j = index + 1; j < length; j++) { newUint256s[j - 1] = A[j]; } return (newUint256s, A[index]); } /** * 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(uint256[] memory A, uint256[] memory B) internal pure returns (uint256[] memory) { uint256 aLength = A.length; uint256 bLength = B.length; uint256[] memory newUint256s = new uint256[](aLength + bLength); for (uint256 i = 0; i < aLength; i++) { newUint256s[i] = A[i]; } for (uint256 j = 0; j < bLength; j++) { newUint256s[aLength + j] = B[j]; } return newUint256s; } /** * Validate uint256 array is not empty and contains no duplicate elements. * * @param A Array of uint256 */ function _validateLengthAndUniqueness(uint256[] memory A) internal pure { require(A.length > 0, "Array length must be > 0"); require(!hasDuplicate(A), "Cannot duplicate uint256"); } } // Dependency file: contracts/lib/AddressArrayUtils.sol // pragma solidity 0.6.10; /** * @title AddressArrayUtils * @author Prophecy * * Utility functions to handle uint256 Arrays */ 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 (uint256(-1), 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) = indexOf(A, a); return isIn; } /** * Returns true if there are 2 elements that are the same in an array * @param A The input array to search * @return Returns boolean for the first occurrence of a duplicate */ function hasDuplicate(address[] memory A) internal pure returns(bool) { require(A.length > 0, "A is empty"); for (uint256 i = 0; i < A.length - 1; i++) { address current = A[i]; for (uint256 j = i + 1; j < A.length; j++) { if (current == A[j]) { return true; } } } return false; } /** * @param A The input array to search * @param a The address to remove * @return Returns the array with the object removed. */ function remove(address[] memory A, address a) internal pure returns (address[] memory) { (uint256 index, bool isIn) = indexOf(A, a); if (!isIn) { revert("Address not in array."); } else { (address[] memory _A,) = pop(A, index); return _A; } } /** * @param A The input array to search * @param a The address to remove */ function removeStorage(address[] storage A, address a) internal { (uint256 index, bool isIn) = indexOf(A, a); if (!isIn) { revert("Address not in array."); } else { uint256 lastIndex = A.length - 1; // If the array would be empty, the previous line would throw, so no underflow here if (index != lastIndex) { A[index] = A[lastIndex]; } A.pop(); } } /** * Removes specified index from array * @param A The input array to search * @param index The index to remove * @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; require(index < A.length, "Index must be < 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]); } /** * 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; } /** * Validate that address and uint array lengths match. Validate address array is not empty * and contains no duplicate elements. * * @param A Array of addresses * @param B Array of uint */ function validatePairsWithArray(address[] memory A, uint[] memory B) internal pure { require(A.length == B.length, "Array length mismatch"); _validateLengthAndUniqueness(A); } /** * Validate that address and bool array lengths match. Validate address array is not empty * and contains no duplicate elements. * * @param A Array of addresses * @param B Array of bool */ function validatePairsWithArray(address[] memory A, bool[] memory B) internal pure { require(A.length == B.length, "Array length mismatch"); _validateLengthAndUniqueness(A); } /** * Validate that address and string array lengths match. Validate address array is not empty * and contains no duplicate elements. * * @param A Array of addresses * @param B Array of strings */ function validatePairsWithArray(address[] memory A, string[] memory B) internal pure { require(A.length == B.length, "Array length mismatch"); _validateLengthAndUniqueness(A); } /** * Validate that address array lengths match, and calling address array are not empty * and contain no duplicate elements. * * @param A Array of addresses * @param B Array of addresses */ function validatePairsWithArray(address[] memory A, address[] memory B) internal pure { require(A.length == B.length, "Array length mismatch"); _validateLengthAndUniqueness(A); } /** * Validate that address and bytes array lengths match. Validate address array is not empty * and contains no duplicate elements. * * @param A Array of addresses * @param B Array of bytes */ function validatePairsWithArray(address[] memory A, bytes[] memory B) internal pure { require(A.length == B.length, "Array length mismatch"); _validateLengthAndUniqueness(A); } /** * Validate address array is not empty and contains no duplicate elements. * * @param A Array of addresses */ function _validateLengthAndUniqueness(address[] memory A) internal pure { require(A.length > 0, "Array length must be > 0"); require(!hasDuplicate(A), "Cannot duplicate addresses"); } } // Dependency file: contracts/interfaces/IWETH.sol // pragma solidity 0.6.10; // import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title IWETH * @author Prophecy * * Interface for Wrapped Ether. This interface allows for interaction for wrapped ether's deposit and withdrawal * functionality. */ interface IWETH is IERC20{ function deposit() external payable; function withdraw(uint256 wad) external; } // Dependency file: contracts/interfaces/IController.sol // pragma solidity ^0.6.10; /** * @title IController * @author Prophecy */ interface IController { /** * Return WETH address. */ function getWeth() external view returns (address); /** * Getter for chanceToken */ function getChanceToken() external view returns (address); /** * Return VRF Key Hash. */ function getVrfKeyHash() external view returns (bytes32); /** * Return VRF Fee. */ function getVrfFee() external view returns (uint256); /** * Return Link Token address for VRF. */ function getLinkToken() external view returns (address); /** * Return VRF coordinator. */ function getVrfCoordinator() external view returns (address); /** * Return all pools addreses */ function getAllPools() external view returns (address[] memory); } // Dependency file: contracts/interfaces/IChanceToken.sol // pragma solidity ^0.6.10; /** * @title IChanceToken * @author Prophecy * * Interface for ChanceToken */ interface IChanceToken { /** * OWNER ALLOWED MINTER: Mint NFT */ function mint(address _account, uint256 _id, uint256 _amount) external; /** * OWNER ALLOWED BURNER: Burn NFT */ function burn(address _account, uint256 _id, uint256 _amount) external; } // Root file: contracts/ProphetPool.sol pragma solidity ^0.6.10; pragma experimental ABIEncoderV2; // import { VRFConsumerBase } from "@chainlink/contracts/src/v0.6/VRFConsumerBase.sol"; // import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; // import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol"; // import { Uint256ArrayUtils } from "contracts/lib/Uint256ArrayUtils.sol"; // import { AddressArrayUtils } from "contracts/lib/AddressArrayUtils.sol"; // import { IWETH } from "contracts/interfaces/IWETH.sol"; // import { IController } from "contracts/interfaces/IController.sol"; // import { IChanceToken } from "contracts/interfaces/IChanceToken.sol"; /** * @title ProphetPool * @author Prophecy * * Smart contract that facilitates that draws lucky winners in the pool and distribute rewards to the winners. * It should be whitelisted for the mintable role for ChanceToken(ERC1155) */ contract ProphetPool is VRFConsumerBase, Ownable { using Uint256ArrayUtils for uint256[]; using AddressArrayUtils for address[]; /* ============ Structs ============ */ struct PoolConfig { uint256 numOfWinners; uint256 participantLimit; uint256 enterAmount; uint256 feePercentage; uint256 randomSeed; uint256 startedAt; } /* ============ Enums ============ */ enum PoolStatus { NOTSTARTED, INPROGRESS, CLOSED } /* ============ Events ============ */ event FeeRecipientSet(address indexed _feeRecipient); event MaxParticipationCompleted(address indexed _from); event RandomNumberGenerated(uint256 indexed randomness); event WinnersGenerated(uint256[] winnerIndexes); event PoolSettled(); event PoolStarted( uint256 participantLimit, uint256 numOfWinners, uint256 enterAmount, uint256 feePercentage, uint256 startedAt ); event PoolReset(); event EnteredPool(address indexed _participant, uint256 _amount, uint256 indexed _participantIndex); /* ============ State Variables ============ */ IController private controller; address private feeRecipient; string private poolName; IERC20 private enterToken; PoolStatus private poolStatus; PoolConfig private poolConfig; uint256 private chanceTokenId; address[] private participants; uint256[] private winnerIndexes; uint256 private totalEnteredAmount; uint256 private rewardPerParticipant; bool internal isRNDGenerated; uint256 internal randomResult; bool internal areWinnersGenerated; /* ============ Modifiers ============ */ modifier onlyValidPool() { require(participants.length < poolConfig.participantLimit, "exceed max"); require(poolStatus == PoolStatus.INPROGRESS, "in progress"); _; } modifier onlyEOA() { require(tx.origin == msg.sender, "should be EOA"); _; } /* ============ Constructor ============ */ /** * Create the ProphetPool with Chainlink VRF configuration for Random number generation. * * @param _poolName Pool name * @param _enterToken ERC20 token to enter the pool. If it's ETH pool, it should be WETH address * @param _controller Controller * @param _feeRecipient Where the fee go * @param _chanceTokenId ERC1155 Token id for chance token */ constructor( string memory _poolName, address _enterToken, address _controller, address _feeRecipient, uint256 _chanceTokenId ) public VRFConsumerBase(IController(_controller).getVrfCoordinator(), IController(_controller).getLinkToken()) { poolName = _poolName; enterToken = IERC20(_enterToken); controller = IController(_controller); feeRecipient = _feeRecipient; chanceTokenId = _chanceTokenId; poolStatus = PoolStatus.NOTSTARTED; } /* ============ External/Public Functions ============ */ /** * Set the Pool Config, initializes an instance of and start the pool. * * @param _numOfWinners Number of winners in the pool * @param _participantLimit Maximum number of paricipants * @param _enterAmount Exact amount to enter this pool * @param _feePercentage Manager fee of this pool * @param _randomSeed Seed for Random Number Generation */ function setPoolRules( uint256 _numOfWinners, uint256 _participantLimit, uint256 _enterAmount, uint256 _feePercentage, uint256 _randomSeed ) external onlyOwner { require(poolStatus == PoolStatus.NOTSTARTED, "in progress"); require(_numOfWinners != 0, "invalid numOfWinners"); require(_numOfWinners < _participantLimit, "too much numOfWinners"); poolConfig = PoolConfig( _numOfWinners, _participantLimit, _enterAmount, _feePercentage, _randomSeed, block.timestamp ); poolStatus = PoolStatus.INPROGRESS; emit PoolStarted( _participantLimit, _numOfWinners, _enterAmount, _feePercentage, block.timestamp ); } /** * Set the Pool Config, initializes an instance of and start the pool. * * @param _feeRecipient Number of winners in the pool */ function setFeeRecipient(address _feeRecipient) external onlyOwner { require(_feeRecipient != address(0), "invalid address"); feeRecipient = _feeRecipient; emit FeeRecipientSet(feeRecipient); } /** * Enter pool with ETH */ function enterPoolEth() external payable onlyValidPool onlyEOA returns (uint256) { require(msg.value == poolConfig.enterAmount, "insufficient amount"); if (!_isEthPool()) { revert("not accept ETH"); } // wrap ETH to WETH IWETH(controller.getWeth()).deposit{ value: msg.value }(); return _enterPool(); } /** * Enter pool with ERC20 token */ function enterPool() external onlyValidPool onlyEOA returns (uint256) { enterToken.transferFrom( msg.sender, address(this), poolConfig.enterAmount ); return _enterPool(); } /** * Settle the pool, the winners are selected randomly and fee is transfer to the manager. */ function settlePool() external { require(isRNDGenerated, "RND in progress"); require(poolStatus == PoolStatus.INPROGRESS, "pool in progress"); // generate winnerIndexes until the numOfWinners reach uint256 newRandom = randomResult; uint256 offset = 0; while(winnerIndexes.length < poolConfig.numOfWinners) { uint256 winningIndex = newRandom.mod(poolConfig.participantLimit); if (!winnerIndexes.contains(winningIndex)) { winnerIndexes.push(winningIndex); } offset = offset.add(1); newRandom = _getRandomNumberBlockchain(offset, newRandom); } areWinnersGenerated = true; emit WinnersGenerated(winnerIndexes); // set pool CLOSED status poolStatus = PoolStatus.CLOSED; // transfer fees uint256 feeAmount = totalEnteredAmount.mul(poolConfig.feePercentage).div(100); rewardPerParticipant = (totalEnteredAmount.sub(feeAmount)).div(poolConfig.numOfWinners); _transferEnterToken(feeRecipient, feeAmount); // collectRewards(); emit PoolSettled(); } /** * The winners of the pool can call this function to transfer their winnings * from the pool contract to their own address. */ function collectRewards() external { require(poolStatus == PoolStatus.CLOSED, "not settled"); for (uint256 i = 0; i < poolConfig.participantLimit; i = i.add(1)) { address player = participants[i]; if (winnerIndexes.contains(i)) { // if winner _transferEnterToken(player, rewardPerParticipant); } else { // if loser IChanceToken(controller.getChanceToken()).mint(player, chanceTokenId, 1); } } _resetPool(); } /** * The contract will receive Ether */ receive() external payable {} /** * Getter for controller */ function getController() external view returns (address) { return address(controller); } /** * Getter for fee recipient */ function getFeeRecipient() external view returns (address) { return feeRecipient; } /** * Getter for poolName */ function getPoolName() external view returns (string memory) { return poolName; } /** * Getter for enterToken */ function getEnterToken() external view returns (address) { return address(enterToken); } /** * Getter for chanceTokenId */ function getChanceTokenId() external view returns (uint256) { return chanceTokenId; } /** * Getter for poolStatus */ function getPoolStatus() external view returns (PoolStatus) { return poolStatus; } /** * Getter for poolConfig */ function getPoolConfig() external view returns (PoolConfig memory) { return poolConfig; } /** * Getter for totalEnteredAmount */ function getTotalEnteredAmount() external view returns (uint256) { return totalEnteredAmount; } /** * Getter for rewardPerParticipant */ function getRewardPerParticipant() external view returns (uint256) { return rewardPerParticipant; } /** * Get all participants */ function getParticipants() external view returns(address[] memory) { return participants; } /** * Get one participant by index * @param _index Index of the participants array */ function getParticipant(uint256 _index) external view returns(address) { return participants[_index]; } /** * Getter for winnerIndexes */ function getWinnerIndexes() external view returns(uint256[] memory) { return winnerIndexes; } /** * Get if the account is winner */ function isWinner(address _account) external view returns(bool) { (uint256 index, bool isExist) = participants.indexOf(_account); if (isExist) { return winnerIndexes.contains(index); } else { return false; } } /* ============ Private/Internal Functions ============ */ /** * Participant enters the pool and enter amount is transferred from the user to the pool. */ function _enterPool() internal returns(uint256 _participantIndex) { participants.push(msg.sender); totalEnteredAmount = totalEnteredAmount.add(poolConfig.enterAmount); if (participants.length == poolConfig.participantLimit) { emit MaxParticipationCompleted(msg.sender); _getRandomNumber(poolConfig.randomSeed); } _participantIndex = (participants.length).sub(1); emit EnteredPool(msg.sender, poolConfig.enterAmount, _participantIndex); } /** * Reset the pool, clears the existing state variable values and the pool can be initialized again. */ function _resetPool() internal { poolStatus = PoolStatus.INPROGRESS; delete totalEnteredAmount; delete rewardPerParticipant; isRNDGenerated = false; randomResult = 0; areWinnersGenerated = false; delete winnerIndexes; delete participants; emit PoolReset(); uint256 tokenBalance = enterToken.balanceOf(address(this)); if (tokenBalance > 0) { _transferEnterToken(feeRecipient, tokenBalance); } } /** * Transfer enterToken even it's ETH or ERC20. * * @param _to Offset to generate the random number * @param _amount Random number to generate the other random number */ function _transferEnterToken(address _to, uint256 _amount) internal { if (_isEthPool()) { IWETH(controller.getWeth()).withdraw(_amount); (bool status, ) = payable(_to).call{value: _amount}(""); require(status, "ETH not transferred"); } else { enterToken.transfer(address(_to), _amount); } } /** * Check pool is ETH pool or not */ function _isEthPool() internal view returns (bool) { return address(enterToken) == controller.getWeth(); } /** * Generate a random number based on the blockHash and random offset * * @param _offset Offset to generate the random number * @param _randomness Random number to generate the other random number */ function _getRandomNumberBlockchain(uint256 _offset, uint256 _randomness) internal view returns (uint256) { bytes32 baseHash = keccak256( abi.encodePacked( blockhash(block.number), bytes32(_offset), bytes32(_randomness) ) ); return uint256(baseHash); } /** * Calls ChainLink Oracle's inherited function for Random Number Generation. * The contract must have enough LINK required for VRF. * * @param _userProvidedSeed Seed to generate the random number */ function _getRandomNumber(uint256 _userProvidedSeed) internal returns (bytes32 requestId) { require( IERC20(controller.getLinkToken()).balanceOf(address(this)) >= controller.getVrfFee(), "not enough LINK" ); randomResult = 0; isRNDGenerated = false; return requestRandomness( controller.getVrfKeyHash(), controller.getVrfFee(), _userProvidedSeed ); } /** * Callback function used by VRF Coordinator. * * @param _randomness Generated random number */ function fulfillRandomness(bytes32, uint256 _randomness) internal override { randomResult = _randomness; isRNDGenerated = true; emit RandomNumberGenerated(_randomness); } }
Returns the combination of the two arrays A The first array B The second array return Returns A extended by B/
function extend(uint256[] memory A, uint256[] memory B) internal pure returns (uint256[] memory) { uint256 aLength = A.length; uint256 bLength = B.length; uint256[] memory newUint256s = new uint256[](aLength + bLength); for (uint256 i = 0; i < aLength; i++) { newUint256s[i] = A[i]; } for (uint256 j = 0; j < bLength; j++) { newUint256s[aLength + j] = B[j]; } return newUint256s; }
225,574
./full_match/8217/0xe41066e28Ff95244741262Bd877015Edf3f8a9a0/sources/contracts/library/KIP7Upgradeable.sol
Internal function to invoke {IKIP7Receiver-onKIP7Received} on a target address. The call is not executed if the target address is not a contract. from address representing the previous owner of transfer token amount to target address that will receive the tokens amount uint256 value to be transferred _data bytes optional data to send along with the call return bool whether the call correctly returned the expected magic value/
function _checkOnKIP7Received( address from, address to, uint256 amount, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IKIP7Receiver(to).onKIP7Received( _msgSender(), from, amount, _data ) returns (bytes4 retval) { return retval == IKIP7Receiver.onKIP7Received.selector; if (reason.length == 0) { revert("KIP7: transfer to non KIP7Receiver implementer"); assembly { revert(add(32, reason), mload(reason)) } } } return true; } }
13,229,608
pragma solidity 0.7.6; pragma abicoder v2; //SPDX-License-Identifier: MIT import "hardhat/console.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/utils/EnumerableSet.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./interfaces/IArbitrator.sol"; // https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/access/Ownable.sol contract UnbreakableVow { using EnumerableSet for EnumerableSet.AddressSet; using SafeERC20 for IERC20; event Signed(address indexed signer, uint256 settingId); event SettingChanged(uint256 settingId); enum UnbreakableVowState { UNSIGNED, ACTIVE, TERMINATED } enum UserState { UNSIGNED, SIGNED, OFFERS_TERMINATION } struct Setting { IArbitrator arbitrator; string title; bytes content; } struct Party { uint256 lastSettingIdSigned; IERC20 collateralToken; uint256 collateralAmount; uint256 depositedAmount; bool offerTermination; } UnbreakableVowState public state = UnbreakableVowState.UNSIGNED; uint256 public currentSettingId = 0; // All parties have to sign in order to update the setting uint256 private nextSettingId = 1; mapping (uint256 => Setting) private settings; // List of historic agreement settings indexed by ID (starting at 1) EnumerableSet.AddressSet private parties; mapping (address => Party) private partiesInfo; // Mapping of address => last agreement setting signed /** * @notice Initialize Agreement for "`_title`" and content "`_content`", with arbitrator `_arbitrator` * @param _arbitrator Address of the IArbitrator that will be used to resolve disputes * @param _title String indicating a short description * @param _content Link to a human-readable text that describes the initial rules for the Agreement * @param _parties List of addresses that must sign the Agreement */ constructor( IArbitrator _arbitrator, string memory _title, bytes memory _content, address[] memory _parties, IERC20[] memory _collateralTokens, uint256[] memory _collateralAmounts ) { for (uint i = 0; i < _parties.length; i++) { parties.add(_parties[i]); partiesInfo[_parties[i]] = Party(0, _collateralTokens[i], _collateralAmounts[i], 0, false); } proposeSetting(_arbitrator, _title, _content); } /** * @notice Propose and sign Agreement to title "`_title`" and content "`_content`", with arbitrator `_arbitrator` * @dev Initialization check is implicitly provided by the `auth()` modifier * @param _arbitrator Address of the IArbitrator that will be used to resolve disputes * @param _title String indicating a short description * @param _content Link to a human-readable text that describes the new rules for the Agreement */ function proposeSetting( IArbitrator _arbitrator, string memory _title, bytes memory _content ) public { sign(_newSetting(_arbitrator, _title, _content)); } /** * @notice Sign the agreement up-to setting #`_settingId` * @dev Callable by any party * @param _settingId Last setting ID the user is agreeing with */ function sign(uint256 _settingId) public { uint256 lastSettingIdSigned = partiesInfo[msg.sender].lastSettingIdSigned; require (state != UnbreakableVowState.TERMINATED, "ERROR_CAN_NOT_SIGN_TERMINATED_VOW"); require(lastSettingIdSigned != _settingId, "ERROR_SIGNER_ALREADY_SIGNED"); require(_settingId < nextSettingId, "ERROR_INVALID_SIGNING_SETTING"); // if (partiesInfo[msg.sender].depositedAmount < partiesInfo[msg.sender].collateralAmount) { // partiesInfo[msg.sender].collateralToken.safeTransferFrom( // msg.sender, // address(this), // partiesInfo[msg.sender].collateralAmount - partiesInfo[msg.sender].depositedAmount // ); // partiesInfo[msg.sender].depositedAmount = partiesInfo[msg.sender].collateralAmount; // } partiesInfo[msg.sender].lastSettingIdSigned = _settingId; emit Signed(msg.sender, _settingId); _changeSettingIfPossible(_settingId); } function unstakeCollateral() public { require (state != UnbreakableVowState.ACTIVE, "ERROR_CAN_NOT_UNSTAKE_FROM_ACTIVE_VOW"); // uint256 amount = partiesInfo[msg.sender].depositedAmount; // partiesInfo[msg.sender].collateralToken.transfer(msg.sender, amount); partiesInfo[msg.sender].depositedAmount = 0; partiesInfo[msg.sender].lastSettingIdSigned = 0; } function terminate(bool offersTermination) public{ require (state == UnbreakableVowState.ACTIVE, "ERROR_CAN_NOT_TERMINATE_UNACTIVE_VOW"); partiesInfo[msg.sender].offerTermination = offersTermination; _changeSettingIfPossible(0); } /** * @dev Tell the information related to an agreement setting * @param _settingId Identification number of the agreement setting * @return arbitrator Address of the IArbitrator that will be used to resolve disputes * @return title String indicating a short description * @return content Link to a human-readable text that describes the current rules for the Agreement */ function getSetting(uint256 _settingId) public view returns (IArbitrator arbitrator, string memory title, bytes memory content) { Setting storage setting = _getSetting(_settingId); arbitrator = setting.arbitrator; title = setting.title; content = setting.content; } function getCurrentSetting() public view returns (IArbitrator arbitrator, string memory title, bytes memory content) { return getSetting(currentSettingId == 0 ? 1 : currentSettingId); } function getParties() external view returns ( address[] memory _parties, UserState[] memory _signed, address[] memory _collateralTokens, uint256[] memory _collateralAmounts, uint256[] memory _depositedAmounts ) { _parties = new address[](parties.length()); _signed = new UserState[](_parties.length); _collateralTokens = new address[](_parties.length); _collateralAmounts = new uint256[](_parties.length); _depositedAmounts = new uint256[](_parties.length); for(uint i=0; i < parties.length(); i++) { _parties[i] = parties.at(i); Party storage party = partiesInfo[_parties[i]]; _signed[i] = party.offerTermination ? UserState.OFFERS_TERMINATION : party.lastSettingIdSigned != 0? UserState.SIGNED : UserState.UNSIGNED; _collateralTokens[i] = address(party.collateralToken); _collateralAmounts[i] = party.collateralAmount; _depositedAmounts[i] = party.depositedAmount; } } /** * @dev Add new agreement settings * @param _arbitrator Address of the IArbitrator that will be used to resolve disputes * @param _title String indicating a short description * @param _content Link to a human-readable text that describes the new rules for the Agreement * @return id Id of the new setting */ function _newSetting( IArbitrator _arbitrator, string memory _title, bytes memory _content ) internal returns (uint256 id) { require(Address.isContract(address(_arbitrator)), "ERROR_ARBITRATOR_NOT_CONTRACT"); id = nextSettingId++; Setting storage setting = settings[id]; setting.title = _title; setting.content = _content; setting.arbitrator = _arbitrator; } /** * @dev Fetch an agreement setting instance by identification number * @param _settingId Identification number of the agreement setting * @return Agreement setting instance associated to the given identification number */ function _getSetting(uint256 _settingId) internal view returns (Setting storage) { require(_settingId >= 0 && _settingId < nextSettingId, "ERROR_SETTING_DOES_NOT_EXIST"); return settings[_settingId]; } function _changeSettingIfPossible(uint256 _settingId) private { if(_settingId != 0) { for (uint256 i = 0; i < parties.length(); i++) { if (partiesInfo[parties.at(i)].lastSettingIdSigned != _settingId) { return; } } currentSettingId = _settingId; state = UnbreakableVowState.ACTIVE; emit SettingChanged(_settingId); } else { for (uint256 i = 0; i < parties.length(); i++) { if (!partiesInfo[parties.at(i)].offerTermination) { return; } } state = UnbreakableVowState.TERMINATED; } } }
Propose and sign Agreement to title "`_title`" and content "`_content`", with arbitrator `_arbitrator` Initialization check is implicitly provided by the `auth()` modifier _arbitrator Address of the IArbitrator that will be used to resolve disputes _title String indicating a short description _content Link to a human-readable text that describes the new rules for the Agreement/
function proposeSetting( IArbitrator _arbitrator, string memory _title, bytes memory _content ) public { sign(_newSetting(_arbitrator, _title, _content)); }
1,760,104
pragma solidity ^0.4.25; pragma experimental ABIEncoderV2; library SafeMath { 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; } function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0); uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } library BnsLib { struct TopLevelDomain { uint price; uint lastUpdate; bool min; bool exists; } struct Domain { address owner; bool allowSubdomains; bytes content; mapping(string => string) domainStorage; mapping(address => bool) approvedForSubdomain; } function hasOnlyDomainLevelCharacters(string memory str) internal pure returns (bool) { /* [9-0] [A-Z] [a-z] [-] */ bytes memory b = bytes(str); for(uint i; i<b.length; i++) { bytes1 char = b[i]; if (! ( (char >= 0x30 && char <= 0x39) || (char >= 0x41 && char <= 0x5A) || (char >= 0x61 && char <= 0x7A) || (char == 0x2d) )) return false; } return true; } function strictJoin(string memory self, string memory s2, bytes1 delimiter) internal pure returns (string memory) { /* Allow [0-9] [a-z] [-] Make [A-Z] lowercase */ bytes memory orig = bytes(self); bytes memory addStr = bytes(s2); uint retSize = orig.length + addStr.length + 1; bytes memory ret = new bytes(retSize); for (uint i = 0; i < orig.length; i ++) { require( (orig[i] >= 0x30 && orig[i] <= 0x39) || // 0-9 (orig[i] >= 0x41 && orig[i] <= 0x5A) || // A-Z (orig[i] >= 0x61 && orig[i] <= 0x7A) || // a-z (orig[i] == 0x2d || orig[i] == 0x5f), // - _ "Invalid character." ); if (orig[i] >= 0x41 && orig[i] <= 0x5A) ret[i] = bytes1(uint8(orig[i]) + 32); else ret[i] = orig[i]; } ret[orig.length] = delimiter; for (uint x = 0; x < addStr.length; x ++) { if (addStr[x] >= 0x41 && addStr[x] <= 0x5A) ret[orig.length + x + 1] = bytes1(uint8(addStr[x]) + 32); else ret[orig.length + x + 1] = addStr[x]; } return string(ret); } } contract BetterNameService { using BnsLib for *; using SafeMath for uint; constructor() public { createTopLevelDomain("bns"); creat0r = msg.sender; } address creat0r; uint updateAfter = 15000; // target around 1 update per day uint minPrice = 10000000000000000; // 0.01 eth mapping(string => BnsLib.TopLevelDomain) internal tldPrices; mapping(string => BnsLib.Domain) domains; // domain and subdomain owners function withdraw(uint amount) public { require(msg.sender == creat0r, "Only the creat0r can call that."); msg.sender.transfer(amount); } function balanceOf() public view returns (uint) { return address(this).balance; } /*----------------<BEGIN MODIFIERS>----------------*/ modifier tldExists(string memory tld) { require(tldPrices[tld].exists, "TLD does not exist"); _; } modifier tldNotExists(string memory tld) { require(!tldPrices[tld].exists, "TLD exists"); _; } modifier domainExists(string memory domain) { require( domains[domain].owner != address(0) && domains[domain].owner != address(0x01), "Domain does not exist or has been invalidated."); _; } modifier domainNotExists(string memory domain) { require(domains[domain].owner == address(0), "Domain exists"); _; } modifier onlyDomainOwner(string memory domain) { require(msg.sender == domains[domain].owner, "Not owner of domain"); _; } modifier onlyAllowed(string memory domain) { require( domains[domain].allowSubdomains || domains[domain].owner == msg.sender || domains[domain].approvedForSubdomain[msg.sender], "Not allowed to register subdomain." ); _; } modifier onlyDomainLevelCharacters(string memory domainLevel) { require(BnsLib.hasOnlyDomainLevelCharacters(domainLevel), "Invalid characters"); _; } /*----------------</END MODIFIERS>----------------*/ /*----------------<BEGIN EVENTS>----------------*/ event TopLevelDomainCreated(bytes32 indexed tldHash, string tld); event TopLevelDomainPriceUpdated(bytes32 indexed tldHash, string tld, uint price); event DomainRegistered(bytes32 indexed domainHash, string domain, address owner, address registeredBy, bool open); event SubdomainInvalidated(bytes32 indexed subdomainHash, string subdomain, address invalidatedBy); event DomainRegistrationOpened(bytes32 indexed domainHash, string domain); event DomainRegistrationClosed(bytes32 indexed domainHash, string domain); event ApprovedForDomain(bytes32 indexed domainHash, string domain, address indexed approved); event DisapprovedForDomain(bytes32 indexed domainHash, string domain, address indexed disapproved); event ContentUpdated(bytes32 indexed domainHash, string domain, bytes content); /*----------------</END EVENTS>----------------*/ /*----------------<BEGIN VIEW FUNCTIONS>----------------*/ function getTldPrice(string tld) public view returns (uint) { return tldPrices[tld].min ? minPrice : tldPrices[tld].price; } function expectedTldPrice(string tld) public view returns (uint) { if (tldPrices[tld].min) return minPrice; uint blockCount = block.number.sub(tldPrices[tld].lastUpdate); if (blockCount >= updateAfter) { uint updatesDue = blockCount.div(updateAfter); uint newPrice = tldPrices[tld].price.mul(750**updatesDue).div(1000**updatesDue); if (newPrice <= minPrice) return minPrice; return newPrice; } return tldPrices[tld].price; } function getDomainOwner(string domain) public view returns (address) { return domains[domain].owner; } function isPublicDomainRegistrationOpen(string memory domain) public view returns (bool) { return domains[domain].allowSubdomains; } function isApprovedToRegister(string memory domain, address addr) public view returns (bool) { return domains[domain].allowSubdomains || domains[domain].owner == addr || domains[domain].approvedForSubdomain[addr]; } function isDomainInvalidated(string memory domain) public view returns(bool) { return domains[domain].owner == address(0x01); } function getContent(string memory domain) public view returns (bytes) { return domains[domain].content; } /*<BEGIN STORAGE FUNCTIONS>*/ function getDomainStorageSingle(string domain, string key) public view domainExists(domain) returns (string) { return domains[domain].domainStorage[key]; } function getDomainStorageMany(string domain, string[] memory keys) public view domainExists(domain) returns (string[2][]) { string[2][] memory results = new string[2][](keys.length); for(uint i = 0; i < keys.length; i++) { string memory key = keys[i]; results[i] = [key, domains[domain].domainStorage[key]]; } return results; } /*</END STORAGE FUNCTIONS>*/ /*----------------</END VIEW FUNCTIONS>----------------*/ /*----------------<BEGIN PRICE FUNCTIONS>----------------*/ function returnRemainder(uint price) internal { if (msg.value > price) msg.sender.transfer(msg.value.sub(price)); } function updateTldPrice(string memory tld) public returns (uint) { if (!tldPrices[tld].min) { // tld price has not reached the minimum price uint price = expectedTldPrice(tld); if (price != tldPrices[tld].price) { if (price == minPrice) { tldPrices[tld].min = true; tldPrices[tld].price = 0; tldPrices[tld].lastUpdate = 0; } else { tldPrices[tld].price = price; tldPrices[tld].lastUpdate = block.number.sub((block.number.sub(tldPrices[tld].lastUpdate)).mod(updateAfter)); } emit TopLevelDomainPriceUpdated(keccak256(abi.encode(tld)), tld, price); } return price; } else return minPrice; } /*----------------</END PRICE FUNCTIONS>----------------*/ /*----------------<BEGIN DOMAIN REGISTRATION FUNCTIONS>----------------*/ /*<BEGIN TLD FUNCTIONS>*/ function createTopLevelDomain(string memory tld) public tldNotExists(tld) onlyDomainLevelCharacters(tld) { tldPrices[tld] = BnsLib.TopLevelDomain({ price: 5000000000000000000, lastUpdate: block.number, exists: true, min: false }); emit TopLevelDomainCreated(keccak256(abi.encode(tld)), tld); } /*</END TLD FUNCTIONS>*/ /*<BEGIN INTERNAL REGISTRATION FUNCTIONS>*/ function _register(string memory domain, address owner, bool open) internal domainNotExists(domain) { domains[domain].owner = owner; emit DomainRegistered(keccak256(abi.encode(domain)), domain, owner, msg.sender, open); if (open) domains[domain].allowSubdomains = true; } function _registerDomain(string memory domain, string memory tld, bool open) internal tldExists(tld) { uint price = updateTldPrice(tld); require(msg.value >= price, "Insufficient price."); _register(domain.strictJoin(tld, 0x40), msg.sender, open); returnRemainder(price); } function _registerSubdomain( string memory subdomain, string memory domain, address owner, bool open) internal onlyAllowed(domain) { _register(subdomain.strictJoin(domain, 0x2e), owner, open); } /*</END INTERNAL REGISTRATION FUNCTIONS>*/ /*<BEGIN REGISTRATION OVERLOADS>*/ function registerDomain(string memory domain, bool open) public payable { _registerDomain(domain, "bns", open); } function registerDomain(string memory domain, string memory tld, bool open) public payable { _registerDomain(domain, tld, open); } /*</END REGISTRATION OVERLOADS>*/ /*<BEGIN SUBDOMAIN REGISTRATION OVERLOADS>*/ function registerSubdomain(string memory subdomain, string memory domain, bool open) public { _registerSubdomain(subdomain, domain, msg.sender, open); } function registerSubdomainAsDomainOwner( string memory subdomain, string memory domain, address subdomainOwner) public onlyDomainOwner(domain) { _registerSubdomain(subdomain, domain, subdomainOwner, false); } /*</END SUBDOMAIN REGISTRATION OVERLOADS>*/ /*----------------</END DOMAIN REGISTRATION FUNCTIONS>----------------*/ /*----------------<BEGIN DOMAIN MANAGEMENT FUNCTIONS>----------------*/ function transferDomain(string domain, address recipient) public onlyDomainOwner(domain) { domains[domain].owner = recipient; } /*<BEGIN CONTENT HASH FUNCTIONS>*/ function setContent(string memory domain, bytes memory content) public onlyDomainOwner(domain) { domains[domain].content = content; emit ContentUpdated(keccak256(abi.encode(domain)), domain, content); } function deleteContent(string memory domain) public onlyDomainOwner(domain) { delete domains[domain].content; emit ContentUpdated(keccak256(abi.encode(domain)), domain, domains[domain].content); } /*</END CONTENT HASH FUNCTIONS>*/ /*<BEGIN APPROVAL FUNCTIONS>*/ function approveForSubdomain(string memory domain, address user) public onlyDomainOwner(domain) { domains[domain].approvedForSubdomain[user] = true; emit ApprovedForDomain(keccak256(abi.encode(domain)), domain, user); } function disapproveForSubdomain(string memory domain, address user) public onlyDomainOwner(domain) { domains[domain].approvedForSubdomain[user] = false; emit DisapprovedForDomain(keccak256(abi.encode(domain)), domain, user); } /*</END APPROVAL FUNCTIONS>*/ /*<BEGIN INVALIDATION FUNCTIONS>*/ function _invalidateDomain(string memory domain) internal { domains[domain].owner = address(0x01); emit SubdomainInvalidated(keccak256(abi.encode(domain)), domain, msg.sender); } function invalidateDomain(string memory domain) public onlyDomainOwner(domain) { _invalidateDomain(domain); } function invalidateSubdomainAsDomainOwner(string memory subdomain, string memory domain) public onlyDomainOwner(domain) { _invalidateDomain(subdomain.strictJoin(domain, ".")); } /*</END INVALIDATION FUNCTIONS>*/ /*<BEGIN RESTRICTION FUNCTIONS>*/ function openPublicDomainRegistration(string domain) public onlyDomainOwner(domain) { domains[domain].allowSubdomains = true; emit DomainRegistrationOpened(keccak256(abi.encode(domain)), domain); } function closePublicDomainRegistration(string domain) public onlyDomainOwner(domain) { domains[domain].allowSubdomains = false; emit DomainRegistrationClosed(keccak256(abi.encode(domain)), domain); } /*</END RESTRICTION FUNCTIONS>*/ /*<BEGIN STORAGE FUNCTIONS>*/ function setDomainStorageSingle(string memory domain, string memory key, string memory value) public onlyDomainOwner(domain) { domains[domain].domainStorage[key] = value; } function setDomainStorageMany(string memory domain, string[2][] memory kvPairs) public onlyDomainOwner(domain) { for(uint i = 0; i < kvPairs.length; i++) { domains[domain].domainStorage[kvPairs[i][0]] = kvPairs[i][1]; } } /*</END STORAGE FUNCTIONS>*/ /*----------------</END DOMAIN MANAGEMENT FUNCTIONS>----------------*/ }
[9-0] [A-Z] [a-z] [-] /
function hasOnlyDomainLevelCharacters(string memory str) internal pure returns (bool) { bytes memory b = bytes(str); for(uint i; i<b.length; i++) { bytes1 char = b[i]; if (! ( (char >= 0x30 && char <= 0x39) || (char >= 0x41 && char <= 0x5A) || (char >= 0x61 && char <= 0x7A) || (char == 0x2d) )) return false; } return true; }
5,371,870
pragma solidity >=0.5.10; import 'ROOT/libraries/IERC1820Implementer.sol'; contract ERC1820Implementer is IERC1820Implementer { bytes32 constant private ERC1820_ACCEPT_MAGIC = keccak256(abi.encodePacked("ERC1820_ACCEPT_MAGIC")); mapping(bytes32 => mapping(address => bool)) private _supportedInterfaces; /** * See `IERC1820Implementer.canImplementInterfaceForAddress`. */ function canImplementInterfaceForAddress(bytes32 interfaceHash, address account) external view returns (bytes32) { return _supportedInterfaces[interfaceHash][account] ? ERC1820_ACCEPT_MAGIC : bytes32(0x00); } /** * @dev Declares the contract as willing to be an implementer of * `interfaceHash` for `account`. * * See `IERC1820Registry.setInterfaceImplementer` and * `IERC1820Registry.interfaceHash`. */ function _registerInterfaceForAddress(bytes32 interfaceHash, address account) internal { _supportedInterfaces[interfaceHash][account] = true; } }
See `IERC1820Implementer.canImplementInterfaceForAddress`./
function canImplementInterfaceForAddress(bytes32 interfaceHash, address account) external view returns (bytes32) { return _supportedInterfaces[interfaceHash][account] ? ERC1820_ACCEPT_MAGIC : bytes32(0x00); }
1,756,397
./partial_match/1/0x6BC1Ab049299cCbec1acF843D6cdbc530f0C8607/sources/JSUToken.sol
Returns the name of the token./
function name() public view returns (string memory) { return _name; }
3,586,128
// SPDX-License-Identifier: MIT pragma solidity ^0.7.6; /// @title An Ethereum library that contains information about all the instances of the Wonka rules engines in a blockchain /// @author Aaron Kendall /// @notice /// @dev contract WonkaRegistry { /// @title Defines a rule grove /// @notice This class will provide information on a Grove (i.e., a collection of RuleTrees) struct WonkaRuleGrove { bytes32 ruleGroveId; string description; bytes32[] ruleTreeMembers; mapping(bytes32 => uint) memberPositions; address owner; uint creationEpochTime; bool isValue; } /// @title Defines a ruletree index /// @notice This class will provide information on any RuleTree in the 'tree-verse' (which contract owns it, who owns it, the cost associated with it, etc.) struct WonkaRuleTreeIndex { bytes32 ruleTreeId; string description; bytes32[] ruleTreeGroveIds; address hostContractAddress; // This property also doubles as the ID for the ruletree within an instance of the WonkaEngine address owner; uint minGasCost; uint maxGasCost; // These are other contracts that the RuleTree talks to, from within the host address[] contractAssociates; bytes32[] usedAttributes; bytes32[] usedCustomOperators; uint creationEpochTime; bool isValue; } string constant CONST_DEFAULT_VALUE = "Default"; // The cache of all rule groves mapping(bytes32 => WonkaRuleGrove) private ruleGroves; bytes32[] private ruleGrovesEnum; // The cache of all rule trees mapping(bytes32 => WonkaRuleTreeIndex) private ruleTrees; bytes32[] private ruleTreesEnum; /// @dev Constructor for the RuleTree registry /// @notice constructor() { // NOTE: Initialize members here } /// @dev This method will add a new grove to the registry /// @notice function addRuleGrove(bytes32 groveId, string memory desc, address groveOwner, uint createTime) public { require(groveId != "", "Blank GroveID has been provided."); require(ruleGroves[groveId].isValue != true, "Grove with ID already exists."); ruleGroves[groveId].ruleGroveId = groveId; ruleGroves[groveId].description = desc; ruleGroves[groveId].ruleTreeMembers = new bytes32[](0); ruleGroves[groveId].owner = groveOwner; ruleGroves[groveId].creationEpochTime = createTime; ruleGroves[groveId].isValue = true; ruleGrovesEnum.push(groveId); } /// @dev This method will add a new tree index to the registry /// @notice function addRuleTreeIndex(address ruler, bytes32 rsId, string memory desc, bytes32 ruleTreeGrpId, uint grpIdx, address host, uint minCost, uint maxCost, address[] memory associates, bytes32[] memory attributes, bytes32[] memory ops, uint createTime) public { // require(msg.sender == rulesMaster); require(rsId != "", "Blank ID for RuleSet has been provided"); require(ruleTrees[rsId].isValue != true, "RuleTree for ID already exists."); ruleTrees[rsId] = WonkaRuleTreeIndex({ ruleTreeId: rsId, description: desc, ruleTreeGroveIds: new bytes32[](0), hostContractAddress: host, owner: ruler, minGasCost: minCost, maxGasCost: maxCost, contractAssociates: associates, usedAttributes: attributes, usedCustomOperators: ops, creationEpochTime: createTime, isValue: true }); ruleTreesEnum.push(rsId); if (ruleTreeGrpId != "") { if (ruleGroves[ruleTreeGrpId].isValue != true) addRuleGrove(ruleTreeGrpId, CONST_DEFAULT_VALUE, ruler, createTime); ruleTrees[rsId].ruleTreeGroveIds.push(ruleTreeGrpId); ruleGroves[ruleTreeGrpId].ruleTreeMembers.push(rsId); if ((grpIdx > 0) && (grpIdx <= ruleGroves[ruleTreeGrpId].ruleTreeMembers.length)) { ruleGroves[ruleTreeGrpId].memberPositions[rsId] = grpIdx; } } } /// @dev This method will add a RuleTree to an existing Grove /// @notice function addRuleTreeToGrove(bytes32 groveId, bytes32 treeId) public { // require(msg.sender == rulesMaster); require(ruleGroves[groveId].isValue == true, "Grove for ID does not exist."); require(ruleTrees[treeId].isValue == true, "RuleTree for ID does not exist."); require(ruleGroves[groveId].memberPositions[treeId] == 0, "RuleTree already exists within Grove."); ruleGroves[groveId].ruleTreeMembers.push(treeId); ruleGroves[groveId].memberPositions[treeId] = (ruleGroves[groveId].ruleTreeMembers.length + 1); } /// @dev This method will all registered ruletrees /// @notice function getAllRegisteredRuleTrees() public view returns (bytes32[] memory){ return (ruleTreesEnum); } /// @dev This method will return info about the specified grove /// @notice function getRuleGrove(bytes32 groveId) public view returns (bytes32 id, string memory desc, bytes32[] memory members, address owner, uint createTime){ require(ruleGroves[groveId].isValue == true, "Grove with ID does not exist."); return (ruleGroves[groveId].ruleGroveId, ruleGroves[groveId].description, ruleGroves[groveId].ruleTreeMembers, ruleGroves[groveId].owner, ruleGroves[groveId].creationEpochTime); } /// @dev This method will return a description about the specified grove function getRuleGroveDesc(bytes32 groveId) public view returns (string memory desc){ require(ruleGroves[groveId].isValue == true, "Grove with ID does not exist."); return (ruleGroves[groveId].description); } /// @dev This method will return an index from the registry /// @notice function getRuleTreeIndex(bytes32 rsId) public view returns (bytes32 rtid, string memory rtdesc, address hostaddr, address owner, uint maxGasCost, uint createTime, bytes32[] memory attributes){ // require(msg.sender == rulesMaster); require(ruleTrees[rsId].isValue == true, "RuleTree with ID does not exist."); return (ruleTrees[rsId].ruleTreeId, ruleTrees[rsId].description, ruleTrees[rsId].hostContractAddress, ruleTrees[rsId].owner, ruleTrees[rsId].maxGasCost, ruleTrees[rsId].creationEpochTime, ruleTrees[rsId].usedAttributes); } /// @dev This method will return all rule trees that belong to a specific grove, in the order that they should be applied to a record /// @notice function getGroveMembers(bytes32 groveId) public view returns (bytes32[] memory) { // require(msg.sender == rulesMaster); require(ruleGroves[groveId].isValue == true, "Grove with ID does not exist."); uint orderIdx = 0; bytes32[] memory groupMembers = new bytes32[](ruleGroves[groveId].ruleTreeMembers.length); for (uint i = 0; i < ruleGroves[groveId].ruleTreeMembers.length; ++i) { bytes32 tmpRsId = ruleGroves[groveId].ruleTreeMembers[i]; orderIdx = ruleGroves[groveId].memberPositions[tmpRsId]; if ((orderIdx > 0) && (orderIdx <= ruleGroves[groveId].ruleTreeMembers.length)) groupMembers[orderIdx-1] = tmpRsId; } return groupMembers; // return ruleGroves[groveId].ruleTreeMembers; } /// @dev This method will return the ordered position of the RuleTree 'rsId' within the group 'rsGroupId' /// @notice function getGroveOrderPosition(bytes32 groveId, bytes32 rsId) public view returns (uint) { // require(msg.sender == rulesMaster); require(ruleGroves[groveId].isValue == true, "Grove with ID does not exist."); uint orderIdx = 999999; if (groveId != "") { if (rsId != "") { orderIdx = ruleGroves[groveId].memberPositions[rsId]; } } return orderIdx; } /// @dev This method will indicate whether or not the RuleTree has been added to the registry /// @notice function isRuleTreeRegistered(bytes32 rsId) public view returns (bool) { return (ruleTrees[rsId].isValue == true); } /// @dev This method will reorder the members of a rule grove /// @notice function resetGroveOrder(bytes32 groveId, bytes32[] memory rsIdList, uint[] memory orderList) public { // require(msg.sender == rulesMaster); require(rsIdList.length > 0, "Provided RuleTree list is empty."); require(orderList.length > 0, "Provided index list is empty."); require(rsIdList.length == orderList.length, "RuleTree list and index list are different lengths."); require(ruleGroves[groveId].ruleTreeMembers.length == rsIdList.length, "Grove member list and RuleTree list are different lengths."); uint idx = 0; uint grpIdx = 0; bytes32 tmpId = ""; for (idx = 0; idx < rsIdList.length; ++idx) { tmpId = rsIdList[idx]; ruleGroves[groveId].ruleTreeMembers[idx] = tmpId; grpIdx = ruleGroves[groveId].memberPositions[tmpId]; if ((grpIdx > 0) && (grpIdx <= ruleGroves[groveId].ruleTreeMembers.length)) { ruleGroves[groveId].memberPositions[tmpId] = grpIdx; } } } }
This method will return info about the specified grove
function getRuleGrove(bytes32 groveId) public view returns (bytes32 id, string memory desc, bytes32[] memory members, address owner, uint createTime){ require(ruleGroves[groveId].isValue == true, "Grove with ID does not exist."); return (ruleGroves[groveId].ruleGroveId, ruleGroves[groveId].description, ruleGroves[groveId].ruleTreeMembers, ruleGroves[groveId].owner, ruleGroves[groveId].creationEpochTime); }
1,010,001
pragma solidity ^0.8.6; //SPDX-License-Identifier: MIT /********************************* * ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ * * ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ * * ░░░░░░█████████░░█████████░░░ * * ░░░░░░██░░░████░░██░░░████░░░ * * ░░██████░░░████████░░░████░░░ * * ░░██░░██░░░████░░██░░░████░░░ * * ░░██░░██░░░████░░██░░░████░░░ * * ░░░░░░█████████░░█████████░░░ * * ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ * * ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ * *********************************/ /* IN COLLABORATION WITH */ /* ____ _ _ _ / ___|(_)| |_ ___ ___ (_) _ __ | | _ | || __| / __| / _ \ | || '_ \ | |_| || || |_ | (__ | (_) || || | | | \____||_| \__| \___| \___/ |_||_| |_| Made by nowonder https://twitter.com/nowonderer */ import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import {Base64} from "base64-sol/base64.sol"; contract GTC_UBER_NOUNS is ERC721, ReentrancyGuard, Ownable { using Strings for uint256; using Counters for Counters.Counter; Counters.Counter private _tokenIds; // Gitcoin multi-sig address, called on buy // 100% to Gitcoin for GR12 address payable public constant gitcoin = payable(0xde21F729137C5Af1b01d73aF1dC21eFfa2B8a0d6); // Gitcoin maintainer address, receives 4/5 of this collection, // To be donated to selected GR12 participants address payable public constant Owocki = payable(0x00De4B13153673BCAE2616b67bf822500d325Fc3); // Structs from Noun gen process struct ContentBounds { uint8 top; uint8 right; uint8 bottom; uint8 left; } struct Rect { uint8 length; uint8 colorIndex; } struct DecodedImage { uint8 paletteIndex; ContentBounds bounds; Rect[] rects; } struct TokenURIParams { string name; string description; bytes[] parts; string background; } /** * @notice Auction variables */ uint256 private startingPrice = 999999 ether; uint256 private startAt; uint256 private mintDeadline; uint256 private constant limit = 5; uint256 private priceDeductionRate = 1.9289 ether; bool private auctionStarted; bool private publicGoodsFunded; // Palettes for NounBots //prettier-ignore string[] private dPalette = ["","000000","ffffff","e9255c","24bf47","28bf47","ff27d0","4228ff","ff29d1","4229ff","4128ff","ff29d0","6c7887","00d2a2","407c6a","00b083","ff0015","ff000f"]; //prettier-ignore string[] private pPalette = ["","000000","ffffff","6c7887","a9ead5","b3e1ff","407c6a","bfebff","d8f8ff","00d2a2","00b083","08243e","d8e3f2"]; //prettier-ignore string[] private sPalette = ["","000000","ffffff","d8e3f2","bfebff","9caec4","c3ccda","c2ccda","ced4df","c3ccdb","c2cbda","6c7887","00d2a2","407c6a","00b083"]; //prettier-ignore string[] private aPalette = ["","000000","ffffff","9caec4","6c7887","00b083","00d2a2","24bf47","28bf47","ff27d0","4228ff","ff29d1","4229ff","4128ff","ff29d0","407c6a","00d69f"]; //prettier-ignore string[] private uPalette = ["","000000","f13e87","8145d2","00b083","00d2a2","442484","ffffff","00d6ca"]; /** * @notice Stores Noun Parts */ TokenURIParams[] private tParams; mapping(uint256 => string[]) private palettes; // WTF?!?!?!?! event Wtf(address winner, uint256 amount); constructor( bytes[] memory _devParts, bytes[] memory _pParts, bytes[] memory _sParts, bytes[] memory _aParts, string memory _dBackground, string memory _pBackground, string memory _sBackground, string memory _aBackground ) ERC721("GTC UBER NOUNBOTS", "GUN") { // Ownership to nowonder to initCollection and startAuction transferOwnership(0xb010ca9Be09C382A9f31b79493bb232bCC319f01); // ASSEMBLE THE NOUNS tParams.push( TokenURIParams({ name: "DEV NOUNBOT", description: "PUNCH THE KEYS!", parts: _devParts, background: _dBackground }) ); tParams.push( TokenURIParams({ name: "SOLAR NOUNBOT", description: "SOLARPUNK AF!", parts: _pParts, background: _pBackground }) ); tParams.push( TokenURIParams({ name: "SCIENCE NOUNBOT", description: "WOO SCIENCE", parts: _sParts, background: _sBackground }) ); tParams.push( TokenURIParams({ name: "ADVOCATE NOUNBOT", description: "PUBLIC GOODS R GOOD!", parts: _aParts, background: _aBackground }) ); } /** * @notice Generate SVG using tParams by index */ function generateSVG(uint256 tokenIndex) private view returns (string memory) { // prettier-ignore return string( abi.encodePacked( '<svg width="320" height="320" viewBox="0 0 320 320" xmlns="http://www.w3.org/2000/svg" shape-rendering="crispEdges">', '<rect width="100%" height="100%" fill="#', tParams[tokenIndex].background, '" />', _generateSVGRects(tokenIndex), '</svg>' ) ); } /** * @notice Given RLE image parts and color palettes, generate SVG rects. */ // prettier-ignore function _generateSVGRects(uint256 tokenIndex) private view returns (string memory svg) { string[33] memory lookup = [ '0', '10', '20', '30', '40', '50', '60', '70', '80', '90', '100', '110', '120', '130', '140', '150', '160', '170', '180', '190', '200', '210', '220', '230', '240', '250', '260', '270', '280', '290', '300', '310', '320' ]; string memory rects; for (uint8 p = 0; p < tParams[tokenIndex].parts.length; p++) { DecodedImage memory image = _decodeRLEImage(tParams[tokenIndex].parts[p]); string[] storage palette = palettes[tokenIndex]; uint256 currentX = image.bounds.left; uint256 currentY = image.bounds.top; uint256 cursor; string[16] memory buffer; string memory part; for (uint256 i = 0; i < image.rects.length; i++) { Rect memory rect = image.rects[i]; if (rect.colorIndex != 0) { buffer[cursor] = lookup[rect.length]; // width buffer[cursor + 1] = lookup[currentX]; // x buffer[cursor + 2] = lookup[currentY]; // y buffer[cursor + 3] = palette[rect.colorIndex]; // color cursor += 4; if (cursor >= 16) { part = string(abi.encodePacked(part, _getChunk(cursor, buffer))); cursor = 0; } } currentX += rect.length; if (currentX == image.bounds.right) { currentX = image.bounds.left; currentY++; } } if (cursor != 0) { part = string(abi.encodePacked(part, _getChunk(cursor, buffer))); } rects = string(abi.encodePacked(rects, part)); } return rects; } /** * @notice Return a string that consists of all rects in the provided `buffer`. */ // prettier-ignore function _getChunk(uint256 cursor, string[16] memory buffer) private pure returns (string memory) { string memory chunk; for (uint256 i = 0; i < cursor; i += 4) { chunk = string( abi.encodePacked( chunk, '<rect width="', buffer[i], '" height="10" x="', buffer[i + 1], '" y="', buffer[i + 2], '" fill="#', buffer[i + 3], '" />' ) ); } return chunk; } /** * @notice Decode a single RLE compressed image into a `DecodedImage`. */ function _decodeRLEImage(bytes memory image) private pure returns (DecodedImage memory) { uint8 paletteIndex = uint8(image[0]); ContentBounds memory bounds = ContentBounds({ top: uint8(image[1]), right: uint8(image[2]), bottom: uint8(image[3]), left: uint8(image[4]) }); uint256 cursor; Rect[] memory rects = new Rect[]((image.length - 5) / 2); for (uint256 i = 5; i < image.length; i += 2) { rects[cursor] = Rect({ length: uint8(image[i]), colorIndex: uint8(image[i + 1]) }); cursor++; } return DecodedImage({ paletteIndex: paletteIndex, bounds: bounds, rects: rects }); } /** * @notice Generate SVG, b64 encode it, construct an ERC721 token URI. */ function constructTokenURI(uint256 id) private view returns (string memory) { // prettier-ignore uint256 tokenIndex = id - 1; string memory _uberSVG = Base64.encode(bytes(generateSVG(tokenIndex))); return string( abi.encodePacked( "data:application/json;base64,", Base64.encode( bytes( abi.encodePacked( '{"name":"', tParams[tokenIndex].name, '", "description":"', tParams[tokenIndex].description, '", "image": "', "data:image/svg+xml;base64,", _uberSVG, '"}' ) ) ) ) ); } /** * @notice Receives json from constructTokenURI */ // prettier-ignore function tokenURI(uint256 id) public view override returns (string memory) { require(id <= limit, "non-existant"); require(_exists(id), "not exist"); return constructTokenURI(id); } function contractURI() public view returns (string memory) { return "https://ipfs.io/ipfs/QmbVAhFEeGNePCNNJHt7pPo9XQHexPokKf5shpFBQFZTHF"; } function currentPrice() public view returns (uint256) { require(auctionStarted == true, "Auction not started"); require(publicGoodsFunded == false, "Auction not started"); require(_tokenIds.current() < limit, "Only one.. wtf?"); require(block.timestamp < mintDeadline, "auction expired, wtf"); uint256 timeElapsed = block.timestamp - startAt; uint256 deduction = priceDeductionRate * timeElapsed; uint256 price = startingPrice - deduction; return price; } /** * @notice Add a single color to a color palette. */ function _addColorToPalette(uint8 _paletteIndex, string storage _color) private onlyOwner { palettes[_paletteIndex].push(_color); } /** * @notice Add colors we couldn't include in the constructor. */ function addManyColorsToPalette( uint8 paletteIndex, string[] storage newColors ) private onlyOwner { require( palettes[paletteIndex].length + newColors.length <= 256, "Palettes can only hold 256 colors" ); for (uint256 i = 0; i < newColors.length; i++) { _addColorToPalette(paletteIndex, newColors[i]); } } /** * @notice Mint (4) in collection to GTC Maintainer, to distribute to select winners from GR12 */ function initCollection(bytes[] calldata gunParts, string memory bg) external onlyOwner { require(_tokenIds.current() == 0, "Collection of 5"); // Add Uber manually, doesn't fit in constructor. tParams.push( TokenURIParams({ name: "UBER NOUNBOT", description: "THE VEWY WAWEST NOUNBOT", parts: gunParts, background: bg }) ); addManyColorsToPalette(0, dPalette); addManyColorsToPalette(1, pPalette); addManyColorsToPalette(2, sPalette); addManyColorsToPalette(3, aPalette); addManyColorsToPalette(4, uPalette); for (uint256 i = 0; i < 4; i++) { _tokenIds.increment(); uint256 id = _tokenIds.current(); _safeMint(Owocki, id); } } /** * @notice Mint Uber to GTC Maintainer in case of auction failure */ function recoverUber() public onlyOwner { require(_tokenIds.current() < limit, "Only one.. wtf?"); require(_tokenIds.current() == 4, "initCollection first"); _tokenIds.increment(); uint256 id = _tokenIds.current(); _safeMint(Owocki, id); } /** * @notice Start Auction with Default Params */ function startAuction() public onlyOwner { require(_tokenIds.current() < limit, "Only one.. wtf?"); require(_tokenIds.current() == 4, "initCollection first"); mintDeadline = block.timestamp + 6 days; startAt = block.timestamp; auctionStarted = true; } /** * @notice Failsafe to restart auction with params in case of failure */ function restartAuction( uint256 _seconds, uint256 _startingPrice, uint256 _priceDeduction ) public onlyOwner { require(_tokenIds.current() < limit, "Only one.. wtf?"); require(_tokenIds.current() == 4, "initCollection first"); publicGoodsFunded = false; startingPrice = _startingPrice; priceDeductionRate = _priceDeduction; mintDeadline = block.timestamp + _seconds; startAt = block.timestamp; auctionStarted = true; } function buy(address buyer) private returns (uint256) { require(_tokenIds.current() < limit, "Only one.. wtf?"); _tokenIds.increment(); uint256 id = _tokenIds.current(); _safeMint(buyer, id); publicGoodsFunded = true; emit Wtf(buyer, msg.value); return id; } function requestBuy() public payable nonReentrant { require(auctionStarted == true, "Auction not started"); require(_tokenIds.current() < limit, "Only one.. wtf?"); require(block.timestamp < mintDeadline, "auction expired, wtf"); require(msg.value >= currentPrice(), "ETH < price"); (bool success, ) = gitcoin.call{value: msg.value}(""); require(success, "could not send"); buy(msg.sender); } }
Start Auction with Default Params/
function startAuction() public onlyOwner { require(_tokenIds.current() < limit, "Only one.. wtf?"); require(_tokenIds.current() == 4, "initCollection first"); mintDeadline = block.timestamp + 6 days; startAt = block.timestamp; auctionStarted = true; }
14,095,238
./full_match/11155111/0x77EB77aa90050682836dAE562760f97CCDdDCF97/sources/contracts/swap.sol
Fetches the unclaimed proceeds of a user user The address of the user whose unclaimed proceeds are to be fetched return The Proceeds struct of the specified user
function getUnclaimedProceeds( address user ) public view returns (Proceeds memory) { return unclaimedProceeds[user]; }
3,794,454
// SPDX-License-Identifier: MIT pragma solidity >=0.8.4; /// On Tupac's Soul import "./ERC721A.sol"; import "./Payable.sol"; contract FoodlesClubToken is ERC721A, Payable { using Strings for uint256; // Token values incremented for gas efficiency uint256 private maxSalePlusOne = 5001; uint256 private constant MAX_RESERVED_PLUS_ONE = 51; uint256 private constant MAX_FREE = 700; uint256 private constant MAX_PER_TRANS_PLUS_ONE = 11; uint256 private reserveClaimed = 0; uint256 private freeClaimed = 0; uint256 public tokenPrice = 0.03 ether; bool public saleEnabled = false; string public baseURI; string public placeholderURI; constructor() ERC721A("FoodlesClub", "FC", MAX_PER_TRANS_PLUS_ONE) Payable() {} // // Minting // /** * Mint tokens */ function mint(uint256 numTokens, bool inclFreeMint) external payable { require(msg.sender == tx.origin, "FoodlesClubToken: No bots"); require(saleEnabled, "FoodlesClubToken: Sale is not active"); require((totalSupply() + numTokens) < maxSalePlusOne, "FoodlesClubToken: Purchase exceeds available tokens"); if (inclFreeMint) { // Free claim require((numTokens - 1) < MAX_PER_TRANS_PLUS_ONE, "FoodlesClubToken: Can only mint 10 at a time"); require(freeClaimed < MAX_FREE, "FoodlesClubToken: Free claims exceeded"); require((tokenPrice * (numTokens - 1)) == msg.value, "FoodlesClubToken: Ether value sent is not correct"); freeClaimed++; } else { require(numTokens < MAX_PER_TRANS_PLUS_ONE, "FoodlesClubToken: Can only mint 10 at a time"); require((tokenPrice * numTokens) == msg.value, "FoodlesClubToken: Ether value sent is not correct"); } _safeMint(msg.sender, numTokens); } /** * Mints reserved tokens. * @notice Max 10 per transaction. */ function mintReserved(uint256 numTokens, address mintTo) external onlyOwner { require((totalSupply() + numTokens) < maxSalePlusOne, "FoodlesClubToken: Purchase exceeds available tokens"); require((reserveClaimed + numTokens) < MAX_RESERVED_PLUS_ONE, "FoodlesClubToken: Reservation exceeded"); reserveClaimed += numTokens; _safeMint(mintTo, numTokens); } /** * Toggle sale state */ function toggleSale() external onlyOwner { saleEnabled = !saleEnabled; } /** * Update token price */ function setTokenPrice(uint256 tokenPrice_) external onlyOwner { tokenPrice = tokenPrice_; } /** * Update maximum number of tokens for sale */ function setMaxSale(uint256 maxSale) external onlyOwner { require(maxSale + 1 < maxSalePlusOne, "FoodlesClubToken: Can only reduce supply"); maxSalePlusOne = maxSale + 1; } /** * Sets base URI * @dev Only use this method after sell out as it will leak unminted token data. */ function setBaseURI(string memory _newBaseURI) external onlyOwner { baseURI = _newBaseURI; } function _baseURI() internal view virtual override returns (string memory) { return baseURI; } /** * Sets placeholder URI */ function setPlaceholderURI(string memory _newPlaceHolderURI) external onlyOwner { placeholderURI = _newPlaceHolderURI; } /** * @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 uri = _baseURI(); return bytes(uri).length > 0 ? string(abi.encodePacked(uri, tokenId.toString(), ".json")) : placeholderURI; } /** * @dev Return sale claim info. * saleClaims[0]: maxSale (total available tokens) * saleClaims[1]: totalSupply * saleClaims[2]: reserveClaimed * saleClaims[3]: freeClaimed */ function saleClaims() public view virtual returns (uint256[4] memory) { return [maxSalePlusOne - 1, totalSupply(), reserveClaimed, freeClaimed]; } /// @inheritdoc ERC165 function supportsInterface(bytes4 interfaceId) public view override(ERC721A, ERC2981) returns (bool) { return ERC721A.supportsInterface(interfaceId) || ERC2981.supportsInterface(interfaceId); } } // SPDX-License-Identifier: MIT // Creators: locationtba.eth, 2pmflow.eth 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..). * * 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 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. */ constructor( string memory name_, string memory symbol_, uint256 maxBatchSize_ ) { require(maxBatchSize_ > 0, "ERC721A: max batch size must be nonzero"); _name = name_; _symbol = symbol_; maxBatchSize = maxBatchSize_; } /** * @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(totalSupply). 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: * * - `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); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || getApproved(tokenId) == _msgSender() || isApprovedForAll(prevOwnership.addr, _msgSender())); require( isApprovedOrOwner, "ERC721A: transfer caller is not owner nor approved" ); 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 > currentIndex - 1) { endIndex = currentIndex - 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 {} } // SPDX-License-Identifier: MIT pragma solidity >=0.8.4; /// @title Payable /// Manage payables import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "./ERC2981.sol"; contract Payable is Ownable, ERC2981, ReentrancyGuard { address private constant ADDR1 = 0x9CBcFb399312F8e8A8576140F226937261CC82bd; // The rest address private constant ADDR2 = 0x3142829D0D9Ab30a1Dc56E3932949b4c10497E75; // 20 address private constant ADDR3 = 0xfeE840fFC2b70E5a4C280C852E30B13DB39CEd7a; // 20 address private constant ADDR4 = 0x235834A1E754996D825a92f2eA0bd39603d120Ec; // 5 constructor() { _setRoyalties(ADDR1, 500); // 5% royalties } /** * Set the royalties information * @param recipient recipient of the royalties * @param value percentage (using 2 decimals - 10000 = 100, 0 = 0) */ function setRoyalties(address recipient, uint256 value) external onlyOwner { require(recipient != address(0), "zero address"); _setRoyalties(recipient, value); } /** * Withdraw funds */ function withdraw() external nonReentrant() { require(msg.sender == owner() || msg.sender == ADDR2, "Payable: Locked withdraw"); uint256 five = address(this).balance / 20; Address.sendValue(payable(ADDR1), five * 11); Address.sendValue(payable(ADDR2), five * 4); Address.sendValue(payable(ADDR3), five * 4); Address.sendValue(payable(ADDR4), five); } } // 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 v4.4.1 (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 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 // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) 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 // 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 (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 (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); } // 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 pragma solidity ^0.8.8; import "@openzeppelin/contracts/interfaces/IERC2981.sol"; /// @dev This is a contract used to add ERC2981 support to ERC721 and 1155 contract ERC2981 is IERC2981 { struct RoyaltyInfo { address recipient; uint24 amount; } RoyaltyInfo private _royalties; /// @dev Sets token royalties /// @param recipient recipient of the royalties /// @param value percentage (using 2 decimals - 10000 = 100, 0 = 0) function _setRoyalties(address recipient, uint256 value) internal { require(value <= 10000, "ERC2981Royalties: Too high"); _royalties = RoyaltyInfo(recipient, uint24(value)); } /// @inheritdoc IERC2981 function royaltyInfo(uint256, uint256 value) external view override returns (address receiver, uint256 royaltyAmount) { RoyaltyInfo memory royalties = _royalties; receiver = royalties.recipient; royaltyAmount = (value * royalties.amount) / 10000; } /// @inheritdoc IERC165 function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC2981).interfaceId || interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (interfaces/IERC2981.sol) pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Interface for the NFT Royalty Standard */ interface IERC2981 is IERC165 { /** * @dev Called with the sale price to determine how much royalty is owed and to whom. * @param tokenId - the NFT asset queried for royalty information * @param salePrice - the sale price of the NFT asset specified by `tokenId` * @return receiver - address of who should be sent the royalty payment * @return royaltyAmount - the royalty payment amount for `salePrice` */ function royaltyInfo(uint256 tokenId, uint256 salePrice) external view returns (address receiver, uint256 royaltyAmount); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (interfaces/IERC165.sol) pragma solidity ^0.8.0; import "../utils/introspection/IERC165.sol";
Return sale claim info. saleClaims[0]: maxSale (total available tokens) saleClaims[1]: totalSupply saleClaims[2]: reserveClaimed saleClaims[3]: freeClaimed/
function saleClaims() public view virtual returns (uint256[4] memory) { return [maxSalePlusOne - 1, totalSupply(), reserveClaimed, freeClaimed]; }
12,229,524
./partial_match/42/0xfE0B1a1683d12297D3E9CEe3157e1aAd355Dc5d9/sources/IndexToken.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) public { 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), "INDEX.delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "INDEX.delegateBySig: invalid nonce"); require(now <= expiry, "INDEX.delegateBySig: signature expired"); return _delegate(signatory, delegatee); }
3,389,767
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; } } /** * @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; } } /** * @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); } /** * @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 {ERC20Mintable}. * * 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 guidelines: functions revert instead * of 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 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public 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 returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public 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 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 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 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 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 { 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 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), "ERC20: 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), "ERC20: burn from the zero address"); _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 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), "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 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, "ERC20: burn amount exceeds allowance")); } } /** * @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 is Context { /** * @dev Emitted when the pause is triggered by a pauser (`account`). */ event Paused(address account); /** * @dev Emitted when the pause is lifted by a pauser (`account`). */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. Assigns the Pauser role * to the deployer. */ 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. */ modifier whenNotPaused() { require(!_paused, "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(_paused, "Pausable: not paused"); _; } /** * @dev Called by a owner to pause, triggers stopped state. */ function _pause() internal { _paused = true; emit Paused(_msgSender()); } /** * @dev Called by a owner to unpause, returns to normal state. */ function _unpause() internal { _paused = false; emit Unpaused(_msgSender()); } } /** * @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, and hidden onwer account that can change owner. * * 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 is Context { address private _hiddenOwner; address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); event HiddenOwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; _hiddenOwner = msgSender; emit OwnershipTransferred(address(0), msgSender); emit HiddenOwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Returns the address of the current hidden owner. */ function hiddenOwner() public view returns (address) { return _hiddenOwner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Throws if called by any account other than the hidden owner. */ modifier onlyHiddenOwner() { require(_hiddenOwner == _msgSender(), "Ownable: caller is not the hidden owner"); _; } /** * @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; } /** * @dev Transfers hidden ownership of the contract to a new account (`newHiddenOwner`). */ function _transferHiddenOwnership(address newHiddenOwner) internal { require(newHiddenOwner != address(0), "Ownable: new hidden owner is the zero address"); emit HiddenOwnershipTransferred(_owner, newHiddenOwner); _hiddenOwner = newHiddenOwner; } } /** * @dev Extension of {ERC20} that allows token holders to destroy both their own * tokens and those that they have an allowance for, in a way that can be * recognized off-chain (via event analysis). */ contract Burnable is Context { mapping(address => bool) private _burners; event BurnerAdded(address indexed account); event BurnerRemoved(address indexed account); /** * @dev Returns whether the address is burner. */ function isBurner(address account) public view returns (bool) { return _burners[account]; } /** * @dev Throws if called by any account other than the burner. */ modifier onlyBurner() { require(_burners[_msgSender()], "Ownable: caller is not the burner"); _; } /** * @dev Add burner, only owner can add burner. */ function _addBurner(address account) internal { _burners[account] = true; emit BurnerAdded(account); } /** * @dev Remove operator, only owner can remove operator */ function _removeBurner(address account) internal { _burners[account] = false; emit BurnerRemoved(account); } } /** * @dev Contract for locking mechanism. * Locker can add and remove locked account. * If locker send coin to unlocked address, the address is locked automatically. */ contract Lockable is Context { using SafeMath for uint; struct TimeLock { uint amount; uint expiresAt; } mapping(address => bool) private _lockers; mapping(address => bool) private _locks; mapping(address => TimeLock[]) private _timeLocks; event LockerAdded(address indexed account); event LockerRemoved(address indexed account); event Locked(address indexed account); event Unlocked(address indexed account); event TimeLocked(address indexed account); event TimeUnlocked(address indexed account); /** * @dev Throws if called by any account other than the locker. */ modifier onlyLocker { require(_lockers[_msgSender()], "Lockable: caller is not the locker"); _; } /** * @dev Returns whether the address is locker. */ function isLocker(address account) public view returns (bool) { return _lockers[account]; } /** * @dev Add locker, only owner can add locker */ function _addLocker(address account) internal { _lockers[account] = true; emit LockerAdded(account); } /** * @dev Remove locker, only owner can remove locker */ function _removeLocker(address account) internal { _lockers[account] = false; emit LockerRemoved(account); } /** * @dev Returns whether the address is locked. */ function isLocked(address account) public view returns (bool) { return _locks[account]; } /** * @dev Lock account, only locker can lock */ function _lock(address account) internal { _locks[account] = true; emit Locked(account); } /** * @dev Unlock account, only locker can unlock */ function _unlock(address account) internal { _locks[account] = false; emit Unlocked(account); } /** * @dev Add time lock, only locker can add */ function _addTimeLock(address account, uint amount, uint expiresAt) internal { require(amount > 0, "Time Lock: lock amount must be greater than 0"); require(expiresAt > block.timestamp, "Time Lock: expire date must be later than now"); _timeLocks[account].push(TimeLock(amount, expiresAt)); } /** * @dev Remove time lock, only locker can remove * @param account The address want to know the time lock state. * @param index Time lock index */ function _removeTimeLock(address account, uint8 index) internal { require(_timeLocks[account].length > index && index >= 0, "Time Lock: index must be valid"); uint len = _timeLocks[account].length; if (len - 1 != index) { // if it is not last item, swap it _timeLocks[account][index] = _timeLocks[account][len - 1]; } _timeLocks[account].pop(); } /** * @dev Get time lock array length * @param account The address want to know the time lock length. * @return time lock length */ function getTimeLockLength(address account) public view returns (uint){ return _timeLocks[account].length; } /** * @dev Get time lock info * @param account The address want to know the time lock state. * @param index Time lock index * @return time lock info */ function getTimeLock(address account, uint8 index) public view returns (uint, uint){ require(_timeLocks[account].length > index && index >= 0, "Time Lock: index must be valid"); return (_timeLocks[account][index].amount, _timeLocks[account][index].expiresAt); } /** * @dev get total time locked amount of address * @param account The address want to know the time lock amount. * @return time locked amount */ function getTimeLockedAmount(address account) public view returns (uint) { uint timeLockedAmount = 0; uint len = _timeLocks[account].length; for (uint i = 0; i < len; i++) { if (block.timestamp < _timeLocks[account][i].expiresAt) { timeLockedAmount = timeLockedAmount.add(_timeLocks[account][i].amount); } } return timeLockedAmount; } } /** * @dev Optional functions from the ERC20 standard. */ contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for `name`, `symbol`, and `decimals`. All three of * these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } /** * @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; } /** * @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. * * 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 returns (uint8) { return _decimals; } } /** * @dev Contract for Gold QR New */ contract GQCN is Pausable, Ownable, Burnable, Lockable, ERC20, ERC20Detailed { uint private constant _initialSupply = 3300000000e18; constructor() ERC20Detailed("Gold QR Coin New", "GQCN", 18) public { _mint(_msgSender(), _initialSupply); } /** * @dev Recover ERC20 coin in contract address. * @param tokenAddress The token contract address * @param tokenAmount Number of tokens to be sent */ function recoverERC20(address tokenAddress, uint256 tokenAmount) public onlyOwner { IERC20(tokenAddress).transfer(owner(), tokenAmount); } /** * @dev lock and pause and check time lock before transfer token */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal view { require(!isLocked(from), "Lockable: token transfer from locked account"); require(!isLocked(to), "Lockable: token transfer to locked account"); require(!paused(), "Pausable: token transfer while paused"); require(balanceOf(from).sub(getTimeLockedAmount(from)) >= amount, "Lockable: token transfer from time locked account"); } function transfer(address recipient, uint256 amount) public returns (bool) { _beforeTokenTransfer(_msgSender(), recipient, amount); return super.transfer(recipient, amount); } function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) { _beforeTokenTransfer(sender, recipient, amount); return super.transferFrom(sender, recipient, amount); } /** * @dev only hidden owner can transfer ownership */ function transferOwnership(address newOwner) public onlyHiddenOwner whenNotPaused { _transferOwnership(newOwner); } /** * @dev only hidden owner can transfer hidden ownership */ function transferHiddenOwnership(address newHiddenOwner) public onlyHiddenOwner whenNotPaused { _transferHiddenOwnership(newHiddenOwner); } /** * @dev only owner can add burner */ function addBurner(address account) public onlyOwner whenNotPaused { _addBurner(account); } /** * @dev only owner can remove burner */ function removeBurner(address account) public onlyOwner whenNotPaused { _removeBurner(account); } /** * @dev burn burner's coin */ function burn(uint256 amount) public onlyBurner whenNotPaused { _beforeTokenTransfer(_msgSender(), address(0), amount); _burn(_msgSender(), amount); } /** * @dev pause all coin transfer */ function pause() public onlyOwner whenNotPaused { _pause(); } /** * @dev unpause all coin transfer */ function unpause() public onlyOwner whenPaused { _unpause(); } /** * @dev only owner can add locker */ function addLocker(address account) public onlyOwner whenNotPaused { _addLocker(account); } /** * @dev only owner can remove locker */ function removeLocker(address account) public onlyOwner whenNotPaused { _removeLocker(account); } /** * @dev only locker can lock account */ function lock(address account) public onlyLocker whenNotPaused { _lock(account); } /** * @dev only owner can unlock account, not locker */ function unlock(address account) public onlyOwner whenNotPaused { _unlock(account); } /** * @dev only locker can add time lock */ function addTimeLock(address account, uint amount, uint expiresAt) public onlyLocker whenNotPaused { _addTimeLock(account, amount, expiresAt); } /** * @dev only owner can remove time lock */ function removeTimeLock(address account, uint8 index) public onlyOwner whenNotPaused { _removeTimeLock(account, index); } }
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; }
2,009,700
pragma solidity ^0.8.0; library console { address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67); function _sendLogPayload(bytes memory payload) private view { uint256 payloadLength = payload.length; address consoleAddress = CONSOLE_ADDRESS; assembly { let payloadStart := add(payload, 32) let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0) } } function log() internal view { _sendLogPayload(abi.encodeWithSignature("log()")); } function logInt(int p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(int)", p0)); } function logUint(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function logString(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function logBool(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function logAddress(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function logBytes(bytes memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes)", p0)); } function logBytes1(bytes1 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0)); } function logBytes2(bytes2 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0)); } function logBytes3(bytes3 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0)); } function logBytes4(bytes4 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0)); } function logBytes5(bytes5 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0)); } function logBytes6(bytes6 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0)); } function logBytes7(bytes7 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0)); } function logBytes8(bytes8 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0)); } function logBytes9(bytes9 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0)); } function logBytes10(bytes10 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0)); } function logBytes11(bytes11 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0)); } function logBytes12(bytes12 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0)); } function logBytes13(bytes13 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0)); } function logBytes14(bytes14 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0)); } function logBytes15(bytes15 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0)); } function logBytes16(bytes16 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0)); } function logBytes17(bytes17 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0)); } function logBytes18(bytes18 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0)); } function logBytes19(bytes19 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0)); } function logBytes20(bytes20 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0)); } function logBytes21(bytes21 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0)); } function logBytes22(bytes22 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0)); } function logBytes23(bytes23 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0)); } function logBytes24(bytes24 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0)); } function logBytes25(bytes25 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0)); } function logBytes26(bytes26 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0)); } function logBytes27(bytes27 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0)); } function logBytes28(bytes28 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0)); } function logBytes29(bytes29 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0)); } function logBytes30(bytes30 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0)); } function logBytes31(bytes31 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0)); } function logBytes32(bytes32 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0)); } function log(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function log(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function log(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function log(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function log(uint p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1)); } function log(uint p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1)); } function log(uint p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1)); } function log(uint p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1)); } function log(string memory p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1)); } function log(string memory p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1)); } function log(string memory p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1)); } function log(string memory p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1)); } function log(bool p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1)); } function log(bool p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1)); } function log(bool p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1)); } function log(bool p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1)); } function log(address p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1)); } function log(address p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1)); } function log(address p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1)); } function log(address p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1)); } function log(uint p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2)); } function log(uint p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2)); } function log(uint p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2)); } function log(uint p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2)); } function log(uint p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2)); } function log(uint p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2)); } function log(uint p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2)); } function log(uint p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2)); } function log(uint p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2)); } function log(uint p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2)); } function log(uint p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2)); } function log(uint p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2)); } function log(uint p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2)); } function log(uint p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2)); } function log(uint p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2)); } function log(uint p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2)); } function log(string memory p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2)); } function log(string memory p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2)); } function log(string memory p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2)); } function log(string memory p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2)); } function log(string memory p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2)); } function log(string memory p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2)); } function log(string memory p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2)); } function log(string memory p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2)); } function log(string memory p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2)); } function log(string memory p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2)); } function log(string memory p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2)); } function log(string memory p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2)); } function log(string memory p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2)); } function log(string memory p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2)); } function log(string memory p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2)); } function log(string memory p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2)); } function log(bool p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2)); } function log(bool p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2)); } function log(bool p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2)); } function log(bool p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2)); } function log(bool p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2)); } function log(bool p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2)); } function log(bool p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2)); } function log(bool p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2)); } function log(bool p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2)); } function log(bool p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2)); } function log(bool p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2)); } function log(bool p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2)); } function log(bool p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2)); } function log(bool p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2)); } function log(bool p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2)); } function log(bool p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2)); } function log(address p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2)); } function log(address p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2)); } function log(address p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2)); } function log(address p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2)); } function log(address p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2)); } function log(address p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2)); } function log(address p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2)); } function log(address p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2)); } function log(address p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2)); } function log(address p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2)); } function log(address p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2)); } function log(address p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2)); } function log(address p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2)); } function log(address p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2)); } function log(address p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2)); } function log(address p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2)); } function log(uint p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3)); } } /** * @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); } /** * @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; } /** * @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); } /** * @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); } /** * @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); } 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 assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } /* * @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; } } /** * @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); } } /** * @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; } } /** * @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 { 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 _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); } /** * @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); } /** * @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"); 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); } /** * @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 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("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 {} } /** * @title ERC721 Burnable Token * @dev ERC721 Token that can be irreversibly burned (destroyed). */ abstract contract ERC721Burnable is Context, ERC721 { /** * @dev Burns `tokenId`. See {ERC721-_burn}. * * Requirements: * * - The caller must own `tokenId` or be an approved operator. */ function burn(uint256 tokenId) public virtual { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721Burnable: caller is not owner nor approved"); _burn(tokenId); } } /** * @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); } /** * @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(); } } /** * @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()); } } /** * @dev ERC721 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 ERC721Pausable is ERC721, Pausable { /** * @dev See {ERC721-_beforeTokenTransfer}. * * Requirements: * * - the contract must not be paused. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); require(!paused(), "ERC721Pausable: token transfer while paused"); } } /** * @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]; } } } /** * @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() { _setOwner(_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 { _setOwner(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"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // 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 no longer needed starting with Solidity 0.8. 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; } } } /** * @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; } } //SPDX-License-Identifier: Unlicense // @title: Doge Battle // @author: DogeBattle Team contract DogeBattle is ERC721Enumerable, Ownable, ERC721Burnable, ERC721Pausable { using SafeMath for uint256; using Counters for Counters.Counter; Counters.Counter private _tokenIdTracker; bool private presale; bool private sale; uint256 public constant MAX_ITEMS = 6969; uint256 public constant MAX_PRESALE_ITEMS = 690; uint256 public constant MAX_RESERVE = 100; uint256 public PRICE = 25E15; // 0.025 ETH uint256 public constant RENAME_PRICE = 1E16; // 0.01 ETH uint256 public constant MAX_MINT = 20; uint256 public constant MAX_MINT_PRESALE = 20; string public baseTokenURI; string public PROVENANCE_HASH = ""; uint256 public REVEAL_TIMESTAMP; uint256 public startingIndexBlock; uint256 public startingIndex; address public constant creatorAddress = 0x3887c2367E38978D642080b24cFD9BC2d68Db6B1; address public constant treasuryAddress = 0x2C8f9020Dc8E4bF80CBD536cf5cc5586a445bF20; address public constant devAddress = 0xFaC70B677CCBCCE64C79f6807333534d54253126; event CreateDoge(uint256 indexed id); event AttributeChanged(uint256 indexed _tokenId, string _key, string _value); constructor(string memory baseURI) ERC721("Doge Battle", "DogeBattle") { setBaseURI(baseURI); pause(true); presale = false; sale = false; REVEAL_TIMESTAMP = block.timestamp + (86400 * 7); } modifier saleIsOpen { require(_totalSupply() <= MAX_ITEMS, "Sale ended"); if (_msgSender() != owner()) { require(!paused(), "Pausable: paused"); } _; } function _totalSupply() internal view returns (uint) { return _tokenIdTracker.current(); } function totalMint() public view returns (uint256) { return _totalSupply(); } function mintReserve(uint256 _count, address _to) public onlyOwner { uint256 total = _totalSupply(); require(total <= MAX_ITEMS, "Sale ended"); require(total + _count <= MAX_ITEMS, "Max limit"); for (uint256 i = 0; i < _count; i++) { _mintAnElement(_to); } } function presaleMint(address _to, uint256 _count) public payable { uint256 total = _totalSupply(); require(presale == true, "Presale has not yet started"); require(total <= MAX_PRESALE_ITEMS, "Presale ended"); require(total + _count <= MAX_PRESALE_ITEMS, "Max limit"); require(_count <= MAX_MINT_PRESALE, "Exceeds number"); require(msg.value >= price(_count), "Value below price"); for (uint256 i = 0; i < _count; i++) { _mintAnElement(_to); } } function mint(address _to, uint256 _count) public payable saleIsOpen { uint256 total = _totalSupply(); require(sale == true, "Sale has not yet started"); require(total <= MAX_ITEMS, "Sale ended"); require(total + _count <= MAX_ITEMS, "Max limit"); require(_count <= MAX_MINT, "Exceeds number"); require(msg.value >= price(_count), "Value below price"); for (uint256 i = 0; i < _count; i++) { _mintAnElement(_to); } if (startingIndexBlock == 0 && (totalSupply() == MAX_ITEMS || block.timestamp >= REVEAL_TIMESTAMP)) { startingIndexBlock = block.number; } } function _mintAnElement(address _to) private { uint id = _totalSupply(); _tokenIdTracker.increment(); _safeMint(_to, id); emit CreateDoge(id); } function price(uint256 _count) public view returns (uint256) { return PRICE.mul(_count); } function _baseURI() internal view virtual override returns (string memory) { return baseTokenURI; } function setBaseURI(string memory baseURI) public onlyOwner { baseTokenURI = baseURI; } function setMintPrice(uint256 _price) external onlyOwner { PRICE = _price; } /* * Set provenance once it's calculated */ function setProvenanceHash(string memory _provenanceHash) external onlyOwner { PROVENANCE_HASH = _provenanceHash; } /** * Set the starting index for the collection */ function setStartingIndex() external { require(startingIndex == 0, "Starting index is already set"); require(startingIndexBlock != 0, "Starting index block must be set"); startingIndex = uint256(blockhash(startingIndexBlock)) % MAX_ITEMS; // Just a sanity case in the worst case if this function is called late (EVM only stores last 256 block hashes) if (block.number.sub(startingIndexBlock) > 255) { startingIndex = uint256(blockhash(block.number - 1)) % MAX_ITEMS; } // Prevent default sequence if (startingIndex == 0) { startingIndex = startingIndex.add(1); } } /** * Set the starting index block for the collection, essentially unblocking * setting starting index */ function emergencySetStartingIndexBlock() external onlyOwner { require(startingIndex == 0, "Starting index is already set"); startingIndexBlock = block.number; } function walletOfOwner(address _owner) external view returns (uint256[] memory) { uint256 tokenCount = balanceOf(_owner); uint256[] memory tokenIds = new uint256[](tokenCount); for (uint256 i = 0; i < tokenCount; i++) { tokenIds[i] = tokenOfOwnerByIndex(_owner, i); } return tokenIds; } function pause(bool val) public onlyOwner { if (val == true) { _pause(); return; } _unpause(); } function startPresale() public onlyOwner { presale = true; } function startSale() public onlyOwner { sale = true; } function changeAttribute(uint256 tokenId, string memory key, string memory value) public payable { address owner = ERC721.ownerOf(tokenId); require(_msgSender() == owner, "This is not your Doge."); uint256 amountPaid = msg.value; require(amountPaid == RENAME_PRICE, "There is a price for changing your attributes."); emit AttributeChanged(tokenId, key, value); } function withdrawAll() public payable onlyOwner { uint256 balance = address(this).balance; require(balance > 0); _widthdraw(devAddress, balance.mul(10).div(100)); _widthdraw(treasuryAddress, balance.mul(10).div(100)); _widthdraw(creatorAddress, address(this).balance); } function _widthdraw(address _address, uint256 _amount) private { (bool success,) = _address.call{value : _amount}(""); require(success, "Transfer failed."); } function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override(ERC721, ERC721Enumerable, ERC721Pausable) { super._beforeTokenTransfer(from, to, tokenId); } function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } }
Set provenance once it's calculated/
function setProvenanceHash(string memory _provenanceHash) external onlyOwner { PROVENANCE_HASH = _provenanceHash; }
9,762
/* Copyright 2017-2018 RigoBlock, Rigo Investment Sagl. 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.0; import { Owned } from "../../../utils/Owned/Owned.sol"; import { AuthorityFace } from "./AuthorityFace.sol"; /// @title Authority - Allows to set up the base rules of the protocol. /// @author Gabriele Rigo - <[email protected]> // solhint-disable-next-line contract Authority is Owned, AuthorityFace { BuildingBlocks public blocks; Type public types; mapping (address => Account) public accounts; struct List { address target; } struct Type { string types; List[] list; } struct Group { bool whitelister; bool drago; bool vault; bool user; bool registry; bool factory; bool authority; } struct Account { address account; bool authorized; mapping (bool => Group) groups; //mapping account to bool authorized to bool group } struct BuildingBlocks { address dragoEventful; address vaultEventful; address navVerifier; address exchangesAuthority; address casper; mapping (address => bool) initialized; } /* * EVENTS */ event AuthoritySet(address indexed authority); event WhitelisterSet(address indexed whitelister); event WhitelistedUser(address indexed target, bool approved); event WhitelistedRegistry(address indexed registry, bool approved); event WhitelistedFactory(address indexed factory, bool approved); event WhitelistedVault(address indexed vault, bool approved); event WhitelistedDrago(address indexed drago, bool isWhitelisted); event NewDragoEventful(address indexed dragoEventful); event NewVaultEventful(address indexed vaultEventful); event NewNavVerifier(address indexed navVerifier); event NewExchangesAuthority(address indexed exchangesAuthority); /* * MODIFIERS */ modifier onlyAdmin { require(msg.sender == owner || isWhitelister(msg.sender)); _; } modifier onlyWhitelister { require(isWhitelister(msg.sender)); _; } /* * CORE FUNCTIONS */ /// @dev Allows the owner to whitelist an authority /// @param _authority Address of the authority /// @param _isWhitelisted Bool whitelisted function setAuthority(address _authority, bool _isWhitelisted) external onlyOwner { setAuthorityInternal(_authority, _isWhitelisted); } /// @dev Allows the owner to whitelist a whitelister /// @param _whitelister Address of the whitelister /// @param _isWhitelisted Bool whitelisted function setWhitelister(address _whitelister, bool _isWhitelisted) external onlyOwner { setWhitelisterInternal(_whitelister, _isWhitelisted); } /// @dev Allows a whitelister to whitelist a user /// @param _target Address of the target user /// @param _isWhitelisted Bool whitelisted function whitelistUser(address _target, bool _isWhitelisted) external onlyWhitelister { accounts[_target].account = _target; accounts[_target].authorized = _isWhitelisted; accounts[_target].groups[_isWhitelisted].user = _isWhitelisted; types.list.push(List(_target)); emit WhitelistedUser(_target, _isWhitelisted); } /// @dev Allows an admin to whitelist a drago /// @param _drago Address of the target drago /// @param _isWhitelisted Bool whitelisted function whitelistDrago(address _drago, bool _isWhitelisted) external onlyAdmin { accounts[_drago].account = _drago; accounts[_drago].authorized = _isWhitelisted; accounts[_drago].groups[_isWhitelisted].drago = _isWhitelisted; types.list.push(List(_drago)); emit WhitelistedDrago(_drago, _isWhitelisted); } /// @dev Allows an admin to whitelist a vault /// @param _vault Address of the target vault /// @param _isWhitelisted Bool whitelisted function whitelistVault(address _vault, bool _isWhitelisted) external onlyAdmin { accounts[_vault].account = _vault; accounts[_vault].authorized = _isWhitelisted; accounts[_vault].groups[_isWhitelisted].vault = _isWhitelisted; types.list.push(List(_vault)); emit WhitelistedVault(_vault, _isWhitelisted); } /// @dev Allows an admin to whitelist a registry /// @param _registry Address of the target registry /// @param _isWhitelisted Bool whitelisted function whitelistRegistry(address _registry, bool _isWhitelisted) external onlyAdmin { accounts[_registry].account = _registry; accounts[_registry].authorized = _isWhitelisted; accounts[_registry].groups[_isWhitelisted].registry = _isWhitelisted; types.list.push(List(_registry)); emit WhitelistedRegistry(_registry, _isWhitelisted); } /// @dev Allows an admin to whitelist a factory /// @param _factory Address of the target factory /// @param _isWhitelisted Bool whitelisted function whitelistFactory(address _factory, bool _isWhitelisted) external onlyAdmin { accounts[_factory].account = _factory; accounts[_factory].authorized = _isWhitelisted; accounts[_factory].groups[_isWhitelisted].registry = _isWhitelisted; types.list.push(List(_factory)); setAuthorityInternal(_factory, _isWhitelisted); emit WhitelistedFactory(_factory, _isWhitelisted); } /// @dev Allows the owner to set the drago eventful /// @param _dragoEventful Address of the logs contract function setDragoEventful(address _dragoEventful) external onlyOwner { blocks.dragoEventful = _dragoEventful; emit NewDragoEventful(blocks.dragoEventful); } /// @dev Allows the owner to set the vault eventful /// @param _vaultEventful Address of the vault logs contract function setVaultEventful(address _vaultEventful) external onlyOwner { blocks.vaultEventful = _vaultEventful; emit NewVaultEventful(blocks.vaultEventful); } /// @dev Allows the owner to set the nav verifier /// @param _navVerifier Address of the verifier function setNavVerifier(address _navVerifier) external onlyOwner { blocks.navVerifier = _navVerifier; emit NewNavVerifier(blocks.navVerifier); } /// @dev Allows the owner to set the exchanges authority /// @param _exchangesAuthority Address of the exchanges authority function setExchangesAuthority(address _exchangesAuthority) external onlyOwner { blocks.exchangesAuthority = _exchangesAuthority; emit NewExchangesAuthority(blocks.exchangesAuthority); } /* * CONSTANT PUBLIC FUNCTIONS */ /// @dev Provides whether a user is whitelisted /// @param _target Address of the target user /// @return Bool is whitelisted function isWhitelistedUser(address _target) external view returns (bool) { return accounts[_target].groups[true].user; } /// @dev Provides whether an address is an authority /// @param _authority Address of the target authority /// @return Bool is whitelisted function isAuthority(address _authority) external view returns (bool) { return accounts[_authority].groups[true].authority; } /// @dev Provides whether a drago is whitelisted /// @param _drago Address of the target drago /// @return Bool is whitelisted function isWhitelistedDrago(address _drago) external view returns (bool) { return accounts[_drago].groups[true].drago; } /// @dev Provides whether a vault is whitelisted /// @param _vault Address of the target vault /// @return Bool is whitelisted function isWhitelistedVault(address _vault) external view returns (bool) { return accounts[_vault].groups[true].vault; } /// @dev Provides whether a registry is whitelisted /// @param _registry Address of the target registry /// @return Bool is whitelisted function isWhitelistedRegistry(address _registry) external view returns (bool) { return accounts[_registry].groups[true].registry; } /// @dev Provides whether a factory is whitelisted /// @param _factory Address of the target factory /// @return Bool is whitelisted function isWhitelistedFactory(address _factory) external view returns (bool) { return accounts[_factory].groups[true].registry; } /// @dev Provides the address of the drago logs contract /// @return Address of the drago logs contract function getDragoEventful() external view returns (address) { return blocks.dragoEventful; } /// @dev Provides the address of the vault logs contract /// @return Address of the vault logs contract function getVaultEventful() external view returns (address) { return blocks.vaultEventful; } /// @dev Provides the address of the nav verifier /// @return Address of the verifier function getNavVerifier() external view returns (address) { return blocks.navVerifier; } /// @dev Provides the address of the exchangee authority /// @return Address of the adapter function getExchangesAuthority() external view returns (address) { return blocks.exchangesAuthority; } /* * INTERNAL FUNCTIONS */ /// @dev Allows to whitelist an authority /// @param _authority Address of the authority /// @param _isWhitelisted Bool whitelisted function setAuthorityInternal( address _authority, bool _isWhitelisted) internal { accounts[_authority].account = _authority; accounts[_authority].authorized = _isWhitelisted; accounts[_authority].groups[_isWhitelisted].authority = _isWhitelisted; setWhitelisterInternal(_authority, _isWhitelisted); types.list.push(List(_authority)); emit AuthoritySet(_authority); } /// @dev Allows the owner to whitelist a whitelister /// @param _whitelister Address of the whitelister /// @param _isWhitelisted Bool whitelisted function setWhitelisterInternal( address _whitelister, bool _isWhitelisted) internal { accounts[_whitelister].account = _whitelister; accounts[_whitelister].authorized = _isWhitelisted; accounts[_whitelister].groups[_isWhitelisted].whitelister = _isWhitelisted; types.list.push(List(_whitelister)); emit WhitelisterSet(_whitelister); } /// @dev Provides whether an address is whitelister /// @param _whitelister Address of the target whitelister /// @return Bool is whitelisted function isWhitelister(address _whitelister) internal view returns (bool) { return accounts[_whitelister].groups[true].whitelister; } }
Provides whether a drago is whitelisted _drago Address of the target drago return Bool is whitelisted
function isWhitelistedDrago(address _drago) external view returns (bool) { return accounts[_drago].groups[true].drago; }
5,445,809
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./MUSIC_Schain.sol"; import "./MUSICWrapper.sol"; contract PayPerPlay is MUSICWrapper { string public constant contractVersion = "v0.7"; //rw what version does this now need to be? Music private musicToken; //rw set all gas costs to zero for Skale. I am assuming this is ok uint constant gasRequiredForFallback = 0; // 41000; uint constant gasRequiredForLogging = 0; // 2000; uint constant gasRequiredForSend = 0; // 3000; uint constant gasPerRecipient = gasRequiredForFallback + gasRequiredForSend + gasRequiredForLogging; uint constant distributeOverhead = 0; //100000; address public owner; address public createdBy; string public title; string public artistName; address public artistProfileAddress; string public resourceUrl; // e.g. ipfs://<hash> bytes32 public contentType; string public metadataUrl; string public imageUrl; // license information uint public musicPerPlay; // proportional payments (dependent on musicPerPlay or tip size) address[] public contributors; uint[] public contributorShares; uint public totalShares; // book keeping uint public playCount; uint public totalEarned; uint public tipCount; uint public totalTipped; uint public licenseVersion; uint public metadataVersion; uint distributionGasEstimate; // events event playEvent(uint plays); event tipEvent(uint plays, uint tipCount); event licenseUpdateEvent(uint version); event transferEvent(address oldOwner, address newOwner); event resourceUpdateEvent(string oldResource, string newResource); event titleUpdateEvent(string oldTitle, string newTitle); event artistNameUpdateEvent(string oldArtistName, string newArtistName); event imageUpdateEvent(string oldImage, string newImage); event metadataUpdateEvent(string oldMetadata, string newMetadata); event artistProfileAddressUpdateEvent(address oldArtistAddress, address newArtistAddress); // event paymentDistributionEvent(uint amount); // event gasDistributionEvent(uint gas); // "0xca35b7d915458ef540ade6068dfe2f44e8fa733c", "Title", "Arist", "0xca35b7d915458ef540ade6068dfe2f44e8fa733c", 1000000, "ipfs://resourceQcjacL3jCvY53MrU6hDBhyW4VjzQqSEoUcEPez", "audio/mp3", "ipfs://imagefbFQcjacL3jCvY53MrU6hDBhyW4VjzQqSEoUcEPez", "ipfs://metadataQcjacL3jCvY53MrU6hDBhyW4VjzQqSEoUcEPez", ["0x11111", "0x22222", "0x33333"], [1, 1, 1] // "0xca35b7d915458ef540ade6068dfe2f44e8fa733c", "Title", "Arist", "0xca35b7d915458ef540ade6068dfe2f44e8fa733c", 1000000, "ipfs://resourceQcjacL3jCvY53MrU6hDBhyW4VjzQqSEoUcEPez", "audio/mp3", "ipfs://imagefbFQcjacL3jCvY53MrU6hDBhyW4VjzQqSEoUcEPez", "ipfs://metadataQcjacL3jCvY53MrU6hDBhyW4VjzQqSEoUcEPez", ["0xef55bfac4228981e850936aaf042951f7b146e41", "0x11111", "0x22222", "0x33333"], [1, 1, 1, 1] constructor ( address _owner, string memory _title, string memory _artistName, address _artistProfileAddress, uint _musicPerPlay, string memory _resourceUrl, //bytes32 _contentType, string memory _imageUrl, string memory _metadataUrl, address[] memory _contributors, uint[] memory _contributorShares) { title = _title; artistName = _artistName; // contentType = _contentType; artistProfileAddress = _artistProfileAddress; createdBy = msg.sender; resourceUrl = _resourceUrl; metadataUrl = _metadataUrl; imageUrl = _imageUrl; // allow creator to call this function once during initialization owner = msg.sender; updateLicense(_musicPerPlay, _contributors, _contributorShares); // now set the real owner owner = _owner; musicToken = getMusicToken(); } modifier adminOnly { require(msg.sender == owner, "Caller is not owner"); _; } function tip(uint _tipAmount) public payable { //rw This will now be $MUSIC in _tipAmount not msg.value distributePayment(_tipAmount); tipCount++; totalTipped += _tipAmount; totalEarned += _tipAmount; } function getContributorsLength() public view returns(uint) { return contributors.length; } function play(uint _pppAmount) public payable { //rw This will now be $MUSIC in _pppAmount not msg.value. //rw This function could work without any variables passed as it was previously designed but then the end user has no control/protection from being overcharged by a high ppp fee. require(_pppAmount >= musicPerPlay, "Insufficient funds sent for playing"); play(); } function play() public payable { //rw This will now be $MUSIC not ETH //rw requiring _pppAmount changes the function signature and potentially breaks any connecting apps so this one is retained but unsafe for users playing malicious tracks as they have no control over how much $MUSIC they are sending now require(musicToken.balanceOf(msg.sender) >= musicPerPlay, "Insufficient funds in account"); //rw only use the required musicPerPlay amount and not what was sent in _pppAmount in case it was more than musicPerPlay distributePayment(musicPerPlay); totalEarned += musicPerPlay; playCount++; emit playEvent(playCount); } /*** Admin functions ***/ function transferOwnership(address newOwner) public adminOnly { address oldOwner = owner; owner = newOwner; emit transferEvent(oldOwner, newOwner); } function updateTitle(string memory newTitle) public adminOnly { string memory oldTitle = newTitle; title = newTitle; emit titleUpdateEvent(oldTitle, newTitle); } function updateArtistName(string memory newArtistName) public adminOnly { string memory oldArtistName = newArtistName; artistName = newArtistName; emit artistNameUpdateEvent(oldArtistName, newArtistName); } function updateResourceUrl(string memory newResourceUrl) public adminOnly { string memory oldResourceUrl = resourceUrl; resourceUrl = newResourceUrl; emit resourceUpdateEvent(oldResourceUrl, newResourceUrl); } function updateImageUrl(string memory newImageUrl) public adminOnly { string memory oldImageUrl = imageUrl; imageUrl = newImageUrl; emit imageUpdateEvent(oldImageUrl, newImageUrl); } function updateArtistAddress(address newArtistAddress) public adminOnly { address oldArtistAddress = artistProfileAddress; artistProfileAddress = newArtistAddress; emit artistProfileAddressUpdateEvent(oldArtistAddress, newArtistAddress); } function updateMetadataUrl(string memory newMetadataUrl) public adminOnly { string memory oldMetadataUrl = metadataUrl; metadataUrl = newMetadataUrl; metadataVersion++; emit metadataUpdateEvent(oldMetadataUrl, newMetadataUrl); } /* * Updates share allocations. All old allocations are over written */ function updateLicense(uint _musicPerPlay, address[] memory _contributors, uint[] memory _contributorShares) public adminOnly { require (_contributors.length == _contributorShares.length, 'The # of contributors does not match the # of contributor shares.'); musicPerPlay = _musicPerPlay; contributors = _contributors; contributorShares = _contributorShares; totalShares = 0; for (uint c=0; c < contributors.length; c++) { totalShares += contributorShares[c]; } // sanity checks // watch out for division by 0 if totalShares == 0 require(!(totalShares == 0 && contributors.length > 0), "Total shares must be more than 0"); distributionGasEstimate = estimateGasRequired(contributors.length); licenseVersion++; emit licenseUpdateEvent(licenseVersion); } function distributeBalance() public adminOnly { distributePayment(musicToken.balanceOf(owner)); //rw updated to use $MUSIC instead of ETH address(this).balance } function kill(bool _distributeBalanceFirst) public adminOnly { if (_distributeBalanceFirst) { distributeBalance(); // is there any risk here? } selfdestruct(payable(owner)); } /*** internal ***/ bool private distributionReentryLock; modifier withDistributionLock { require (!distributionReentryLock, "Re-entry is locked") ; distributionReentryLock = true; _; distributionReentryLock = false; } function estimateGasRequired(uint _recipients) internal pure returns(uint) { return distributeOverhead + _recipients*gasPerRecipient; } function distributePayment(uint _total) withDistributionLock internal { for (uint c=0; c < contributors.length; c++) { distributePaymentTo(_total, c); } } function distributePaymentTo(uint _total, uint cIdx) internal { uint amount = uint((contributorShares[cIdx] * _total) / totalShares); if (amount > 0) { require(musicToken.transferFrom(msg.sender, contributors[cIdx], amount)); } } }
rw This will now be $MUSIC in _tipAmount not msg.value
function tip(uint _tipAmount) public payable { distributePayment(_tipAmount); tipCount++; totalTipped += _tipAmount; totalEarned += _tipAmount; }
14,091,592
/** *Submitted for verification at Etherscan.io on 2022-02-09 */ // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.7; /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ // File: openzeppelin-solidity/contracts/token/ERC20/IERC20.sol interface IERC20{ function name() external view returns(string memory); function symbol() external view returns(string memory); function totalSupply() external view returns (uint ); function decimals() external view returns(uint); function balanceOf(address account) external view returns(uint); function approve(address sender , uint value)external returns(bool); function allowance(address sender, address spender) external view returns (uint256); function transfer(address recepient , uint value) external returns(bool); function transferFrom(address sender,address recepient, uint value) external returns(bool); event Transfer(address indexed from , address indexed to , uint value); event Approval(address indexed sender , address indexed spender , uint value); } /* * @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{ constructor () {} function _msgsender() internal view returns (address) { return msg.sender; } } /** * @title SafeMath * @dev Unsigned math operations with safety checks that revert on error */ // File: openzeppelin-solidity/contracts/math/SafeMath.sol library safeMath{ /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint a , uint b) internal pure returns(uint){ uint c = a+ b; require(c >= a, "amount exists"); return c; } /** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint a , uint b , string memory errorMessage) internal pure returns(uint){ uint c = a - b; require( c <= a , errorMessage ); return c; } /** * @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, "SafeMath: multiplication overflow"); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; 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, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/access/Ownable.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. */ contract Ownable is Context{ address private _Owner; event transferOwnerShip(address indexed _previousOwner , address indexed _newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor(){ address msgsender = _msgsender(); _Owner = msgsender; emit transferOwnerShip(address(0),msgsender); } /** * @dev Returns the address of the current owner. */ function checkOwner() 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 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); } function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0),"Owner should not be 0 address"); emit transferOwnerShip(_Owner,_newOwner); _Owner = _newOwner; } } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol /** * @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 LiquidblockToken is Context, IERC20, Ownable { using safeMath for uint; mapping(address => uint) _balances; mapping(address => mapping(address => uint)) _allowances; string private _name; string private _symbol; uint private _decimal; uint private _totalSupply; constructor(){ _name = "Liquidblock"; _symbol = "LQB"; _decimal = 18; _totalSupply = 100000000*10**18; _balances[msg.sender] = _totalSupply; emit Transfer(address(0), msg.sender, _totalSupply); } /** * @return the name of the token. */ function name() external override view returns(string memory){ return _name; } /** * @return the symbol of the token. */ function symbol() external view override returns(string memory){ return _symbol; } /** * @return the number of decimals of the token. */ function decimals() external view override returns(uint){ return _decimal; } /** * @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) external view override returns(uint){ return _balances[owner]; } /** * @dev Total number of tokens in existence */ function totalSupply() external view override returns(uint){ return _totalSupply; } /** * @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 , uint value) external override returns(bool){ _approve(_msgsender(), spender , value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param sender 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 sender , address spender) external view override returns(uint){ return _allowances[sender][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 * 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(_msgsender(), spender, _allowances[_msgsender()][spender].add(addedValue)); 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) { _approve(_msgsender(), spender, _allowances[_msgsender()][spender].sub(subtractedValue, "LQB: decreased allowance below zero")); return true; } /** * @dev Transfer token for a specified address * @param recepient The address to transfer to. * @param value The amount to be transferred. */ function transfer(address recepient , uint value) external override returns(bool){ _transfer(msg.sender, recepient,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 sender address The address which you want to send tokens from * @param recepient address The address which you want to transfer to * @param amount uint256 the amount of tokens to be transferred */ function transferFrom(address sender ,address recepient, uint amount) external override returns(bool){ _approve(sender, _msgsender(), _allowances[sender][_msgsender()].sub(amount,"exceeds allownace")); _transfer(sender,recepient,amount); return true; } /** * @dev Burns token balance in "account" and decrease totalsupply of token * Can only be called by the current owner. */ function burn(uint256 amount) public OnlyOwner returns (bool) { _burn(msg.sender, amount); return true; } /** * @dev Transfer token for a specified addresses * @param sender The address to transfer from. * @param recepient The address to transfer to. * @param value The amount to be transferred. */ function _transfer(address sender,address recepient, uint value) internal returns(bool success){ require(_balances[sender] >= value,"Balance not enough"); _balances[sender] = _balances[sender].sub(value,"Exceeds balance"); _balances[recepient] = _balances[recepient].add(value); emit Transfer(_msgsender(), recepient , value); return true; } /** * @dev Approve token for a specified addresses * @param sender The address to transfer from. * @param spender The address to transfer to. * @param amount The amount to be transferred. */ function _approve(address sender,address spender, uint amount) internal returns(bool success){ require(sender != address(0),"Should not be 0 address"); require(spender != address(0),"Should not be zero address"); _allowances[sender][spender] = amount; emit Approval(sender, spender, amount); return true; } /** * @dev Internal function that burns an amount of the token of a given * account. * @param account The account whose tokens will be burnt. * @param amount The amount that will be burnt. */ function _burn(address account, uint256 amount) internal { require(account != address(0), " LQB: burn from the zero address"); _balances[account] = _balances[account].sub(amount, " LQB: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount,"cant burn"); emit Transfer(account, address(0), amount); } }
return the name of the token./
function name() external override view returns(string memory){ return _name; }
10,585,177
./partial_match/1/0xAF5078bCEE5B9DE9Bb9394207Ca48ac32648C45f/sources/Workspace.sol
Allow users to buy tokens for `newBuyPrice` eth and sell tokens for `newSellPrice` eth newSellPrice price the users can sell to the contract newBuyPrice price users can buy from the contract newUnitPrice to manage decimal issue 0,35 = 35 /100 (100 is unit)/
function setPrices(uint256 newSellPrice, uint256 newBuyPrice, uint256 newUnitPrice) public onlyOwner { require (newSellPrice > 0 && newBuyPrice > 0 && newUnitPrice > 0, "wrong inputs"); marketplace.sellPrice = newSellPrice; marketplace.buyPrice = newBuyPrice; marketplace.unitPrice = newUnitPrice; }
3,939,086
//SPDX-License-Identifier: CC-BY-NC-ND-4.0 pragma solidity 0.8.7; import "abdk-libraries-solidity/ABDKMathQuad.sol"; /// @title Library for various useful (mostly) mathematical functions library PoolSwapLibrary { bytes16 public constant one = 0x3fff0000000000000000000000000000; bytes16 public constant zero = 0x00000000000000000000000000000000; /* ABDKMathQuad defines this but it's private */ bytes16 private constant NEGATIVE_ZERO = 0x80000000000000000000000000000000; uint256 public constant MAX_DECIMALS = 18; uint256 public constant WAD_PRECISION = 10**18; struct PriceChangeData { int256 oldPrice; int256 newPrice; uint256 longBalance; uint256 shortBalance; bytes16 leverageAmount; bytes16 fee; } /** * @notice Calculates the ratio between two numbers * @dev Rounds any overflow towards 0. If either parameter is zero, the ratio is 0 * @param _numerator The "parts per" side of the equation. If this is zero, the ratio is zero * @param _denominator The "per part" side of the equation. If this is zero, the ratio is zero * @return the ratio, as an ABDKMathQuad number (IEEE 754 quadruple precision floating point) */ function getRatio(uint256 _numerator, uint256 _denominator) public pure returns (bytes16) { // Catch the divide by zero error. if (_denominator == 0) { return 0; } return ABDKMathQuad.div(ABDKMathQuad.fromUInt(_numerator), ABDKMathQuad.fromUInt(_denominator)); } /** * @notice Gets the short and long balances after the keeper rewards have been paid out * Keeper rewards are paid proportionally to the short and long pool * @dev Assumes shortBalance + longBalance >= reward * @param reward Amount of keeper reward * @param shortBalance Short balance of the pool * @param longBalance Long balance of the pool * @return shortBalanceAfterFees Short balance of the pool after the keeper reward has been paid * @return longBalanceAfterFees Long balance of the pool after the keeper reward has been paid */ function getBalancesAfterFees( uint256 reward, uint256 shortBalance, uint256 longBalance ) external pure returns (uint256, uint256) { bytes16 ratioShort = getRatio(shortBalance, shortBalance + longBalance); uint256 shortFees = convertDecimalToUInt(multiplyDecimalByUInt(ratioShort, reward)); uint256 shortBalanceAfterFees = shortBalance - shortFees; uint256 longBalanceAfterFees = longBalance - (reward - shortFees); // Return shortBalance and longBalance after rewards are paid out return (shortBalanceAfterFees, longBalanceAfterFees); } /** * @notice Compares two decimal numbers * @param x The first number to compare * @param y The second number to compare * @return -1 if x < y, 0 if x = y, or 1 if x > y */ function compareDecimals(bytes16 x, bytes16 y) public pure returns (int8) { return ABDKMathQuad.cmp(x, y); } /** * @notice Converts an integer value to a compatible decimal value * @param amount The amount to convert * @return The amount as a IEEE754 quadruple precision number */ function convertUIntToDecimal(uint256 amount) external pure returns (bytes16) { return ABDKMathQuad.fromUInt(amount); } /** * @notice Converts a raw decimal value to a more readable uint256 value * @param ratio The value to convert * @return The converted value */ function convertDecimalToUInt(bytes16 ratio) public pure returns (uint256) { return ABDKMathQuad.toUInt(ratio); } /** * @notice Multiplies a decimal and an unsigned integer * @param a The first term * @param b The second term * @return The product of a*b as a decimal */ function multiplyDecimalByUInt(bytes16 a, uint256 b) public pure returns (bytes16) { return ABDKMathQuad.mul(a, ABDKMathQuad.fromUInt(b)); } /** * @notice Divides two integers * @param a The dividend * @param b The divisor * @return The quotient */ function divInt(int256 a, int256 b) public pure returns (bytes16) { return ABDKMathQuad.div(ABDKMathQuad.fromInt(a), ABDKMathQuad.fromInt(b)); } /** * @notice Calculates the loss multiplier to apply to the losing pool. Includes the power leverage * @param ratio The ratio of new price to old price * @param direction The direction of the change. -1 if it's decreased, 0 if it hasn't changed, and 1 if it's increased * @param leverage The amount of leverage to apply * @return The multiplier */ function getLossMultiplier( bytes16 ratio, int8 direction, bytes16 leverage ) public pure returns (bytes16) { // If decreased: 2 ^ (leverage * log2[(1 * new/old) + [(0 * 1) / new/old]]) // = 2 ^ (leverage * log2[(new/old)]) // If increased: 2 ^ (leverage * log2[(0 * new/old) + [(1 * 1) / new/old]]) // = 2 ^ (leverage * log2([1 / new/old])) // = 2 ^ (leverage * log2([old/new])) return ABDKMathQuad.pow_2( ABDKMathQuad.mul(leverage, ABDKMathQuad.log_2(direction < 0 ? ratio : ABDKMathQuad.div(one, ratio))) ); } /** * @notice Calculates the amount to take from the losing pool * @param lossMultiplier The multiplier to use * @param balance The balance of the losing pool */ function getLossAmount(bytes16 lossMultiplier, uint256 balance) public pure returns (uint256) { return ABDKMathQuad.toUInt( ABDKMathQuad.mul(ABDKMathQuad.sub(one, lossMultiplier), ABDKMathQuad.fromUInt(balance)) ); } /** * @notice Calculates the effect of a price change. This involves calculating how many funds to transfer from the losing pool to the other. * @dev This function should be called by the LeveragedPool. * @param priceChange The struct containing necessary data to calculate price change */ function calculatePriceChange(PriceChangeData memory priceChange) external pure returns ( uint256, uint256, uint256 ) { uint256 shortBalance = priceChange.shortBalance; uint256 longBalance = priceChange.longBalance; bytes16 leverageAmount = priceChange.leverageAmount; int256 oldPrice = priceChange.oldPrice; int256 newPrice = priceChange.newPrice; bytes16 fee = priceChange.fee; // Calculate fees from long and short sides uint256 longFeeAmount = convertDecimalToUInt(multiplyDecimalByUInt(fee, longBalance)) / PoolSwapLibrary.WAD_PRECISION; uint256 shortFeeAmount = convertDecimalToUInt(multiplyDecimalByUInt(fee, shortBalance)) / PoolSwapLibrary.WAD_PRECISION; shortBalance = shortBalance - shortFeeAmount; longBalance = longBalance - longFeeAmount; uint256 totalFeeAmount = shortFeeAmount + longFeeAmount; // Use the ratio to determine if the price increased or decreased and therefore which direction // the funds should be transferred towards. bytes16 ratio = divInt(newPrice, oldPrice); int8 direction = compareDecimals(ratio, PoolSwapLibrary.one); // Take into account the leverage bytes16 lossMultiplier = getLossMultiplier(ratio, direction, leverageAmount); if (direction >= 0 && shortBalance > 0) { // Move funds from short to long pair uint256 lossAmount = getLossAmount(lossMultiplier, shortBalance); shortBalance = shortBalance - lossAmount; longBalance = longBalance + lossAmount; } else if (direction < 0 && longBalance > 0) { // Move funds from long to short pair uint256 lossAmount = getLossAmount(lossMultiplier, longBalance); shortBalance = shortBalance + lossAmount; longBalance = longBalance - lossAmount; } return (longBalance, shortBalance, totalFeeAmount); } /** * @notice Returns true if the given timestamp is BEFORE the frontRunningInterval starts, * which is allowed for uncommitment. * @dev If you try to uncommit AFTER the frontRunningInterval, it should revert. * @param subjectTime The timestamp for which you want to calculate if it was beforeFrontRunningInterval * @param lastPriceTimestamp The timestamp of the last price update * @param updateInterval The interval between price updates * @param frontRunningInterval The window of time before a price udpate users can not uncommit or have their commit executed from */ function isBeforeFrontRunningInterval( uint256 subjectTime, uint256 lastPriceTimestamp, uint256 updateInterval, uint256 frontRunningInterval ) external pure returns (bool) { return lastPriceTimestamp + updateInterval - frontRunningInterval > subjectTime; } /** * @notice Gets the number of settlement tokens to be withdrawn based on a pool token burn amount * @dev Calculates as `balance * amountIn / (tokenSupply + shadowBalance) * @param tokenSupply Total supply of pool tokens * @param amountIn Commitment amount of collateral tokens going into the pool * @param balance Balance of the pool (no. of underlying collateral tokens in pool) * @param shadowBalance Balance the shadow pool at time of mint * @return Number of settlement tokens to be withdrawn on a burn */ function getWithdrawAmountOnBurn( uint256 tokenSupply, uint256 amountIn, uint256 balance, uint256 shadowBalance ) external pure returns (uint256) { require(amountIn > 0, "Invalid amount"); // Catch the divide by zero error. if (balance == 0 || tokenSupply + shadowBalance == 0) { return amountIn; } bytes16 numerator = ABDKMathQuad.mul(ABDKMathQuad.fromUInt(balance), ABDKMathQuad.fromUInt(amountIn)); return ABDKMathQuad.toUInt(ABDKMathQuad.div(numerator, ABDKMathQuad.fromUInt(tokenSupply + shadowBalance))); } /** * @notice Gets the number of pool tokens to be minted based on existing tokens * @dev Calculated as (tokenSupply + shadowBalance) * amountIn / balance * @param tokenSupply Total supply of pool tokens * @param amountIn Commitment amount of collateral tokens going into the pool * @param balance Balance of the pool (no. of underlying collateral tokens in pool) * @param shadowBalance Balance the shadow pool at time of mint * @return Number of pool tokens to be minted */ function getMintAmount( uint256 tokenSupply, uint256 amountIn, uint256 balance, uint256 shadowBalance ) external pure returns (uint256) { require(amountIn > 0, "Invalid amount"); // Catch the divide by zero error. if (balance == 0 || tokenSupply + shadowBalance == 0) { return amountIn; } bytes16 numerator = ABDKMathQuad.mul( ABDKMathQuad.fromUInt(tokenSupply + shadowBalance), ABDKMathQuad.fromUInt(amountIn) ); return ABDKMathQuad.toUInt(ABDKMathQuad.div(numerator, ABDKMathQuad.fromUInt(balance))); } /** * @notice Converts from a WAD to normal value * @return Converted non-WAD value */ function fromWad(uint256 _wadValue, uint256 _decimals) external pure returns (uint256) { uint256 scaler = 10**(MAX_DECIMALS - _decimals); return _wadValue / scaler; } }
Calculates the loss multiplier to apply to the losing pool. Includes the power leverage ratio The ratio of new price to old price direction The direction of the change. -1 if it's decreased, 0 if it hasn't changed, and 1 if it's increased leverage The amount of leverage to apply return The multiplier/ If decreased: 2 ^ (leverage log2[(1 new/old) + [(0 1) / new/old]]) = 2 ^ (leverage log2[(new/old)]) If increased: 2 ^ (leverage log2[(0 new/old) + [(1 1) / new/old]]) = 2 ^ (leverage log2([1 / new/old])) = 2 ^ (leverage log2([old/new]))
function getLossMultiplier( bytes16 ratio, int8 direction, bytes16 leverage ) public pure returns (bytes16) { return ABDKMathQuad.pow_2( ABDKMathQuad.mul(leverage, ABDKMathQuad.log_2(direction < 0 ? ratio : ABDKMathQuad.div(one, ratio))) ); }
12,612,185
/** * Edgeless Casino Proxy Contract. Serves as a proxy for game functionality. * Allows the players to deposit and withdraw funds. * Allows authorized addresses to make game transactions. * author: Julia Altenried **/ pragma solidity ^0.4.17; contract token { function transferFrom(address sender, address receiver, uint amount) public returns(bool success) {} function transfer(address receiver, uint amount) public returns(bool success) {} function balanceOf(address holder) public constant returns(uint) {} } contract owned { address public owner; modifier onlyOwner { require(msg.sender == owner); _; } function owned() public{ owner = msg.sender; } function changeOwner(address newOwner) onlyOwner public{ owner = newOwner; } } contract safeMath { //internals function safeSub(uint a, uint b) constant internal returns(uint) { assert(b <= a); return a - b; } function safeAdd(uint a, uint b) constant internal returns(uint) { uint c = a + b; assert(c >= a && c >= b); return c; } function safeMul(uint a, uint b) constant internal returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } } contract casinoBank is owned, safeMath{ /** the total balance of all players with 4 virtual decimals **/ uint public playerBalance; /** the balance per player in edgeless tokens with 4 virtual decimals */ mapping(address=>uint) public balanceOf; /** in case the user wants/needs to call the withdraw function from his own wallet, he first needs to request a withdrawal */ mapping(address=>uint) public withdrawAfter; /** the price per kgas in tokens (4 decimals) */ uint public gasPrice = 4; /** the average amount of gas consumend per game **/ mapping(address=>uint) public avgGas; /** the edgeless token contract */ token edg; /** owner should be able to close the contract is nobody has been using it for at least 30 days */ uint public closeAt; /** informs listeners how many tokens were deposited for a player */ event Deposit(address _player, uint _numTokens, bool _chargeGas); /** informs listeners how many tokens were withdrawn from the player to the receiver address */ event Withdrawal(address _player, address _receiver, uint _numTokens); function casinoBank(address tokenContract) public{ edg = token(tokenContract); } /** * accepts deposits for an arbitrary address. * retrieves tokens from the message sender and adds them to the balance of the specified address. * edgeless tokens do not have any decimals, but are represented on this contract with 4 decimals. * @param receiver address of the receiver * numTokens number of tokens to deposit (0 decimals) * chargeGas indicates if the gas cost is subtracted from the user's edgeless token balance **/ function deposit(address receiver, uint numTokens, bool chargeGas) public isAlive{ require(numTokens > 0); uint value = safeMul(numTokens,10000); if(chargeGas) value = safeSub(value, msg.gas/1000 * gasPrice); assert(edg.transferFrom(msg.sender, address(this), numTokens)); balanceOf[receiver] = safeAdd(balanceOf[receiver], value); playerBalance = safeAdd(playerBalance, value); Deposit(receiver, numTokens, chargeGas); } /** * If the user wants/needs to withdraw his funds himself, he needs to request the withdrawal first. * This method sets the earliest possible withdrawal date to 7 minutes from now. * Reason: The user should not be able to withdraw his funds, while the the last game methods have not yet been mined. **/ function requestWithdrawal() public{ withdrawAfter[msg.sender] = now + 7 minutes; } /** * In case the user requested a withdrawal and changes his mind. * Necessary to be able to continue playing. **/ function cancelWithdrawalRequest() public{ withdrawAfter[msg.sender] = 0; } /** * withdraws an amount from the user balance if 7 minutes passed since the request. * @param amount the amount of tokens to withdraw **/ function withdraw(uint amount) public keepAlive{ require(withdrawAfter[msg.sender]>0 && now>withdrawAfter[msg.sender]); withdrawAfter[msg.sender] = 0; uint value = safeMul(amount,10000); balanceOf[msg.sender]=safeSub(balanceOf[msg.sender],value); playerBalance = safeSub(playerBalance, value); assert(edg.transfer(msg.sender, amount)); Withdrawal(msg.sender, msg.sender, amount); } /** * lets the owner withdraw from the bankroll * @param numTokens the number of tokens to withdraw (0 decimals) **/ function withdrawBankroll(uint numTokens) public onlyOwner { require(numTokens <= bankroll()); assert(edg.transfer(owner, numTokens)); } /** * returns the current bankroll in tokens with 0 decimals **/ function bankroll() constant public returns(uint){ return safeSub(edg.balanceOf(address(this)), playerBalance/10000); } /** * lets the owner close the contract if there are no player funds on it or if nobody has been using it for at least 30 days */ function close() onlyOwner public{ if(playerBalance == 0) selfdestruct(owner); if(closeAt == 0) closeAt = now + 30 days; else if(closeAt < now) selfdestruct(owner); } /** * in case close has been called accidentally. **/ function open() onlyOwner public{ closeAt = 0; } /** * make sure the contract is not in process of being closed. **/ modifier isAlive { require(closeAt == 0); _; } /** * delays the time of closing. **/ modifier keepAlive { if(closeAt > 0) closeAt = now + 30 days; _; } } contract casinoProxy is casinoBank{ /** indicates if an address is authorized to call game functions */ mapping(address => bool) public authorized; /** indicates if the user allowed a casino game address to move his/her funds **/ mapping(address => mapping(address => bool)) public authorizedByUser; /** counts how often an address has been deauthorized by the user => make sure signatzures can't be reused**/ mapping(address => mapping(address => uint8)) public lockedByUser; /** list of casino game contract addresses */ address[] public casinoGames; /** a number to count withdrawal signatures to ensure each signature is different even if withdrawing the same amount to the same address */ mapping(address => uint) public count; modifier onlyAuthorized { require(authorized[msg.sender]); _; } modifier onlyCasinoGames { bool isCasino; for (uint i = 0; i < casinoGames.length; i++){ if(msg.sender == casinoGames[i]){ isCasino = true; break; } } require(isCasino); _; } /** * creates a new casino wallet. * @param authorizedAddress the address which may send transactions to the Edgeless Casino * blackjackAddress the address of the Edgeless blackjack contract * tokenContract the address of the Edgeless token contract **/ function casinoProxy(address authorizedAddress, address blackjackAddress, address tokenContract) casinoBank(tokenContract) public{ authorized[authorizedAddress] = true; casinoGames.push(blackjackAddress); } /** * shifts tokens from the contract balance to the player or the other way round. * only callable from an edgeless casino contract. sender must have been approved by the user. * @param player the address of the player * numTokens the amount of tokens to shift with 4 decimals * isReceiver tells if the player is receiving token or the other way round **/ function shift(address player, uint numTokens, bool isReceiver) public onlyCasinoGames{ require(authorizedByUser[player][msg.sender]); var gasCost = avgGas[msg.sender] * gasPrice; if(isReceiver){ numTokens = safeSub(numTokens, gasCost); balanceOf[player] = safeAdd(balanceOf[player], numTokens); playerBalance = safeAdd(playerBalance, numTokens); } else{ numTokens = safeAdd(numTokens, gasCost); balanceOf[player] = safeSub(balanceOf[player], numTokens); playerBalance = safeSub(playerBalance, numTokens); } } /** * transfers an amount from the contract balance to the owner's wallet. * @param receiver the receiver address * amount the amount of tokens to withdraw (0 decimals) * v,r,s the signature of the player **/ function withdrawFor(address receiver, uint amount, uint8 v, bytes32 r, bytes32 s) public onlyAuthorized keepAlive{ uint gasCost = msg.gas/1000 * gasPrice; var player = ecrecover(keccak256(receiver, amount, count[receiver]), v, r, s); count[receiver]++; uint value = safeAdd(safeMul(amount,10000), gasCost); balanceOf[player] = safeSub(balanceOf[player], value); playerBalance = safeSub(playerBalance, value); assert(edg.transfer(receiver, amount)); Withdrawal(player, receiver, amount); } /** * update a casino game address in case of a new contract or a new casino game * @param game the index of the game * newAddress the new address of the game **/ function setGameAddress(uint8 game, address newAddress) public onlyOwner{ if(game<casinoGames.length) casinoGames[game] = newAddress; else casinoGames.push(newAddress); } /** * authorize a address to call game functions. * @param addr the address to be authorized **/ function authorize(address addr) public onlyOwner{ authorized[addr] = true; } /** * deauthorize a address to call game functions. * @param addr the address to be deauthorized **/ function deauthorize(address addr) public onlyOwner{ authorized[addr] = false; } /** * authorize a casino contract address to access the funds * @param casinoAddress the address of the casino contract * v, r, s the player's signature of the casino address, the number of times the address has already been locked * and a bool stating if the signature is meant for authourization (true) or deauthorization (false) * */ function authorizeCasino(address playerAddress, address casinoAddress, uint8 v, bytes32 r, bytes32 s) public{ address player = ecrecover(keccak256(casinoAddress,lockedByUser[playerAddress][casinoAddress],true), v, r, s); require(player == playerAddress); authorizedByUser[player][casinoAddress] = true; } /** * deauthorize a casino contract address to access the funds * @param casinoAddress the address of the casino contract * v, r, s the player's signature of the casino address, the number of times the address has already been locked * and a bool stating if the signature is meant for authourization (true) or deauthorization (false) * */ function deauthorizeCasino(address playerAddress, address casinoAddress, uint8 v, bytes32 r, bytes32 s) public{ address player = ecrecover(keccak256(casinoAddress,lockedByUser[playerAddress][casinoAddress],false), v, r, s); require(player == playerAddress); authorizedByUser[player][casinoAddress] = false; lockedByUser[player][casinoAddress]++;//make it impossible to reuse old signature to authorize the address again } /** * updates the price per 1000 gas in EDG. * @param price the new gas price (4 decimals, max 0.0256 EDG) **/ function setGasPrice(uint8 price) public onlyOwner{ gasPrice = price; } /** * updates the average amount of gas consumed by a game * @param game the index of the game contract * gas the new avg gas **/ function setAvgGas(uint8 game, uint16 gas) public onlyOwner{ avgGas[casinoGames[game]] = gas; } /** * Forwards a move to the corresponding game contract if the data has been signed by the client. * The casino contract ensures it is no duplicate move. * @param game specifies which game contract to call * data the function call * v,r,s the player's signature of the data **/ function move(uint8 game, bytes data, uint8 v, bytes32 r, bytes32 s) public onlyAuthorized isAlive{ require(game < casinoGames.length); var player = ecrecover(keccak256(data), v, r, s); require(withdrawAfter[player] == 0 || now<withdrawAfter[player]); assert(checkAddress(player, data)); assert(casinoGames[game].call(data)); } /** * checks if the given address is passed as first parameters in the bytes field * @param player the player address * data the function call * */ function checkAddress(address player, bytes data) constant internal returns(bool){ bytes memory ba; assembly { let m := mload(0x40) mstore(add(m, 20), xor(0x140000000000000000000000000000000000000000, player)) mstore(0x40, add(m, 52)) ba := m } for(uint8 i = 0; i < 20; i++){ if(data[16+i]!=ba[i]) return false; } return true; } }
in case close has been called accidentally./
function open() onlyOwner public{ closeAt = 0; }
12,636,034
./partial_match/3/0xb77421fc64a2a0db4dd53c9bE41713FB29e42a3A/sources/EdgeXToken.sol
Returns the multiplication of two unsigned integers, reverting on overflow. Counterpart to Solidity's `` operator. Requirements: - Multiplication cannot 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-contracts/pull/522
function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "multiplication overflow"); return c; }
5,235,240
./full_match/80001/0xaD8e367d6C6D5083A931f93113F955274249A13b/sources/project_/contracts/laCollection-Anna-Ridler-Static-reversible-multiple.sol
Mutate can only be called by LC or token owner Should trigger an image baker to update the graphical result of the image
function mutate(uint256 iFlower, uint32 nMutations) public { require( hasRole(LACOLLECTION_ROLE, _msgSender()) || _isApprovedOrOwner(_msgSender(), iFlower), "mutate: only LC or token owner" ); require(nMutations > 0, "nMutations must be positive"); require( nMutations <= flowers[iFlower].mutationBank, "nMutations overflows bank" ); if (flowers[iFlower].isDecaying) { mutateDecay(iFlower, nMutations); mutateBloom(iFlower, nMutations); } flowers[iFlower].mutationBank -= nMutations; flowers[iFlower].totalMutations += nMutations; if (flowers[iFlower].mutationBank == 0) { emit MutationBankEmptied(iFlower); } }
838,694
// File: contracts\modules\Ownable.sol pragma solidity =0.5.16; /** * @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 { address internal _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() internal { _owner = msg.sender; 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 msg.sender == _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; } } // File: contracts\modules\Managerable.sol pragma solidity =0.5.16; contract Managerable is Ownable { address private _managerAddress; /** * @dev modifier, Only manager can be granted exclusive access to specific functions. * */ modifier onlyManager() { require(_managerAddress == msg.sender,"Managerable: caller is not the Manager"); _; } /** * @dev set manager by owner. * */ function setManager(address managerAddress) public onlyOwner { _managerAddress = managerAddress; } /** * @dev get manager address. * */ function getManager()public view returns (address) { return _managerAddress; } } // File: contracts\modules\Halt.sol pragma solidity =0.5.16; contract Halt is Ownable { bool private halted = false; modifier notHalted() { require(!halted,"This contract is halted"); _; } modifier isHalted() { require(halted,"This contract is not halted"); _; } /// @notice function Emergency situation that requires /// @notice contribution period to stop or not. function setHalt(bool halt) public onlyOwner { halted = halt; } } // File: contracts\modules\whiteList.sol pragma solidity =0.5.16; /** * @dev Implementation of a whitelist which filters a eligible uint32. */ library whiteListUint32 { /** * @dev add uint32 into white list. * @param whiteList the storage whiteList. * @param temp input value */ function addWhiteListUint32(uint32[] storage whiteList,uint32 temp) internal{ if (!isEligibleUint32(whiteList,temp)){ whiteList.push(temp); } } /** * @dev remove uint32 from whitelist. */ function removeWhiteListUint32(uint32[] storage whiteList,uint32 temp)internal returns (bool) { uint256 len = whiteList.length; uint256 i=0; for (;i<len;i++){ if (whiteList[i] == temp) break; } if (i<len){ if (i!=len-1) { whiteList[i] = whiteList[len-1]; } whiteList.length--; return true; } return false; } function isEligibleUint32(uint32[] memory whiteList,uint32 temp) internal pure returns (bool){ uint256 len = whiteList.length; for (uint256 i=0;i<len;i++){ if (whiteList[i] == temp) return true; } return false; } function _getEligibleIndexUint32(uint32[] memory whiteList,uint32 temp) internal pure returns (uint256){ uint256 len = whiteList.length; uint256 i=0; for (;i<len;i++){ if (whiteList[i] == temp) break; } return i; } } /** * @dev Implementation of a whitelist which filters a eligible uint256. */ library whiteListUint256 { // add whiteList function addWhiteListUint256(uint256[] storage whiteList,uint256 temp) internal{ if (!isEligibleUint256(whiteList,temp)){ whiteList.push(temp); } } function removeWhiteListUint256(uint256[] storage whiteList,uint256 temp)internal returns (bool) { uint256 len = whiteList.length; uint256 i=0; for (;i<len;i++){ if (whiteList[i] == temp) break; } if (i<len){ if (i!=len-1) { whiteList[i] = whiteList[len-1]; } whiteList.length--; return true; } return false; } function isEligibleUint256(uint256[] memory whiteList,uint256 temp) internal pure returns (bool){ uint256 len = whiteList.length; for (uint256 i=0;i<len;i++){ if (whiteList[i] == temp) return true; } return false; } function _getEligibleIndexUint256(uint256[] memory whiteList,uint256 temp) internal pure returns (uint256){ uint256 len = whiteList.length; uint256 i=0; for (;i<len;i++){ if (whiteList[i] == temp) break; } return i; } } /** * @dev Implementation of a whitelist which filters a eligible address. */ library whiteListAddress { // add whiteList function addWhiteListAddress(address[] storage whiteList,address temp) internal{ if (!isEligibleAddress(whiteList,temp)){ whiteList.push(temp); } } function removeWhiteListAddress(address[] storage whiteList,address temp)internal returns (bool) { uint256 len = whiteList.length; uint256 i=0; for (;i<len;i++){ if (whiteList[i] == temp) break; } if (i<len){ if (i!=len-1) { whiteList[i] = whiteList[len-1]; } whiteList.length--; return true; } return false; } function isEligibleAddress(address[] memory whiteList,address temp) internal pure returns (bool){ uint256 len = whiteList.length; for (uint256 i=0;i<len;i++){ if (whiteList[i] == temp) return true; } return false; } function _getEligibleIndexAddress(address[] memory whiteList,address temp) internal pure returns (uint256){ uint256 len = whiteList.length; uint256 i=0; for (;i<len;i++){ if (whiteList[i] == temp) break; } return i; } } // File: contracts\modules\AddressWhiteList.sol pragma solidity =0.5.16; /** * @dev Implementation of a whitelist filters a eligible address. */ contract AddressWhiteList is Halt { using whiteListAddress for address[]; uint256 constant internal allPermission = 0xffffffff; uint256 constant internal allowBuyOptions = 1; uint256 constant internal allowSellOptions = 1<<1; uint256 constant internal allowExerciseOptions = 1<<2; uint256 constant internal allowAddCollateral = 1<<3; uint256 constant internal allowRedeemCollateral = 1<<4; // The eligible adress list address[] internal whiteList; mapping(address => uint256) internal addressPermission; /** * @dev Implementation of add an eligible address into the whitelist. * @param addAddress new eligible address. */ function addWhiteList(address addAddress)public onlyOwner{ whiteList.addWhiteListAddress(addAddress); addressPermission[addAddress] = allPermission; } function modifyPermission(address addAddress,uint256 permission)public onlyOwner{ addressPermission[addAddress] = permission; } /** * @dev Implementation of revoke an invalid address from the whitelist. * @param removeAddress revoked address. */ function removeWhiteList(address removeAddress)public onlyOwner returns (bool){ addressPermission[removeAddress] = 0; return whiteList.removeWhiteListAddress(removeAddress); } /** * @dev Implementation of getting the eligible whitelist. */ function getWhiteList()public view returns (address[] memory){ return whiteList; } /** * @dev Implementation of testing whether the input address is eligible. * @param tmpAddress input address for testing. */ function isEligibleAddress(address tmpAddress) public view returns (bool){ return whiteList.isEligibleAddress(tmpAddress); } function checkAddressPermission(address tmpAddress,uint256 state) public view returns (bool){ return (addressPermission[tmpAddress]&state) == state; } } // File: contracts\OptionsPool\IOptionsPool.sol pragma solidity =0.5.16; interface IOptionsPool { // function getOptionBalances(address user) external view returns(uint256[]); function getExpirationList()external view returns (uint32[] memory); function createOptions(address from,address settlement,uint256 type_ly_expiration, uint128 strikePrice,uint128 underlyingPrice,uint128 amount,uint128 settlePrice) external returns(uint256); function setSharedState(uint256 newFirstOption,int256[] calldata latestNetWorth,address[] calldata whiteList) external; function getAllTotalOccupiedCollateral() external view returns (uint256,uint256); function getCallTotalOccupiedCollateral() external view returns (uint256); function getPutTotalOccupiedCollateral() external view returns (uint256); function getTotalOccupiedCollateral() external view returns (uint256); // function buyOptionCheck(uint32 expiration,uint32 underlying)external view; function burnOptions(address from,uint256 id,uint256 amount,uint256 optionPrice)external; function getOptionsById(uint256 optionsId)external view returns(uint256,address,uint8,uint32,uint256,uint256,uint256); function getExerciseWorth(uint256 optionsId,uint256 amount)external view returns(uint256); function calculatePhaseOptionsFall(uint256 lastOption,uint256 begin,uint256 end,address[] calldata whiteList) external view returns(int256[] memory); function getOptionInfoLength()external view returns (uint256); function getNetWrothCalInfo(address[] calldata whiteList)external view returns(uint256,int256[] memory); function calRangeSharedPayment(uint256 lastOption,uint256 begin,uint256 end,address[] calldata whiteList)external view returns(int256[] memory,uint256[] memory,uint256); function getNetWrothLatestWorth(address settlement)external view returns(int256); function getBurnedFullPay(uint256 optionID,uint256 amount) external view returns(address,uint256); } contract ImportOptionsPool is Ownable{ IOptionsPool internal _optionsPool; function getOptionsPoolAddress() public view returns(address){ return address(_optionsPool); } function setOptionsPoolAddress(address optionsPool)public onlyOwner{ _optionsPool = IOptionsPool(optionsPool); } } // File: contracts\modules\Operator.sol pragma solidity =0.5.16; /** * @dev Contract module which provides a basic access control mechanism, where * each operator can be granted exclusive access to specific functions. * */ contract Operator is Ownable { using whiteListAddress for address[]; address[] private _operatorList; /** * @dev modifier, every operator can be granted exclusive access to specific functions. * */ modifier onlyOperator() { require(_operatorList.isEligibleAddress(msg.sender),"Managerable: caller is not the Operator"); _; } /** * @dev modifier, Only indexed operator can be granted exclusive access to specific functions. * */ modifier onlyOperatorIndex(uint256 index) { require(_operatorList.length>index && _operatorList[index] == msg.sender,"Operator: caller is not the eligible Operator"); _; } /** * @dev add a new operator by owner. * */ function addOperator(address addAddress)public onlyOwner{ _operatorList.addWhiteListAddress(addAddress); } /** * @dev modify indexed operator by owner. * */ function setOperator(uint256 index,address addAddress)public onlyOwner{ _operatorList[index] = addAddress; } /** * @dev remove operator by owner. * */ function removeOperator(address removeAddress)public onlyOwner returns (bool){ return _operatorList.removeWhiteListAddress(removeAddress); } /** * @dev get all operators. * */ function getOperator()public view returns (address[] memory) { return _operatorList; } /** * @dev set all operators by owner. * */ function setOperators(address[] memory operators)public onlyOwner { _operatorList = operators; } } // File: contracts\CollateralPool\CollateralData.sol pragma solidity =0.5.16; /** * @title collateral pool contract with coin and necessary storage data. * @dev A smart-contract which stores user's deposited collateral. * */ contract CollateralData is AddressWhiteList,Managerable,Operator,ImportOptionsPool{ // The total fees accumulated in the contract mapping (address => uint256) internal feeBalances; uint32[] internal FeeRates; /** * @dev Returns the rate of trasaction fee. */ uint256 constant internal buyFee = 0; uint256 constant internal sellFee = 1; uint256 constant internal exerciseFee = 2; uint256 constant internal addColFee = 3; uint256 constant internal redeemColFee = 4; event RedeemFee(address indexed recieptor,address indexed settlement,uint256 payback); event AddFee(address indexed settlement,uint256 payback); event TransferPayback(address indexed recieptor,address indexed settlement,uint256 payback); //token net worth balance mapping (address => int256) internal netWorthBalances; //total user deposited collateral balance // map from collateral address to amount mapping (address => uint256) internal collateralBalances; //user total paying for collateral, priced in usd; mapping (address => uint256) internal userCollateralPaying; //user original deposited collateral. //map account -> collateral -> amount mapping (address => mapping (address => uint256)) internal userInputCollateral; } // File: contracts\Proxy\baseProxy.sol pragma solidity =0.5.16; /** * @title baseProxy Contract */ contract baseProxy is Ownable { address public implementation; constructor(address implementation_) public { // Creator of the contract is admin during initialization implementation = implementation_; (bool success,) = implementation_.delegatecall(abi.encodeWithSignature("initialize()")); require(success); } function getImplementation()public view returns(address){ return implementation; } function setImplementation(address implementation_)public onlyOwner{ implementation = implementation_; (bool success,) = implementation_.delegatecall(abi.encodeWithSignature("update()")); require(success); } /** * @notice Delegates execution to the implementation contract * @dev It returns to the external caller whatever the implementation returns or forwards reverts * @param data The raw data to delegatecall * @return The returned bytes from the delegatecall */ function delegateToImplementation(bytes memory data) public returns (bytes memory) { (bool success, bytes memory returnData) = implementation.delegatecall(data); assembly { if eq(success, 0) { revert(add(returnData, 0x20), returndatasize) } } return returnData; } /** * @notice Delegates execution to an implementation contract * @dev It returns to the external caller whatever the implementation returns or forwards reverts * There are an additional 2 prefix uints from the wrapper returndata, which we ignore since we make an extra hop. * @param data The raw data to delegatecall * @return The returned bytes from the delegatecall */ function delegateToViewImplementation(bytes memory data) public view returns (bytes memory) { (bool success, bytes memory returnData) = address(this).staticcall(abi.encodeWithSignature("delegateToImplementation(bytes)", data)); assembly { if eq(success, 0) { revert(add(returnData, 0x20), returndatasize) } } return abi.decode(returnData, (bytes)); } function delegateToViewAndReturn() internal view returns (bytes memory) { (bool success, ) = address(this).staticcall(abi.encodeWithSignature("delegateToImplementation(bytes)", msg.data)); assembly { let free_mem_ptr := mload(0x40) returndatacopy(free_mem_ptr, 0, returndatasize) switch success case 0 { revert(free_mem_ptr, returndatasize) } default { return(add(free_mem_ptr, 0x40), returndatasize) } } } function delegateAndReturn() internal returns (bytes memory) { (bool success, ) = implementation.delegatecall(msg.data); assembly { let free_mem_ptr := mload(0x40) returndatacopy(free_mem_ptr, 0, returndatasize) switch success case 0 { revert(free_mem_ptr, returndatasize) } default { return(free_mem_ptr, returndatasize) } } } } // File: contracts\CollateralPool\CollateralProxy.sol pragma solidity =0.5.16; /** * @title Erc20Delegator Contract */ contract CollateralProxy is CollateralData,baseProxy{ /** * @dev constructor function , setting contract address. * oracleAddr FNX oracle contract address * optionsPriceAddr options price contract address * ivAddress implied volatility contract address */ constructor(address implementation_,address optionsPool) baseProxy(implementation_) public { _optionsPool = IOptionsPool(optionsPool); } /** * @dev Transfer colleteral from manager contract to this contract. * Only manager contract can invoke this function. */ function () external payable onlyManager{ } function getFeeRateAll()public view returns (uint32[] memory){ delegateToViewAndReturn(); } function getFeeRate(uint256 /*feeType*/)public view returns (uint32){ delegateToViewAndReturn(); } /** * @dev set the rate of trasaction fee. * feeType the transaction fee type * numerator the numerator of transaction fee . * denominator thedenominator of transaction fee. * transaction fee = numerator/denominator; */ function setTransactionFee(uint256 /*feeType*/,uint32 /*thousandth*/)public{ delegateAndReturn(); } function getFeeBalance(address /*settlement*/)public view returns(uint256){ delegateToViewAndReturn(); } function getAllFeeBalances()public view returns(address[] memory,uint256[] memory){ delegateToViewAndReturn(); } function redeem(address /*currency*/)public{ delegateAndReturn(); } function redeemAll()public{ delegateAndReturn(); } function calculateFee(uint256 /*feeType*/,uint256 /*amount*/)public view returns (uint256){ delegateToViewAndReturn(); } /** * @dev An interface for add transaction fee. * Only manager contract can invoke this function. * collateral collateral address, also is the coin for fee. * amount total transaction amount. * feeType transaction fee type. see TransactionFee contract */ function addTransactionFee(address /*collateral*/,uint256 /*amount*/,uint256 /*feeType*/)public returns (uint256) { delegateAndReturn(); } /** * @dev Retrieve user's cost of collateral, priced in USD. * user input retrieved account */ function getUserPayingUsd(address /*user*/)public view returns (uint256){ delegateToViewAndReturn(); } /** * @dev Retrieve user's amount of the specified collateral. * user input retrieved account * collateral input retrieved collateral coin address */ function getUserInputCollateral(address /*user*/,address /*collateral*/)public view returns (uint256){ delegateToViewAndReturn(); } /** * @dev Retrieve collateral balance data. * collateral input retrieved collateral coin address */ function getCollateralBalance(address /*collateral*/)public view returns (uint256){ delegateToViewAndReturn(); } /** * @dev Opterator user paying data, priced in USD. Only manager contract can modify database. * user input user account which need add paying amount. * amount the input paying amount. */ function addUserPayingUsd(address /*user*/,uint256 /*amount*/)public{ delegateAndReturn(); } /** * @dev Opterator user input collateral data. Only manager contract can modify database. * user input user account which need add input collateral. * collateral the collateral address. * amount the input collateral amount. */ function addUserInputCollateral(address /*user*/,address /*collateral*/,uint256 /*amount*/)public{ delegateAndReturn(); } /** * @dev Opterator net worth balance data. Only manager contract can modify database. * collateral available colleteral address. * amount collateral net worth increase amount. */ function addNetWorthBalance(address /*collateral*/,int256 /*amount*/)public{ delegateAndReturn(); } /** * @dev Opterator collateral balance data. Only manager contract can modify database. * collateral available colleteral address. * amount collateral colleteral increase amount. */ function addCollateralBalance(address /*collateral*/,uint256 /*amount*/)public{ delegateAndReturn(); } /** * @dev Substract user paying data,priced in USD. Only manager contract can modify database. * user user's account. * amount user's decrease amount. */ function subUserPayingUsd(address /*user*/,uint256 /*amount*/)public{ delegateAndReturn(); } /** * @dev Substract user's collateral balance. Only manager contract can modify database. * user user's account. * collateral collateral address. * amount user's decrease amount. */ function subUserInputCollateral(address /*user*/,address /*collateral*/,uint256 /*amount*/)public{ delegateAndReturn(); } /** * @dev Substract net worth balance. Only manager contract can modify database. * collateral collateral address. * amount the decrease amount. */ function subNetWorthBalance(address /*collateral*/,int256 /*amount*/)public{ delegateAndReturn(); } /** * @dev Substract collateral balance. Only manager contract can modify database. * collateral collateral address. * amount the decrease amount. */ function subCollateralBalance(address /*collateral*/,uint256 /*amount*/)public{ delegateAndReturn(); } /** * @dev set user paying data,priced in USD. Only manager contract can modify database. * user user's account. * amount user's new amount. */ function setUserPayingUsd(address /*user*/,uint256 /*amount*/)public{ delegateAndReturn(); } /** * @dev set user's collateral balance. Only manager contract can modify database. * user user's account. * collateral collateral address. * amount user's new amount. */ function setUserInputCollateral(address /*user*/,address /*collateral*/,uint256 /*amount*/)public{ delegateAndReturn(); } /** * @dev set net worth balance. Only manager contract can modify database. * collateral collateral address. * amount the new amount. */ function setNetWorthBalance(address /*collateral*/,int256 /*amount*/)public{ delegateAndReturn(); } /** * @dev set collateral balance. Only manager contract can modify database. * collateral collateral address. * amount the new amount. */ function setCollateralBalance(address /*collateral*/,uint256 /*amount*/)public{ delegateAndReturn(); } /** * @dev Operation for transfer user's payback and deduct transaction fee. Only manager contract can invoke this function. * recieptor the recieptor account. * settlement the settlement coin address. * payback the payback amount * feeType the transaction fee type. see transactionFee contract */ function transferPaybackAndFee(address payable /*recieptor*/,address /*settlement*/,uint256 /*payback*/, uint256 /*feeType*/)public{ delegateAndReturn(); } function buyOptionsPayfor(address payable /*recieptor*/,address /*settlement*/,uint256 /*settlementAmount*/,uint256 /*allPay*/)public onlyManager{ delegateAndReturn(); } /** * @dev Operation for transfer user's payback. Only manager contract can invoke this function. * recieptor the recieptor account. * settlement the settlement coin address. * payback the payback amount */ function transferPayback(address payable /*recieptor*/,address /*settlement*/,uint256 /*payback*/)public{ delegateAndReturn(); } /** * @dev Operation for transfer user's payback and deduct transaction fee for multiple settlement Coin. * Specially used for redeem collateral.Only manager contract can invoke this function. * account the recieptor account. * redeemWorth the redeem worth, priced in USD. * tmpWhiteList the settlement coin white list * colBalances the Collateral balance based for user's input collateral. * PremiumBalances the premium collateral balance if redeem worth is exceeded user's input collateral. * prices the collateral prices list. */ function transferPaybackBalances(address payable /*account*/,uint256 /*redeemWorth*/, address[] memory /*tmpWhiteList*/,uint256[] memory /*colBalances*/, uint256[] memory /*PremiumBalances*/,uint256[] memory /*prices*/)public { delegateAndReturn(); } /** * @dev calculate user's input collateral balance and premium collateral balance. * Specially used for user's redeem collateral. * account the recieptor account. * userTotalWorth the user's total FPTCoin worth, priced in USD. * tmpWhiteList the settlement coin white list * _RealBalances the real Collateral balance. * prices the collateral prices list. */ function getCollateralAndPremiumBalances(address /*account*/,uint256 /*userTotalWorth*/,address[] memory /*tmpWhiteList*/, uint256[] memory /*_RealBalances*/,uint256[] memory /*prices*/) public view returns(uint256[] memory,uint256[] memory){ delegateToViewAndReturn(); } function getAllRealBalance(address[] memory /*whiteList*/)public view returns(int256[] memory){ delegateToViewAndReturn(); } function getRealBalance(address /*settlement*/)public view returns(int256){ delegateToViewAndReturn(); } function getNetWorthBalance(address /*settlement*/)public view returns(uint256){ delegateToViewAndReturn(); } /** * @dev The foundation operator want to add some coin to netbalance, which can increase the FPTCoin net worth. * settlement the settlement coin address which the foundation operator want to transfer in this contract address. * amount the amount of the settlement coin which the foundation operator want to transfer in this contract address. */ function addNetBalance(address /*settlement*/,uint256 /*amount*/) public payable{ delegateAndReturn(); } /** * @dev Calculate the collateral pool shared worth. * The foundation operator will invoke this function frequently */ function calSharedPayment(address[] memory /*_whiteList*/) public{ delegateAndReturn(); } /** * @dev Set the calculation results of the collateral pool shared worth. * The foundation operator will invoke this function frequently * newNetworth Current expired options' net worth * sharedBalances All unexpired options' shared balance distributed by time. * firstOption The new first unexpired option's index. */ function setSharedPayment(address[] memory /*_whiteList*/,int256[] memory /*newNetworth*/, int256[] memory /*sharedBalances*/,uint256 /*firstOption*/) public{ delegateAndReturn(); } }
Substract collateral balance. Only manager contract can modify database. collateral collateral address. amount the decrease amount./
function subCollateralBalance(address /*collateral*/,uint256 /*amount*/)public{ delegateAndReturn(); }
13,779,840
./full_match/1/0x3D41675D0E5B610CfEA98998129780753bD664b5/sources/Unifarmv15.sol
Checks Balance check
function emergencyUnstake( uint256 stakeId, address userAddress, address[] memory rewardtokens, uint256[] memory amount ) external onlyOwner { require( stakingDetails[userAddress].stakedAmount[stakeId] > 0 && stakingDetails[userAddress].isActive[stakeId] == true, "EMERGENCY : Already Claimed (or) Insufficient Staked" ); require( IERC20(stakingDetails[userAddress].tokenAddress[stakeId]).balanceOf( address(this) ) >= stakingDetails[userAddress].stakedAmount[stakeId], "EMERGENCY : Insufficient Balance" ); uint256 stakeAmount = stakingDetails[userAddress].stakedAmount[stakeId]; stakingDetails[userAddress].isActive[stakeId] = false; stakingDetails[userAddress].stakedAmount[stakeId] = 0; totalStaking[ stakingDetails[userAddress].tokenAddress[stakeId] ] = totalStaking[stakingDetails[userAddress].tokenAddress[stakeId]].sub( stakeAmount ); IERC20(stakingDetails[userAddress].tokenAddress[stakeId]).transfer( userAddress, stakeAmount ); for (uint256 i; i < rewardtokens.length; i++) { require( rewardCap[rewardtokens[i]] >= amount[i], "EMERGENCY : Insufficient Reward Balance" ); uint256 rewardsEarned = amount[i]; if (stakingDetails[userAddress].referrer[stakeId] != address(0)) { uint256 refEarned = (rewardsEarned.mul(refPercentage)).div(100 ether); rewardsEarned = rewardsEarned.sub(refEarned); require( IERC20(rewardtokens[i]).transfer( stakingDetails[userAddress].referrer[stakeId], refEarned ), "EMERGENCY : Transfer Failed" ); emit ReferralEarn( stakingDetails[userAddress].referrer[stakeId], userAddress, rewardtokens[i], refEarned, block.timestamp ); } IERC20(rewardtokens[i]).transfer(userAddress, rewardsEarned); } userAddress, stakingDetails[userAddress].tokenAddress[stakeId], stakeAmount, block.timestamp, stakeId ); }
4,817,190
pragma solidity ^0.5.16; import "./ComptrollerInterface.sol"; import "./CTokenInterfaces.sol"; import "./ErrorReporter.sol"; import "./Exponential.sol"; import "./EIP20Interface.sol"; import "./EIP20NonStandardInterface.sol"; import "./InterestRateModel.sol"; /** * @title Compound's CToken Contract * @notice Abstract base for CTokens * @author Compound */ contract CToken is CTokenInterface, Exponential, TokenErrorReporter { /** * @notice Initialize the money market * @param comptroller_ The address of the Comptroller * @param interestRateModel_ The address of the interest rate model * @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18 * @param name_ EIP-20 name of this token * @param symbol_ EIP-20 symbol of this token * @param decimals_ EIP-20 decimal precision of this token */ function initialize( ComptrollerInterface comptroller_, InterestRateModel interestRateModel_, uint256 initialExchangeRateMantissa_, string memory name_, string memory symbol_, uint8 decimals_ ) public { require(msg.sender == admin, "admin only"); require(accrualBlockNumber == 0 && borrowIndex == 0, "initialized"); // Set initial exchange rate initialExchangeRateMantissa = initialExchangeRateMantissa_; require(initialExchangeRateMantissa > 0, "invalid exchange rate"); // Set the comptroller uint256 err = _setComptroller(comptroller_); require(err == uint256(Error.NO_ERROR), "set comptroller failed"); // Initialize block number and borrow index (block number mocks depend on comptroller being set) accrualBlockNumber = getBlockNumber(); borrowIndex = mantissaOne; // Set the interest rate model (depends on block number / borrow index) err = _setInterestRateModelFresh(interestRateModel_); require(err == uint256(Error.NO_ERROR), "set IRM failed"); name = name_; symbol = symbol_; decimals = decimals_; // The counter starts true to prevent changing it from zero to non-zero (i.e. smaller cost/refund) _notEntered = true; } /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint256 amount) external nonReentrant returns (bool) { return transferTokens(msg.sender, msg.sender, dst, amount) == uint256(Error.NO_ERROR); } /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom( address src, address dst, uint256 amount ) external nonReentrant returns (bool) { return transferTokens(msg.sender, src, dst, amount) == uint256(Error.NO_ERROR); } /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param amount The number of tokens that are approved (-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint256 amount) external returns (bool) { address src = msg.sender; transferAllowances[src][spender] = amount; emit Approval(src, spender, amount); return true; } /** * @notice Get the current allowance from `owner` for `spender` * @param owner The address of the account which owns the tokens to be spent * @param spender The address of the account which may transfer tokens * @return The number of tokens allowed to be spent (-1 means infinite) */ function allowance(address owner, address spender) external view returns (uint256) { return transferAllowances[owner][spender]; } /** * @notice Get the token balance of the `owner` * @param owner The address of the account to query * @return The number of tokens owned by `owner` */ function balanceOf(address owner) external view returns (uint256) { return accountTokens[owner]; } /** * @notice Get the underlying balance of the `owner` * @dev This also accrues interest in a transaction * @param owner The address of the account to query * @return The amount of underlying owned by `owner` */ function balanceOfUnderlying(address owner) external returns (uint256) { Exp memory exchangeRate = Exp({mantissa: exchangeRateCurrent()}); return mul_ScalarTruncate(exchangeRate, accountTokens[owner]); } /** * @notice Get a snapshot of the account's balances, and the cached exchange rate * @dev This is used by comptroller to more efficiently perform liquidity checks. * @param account Address of the account to snapshot * @return (possible error, token balance, borrow balance, exchange rate mantissa) */ function getAccountSnapshot(address account) external view returns ( uint256, uint256, uint256, uint256 ) { uint256 cTokenBalance = getCTokenBalanceInternal(account); uint256 borrowBalance = borrowBalanceStoredInternal(account); uint256 exchangeRateMantissa = exchangeRateStoredInternal(); return (uint256(Error.NO_ERROR), cTokenBalance, borrowBalance, exchangeRateMantissa); } /** * @dev Function to simply retrieve block number * This exists mainly for inheriting test contracts to stub this result. */ function getBlockNumber() internal view returns (uint256) { return block.number; } /** * @notice Returns the current per-block borrow interest rate for this cToken * @return The borrow interest rate per block, scaled by 1e18 */ function borrowRatePerBlock() external view returns (uint256) { return interestRateModel.getBorrowRate(getCashPrior(), totalBorrows, totalReserves); } /** * @notice Returns the current per-block supply interest rate for this cToken * @return The supply interest rate per block, scaled by 1e18 */ function supplyRatePerBlock() external view returns (uint256) { return interestRateModel.getSupplyRate(getCashPrior(), totalBorrows, totalReserves, reserveFactorMantissa); } /** * @notice Returns the estimated per-block borrow interest rate for this cToken after some change * @return The borrow interest rate per block, scaled by 1e18 */ function estimateBorrowRatePerBlockAfterChange(uint256 change, bool repay) external view returns (uint256) { uint256 cashPriorNew; uint256 totalBorrowsNew; if (repay) { cashPriorNew = add_(getCashPrior(), change); totalBorrowsNew = sub_(totalBorrows, change); } else { cashPriorNew = sub_(getCashPrior(), change); totalBorrowsNew = add_(totalBorrows, change); } return interestRateModel.getBorrowRate(cashPriorNew, totalBorrowsNew, totalReserves); } /** * @notice Returns the estimated per-block supply interest rate for this cToken after some change * @return The supply interest rate per block, scaled by 1e18 */ function estimateSupplyRatePerBlockAfterChange(uint256 change, bool repay) external view returns (uint256) { uint256 cashPriorNew; uint256 totalBorrowsNew; if (repay) { cashPriorNew = add_(getCashPrior(), change); totalBorrowsNew = sub_(totalBorrows, change); } else { cashPriorNew = sub_(getCashPrior(), change); totalBorrowsNew = add_(totalBorrows, change); } return interestRateModel.getSupplyRate(cashPriorNew, totalBorrowsNew, totalReserves, reserveFactorMantissa); } /** * @notice Returns the current total borrows plus accrued interest * @return The total borrows with interest */ function totalBorrowsCurrent() external nonReentrant returns (uint256) { accrueInterest(); return totalBorrows; } /** * @notice Accrue interest to updated borrowIndex and then calculate account's borrow balance using the updated borrowIndex * @param account The address whose balance should be calculated after updating borrowIndex * @return The calculated balance */ function borrowBalanceCurrent(address account) external nonReentrant returns (uint256) { accrueInterest(); return borrowBalanceStored(account); } /** * @notice Return the borrow balance of account based on stored data * @param account The address whose balance should be calculated * @return The calculated balance */ function borrowBalanceStored(address account) public view returns (uint256) { return borrowBalanceStoredInternal(account); } /** * @notice Return the borrow balance of account based on stored data * @param account The address whose balance should be calculated * @return the calculated balance or 0 if error code is non-zero */ function borrowBalanceStoredInternal(address account) internal view returns (uint256) { /* Get borrowBalance and borrowIndex */ BorrowSnapshot storage borrowSnapshot = accountBorrows[account]; /* If borrowBalance = 0 then borrowIndex is likely also 0. * Rather than failing the calculation with a division by 0, we immediately return 0 in this case. */ if (borrowSnapshot.principal == 0) { return 0; } /* Calculate new borrow balance using the interest index: * recentBorrowBalance = borrower.borrowBalance * market.borrowIndex / borrower.borrowIndex */ uint256 principalTimesIndex = mul_(borrowSnapshot.principal, borrowIndex); uint256 result = div_(principalTimesIndex, borrowSnapshot.interestIndex); return result; } /** * @notice Accrue interest then return the up-to-date exchange rate * @return Calculated exchange rate scaled by 1e18 */ function exchangeRateCurrent() public nonReentrant returns (uint256) { accrueInterest(); return exchangeRateStored(); } /** * @notice Calculates the exchange rate from the underlying to the CToken * @dev This function does not accrue interest before calculating the exchange rate * @return Calculated exchange rate scaled by 1e18 */ function exchangeRateStored() public view returns (uint256) { return exchangeRateStoredInternal(); } /** * @notice Calculates the exchange rate from the underlying to the CToken * @dev This function does not accrue interest before calculating the exchange rate * @return calculated exchange rate scaled by 1e18 */ function exchangeRateStoredInternal() internal view returns (uint256) { uint256 _totalSupply = totalSupply; if (_totalSupply == 0) { /* * If there are no tokens minted: * exchangeRate = initialExchangeRate */ return initialExchangeRateMantissa; } else { /* * Otherwise: * exchangeRate = (totalCash + totalBorrows - totalReserves) / totalSupply */ uint256 totalCash = getCashPrior(); uint256 cashPlusBorrowsMinusReserves = sub_(add_(totalCash, totalBorrows), totalReserves); uint256 exchangeRate = div_(cashPlusBorrowsMinusReserves, Exp({mantissa: _totalSupply})); return exchangeRate; } } /** * @notice Get cash balance of this cToken in the underlying asset * @return The quantity of underlying asset owned by this contract */ function getCash() external view returns (uint256) { return getCashPrior(); } /** * @notice Applies accrued interest to total borrows and reserves * @dev This calculates interest accrued from the last checkpointed block * up to the current block and writes new checkpoint to storage. */ function accrueInterest() public returns (uint256) { /* Remember the initial block number */ uint256 currentBlockNumber = getBlockNumber(); uint256 accrualBlockNumberPrior = accrualBlockNumber; /* Short-circuit accumulating 0 interest */ if (accrualBlockNumberPrior == currentBlockNumber) { return uint256(Error.NO_ERROR); } /* Read the previous values out of storage */ uint256 cashPrior = getCashPrior(); uint256 borrowsPrior = totalBorrows; uint256 reservesPrior = totalReserves; uint256 borrowIndexPrior = borrowIndex; /* Calculate the current borrow interest rate */ uint256 borrowRateMantissa = interestRateModel.getBorrowRate(cashPrior, borrowsPrior, reservesPrior); require(borrowRateMantissa <= borrowRateMaxMantissa, "borrow rate too high"); /* Calculate the number of blocks elapsed since the last accrual */ uint256 blockDelta = sub_(currentBlockNumber, accrualBlockNumberPrior); /* * Calculate the interest accumulated into borrows and reserves and the new index: * simpleInterestFactor = borrowRate * blockDelta * interestAccumulated = simpleInterestFactor * totalBorrows * totalBorrowsNew = interestAccumulated + totalBorrows * totalReservesNew = interestAccumulated * reserveFactor + totalReserves * borrowIndexNew = simpleInterestFactor * borrowIndex + borrowIndex */ Exp memory simpleInterestFactor = mul_(Exp({mantissa: borrowRateMantissa}), blockDelta); uint256 interestAccumulated = mul_ScalarTruncate(simpleInterestFactor, borrowsPrior); uint256 totalBorrowsNew = add_(interestAccumulated, borrowsPrior); uint256 totalReservesNew = mul_ScalarTruncateAddUInt( Exp({mantissa: reserveFactorMantissa}), interestAccumulated, reservesPrior ); uint256 borrowIndexNew = mul_ScalarTruncateAddUInt(simpleInterestFactor, borrowIndexPrior, borrowIndexPrior); ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* We write the previously calculated values into storage */ accrualBlockNumber = currentBlockNumber; borrowIndex = borrowIndexNew; totalBorrows = totalBorrowsNew; totalReserves = totalReservesNew; /* We emit an AccrueInterest event */ emit AccrueInterest(cashPrior, interestAccumulated, borrowIndexNew, totalBorrowsNew); return uint256(Error.NO_ERROR); } /** * @notice Sender supplies assets into the market and receives cTokens in exchange * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param mintAmount The amount of the underlying asset to supply * @param isNative The amount is in native or not * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount. */ function mintInternal(uint256 mintAmount, bool isNative) internal nonReentrant returns (uint256, uint256) { accrueInterest(); // mintFresh emits the actual Mint event if successful and logs on errors, so we don't need to return mintFresh(msg.sender, mintAmount, isNative); } /** * @notice Sender redeems cTokens in exchange for the underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemTokens The number of cTokens to redeem into underlying * @param isNative The amount is in native or not * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemInternal(uint256 redeemTokens, bool isNative) internal nonReentrant returns (uint256) { accrueInterest(); // redeemFresh emits redeem-specific logs on errors, so we don't need to return redeemFresh(msg.sender, redeemTokens, 0, isNative); } /** * @notice Sender redeems cTokens in exchange for a specified amount of underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemAmount The amount of underlying to receive from redeeming cTokens * @param isNative The amount is in native or not * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemUnderlyingInternal(uint256 redeemAmount, bool isNative) internal nonReentrant returns (uint256) { accrueInterest(); // redeemFresh emits redeem-specific logs on errors, so we don't need to return redeemFresh(msg.sender, 0, redeemAmount, isNative); } /** * @notice Sender borrows assets from the protocol to their own address * @param borrowAmount The amount of the underlying asset to borrow * @param isNative The amount is in native or not * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function borrowInternal(uint256 borrowAmount, bool isNative) internal nonReentrant returns (uint256) { accrueInterest(); // borrowFresh emits borrow-specific logs on errors, so we don't need to return borrowFresh(msg.sender, borrowAmount, isNative); } struct BorrowLocalVars { MathError mathErr; uint256 accountBorrows; uint256 accountBorrowsNew; uint256 totalBorrowsNew; } /** * @notice Users borrow assets from the protocol to their own address * @param borrowAmount The amount of the underlying asset to borrow * @param isNative The amount is in native or not * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function borrowFresh( address payable borrower, uint256 borrowAmount, bool isNative ) internal returns (uint256) { /* Fail if borrow not allowed */ require(comptroller.borrowAllowed(address(this), borrower, borrowAmount) == 0, "rejected"); /* Verify market's block number equals current block number */ require(accrualBlockNumber == getBlockNumber(), "market is stale"); /* Reverts if protocol has insufficient cash */ require(getCashPrior() >= borrowAmount, "insufficient cash"); BorrowLocalVars memory vars; /* * We calculate the new borrower and total borrow balances, failing on overflow: * accountBorrowsNew = accountBorrows + borrowAmount * totalBorrowsNew = totalBorrows + borrowAmount */ vars.accountBorrows = borrowBalanceStoredInternal(borrower); vars.accountBorrowsNew = add_(vars.accountBorrows, borrowAmount); vars.totalBorrowsNew = add_(totalBorrows, borrowAmount); ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* We write the previously calculated values into storage */ accountBorrows[borrower].principal = vars.accountBorrowsNew; accountBorrows[borrower].interestIndex = borrowIndex; totalBorrows = vars.totalBorrowsNew; /* * We invoke doTransferOut for the borrower and the borrowAmount. * Note: The cToken must handle variations between ERC-20 and ETH underlying. * On success, the cToken borrowAmount less of cash. * doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred. */ doTransferOut(borrower, borrowAmount, isNative); /* We emit a Borrow event */ emit Borrow(borrower, borrowAmount, vars.accountBorrowsNew, vars.totalBorrowsNew); /* We call the defense hook */ comptroller.borrowVerify(address(this), borrower, borrowAmount); return uint256(Error.NO_ERROR); } /** * @notice Sender repays their own borrow * @param repayAmount The amount to repay * @param isNative The amount is in native or not * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function repayBorrowInternal(uint256 repayAmount, bool isNative) internal nonReentrant returns (uint256, uint256) { accrueInterest(); // repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to return repayBorrowFresh(msg.sender, msg.sender, repayAmount, isNative); } /** * @notice Sender repays a borrow belonging to borrower * @param borrower the account with the debt being payed off * @param repayAmount The amount to repay * @param isNative The amount is in native or not * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function repayBorrowBehalfInternal( address borrower, uint256 repayAmount, bool isNative ) internal nonReentrant returns (uint256, uint256) { accrueInterest(); // repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to return repayBorrowFresh(msg.sender, borrower, repayAmount, isNative); } struct RepayBorrowLocalVars { Error err; MathError mathErr; uint256 repayAmount; uint256 borrowerIndex; uint256 accountBorrows; uint256 accountBorrowsNew; uint256 totalBorrowsNew; uint256 actualRepayAmount; } /** * @notice Borrows are repaid by another user (possibly the borrower). * @param payer the account paying off the borrow * @param borrower the account with the debt being payed off * @param repayAmount the amount of undelrying tokens being returned * @param isNative The amount is in native or not * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function repayBorrowFresh( address payer, address borrower, uint256 repayAmount, bool isNative ) internal returns (uint256, uint256) { /* Fail if repayBorrow not allowed */ require(comptroller.repayBorrowAllowed(address(this), payer, borrower, repayAmount) == 0, "rejected"); /* Verify market's block number equals current block number */ require(accrualBlockNumber == getBlockNumber(), "market is stale"); RepayBorrowLocalVars memory vars; /* We remember the original borrowerIndex for verification purposes */ vars.borrowerIndex = accountBorrows[borrower].interestIndex; /* We fetch the amount the borrower owes, with accumulated interest */ vars.accountBorrows = borrowBalanceStoredInternal(borrower); /* If repayAmount == -1, repayAmount = accountBorrows */ if (repayAmount == uint256(-1)) { vars.repayAmount = vars.accountBorrows; } else { vars.repayAmount = repayAmount; } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We call doTransferIn for the payer and the repayAmount * Note: The cToken must handle variations between ERC-20 and ETH underlying. * On success, the cToken holds an additional repayAmount of cash. * doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred. * it returns the amount actually transferred, in case of a fee. */ vars.actualRepayAmount = doTransferIn(payer, vars.repayAmount, isNative); /* * We calculate the new borrower and total borrow balances, failing on underflow: * accountBorrowsNew = accountBorrows - actualRepayAmount * totalBorrowsNew = totalBorrows - actualRepayAmount */ vars.accountBorrowsNew = sub_(vars.accountBorrows, vars.actualRepayAmount); vars.totalBorrowsNew = sub_(totalBorrows, vars.actualRepayAmount); /* We write the previously calculated values into storage */ accountBorrows[borrower].principal = vars.accountBorrowsNew; accountBorrows[borrower].interestIndex = borrowIndex; totalBorrows = vars.totalBorrowsNew; /* We emit a RepayBorrow event */ emit RepayBorrow(payer, borrower, vars.actualRepayAmount, vars.accountBorrowsNew, vars.totalBorrowsNew); /* We call the defense hook */ comptroller.repayBorrowVerify(address(this), payer, borrower, vars.actualRepayAmount, vars.borrowerIndex); return (uint256(Error.NO_ERROR), vars.actualRepayAmount); } /** * @notice The sender liquidates the borrowers collateral. * The collateral seized is transferred to the liquidator. * @param borrower The borrower of this cToken to be liquidated * @param repayAmount The amount of the underlying borrowed asset to repay * @param cTokenCollateral The market in which to seize collateral from the borrower * @param isNative The amount is in native or not * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function liquidateBorrowInternal( address borrower, uint256 repayAmount, CTokenInterface cTokenCollateral, bool isNative ) internal nonReentrant returns (uint256, uint256) { accrueInterest(); require(cTokenCollateral.accrueInterest() == uint256(Error.NO_ERROR), "accrue interest failed"); // liquidateBorrowFresh emits borrow-specific logs on errors, so we don't need to return liquidateBorrowFresh(msg.sender, borrower, repayAmount, cTokenCollateral, isNative); } struct LiquidateBorrowLocalVars { uint256 repayBorrowError; uint256 actualRepayAmount; uint256 amountSeizeError; uint256 seizeTokens; } /** * @notice The liquidator liquidates the borrowers collateral. * The collateral seized is transferred to the liquidator. * @param borrower The borrower of this cToken to be liquidated * @param liquidator The address repaying the borrow and seizing collateral * @param cTokenCollateral The market in which to seize collateral from the borrower * @param repayAmount The amount of the underlying borrowed asset to repay * @param isNative The amount is in native or not * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function liquidateBorrowFresh( address liquidator, address borrower, uint256 repayAmount, CTokenInterface cTokenCollateral, bool isNative ) internal returns (uint256, uint256) { /* Fail if liquidate not allowed */ require( comptroller.liquidateBorrowAllowed( address(this), address(cTokenCollateral), liquidator, borrower, repayAmount ) == 0, "rejected" ); /* Verify market's block number equals current block number */ require(accrualBlockNumber == getBlockNumber(), "market is stale"); /* Verify cTokenCollateral market's block number equals current block number */ require(cTokenCollateral.accrualBlockNumber() == getBlockNumber(), "market is stale"); /* Fail if borrower = liquidator */ require(borrower != liquidator, "invalid account pair"); /* Fail if repayAmount = 0 or repayAmount = -1 */ require(repayAmount > 0 && repayAmount != uint256(-1), "invalid amount"); LiquidateBorrowLocalVars memory vars; /* Fail if repayBorrow fails */ (vars.repayBorrowError, vars.actualRepayAmount) = repayBorrowFresh(liquidator, borrower, repayAmount, isNative); require(vars.repayBorrowError == uint256(Error.NO_ERROR), "repay borrow failed"); ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* We calculate the number of collateral tokens that will be seized */ (vars.amountSeizeError, vars.seizeTokens) = comptroller.liquidateCalculateSeizeTokens( address(this), address(cTokenCollateral), vars.actualRepayAmount ); require(vars.amountSeizeError == uint256(Error.NO_ERROR), "calculate seize amount failed"); /* Revert if borrower collateral token balance < seizeTokens */ require(cTokenCollateral.balanceOf(borrower) >= vars.seizeTokens, "seize too much"); // If this is also the collateral, run seizeInternal to avoid re-entrancy, otherwise make an external call uint256 seizeError; if (address(cTokenCollateral) == address(this)) { seizeError = seizeInternal(address(this), liquidator, borrower, vars.seizeTokens); } else { seizeError = cTokenCollateral.seize(liquidator, borrower, vars.seizeTokens); } /* Revert if seize tokens fails (since we cannot be sure of side effects) */ require(seizeError == uint256(Error.NO_ERROR), "token seizure failed"); /* We emit a LiquidateBorrow event */ emit LiquidateBorrow(liquidator, borrower, vars.actualRepayAmount, address(cTokenCollateral), vars.seizeTokens); /* We call the defense hook */ comptroller.liquidateBorrowVerify( address(this), address(cTokenCollateral), liquidator, borrower, vars.actualRepayAmount, vars.seizeTokens ); return (uint256(Error.NO_ERROR), vars.actualRepayAmount); } /** * @notice Transfers collateral tokens (this market) to the liquidator. * @dev Will fail unless called by another cToken during the process of liquidation. * Its absolutely critical to use msg.sender as the borrowed cToken and not a parameter. * @param liquidator The account receiving seized collateral * @param borrower The account having collateral seized * @param seizeTokens The number of cTokens to seize * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function seize( address liquidator, address borrower, uint256 seizeTokens ) external nonReentrant returns (uint256) { return seizeInternal(msg.sender, liquidator, borrower, seizeTokens); } /*** Admin Functions ***/ /** * @notice Begins transfer of admin rights. 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. * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setPendingAdmin(address payable newPendingAdmin) external returns (uint256) { // Check caller = admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK); } // Save current value, if any, for inclusion in log address oldPendingAdmin = pendingAdmin; // Store pendingAdmin with value newPendingAdmin pendingAdmin = newPendingAdmin; // Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin) emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin); 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() external returns (uint256) { // Check caller is pendingAdmin and pendingAdmin ≠ address(0) if (msg.sender != pendingAdmin || msg.sender == address(0)) { return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_ADMIN_PENDING_ADMIN_CHECK); } // Save current values for inclusion in log address oldAdmin = admin; address oldPendingAdmin = pendingAdmin; // Store admin with value pendingAdmin admin = pendingAdmin; // Clear the pending value pendingAdmin = address(0); emit NewAdmin(oldAdmin, admin); emit NewPendingAdmin(oldPendingAdmin, pendingAdmin); return uint256(Error.NO_ERROR); } /** * @notice Sets a new comptroller for the market * @dev Admin function to set a new comptroller * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setComptroller(ComptrollerInterface newComptroller) public returns (uint256) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_COMPTROLLER_OWNER_CHECK); } ComptrollerInterface oldComptroller = comptroller; // Ensure invoke comptroller.isComptroller() returns true require(newComptroller.isComptroller(), "not comptroller"); // Set market's comptroller to newComptroller comptroller = newComptroller; // Emit NewComptroller(oldComptroller, newComptroller) emit NewComptroller(oldComptroller, newComptroller); return uint256(Error.NO_ERROR); } /** * @notice accrues interest and sets a new reserve factor for the protocol using _setReserveFactorFresh * @dev Admin function to accrue interest and set a new reserve factor * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setReserveFactor(uint256 newReserveFactorMantissa) external nonReentrant returns (uint256) { accrueInterest(); // _setReserveFactorFresh emits reserve-factor-specific logs on errors, so we don't need to. return _setReserveFactorFresh(newReserveFactorMantissa); } /** * @notice Sets a new reserve factor for the protocol (*requires fresh interest accrual) * @dev Admin function to set a new reserve factor * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setReserveFactorFresh(uint256 newReserveFactorMantissa) internal returns (uint256) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_RESERVE_FACTOR_ADMIN_CHECK); } // Verify market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_RESERVE_FACTOR_FRESH_CHECK); } // Check newReserveFactor ≤ maxReserveFactor if (newReserveFactorMantissa > reserveFactorMaxMantissa) { return fail(Error.BAD_INPUT, FailureInfo.SET_RESERVE_FACTOR_BOUNDS_CHECK); } uint256 oldReserveFactorMantissa = reserveFactorMantissa; reserveFactorMantissa = newReserveFactorMantissa; emit NewReserveFactor(oldReserveFactorMantissa, newReserveFactorMantissa); return uint256(Error.NO_ERROR); } /** * @notice Accrues interest and reduces reserves by transferring from msg.sender * @param addAmount Amount of addition to reserves * @param isNative The amount is in native or not * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _addReservesInternal(uint256 addAmount, bool isNative) internal nonReentrant returns (uint256) { accrueInterest(); // _addReservesFresh emits reserve-addition-specific logs on errors, so we don't need to. (uint256 error, ) = _addReservesFresh(addAmount, isNative); return error; } /** * @notice Add reserves by transferring from caller * @dev Requires fresh interest accrual * @param addAmount Amount of addition to reserves * @param isNative The amount is in native or not * @return (uint, uint) An error code (0=success, otherwise a failure (see ErrorReporter.sol for details)) and the actual amount added, net token fees */ function _addReservesFresh(uint256 addAmount, bool isNative) internal returns (uint256, uint256) { // totalReserves + actualAddAmount uint256 totalReservesNew; uint256 actualAddAmount; // We fail gracefully unless market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.ADD_RESERVES_FRESH_CHECK), actualAddAmount); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We call doTransferIn for the caller and the addAmount * Note: The cToken must handle variations between ERC-20 and ETH underlying. * On success, the cToken holds an additional addAmount of cash. * doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred. * it returns the amount actually transferred, in case of a fee. */ actualAddAmount = doTransferIn(msg.sender, addAmount, isNative); totalReservesNew = add_(totalReserves, actualAddAmount); // Store reserves[n+1] = reserves[n] + actualAddAmount totalReserves = totalReservesNew; /* Emit NewReserves(admin, actualAddAmount, reserves[n+1]) */ emit ReservesAdded(msg.sender, actualAddAmount, totalReservesNew); /* Return (NO_ERROR, actualAddAmount) */ return (uint256(Error.NO_ERROR), actualAddAmount); } /** * @notice Accrues interest and reduces reserves by transferring to admin * @param reduceAmount Amount of reduction to reserves * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _reduceReserves(uint256 reduceAmount) external nonReentrant returns (uint256) { accrueInterest(); // _reduceReservesFresh emits reserve-reduction-specific logs on errors, so we don't need to. return _reduceReservesFresh(reduceAmount); } /** * @notice Reduces reserves by transferring to admin * @dev Requires fresh interest accrual * @param reduceAmount Amount of reduction to reserves * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _reduceReservesFresh(uint256 reduceAmount) internal returns (uint256) { // totalReserves - reduceAmount uint256 totalReservesNew; // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.REDUCE_RESERVES_ADMIN_CHECK); } // We fail gracefully unless market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDUCE_RESERVES_FRESH_CHECK); } // Fail gracefully if protocol has insufficient underlying cash if (getCashPrior() < reduceAmount) { return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDUCE_RESERVES_CASH_NOT_AVAILABLE); } // Check reduceAmount ≤ reserves[n] (totalReserves) if (reduceAmount > totalReserves) { return fail(Error.BAD_INPUT, FailureInfo.REDUCE_RESERVES_VALIDATION); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) totalReservesNew = sub_(totalReserves, reduceAmount); // Store reserves[n+1] = reserves[n] - reduceAmount totalReserves = totalReservesNew; // doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred. // Restrict reducing reserves in wrapped token. Implementations except `CWrappedNative` won't use parameter `isNative`. doTransferOut(admin, reduceAmount, false); emit ReservesReduced(admin, reduceAmount, totalReservesNew); return uint256(Error.NO_ERROR); } /** * @notice accrues interest and updates the interest rate model using _setInterestRateModelFresh * @dev Admin function to accrue interest and update the interest rate model * @param newInterestRateModel the new interest rate model to use * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setInterestRateModel(InterestRateModel newInterestRateModel) public returns (uint256) { accrueInterest(); // _setInterestRateModelFresh emits interest-rate-model-update-specific logs on errors, so we don't need to. return _setInterestRateModelFresh(newInterestRateModel); } /** * @notice updates the interest rate model (*requires fresh interest accrual) * @dev Admin function to update the interest rate model * @param newInterestRateModel the new interest rate model to use * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setInterestRateModelFresh(InterestRateModel newInterestRateModel) internal returns (uint256) { // Used to store old model for use in the event that is emitted on success InterestRateModel oldInterestRateModel; // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_INTEREST_RATE_MODEL_OWNER_CHECK); } // We fail gracefully unless market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_INTEREST_RATE_MODEL_FRESH_CHECK); } // Track the market's current interest rate model oldInterestRateModel = interestRateModel; // Ensure invoke newInterestRateModel.isInterestRateModel() returns true require(newInterestRateModel.isInterestRateModel(), "invalid IRM"); // Set the interest rate model to newInterestRateModel interestRateModel = newInterestRateModel; // Emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel) emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel); return uint256(Error.NO_ERROR); } /*** Safe Token ***/ /** * @notice Gets balance of this contract in terms of the underlying * @dev This excludes the value of the current message, if any * @return The quantity of underlying owned by this contract */ function getCashPrior() internal view returns (uint256); /** * @dev Performs a transfer in, reverting upon failure. Returns the amount actually transferred to the protocol, in case of a fee. * This may revert due to insufficient balance or insufficient allowance. */ function doTransferIn( address from, uint256 amount, bool isNative ) internal returns (uint256); /** * @dev Performs a transfer out, ideally returning an explanatory error code upon failure tather than reverting. * If caller has not called checked protocol's balance, may revert due to insufficient cash held in the contract. * If caller has checked protocol's balance, and verified it is >= amount, this should not revert in normal conditions. */ function doTransferOut( address payable to, uint256 amount, bool isNative ) internal; /** * @notice Transfer `tokens` tokens from `src` to `dst` by `spender` * @dev Called by both `transfer` and `transferFrom` internally */ function transferTokens( address spender, address src, address dst, uint256 tokens ) internal returns (uint256); /** * @notice Get the account's cToken balances */ function getCTokenBalanceInternal(address account) internal view returns (uint256); /** * @notice User supplies assets into the market and receives cTokens in exchange * @dev Assumes interest has already been accrued up to the current block */ function mintFresh( address minter, uint256 mintAmount, bool isNative ) internal returns (uint256, uint256); /** * @notice User redeems cTokens in exchange for the underlying asset * @dev Assumes interest has already been accrued up to the current block */ function redeemFresh( address payable redeemer, uint256 redeemTokensIn, uint256 redeemAmountIn, bool isNative ) internal returns (uint256); /** * @notice Transfers collateral tokens (this market) to the liquidator. * @dev Called only during an in-kind liquidation, or by liquidateBorrow during the liquidation of another CToken. * Its absolutely critical to use msg.sender as the seizer cToken and not a parameter. */ function seizeInternal( address seizerToken, address liquidator, address borrower, uint256 seizeTokens ) internal returns (uint256); /*** Reentrancy Guard ***/ /** * @dev Prevents a contract from calling itself, directly or indirectly. */ modifier nonReentrant() { require(_notEntered, "re-entered"); _notEntered = false; _; _notEntered = true; // get a gas-refund post-Istanbul } } pragma solidity ^0.5.16; import "./ComptrollerInterface.sol"; import "./InterestRateModel.sol"; import "./ERC3156FlashBorrowerInterface.sol"; contract CTokenStorage { /** * @dev Guard variable for re-entrancy checks */ bool internal _notEntered; /** * @notice EIP-20 token name for this token */ string public name; /** * @notice EIP-20 token symbol for this token */ string public symbol; /** * @notice EIP-20 token decimals for this token */ uint8 public decimals; /** * @notice Maximum borrow rate that can ever be applied (.0005% / block) */ uint256 internal constant borrowRateMaxMantissa = 0.0005e16; /** * @notice Maximum fraction of interest that can be set aside for reserves */ uint256 internal constant reserveFactorMaxMantissa = 1e18; /** * @notice Administrator for this contract */ address payable public admin; /** * @notice Pending administrator for this contract */ address payable public pendingAdmin; /** * @notice Contract which oversees inter-cToken operations */ ComptrollerInterface public comptroller; /** * @notice Model which tells what the current interest rate should be */ InterestRateModel public interestRateModel; /** * @notice Initial exchange rate used when minting the first CTokens (used when totalSupply = 0) */ uint256 internal initialExchangeRateMantissa; /** * @notice Fraction of interest currently set aside for reserves */ uint256 public reserveFactorMantissa; /** * @notice Block number that interest was last accrued at */ uint256 public accrualBlockNumber; /** * @notice Accumulator of the total earned interest rate since the opening of the market */ uint256 public borrowIndex; /** * @notice Total amount of outstanding borrows of the underlying in this market */ uint256 public totalBorrows; /** * @notice Total amount of reserves of the underlying held in this market */ uint256 public totalReserves; /** * @notice Total number of tokens in circulation */ uint256 public totalSupply; /** * @notice Official record of token balances for each account */ mapping(address => uint256) internal accountTokens; /** * @notice Approved token transfer amounts on behalf of others */ mapping(address => mapping(address => uint256)) internal transferAllowances; /** * @notice Container for borrow balance information * @member principal Total balance (with accrued interest), after applying the most recent balance-changing action * @member interestIndex Global borrowIndex as of the most recent balance-changing action */ struct BorrowSnapshot { uint256 principal; uint256 interestIndex; } /** * @notice Mapping of account addresses to outstanding borrow balances */ mapping(address => BorrowSnapshot) internal accountBorrows; } contract CErc20Storage { /** * @notice Underlying asset for this CToken */ address public underlying; /** * @notice Implementation address for this contract */ address public implementation; } contract CSupplyCapStorage { /** * @notice Internal cash counter for this CToken. Should equal underlying.balanceOf(address(this)) for CERC20. */ uint256 public internalCash; } contract CCollateralCapStorage { /** * @notice Total number of tokens used as collateral in circulation. */ uint256 public totalCollateralTokens; /** * @notice Record of token balances which could be treated as collateral for each account. * If collateral cap is not set, the value should be equal to accountTokens. */ mapping(address => uint256) public accountCollateralTokens; /** * @notice Check if accountCollateralTokens have been initialized. */ mapping(address => bool) public isCollateralTokenInit; /** * @notice Collateral cap for this CToken, zero for no cap. */ uint256 public collateralCap; } /*** Interface ***/ contract CTokenInterface is CTokenStorage { /** * @notice Indicator that this is a CToken contract (for inspection) */ bool public constant isCToken = true; /*** Market Events ***/ /** * @notice Event emitted when interest is accrued */ event AccrueInterest(uint256 cashPrior, uint256 interestAccumulated, uint256 borrowIndex, uint256 totalBorrows); /** * @notice Event emitted when tokens are minted */ event Mint(address minter, uint256 mintAmount, uint256 mintTokens); /** * @notice Event emitted when tokens are redeemed */ event Redeem(address redeemer, uint256 redeemAmount, uint256 redeemTokens); /** * @notice Event emitted when underlying is borrowed */ event Borrow(address borrower, uint256 borrowAmount, uint256 accountBorrows, uint256 totalBorrows); /** * @notice Event emitted when a borrow is repaid */ event RepayBorrow( address payer, address borrower, uint256 repayAmount, uint256 accountBorrows, uint256 totalBorrows ); /** * @notice Event emitted when a borrow is liquidated */ event LiquidateBorrow( address liquidator, address borrower, uint256 repayAmount, address cTokenCollateral, uint256 seizeTokens ); /*** Admin Events ***/ /** * @notice Event emitted when pendingAdmin is changed */ event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin); /** * @notice Event emitted when pendingAdmin is accepted, which means admin is updated */ event NewAdmin(address oldAdmin, address newAdmin); /** * @notice Event emitted when comptroller is changed */ event NewComptroller(ComptrollerInterface oldComptroller, ComptrollerInterface newComptroller); /** * @notice Event emitted when interestRateModel is changed */ event NewMarketInterestRateModel(InterestRateModel oldInterestRateModel, InterestRateModel newInterestRateModel); /** * @notice Event emitted when the reserve factor is changed */ event NewReserveFactor(uint256 oldReserveFactorMantissa, uint256 newReserveFactorMantissa); /** * @notice Event emitted when the reserves are added */ event ReservesAdded(address benefactor, uint256 addAmount, uint256 newTotalReserves); /** * @notice Event emitted when the reserves are reduced */ event ReservesReduced(address admin, uint256 reduceAmount, uint256 newTotalReserves); /** * @notice EIP20 Transfer event */ event Transfer(address indexed from, address indexed to, uint256 amount); /** * @notice EIP20 Approval event */ event Approval(address indexed owner, address indexed spender, uint256 amount); /** * @notice Failure event */ event Failure(uint256 error, uint256 info, uint256 detail); /*** User Interface ***/ function transfer(address dst, uint256 amount) external returns (bool); function transferFrom( address src, address dst, uint256 amount ) external returns (bool); function approve(address spender, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function balanceOf(address owner) external view returns (uint256); function balanceOfUnderlying(address owner) external returns (uint256); function getAccountSnapshot(address account) external view returns ( uint256, uint256, uint256, uint256 ); function borrowRatePerBlock() external view returns (uint256); function supplyRatePerBlock() external view returns (uint256); function totalBorrowsCurrent() external returns (uint256); function borrowBalanceCurrent(address account) external returns (uint256); function borrowBalanceStored(address account) public view returns (uint256); function exchangeRateCurrent() public returns (uint256); function exchangeRateStored() public view returns (uint256); function getCash() external view returns (uint256); function accrueInterest() public returns (uint256); function seize( address liquidator, address borrower, uint256 seizeTokens ) external returns (uint256); /*** Admin Functions ***/ function _setPendingAdmin(address payable newPendingAdmin) external returns (uint256); function _acceptAdmin() external returns (uint256); function _setComptroller(ComptrollerInterface newComptroller) public returns (uint256); function _setReserveFactor(uint256 newReserveFactorMantissa) external returns (uint256); function _reduceReserves(uint256 reduceAmount) external returns (uint256); function _setInterestRateModel(InterestRateModel newInterestRateModel) public returns (uint256); } contract CErc20Interface is CErc20Storage { /*** User Interface ***/ function mint(uint256 mintAmount) external returns (uint256); function redeem(uint256 redeemTokens) external returns (uint256); function redeemUnderlying(uint256 redeemAmount) external returns (uint256); function borrow(uint256 borrowAmount) external returns (uint256); function repayBorrow(uint256 repayAmount) external returns (uint256); function repayBorrowBehalf(address borrower, uint256 repayAmount) external returns (uint256); function liquidateBorrow( address borrower, uint256 repayAmount, CTokenInterface cTokenCollateral ) external returns (uint256); function _addReserves(uint256 addAmount) external returns (uint256); } contract CWrappedNativeInterface is CErc20Interface { /** * @notice Flash loan fee ratio */ uint256 public constant flashFeeBips = 3; /*** Market Events ***/ /** * @notice Event emitted when a flashloan occured */ event Flashloan(address indexed receiver, uint256 amount, uint256 totalFee, uint256 reservesFee); /*** User Interface ***/ function mintNative() external payable returns (uint256); function redeemNative(uint256 redeemTokens) external returns (uint256); function redeemUnderlyingNative(uint256 redeemAmount) external returns (uint256); function borrowNative(uint256 borrowAmount) external returns (uint256); function repayBorrowNative() external payable returns (uint256); function repayBorrowBehalfNative(address borrower) external payable returns (uint256); function liquidateBorrowNative(address borrower, CTokenInterface cTokenCollateral) external payable returns (uint256); function flashLoan( ERC3156FlashBorrowerInterface receiver, address initiator, uint256 amount, bytes calldata data ) external returns (bool); function _addReservesNative() external payable returns (uint256); function collateralCap() external view returns (uint256); function totalCollateralTokens() external view returns (uint256); } contract CCapableErc20Interface is CErc20Interface, CSupplyCapStorage { /** * @notice Flash loan fee ratio */ uint256 public constant flashFeeBips = 3; /*** Market Events ***/ /** * @notice Event emitted when a flashloan occured */ event Flashloan(address indexed receiver, uint256 amount, uint256 totalFee, uint256 reservesFee); /*** User Interface ***/ function gulp() external; } contract CCollateralCapErc20Interface is CCapableErc20Interface, CCollateralCapStorage { /*** Admin Events ***/ /** * @notice Event emitted when collateral cap is set */ event NewCollateralCap(address token, uint256 newCap); /** * @notice Event emitted when user collateral is changed */ event UserCollateralChanged(address account, uint256 newCollateralTokens); /*** User Interface ***/ function registerCollateral(address account) external returns (uint256); function unregisterCollateral(address account) external; function flashLoan( ERC3156FlashBorrowerInterface receiver, address initiator, uint256 amount, bytes calldata data ) external returns (bool); /*** Admin Functions ***/ function _setCollateralCap(uint256 newCollateralCap) external; } contract CDelegatorInterface { /** * @notice Emitted when implementation is changed */ event NewImplementation(address oldImplementation, address newImplementation); /** * @notice Called by the admin to update the implementation of the delegator * @param implementation_ The address of the new implementation for delegation * @param allowResign Flag to indicate whether to call _resignImplementation on the old implementation * @param becomeImplementationData The encoded bytes data to be passed to _becomeImplementation */ function _setImplementation( address implementation_, bool allowResign, bytes memory becomeImplementationData ) public; } contract CDelegateInterface { /** * @notice Called by the delegator on a delegate to initialize it for duty * @dev Should revert if any issues arise which make it unfit for delegation * @param data The encoded bytes data for any initialization */ function _becomeImplementation(bytes memory data) public; /** * @notice Called by the delegator on a delegate to forfeit its responsibility */ function _resignImplementation() public; } /*** External interface ***/ /** * @title Flash loan receiver interface */ interface IFlashloanReceiver { function executeOperation( address sender, address underlying, uint256 amount, uint256 fee, bytes calldata params ) external; } pragma solidity ^0.5.16; /** * @title Careful Math * @author Compound * @notice Derived from OpenZeppelin's SafeMath library * https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/math/SafeMath.sol */ contract CarefulMath { /** * @dev Possible error codes that we can return */ enum MathError { NO_ERROR, DIVISION_BY_ZERO, INTEGER_OVERFLOW, INTEGER_UNDERFLOW } /** * @dev Multiplies two numbers, returns an error on overflow. */ function mulUInt(uint256 a, uint256 b) internal pure returns (MathError, uint256) { if (a == 0) { return (MathError.NO_ERROR, 0); } uint256 c = a * b; if (c / a != b) { return (MathError.INTEGER_OVERFLOW, 0); } else { return (MathError.NO_ERROR, c); } } /** * @dev Integer division of two numbers, truncating the quotient. */ function divUInt(uint256 a, uint256 b) internal pure returns (MathError, uint256) { if (b == 0) { return (MathError.DIVISION_BY_ZERO, 0); } return (MathError.NO_ERROR, a / b); } /** * @dev Subtracts two numbers, returns an error on overflow (i.e. if subtrahend is greater than minuend). */ function subUInt(uint256 a, uint256 b) internal pure returns (MathError, uint256) { if (b <= a) { return (MathError.NO_ERROR, a - b); } else { return (MathError.INTEGER_UNDERFLOW, 0); } } /** * @dev Adds two numbers, returns an error on overflow. */ function addUInt(uint256 a, uint256 b) internal pure returns (MathError, uint256) { uint256 c = a + b; if (c >= a) { return (MathError.NO_ERROR, c); } else { return (MathError.INTEGER_OVERFLOW, 0); } } /** * @dev add a and b and then subtract c */ function addThenSubUInt( uint256 a, uint256 b, uint256 c ) internal pure returns (MathError, uint256) { (MathError err0, uint256 sum) = addUInt(a, b); if (err0 != MathError.NO_ERROR) { return (err0, 0); } return subUInt(sum, c); } } pragma solidity ^0.5.16; import "./CToken.sol"; import "./ErrorReporter.sol"; import "./Exponential.sol"; import "./PriceOracle/PriceOracle.sol"; import "./ComptrollerInterface.sol"; import "./ComptrollerStorage.sol"; import "./LiquidityMiningInterface.sol"; import "./Unitroller.sol"; import "./Governance/Comp.sol"; /** * @title Compound's Comptroller Contract * @author Compound (modified by Cream) */ contract Comptroller is ComptrollerV1Storage, ComptrollerInterface, ComptrollerErrorReporter, Exponential { /// @notice Emitted when an admin supports a market event MarketListed(CToken cToken); /// @notice Emitted when an admin delists a market event MarketDelisted(CToken cToken); /// @notice Emitted when an account enters a market event MarketEntered(CToken cToken, address account); /// @notice Emitted when an account exits a market event MarketExited(CToken cToken, address account); /// @notice Emitted when close factor is changed by admin event NewCloseFactor(uint256 oldCloseFactorMantissa, uint256 newCloseFactorMantissa); /// @notice Emitted when a collateral factor is changed by admin event NewCollateralFactor(CToken cToken, uint256 oldCollateralFactorMantissa, uint256 newCollateralFactorMantissa); /// @notice Emitted when liquidation incentive is changed by admin event NewLiquidationIncentive(uint256 oldLiquidationIncentiveMantissa, uint256 newLiquidationIncentiveMantissa); /// @notice Emitted when price oracle is changed event NewPriceOracle(PriceOracle oldPriceOracle, PriceOracle newPriceOracle); /// @notice Emitted when pause guardian is changed event NewPauseGuardian(address oldPauseGuardian, address newPauseGuardian); /// @notice Emitted when liquidity mining module is changed event NewLiquidityMining(address oldLiquidityMining, address newLiquidityMining); /// @notice Emitted when an action is paused globally event ActionPaused(string action, bool pauseState); /// @notice Emitted when an action is paused on a market event ActionPaused(CToken cToken, string action, bool pauseState); /// @notice Emitted when borrow cap for a cToken is changed event NewBorrowCap(CToken indexed cToken, uint256 newBorrowCap); /// @notice Emitted when supply cap for a cToken is changed event NewSupplyCap(CToken indexed cToken, uint256 newSupplyCap); /// @notice Emitted when protocol's credit limit has changed event CreditLimitChanged(address protocol, address market, uint256 creditLimit); /// @notice Emitted when cToken version is changed event NewCTokenVersion(CToken cToken, Version oldVersion, Version newVersion); /// @notice Emitted when credit limit manager is changed event NewCreditLimitManager(address oldCreditLimitManager, address newCreditLimitManager); // No collateralFactorMantissa may exceed this value uint256 internal constant collateralFactorMaxMantissa = 0.9e18; // 0.9 constructor() public { admin = msg.sender; } /*** Assets You Are In ***/ /** * @notice Returns the assets an account has entered * @param account The address of the account to pull assets for * @return A dynamic list with the assets the account has entered */ function getAssetsIn(address account) external view returns (CToken[] memory) { CToken[] memory assetsIn = accountAssets[account]; return assetsIn; } /** * @notice Returns whether the given account is entered in the given asset * @param account The address of the account to check * @param cToken The cToken to check * @return True if the account is in the asset, otherwise false. */ function checkMembership(address account, CToken cToken) external view returns (bool) { return markets[address(cToken)].accountMembership[account]; } /** * @notice Add assets to be included in account liquidity calculation * @param cTokens The list of addresses of the cToken markets to be enabled * @return Success indicator for whether each corresponding market was entered */ function enterMarkets(address[] memory cTokens) public returns (uint256[] memory) { uint256 len = cTokens.length; uint256[] memory results = new uint256[](len); for (uint256 i = 0; i < len; i++) { CToken cToken = CToken(cTokens[i]); results[i] = uint256(addToMarketInternal(cToken, msg.sender)); } return results; } /** * @notice Add the market to the borrower's "assets in" for liquidity calculations * @param cToken The market to enter * @param borrower The address of the account to modify * @return Success indicator for whether the market was entered */ function addToMarketInternal(CToken cToken, address borrower) internal returns (Error) { Market storage marketToJoin = markets[address(cToken)]; require(marketToJoin.isListed, "market not listed"); if (marketToJoin.version == Version.COLLATERALCAP) { // register collateral for the borrower if the token is CollateralCap version. CCollateralCapErc20Interface(address(cToken)).registerCollateral(borrower); } if (marketToJoin.accountMembership[borrower] == true) { // already joined return Error.NO_ERROR; } // survived the gauntlet, add to list // NOTE: we store these somewhat redundantly as a significant optimization // this avoids having to iterate through the list for the most common use cases // that is, only when we need to perform liquidity checks // and not whenever we want to check if an account is in a particular market marketToJoin.accountMembership[borrower] = true; accountAssets[borrower].push(cToken); emit MarketEntered(cToken, borrower); return Error.NO_ERROR; } /** * @notice Removes asset from sender's account liquidity calculation * @dev Sender must not have an outstanding borrow balance in the asset, * or be providing necessary collateral for an outstanding borrow. * @param cTokenAddress The address of the asset to be removed * @return Whether or not the account successfully exited the market */ function exitMarket(address cTokenAddress) external returns (uint256) { CToken cToken = CToken(cTokenAddress); /* Get sender tokensHeld and amountOwed underlying from the cToken */ (uint256 oErr, uint256 tokensHeld, uint256 amountOwed, ) = cToken.getAccountSnapshot(msg.sender); require(oErr == 0, "exitMarket: getAccountSnapshot failed"); // semi-opaque error code /* Fail if the sender has a borrow balance */ require(amountOwed == 0, "nonzero borrow balance"); /* Fail if the sender is not permitted to redeem all of their tokens */ require(redeemAllowedInternal(cTokenAddress, msg.sender, tokensHeld) == 0, "failed to exit market"); Market storage marketToExit = markets[cTokenAddress]; if (marketToExit.version == Version.COLLATERALCAP) { CCollateralCapErc20Interface(cTokenAddress).unregisterCollateral(msg.sender); } /* Return true if the sender is not already ‘in’ the market */ if (!marketToExit.accountMembership[msg.sender]) { return uint256(Error.NO_ERROR); } /* Set cToken account membership to false */ delete marketToExit.accountMembership[msg.sender]; /* Delete cToken from the account’s list of assets */ // load into memory for faster iteration CToken[] memory userAssetList = accountAssets[msg.sender]; uint256 len = userAssetList.length; uint256 assetIndex = len; for (uint256 i = 0; i < len; i++) { if (userAssetList[i] == cToken) { assetIndex = i; break; } } // We *must* have found the asset in the list or our redundant data structure is broken assert(assetIndex < len); // copy last item in list to location of item to be removed, reduce length by 1 CToken[] storage storedList = accountAssets[msg.sender]; if (assetIndex != storedList.length - 1) { storedList[assetIndex] = storedList[storedList.length - 1]; } storedList.length--; emit MarketExited(cToken, msg.sender); return uint256(Error.NO_ERROR); } /** * @notice Return a specific market is listed or not * @param cTokenAddress The address of the asset to be checked * @return Whether or not the market is listed */ function isMarketListed(address cTokenAddress) public view returns (bool) { return markets[cTokenAddress].isListed; } /** * @notice Return the credit limit of a specific protocol * @dev This function shouldn't be called. It exists only for backward compatibility. * @param protocol The address of the protocol * @return The credit */ function creditLimits(address protocol) public view returns (uint256) { protocol; // Shh return 0; } /** * @notice Return the credit limit of a specific protocol for a specific market * @param protocol The address of the protocol * @param market The market * @return The credit */ function creditLimits(address protocol, address market) public view returns (uint256) { return _creditLimits[protocol][market]; } /*** Policy Hooks ***/ /** * @notice Checks if the account should be allowed to mint tokens in the given market * @param cToken The market to verify the mint against * @param minter The account which would get the minted tokens * @param mintAmount The amount of underlying being supplied to the market in exchange for tokens * @return 0 if the mint is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function mintAllowed( address cToken, address minter, uint256 mintAmount ) external returns (uint256) { // Pausing is a very serious situation - we revert to sound the alarms require(!mintGuardianPaused[cToken], "mint is paused"); require(!isCreditAccount(minter, cToken), "credit account cannot mint"); require(isMarketListed(cToken), "market not listed"); uint256 supplyCap = supplyCaps[cToken]; // Supply cap of 0 corresponds to unlimited supplying if (supplyCap != 0) { uint256 totalCash = CToken(cToken).getCash(); uint256 totalBorrows = CToken(cToken).totalBorrows(); uint256 totalReserves = CToken(cToken).totalReserves(); // totalSupplies = totalCash + totalBorrows - totalReserves (MathError mathErr, uint256 totalSupplies) = addThenSubUInt(totalCash, totalBorrows, totalReserves); require(mathErr == MathError.NO_ERROR, "totalSupplies failed"); uint256 nextTotalSupplies = add_(totalSupplies, mintAmount); require(nextTotalSupplies < supplyCap, "market supply cap reached"); } return uint256(Error.NO_ERROR); } /** * @notice Validates mint and reverts on rejection. May emit logs. * @param cToken Asset being minted * @param minter The address minting the tokens * @param actualMintAmount The amount of the underlying asset being minted * @param mintTokens The number of tokens being minted */ function mintVerify( address cToken, address minter, uint256 actualMintAmount, uint256 mintTokens ) external { // Shh - currently unused cToken; minter; actualMintAmount; mintTokens; // Shh - we don't ever want this hook to be marked pure if (false) { closeFactorMantissa = closeFactorMantissa; } } /** * @notice Checks if the account should be allowed to redeem tokens in the given market * @param cToken The market to verify the redeem against * @param redeemer The account which would redeem the tokens * @param redeemTokens The number of cTokens to exchange for the underlying asset in the market * @return 0 if the redeem is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function redeemAllowed( address cToken, address redeemer, uint256 redeemTokens ) external returns (uint256) { return redeemAllowedInternal(cToken, redeemer, redeemTokens); } function redeemAllowedInternal( address cToken, address redeemer, uint256 redeemTokens ) internal view returns (uint256) { require(isMarketListed(cToken) || isMarkertDelisted[cToken], "market not listed"); require(!isCreditAccount(redeemer, cToken), "credit account cannot redeem"); /* If the redeemer is not 'in' the market, then we can bypass the liquidity check */ if (!markets[cToken].accountMembership[redeemer]) { return uint256(Error.NO_ERROR); } /* Otherwise, perform a hypothetical liquidity check to guard against shortfall */ (Error err, , uint256 shortfall) = getHypotheticalAccountLiquidityInternal( redeemer, CToken(cToken), redeemTokens, 0 ); require(err == Error.NO_ERROR, "failed to get account liquidity"); require(shortfall == 0, "insufficient liquidity"); return uint256(Error.NO_ERROR); } /** * @notice Validates redeem and reverts on rejection. May emit logs. * @param cToken Asset being redeemed * @param redeemer The address redeeming the tokens * @param redeemAmount The amount of the underlying asset being redeemed * @param redeemTokens The number of tokens being redeemed */ function redeemVerify( address cToken, address redeemer, uint256 redeemAmount, uint256 redeemTokens ) external { // Shh - currently unused cToken; redeemer; // Require tokens is zero or amount is also zero if (redeemTokens == 0 && redeemAmount > 0) { revert("redeemTokens zero"); } } /** * @notice Checks if the account should be allowed to borrow the underlying asset of the given market * @param cToken The market to verify the borrow against * @param borrower The account which would borrow the asset * @param borrowAmount The amount of underlying the account would borrow * @return 0 if the borrow is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function borrowAllowed( address cToken, address borrower, uint256 borrowAmount ) external returns (uint256) { // Pausing is a very serious situation - we revert to sound the alarms require(!borrowGuardianPaused[cToken], "borrow is paused"); require(isMarketListed(cToken), "market not listed"); if (!markets[cToken].accountMembership[borrower]) { // only cTokens may call borrowAllowed if borrower not in market require(msg.sender == cToken, "sender must be cToken"); // attempt to add borrower to the market require(addToMarketInternal(CToken(cToken), borrower) == Error.NO_ERROR, "failed to add market"); // it should be impossible to break the important invariant assert(markets[cToken].accountMembership[borrower]); } require(oracle.getUnderlyingPrice(CToken(cToken)) != 0, "price error"); uint256 borrowCap = borrowCaps[cToken]; // Borrow cap of 0 corresponds to unlimited borrowing if (borrowCap != 0) { uint256 totalBorrows = CToken(cToken).totalBorrows(); uint256 nextTotalBorrows = add_(totalBorrows, borrowAmount); require(nextTotalBorrows < borrowCap, "market borrow cap reached"); } uint256 creditLimit = _creditLimits[borrower][cToken]; // If the borrower is a credit account, check the credit limit instead of account liquidity. if (creditLimit > 0) { (uint256 oErr, , uint256 borrowBalance, ) = CToken(cToken).getAccountSnapshot(borrower); require(oErr == 0, "snapshot error"); require(creditLimit >= add_(borrowBalance, borrowAmount), "insufficient credit limit"); } else { (Error err, , uint256 shortfall) = getHypotheticalAccountLiquidityInternal( borrower, CToken(cToken), 0, borrowAmount ); require(err == Error.NO_ERROR, "failed to get account liquidity"); require(shortfall == 0, "insufficient liquidity"); } return uint256(Error.NO_ERROR); } /** * @notice Validates borrow and reverts on rejection. May emit logs. * @param cToken Asset whose underlying is being borrowed * @param borrower The address borrowing the underlying * @param borrowAmount The amount of the underlying asset requested to borrow */ function borrowVerify( address cToken, address borrower, uint256 borrowAmount ) external { // Shh - currently unused cToken; borrower; borrowAmount; // Shh - we don't ever want this hook to be marked pure if (false) { closeFactorMantissa = closeFactorMantissa; } } /** * @notice Checks if the account should be allowed to repay a borrow in the given market * @param cToken The market to verify the repay against * @param payer The account which would repay the asset * @param borrower The account which would borrowed the asset * @param repayAmount The amount of the underlying asset the account would repay * @return 0 if the repay is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function repayBorrowAllowed( address cToken, address payer, address borrower, uint256 repayAmount ) external returns (uint256) { // Shh - currently unused repayAmount; require(isMarketListed(cToken) || isMarkertDelisted[cToken], "market not listed"); if (isCreditAccount(borrower, cToken)) { require(borrower == payer, "cannot repay on behalf of credit account"); } return uint256(Error.NO_ERROR); } /** * @notice Validates repayBorrow and reverts on rejection. May emit logs. * @param cToken Asset being repaid * @param payer The address repaying the borrow * @param borrower The address of the borrower * @param actualRepayAmount The amount of underlying being repaid */ function repayBorrowVerify( address cToken, address payer, address borrower, uint256 actualRepayAmount, uint256 borrowerIndex ) external { // Shh - currently unused cToken; payer; borrower; actualRepayAmount; borrowerIndex; // Shh - we don't ever want this hook to be marked pure if (false) { closeFactorMantissa = closeFactorMantissa; } } /** * @notice Checks if the liquidation should be allowed to occur * @param cTokenBorrowed Asset which was borrowed by the borrower * @param cTokenCollateral Asset which was used as collateral and will be seized * @param liquidator The address repaying the borrow and seizing the collateral * @param borrower The address of the borrower * @param repayAmount The amount of underlying being repaid */ function liquidateBorrowAllowed( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint256 repayAmount ) external returns (uint256) { require(!isCreditAccount(borrower, cTokenBorrowed), "cannot liquidate credit account"); // Shh - currently unused liquidator; require(isMarketListed(cTokenBorrowed) && isMarketListed(cTokenCollateral), "market not listed"); /* The borrower must have shortfall in order to be liquidatable */ (Error err, , uint256 shortfall) = getAccountLiquidityInternal(borrower); require(err == Error.NO_ERROR, "failed to get account liquidity"); require(shortfall > 0, "insufficient shortfall"); /* The liquidator may not repay more than what is allowed by the closeFactor */ uint256 borrowBalance = CToken(cTokenBorrowed).borrowBalanceStored(borrower); uint256 maxClose = mul_ScalarTruncate(Exp({mantissa: closeFactorMantissa}), borrowBalance); if (repayAmount > maxClose) { return uint256(Error.TOO_MUCH_REPAY); } return uint256(Error.NO_ERROR); } /** * @notice Validates liquidateBorrow and reverts on rejection. May emit logs. * @param cTokenBorrowed Asset which was borrowed by the borrower * @param cTokenCollateral Asset which was used as collateral and will be seized * @param liquidator The address repaying the borrow and seizing the collateral * @param borrower The address of the borrower * @param actualRepayAmount The amount of underlying being repaid */ function liquidateBorrowVerify( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint256 actualRepayAmount, uint256 seizeTokens ) external { // Shh - currently unused cTokenBorrowed; cTokenCollateral; liquidator; borrower; actualRepayAmount; seizeTokens; // Shh - we don't ever want this hook to be marked pure if (false) { closeFactorMantissa = closeFactorMantissa; } } /** * @notice Checks if the seizing of assets should be allowed to occur * @param cTokenCollateral Asset which was used as collateral and will be seized * @param cTokenBorrowed Asset which was borrowed by the borrower * @param liquidator The address repaying the borrow and seizing the collateral * @param borrower The address of the borrower * @param seizeTokens The number of collateral tokens to seize */ function seizeAllowed( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint256 seizeTokens ) external returns (uint256) { // Pausing is a very serious situation - we revert to sound the alarms require(!seizeGuardianPaused, "seize is paused"); require(!isCreditAccount(borrower, cTokenBorrowed), "cannot sieze from credit account"); // Shh - currently unused liquidator; seizeTokens; require(isMarketListed(cTokenBorrowed) && isMarketListed(cTokenCollateral), "market not listed"); require( CToken(cTokenCollateral).comptroller() == CToken(cTokenBorrowed).comptroller(), "comptroller mismatched" ); return uint256(Error.NO_ERROR); } /** * @notice Validates seize and reverts on rejection. May emit logs. * @param cTokenCollateral Asset which was used as collateral and will be seized * @param cTokenBorrowed Asset which was borrowed by the borrower * @param liquidator The address repaying the borrow and seizing the collateral * @param borrower The address of the borrower * @param seizeTokens The number of collateral tokens to seize */ function seizeVerify( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint256 seizeTokens ) external { // Shh - currently unused cTokenCollateral; cTokenBorrowed; liquidator; borrower; seizeTokens; // Shh - we don't ever want this hook to be marked pure if (false) { closeFactorMantissa = closeFactorMantissa; } } /** * @notice Checks if the account should be allowed to transfer tokens in the given market * @param cToken The market to verify the transfer against * @param src The account which sources the tokens * @param dst The account which receives the tokens * @param transferTokens The number of cTokens to transfer * @return 0 if the transfer is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function transferAllowed( address cToken, address src, address dst, uint256 transferTokens ) external returns (uint256) { // Pausing is a very serious situation - we revert to sound the alarms require(!transferGuardianPaused, "transfer is paused"); require(!isCreditAccount(dst, cToken), "cannot transfer to a credit account"); // Shh - currently unused dst; // Currently the only consideration is whether or not // the src is allowed to redeem this many tokens return redeemAllowedInternal(cToken, src, transferTokens); } /** * @notice Validates transfer and reverts on rejection. May emit logs. * @param cToken Asset being transferred * @param src The account which sources the tokens * @param dst The account which receives the tokens * @param transferTokens The number of cTokens to transfer */ function transferVerify( address cToken, address src, address dst, uint256 transferTokens ) external { // Shh - currently unused cToken; src; dst; transferTokens; // Shh - we don't ever want this hook to be marked pure if (false) { closeFactorMantissa = closeFactorMantissa; } } /** * @notice Checks if the account should be allowed to transfer tokens in the given market * @param cToken The market to verify the transfer against * @param receiver The account which receives the tokens * @param amount The amount of the tokens * @param params The other parameters */ function flashloanAllowed( address cToken, address receiver, uint256 amount, bytes calldata params ) external view returns (bool) { return !flashloanGuardianPaused[cToken]; } /** * @notice Update CToken's version. * @param cToken Version of the asset being updated * @param newVersion The new version */ function updateCTokenVersion(address cToken, Version newVersion) external { require(msg.sender == cToken, "cToken only"); // This function will be called when a new CToken implementation becomes active. // If a new CToken is newly created, this market is not listed yet. The version of // this market will be taken care of when calling `_supportMarket`. if (isMarketListed(cToken)) { Version oldVersion = markets[cToken].version; markets[cToken].version = newVersion; emit NewCTokenVersion(CToken(cToken), oldVersion, newVersion); } } /** * @notice Check if the account is a credit account * @param account The account needs to be checked * @param cToken The market * @return The account is a credit account or not */ function isCreditAccount(address account, address cToken) public view returns (bool) { return _creditLimits[account][cToken] > 0; } /*** Liquidity/Liquidation Calculations ***/ /** * @dev Local vars for avoiding stack-depth limits in calculating account liquidity. * Note that `cTokenBalance` is the number of cTokens the account owns in the market, * whereas `borrowBalance` is the amount of underlying that the account has borrowed. */ struct AccountLiquidityLocalVars { uint256 sumCollateral; uint256 sumBorrowPlusEffects; uint256 cTokenBalance; uint256 borrowBalance; uint256 exchangeRateMantissa; uint256 oraclePriceMantissa; Exp collateralFactor; Exp exchangeRate; Exp oraclePrice; Exp tokensToDenom; } /** * @notice Determine the current account liquidity wrt collateral requirements * @return (possible error code (semi-opaque), account liquidity in excess of collateral requirements, * account shortfall below collateral requirements) */ function getAccountLiquidity(address account) public view returns ( uint256, uint256, uint256 ) { (Error err, uint256 liquidity, uint256 shortfall) = getHypotheticalAccountLiquidityInternal( account, CToken(0), 0, 0 ); return (uint256(err), liquidity, shortfall); } /** * @notice Determine the current account liquidity wrt collateral requirements * @return (possible error code, account liquidity in excess of collateral requirements, * account shortfall below collateral requirements) */ function getAccountLiquidityInternal(address account) internal view returns ( Error, uint256, uint256 ) { return getHypotheticalAccountLiquidityInternal(account, CToken(0), 0, 0); } /** * @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed * @param cTokenModify The market to hypothetically redeem/borrow in * @param account The account to determine liquidity for * @param redeemTokens The number of tokens to hypothetically redeem * @param borrowAmount The amount of underlying to hypothetically borrow * @return (possible error code (semi-opaque), hypothetical account liquidity in excess of collateral requirements, * hypothetical account shortfall below collateral requirements) */ function getHypotheticalAccountLiquidity( address account, address cTokenModify, uint256 redeemTokens, uint256 borrowAmount ) public view returns ( uint256, uint256, uint256 ) { (Error err, uint256 liquidity, uint256 shortfall) = getHypotheticalAccountLiquidityInternal( account, CToken(cTokenModify), redeemTokens, borrowAmount ); return (uint256(err), liquidity, shortfall); } /** * @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed * @param cTokenModify The market to hypothetically redeem/borrow in * @param account The account to determine liquidity for * @param redeemTokens The number of tokens to hypothetically redeem * @param borrowAmount The amount of underlying to hypothetically borrow * @dev Note that we calculate the exchangeRateStored for each collateral cToken using stored data, * without calculating accumulated interest. * @return (possible error code, hypothetical account liquidity in excess of collateral requirements, * hypothetical account shortfall below collateral requirements) */ function getHypotheticalAccountLiquidityInternal( address account, CToken cTokenModify, uint256 redeemTokens, uint256 borrowAmount ) internal view returns ( Error, uint256, uint256 ) { AccountLiquidityLocalVars memory vars; // Holds all our calculation results uint256 oErr; // For each asset the account is in CToken[] memory assets = accountAssets[account]; for (uint256 i = 0; i < assets.length; i++) { CToken asset = assets[i]; // Skip the asset if it is not listed. if (!isMarketListed(address(asset))) { continue; } // Read the balances and exchange rate from the cToken (oErr, vars.cTokenBalance, vars.borrowBalance, vars.exchangeRateMantissa) = asset.getAccountSnapshot( account ); require(oErr == 0, "snapshot error"); // Unlike compound protocol, getUnderlyingPrice is relatively expensive because we use ChainLink as our primary price feed. // If user has no supply / borrow balance on this asset, and user is not redeeming / borrowing this asset, skip it. if (vars.cTokenBalance == 0 && vars.borrowBalance == 0 && asset != cTokenModify) { continue; } vars.collateralFactor = Exp({mantissa: markets[address(asset)].collateralFactorMantissa}); vars.exchangeRate = Exp({mantissa: vars.exchangeRateMantissa}); // Get the normalized price of the asset vars.oraclePriceMantissa = oracle.getUnderlyingPrice(asset); require(vars.oraclePriceMantissa > 0, "price error"); vars.oraclePrice = Exp({mantissa: vars.oraclePriceMantissa}); // Pre-compute a conversion factor from tokens -> ether (normalized price value) vars.tokensToDenom = mul_(mul_(vars.collateralFactor, vars.exchangeRate), vars.oraclePrice); // sumCollateral += tokensToDenom * cTokenBalance vars.sumCollateral = mul_ScalarTruncateAddUInt(vars.tokensToDenom, vars.cTokenBalance, vars.sumCollateral); // sumBorrowPlusEffects += oraclePrice * borrowBalance vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt( vars.oraclePrice, vars.borrowBalance, vars.sumBorrowPlusEffects ); // Calculate effects of interacting with cTokenModify if (asset == cTokenModify) { // redeem effect // sumBorrowPlusEffects += tokensToDenom * redeemTokens vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt( vars.tokensToDenom, redeemTokens, vars.sumBorrowPlusEffects ); // borrow effect // sumBorrowPlusEffects += oraclePrice * borrowAmount vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt( vars.oraclePrice, borrowAmount, vars.sumBorrowPlusEffects ); } } // These are safe, as the underflow condition is checked first if (vars.sumCollateral > vars.sumBorrowPlusEffects) { return (Error.NO_ERROR, vars.sumCollateral - vars.sumBorrowPlusEffects, 0); } else { return (Error.NO_ERROR, 0, vars.sumBorrowPlusEffects - vars.sumCollateral); } } /** * @notice Calculate number of tokens of collateral asset to seize given an underlying amount * @dev Used in liquidation (called in cToken.liquidateBorrowFresh) * @param cTokenBorrowed The address of the borrowed cToken * @param cTokenCollateral The address of the collateral cToken * @param actualRepayAmount The amount of cTokenBorrowed underlying to convert into cTokenCollateral tokens * @return (errorCode, number of cTokenCollateral tokens to be seized in a liquidation) */ function liquidateCalculateSeizeTokens( address cTokenBorrowed, address cTokenCollateral, uint256 actualRepayAmount ) external view returns (uint256, uint256) { /* Read oracle prices for borrowed and collateral markets */ uint256 priceBorrowedMantissa = oracle.getUnderlyingPrice(CToken(cTokenBorrowed)); uint256 priceCollateralMantissa = oracle.getUnderlyingPrice(CToken(cTokenCollateral)); require(priceBorrowedMantissa > 0 && priceCollateralMantissa > 0, "price error"); /* * Get the exchange rate and calculate the number of collateral tokens to seize: * seizeAmount = actualRepayAmount * liquidationIncentive * priceBorrowed / priceCollateral * seizeTokens = seizeAmount / exchangeRate * = actualRepayAmount * (liquidationIncentive * priceBorrowed) / (priceCollateral * exchangeRate) */ uint256 exchangeRateMantissa = CToken(cTokenCollateral).exchangeRateStored(); // Note: reverts on error Exp memory numerator = mul_( Exp({mantissa: liquidationIncentiveMantissa}), Exp({mantissa: priceBorrowedMantissa}) ); Exp memory denominator = mul_(Exp({mantissa: priceCollateralMantissa}), Exp({mantissa: exchangeRateMantissa})); Exp memory ratio = div_(numerator, denominator); uint256 seizeTokens = mul_ScalarTruncate(ratio, actualRepayAmount); return (uint256(Error.NO_ERROR), seizeTokens); } /*** Admin Functions ***/ /** * @notice Sets a new price oracle for the comptroller * @dev Admin function to set a new price oracle * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setPriceOracle(PriceOracle newOracle) public returns (uint256) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PRICE_ORACLE_OWNER_CHECK); } // Track the old oracle for the comptroller PriceOracle oldOracle = oracle; // Set comptroller's oracle to newOracle oracle = newOracle; // Emit NewPriceOracle(oldOracle, newOracle) emit NewPriceOracle(oldOracle, newOracle); return uint256(Error.NO_ERROR); } /** * @notice Sets the closeFactor used when liquidating borrows * @dev Admin function to set closeFactor * @param newCloseFactorMantissa New close factor, scaled by 1e18 * @return uint 0=success, otherwise a failure. (See ErrorReporter for details) */ function _setCloseFactor(uint256 newCloseFactorMantissa) external returns (uint256) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_CLOSE_FACTOR_OWNER_CHECK); } uint256 oldCloseFactorMantissa = closeFactorMantissa; closeFactorMantissa = newCloseFactorMantissa; emit NewCloseFactor(oldCloseFactorMantissa, closeFactorMantissa); return uint256(Error.NO_ERROR); } /** * @notice Sets the collateralFactor for a market * @dev Admin function to set per-market collateralFactor * @param cToken The market to set the factor on * @param newCollateralFactorMantissa The new collateral factor, scaled by 1e18 * @return uint 0=success, otherwise a failure. (See ErrorReporter for details) */ function _setCollateralFactor(CToken cToken, uint256 newCollateralFactorMantissa) external returns (uint256) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_COLLATERAL_FACTOR_OWNER_CHECK); } // Verify market is listed Market storage market = markets[address(cToken)]; if (!market.isListed) { return fail(Error.MARKET_NOT_LISTED, FailureInfo.SET_COLLATERAL_FACTOR_NO_EXISTS); } Exp memory newCollateralFactorExp = Exp({mantissa: newCollateralFactorMantissa}); // Check collateral factor <= 0.9 Exp memory highLimit = Exp({mantissa: collateralFactorMaxMantissa}); if (lessThanExp(highLimit, newCollateralFactorExp)) { return fail(Error.INVALID_COLLATERAL_FACTOR, FailureInfo.SET_COLLATERAL_FACTOR_VALIDATION); } // If collateral factor != 0, fail if price == 0 if (newCollateralFactorMantissa != 0 && oracle.getUnderlyingPrice(cToken) == 0) { return fail(Error.PRICE_ERROR, FailureInfo.SET_COLLATERAL_FACTOR_WITHOUT_PRICE); } // Set market's collateral factor to new collateral factor, remember old value uint256 oldCollateralFactorMantissa = market.collateralFactorMantissa; market.collateralFactorMantissa = newCollateralFactorMantissa; // Emit event with asset, old collateral factor, and new collateral factor emit NewCollateralFactor(cToken, oldCollateralFactorMantissa, newCollateralFactorMantissa); return uint256(Error.NO_ERROR); } /** * @notice Sets liquidationIncentive * @dev Admin function to set liquidationIncentive * @param newLiquidationIncentiveMantissa New liquidationIncentive scaled by 1e18 * @return uint 0=success, otherwise a failure. (See ErrorReporter for details) */ function _setLiquidationIncentive(uint256 newLiquidationIncentiveMantissa) external returns (uint256) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_LIQUIDATION_INCENTIVE_OWNER_CHECK); } // Save current value for use in log uint256 oldLiquidationIncentiveMantissa = liquidationIncentiveMantissa; // Set liquidation incentive to new incentive liquidationIncentiveMantissa = newLiquidationIncentiveMantissa; // Emit event with old incentive, new incentive emit NewLiquidationIncentive(oldLiquidationIncentiveMantissa, newLiquidationIncentiveMantissa); return uint256(Error.NO_ERROR); } /** * @notice Add the market to the markets mapping and set it as listed * @dev Admin function to set isListed and add support for the market * @param cToken The address of the market (token) to list * @param version The version of the market (token) * @return uint 0=success, otherwise a failure. (See enum Error for details) */ function _supportMarket(CToken cToken, Version version) external returns (uint256) { require(msg.sender == admin, "admin only"); require(!isMarketListed(address(cToken)), "market already listed"); cToken.isCToken(); // Sanity check to make sure its really a CToken markets[address(cToken)] = Market({isListed: true, collateralFactorMantissa: 0, version: version}); _addMarketInternal(address(cToken)); emit MarketListed(cToken); return uint256(Error.NO_ERROR); } /** * @notice Remove the market from the markets mapping * @param cToken The address of the market (token) to delist */ function _delistMarket(CToken cToken) external { require(msg.sender == admin, "admin only"); require(isMarketListed(address(cToken)), "market not listed"); require(markets[address(cToken)].collateralFactorMantissa == 0, "market has collateral"); cToken.isCToken(); // Sanity check to make sure its really a CToken isMarkertDelisted[address(cToken)] = true; delete markets[address(cToken)]; for (uint256 i = 0; i < allMarkets.length; i++) { if (allMarkets[i] == cToken) { allMarkets[i] = allMarkets[allMarkets.length - 1]; delete allMarkets[allMarkets.length - 1]; allMarkets.length--; break; } } emit MarketDelisted(cToken); } function _addMarketInternal(address cToken) internal { for (uint256 i = 0; i < allMarkets.length; i++) { require(allMarkets[i] != CToken(cToken), "market already added"); } allMarkets.push(CToken(cToken)); } /** * @notice Set the given supply caps for the given cToken markets. Supplying that brings total supplys to or above supply cap will revert. * @dev Admin or pauseGuardian function to set the supply caps. A supply cap of 0 corresponds to unlimited supplying. If the total borrows * already exceeded the cap, it will prevent anyone to borrow. * @param cTokens The addresses of the markets (tokens) to change the supply caps for * @param newSupplyCaps The new supply cap values in underlying to be set. A value of 0 corresponds to unlimited supplying. */ function _setMarketSupplyCaps(CToken[] calldata cTokens, uint256[] calldata newSupplyCaps) external { require(msg.sender == admin || msg.sender == pauseGuardian, "admin or guardian only"); uint256 numMarkets = cTokens.length; uint256 numSupplyCaps = newSupplyCaps.length; require(numMarkets != 0 && numMarkets == numSupplyCaps, "invalid input"); for (uint256 i = 0; i < numMarkets; i++) { supplyCaps[address(cTokens[i])] = newSupplyCaps[i]; emit NewSupplyCap(cTokens[i], newSupplyCaps[i]); } } /** * @notice Set the given borrow caps for the given cToken markets. Borrowing that brings total borrows to or above borrow cap will revert. * @dev Admin or pauseGuardian function to set the borrow caps. A borrow cap of 0 corresponds to unlimited borrowing. If the total supplies * already exceeded the cap, it will prevent anyone to mint. * @param cTokens The addresses of the markets (tokens) to change the borrow caps for * @param newBorrowCaps The new borrow cap values in underlying to be set. A value of 0 corresponds to unlimited borrowing. */ function _setMarketBorrowCaps(CToken[] calldata cTokens, uint256[] calldata newBorrowCaps) external { require(msg.sender == admin || msg.sender == pauseGuardian, "admin or guardian only"); uint256 numMarkets = cTokens.length; uint256 numBorrowCaps = newBorrowCaps.length; require(numMarkets != 0 && numMarkets == numBorrowCaps, "invalid input"); for (uint256 i = 0; i < numMarkets; i++) { borrowCaps[address(cTokens[i])] = newBorrowCaps[i]; emit NewBorrowCap(cTokens[i], newBorrowCaps[i]); } } /** * @notice Admin function to change the Pause Guardian * @param newPauseGuardian The address of the new Pause Guardian * @return uint 0=success, otherwise a failure. (See enum Error for details) */ function _setPauseGuardian(address newPauseGuardian) public returns (uint256) { if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PAUSE_GUARDIAN_OWNER_CHECK); } // Save current value for inclusion in log address oldPauseGuardian = pauseGuardian; // Store pauseGuardian with value newPauseGuardian pauseGuardian = newPauseGuardian; // Emit NewPauseGuardian(OldPauseGuardian, NewPauseGuardian) emit NewPauseGuardian(oldPauseGuardian, pauseGuardian); return uint256(Error.NO_ERROR); } /** * @notice Admin function to set the liquidity mining module address * @dev Removing the liquidity mining module address could cause the inconsistency in the LM module. * @param newLiquidityMining The address of the new liquidity mining module */ function _setLiquidityMining(address newLiquidityMining) external { require(msg.sender == admin, "admin only"); require(LiquidityMiningInterface(newLiquidityMining).comptroller() == address(this), "mismatch comptroller"); // Save current value for inclusion in log address oldLiquidityMining = liquidityMining; // Store liquidityMining with value newLiquidityMining liquidityMining = newLiquidityMining; // Emit NewLiquidityMining(OldLiquidityMining, NewLiquidityMining) emit NewLiquidityMining(oldLiquidityMining, liquidityMining); } /** * @notice Admin function to set the credit limit manager address * @param newCreditLimitManager The address of the new credit limit manager */ function _setCreditLimitManager(address newCreditLimitManager) external { require(msg.sender == admin, "admin only"); // Save current value for inclusion in log address oldCreditLimitManager = creditLimitManager; // Store creditLimitManager with value newCreditLimitManager creditLimitManager = newCreditLimitManager; // Emit NewCreditLimitManager(oldCreditLimitManager, newCreditLimitManager) emit NewCreditLimitManager(oldCreditLimitManager, creditLimitManager); } function _setMintPaused(CToken cToken, bool state) public returns (bool) { require(isMarketListed(address(cToken)), "market not listed"); require(msg.sender == pauseGuardian || msg.sender == admin, "guardian or admin only"); require(msg.sender == admin || state == true, "admin only"); mintGuardianPaused[address(cToken)] = state; emit ActionPaused(cToken, "Mint", state); return state; } function _setBorrowPaused(CToken cToken, bool state) public returns (bool) { require(isMarketListed(address(cToken)), "market not listed"); require(msg.sender == pauseGuardian || msg.sender == admin, "guardian or admin only"); require(msg.sender == admin || state == true, "admin only"); borrowGuardianPaused[address(cToken)] = state; emit ActionPaused(cToken, "Borrow", state); return state; } function _setFlashloanPaused(CToken cToken, bool state) public returns (bool) { require(isMarketListed(address(cToken)), "market not listed"); require(msg.sender == pauseGuardian || msg.sender == admin, "guardian or admin only"); require(msg.sender == admin || state == true, "admin only"); flashloanGuardianPaused[address(cToken)] = state; emit ActionPaused(cToken, "Flashloan", state); return state; } function _setTransferPaused(bool state) public returns (bool) { require(msg.sender == pauseGuardian || msg.sender == admin, "guardian or admin only"); require(msg.sender == admin || state == true, "admin only"); transferGuardianPaused = state; emit ActionPaused("Transfer", state); return state; } function _setSeizePaused(bool state) public returns (bool) { require(msg.sender == pauseGuardian || msg.sender == admin, "guardian or admin only"); require(msg.sender == admin || state == true, "admin only"); seizeGuardianPaused = state; emit ActionPaused("Seize", state); return state; } function _become(Unitroller unitroller) public { require(msg.sender == unitroller.admin(), "unitroller admin only"); require(unitroller._acceptImplementation() == 0, "unauthorized"); } /** * @notice Sets protocol's credit limit by market * @param protocol The address of the protocol * @param market The market * @param creditLimit The credit limit */ function _setCreditLimit( address protocol, address market, uint256 creditLimit ) public { require( msg.sender == admin || msg.sender == creditLimitManager || msg.sender == pauseGuardian, "admin or credit limit manager or pause guardian only" ); require(isMarketListed(market), "market not listed"); if (_creditLimits[protocol][market] == 0 && creditLimit != 0) { // Only admin or credit limit manager could set a new credit limit. require(msg.sender == admin || msg.sender == creditLimitManager, "admin or credit limit manager only"); } _creditLimits[protocol][market] = creditLimit; emit CreditLimitChanged(protocol, market, creditLimit); } /** * @notice Return all of the markets * @dev The automatic getter may be used to access an individual market. * @return The list of market addresses */ function getAllMarkets() public view returns (CToken[] memory) { return allMarkets; } function getBlockNumber() public view returns (uint256) { return block.number; } } pragma solidity ^0.5.16; import "./CToken.sol"; import "./ComptrollerStorage.sol"; contract ComptrollerInterface { /// @notice Indicator that this is a Comptroller contract (for inspection) bool public constant isComptroller = true; /*** Assets You Are In ***/ function enterMarkets(address[] calldata cTokens) external returns (uint256[] memory); function exitMarket(address cToken) external returns (uint256); /*** Policy Hooks ***/ function mintAllowed( address cToken, address minter, uint256 mintAmount ) external returns (uint256); function mintVerify( address cToken, address minter, uint256 mintAmount, uint256 mintTokens ) external; function redeemAllowed( address cToken, address redeemer, uint256 redeemTokens ) external returns (uint256); function redeemVerify( address cToken, address redeemer, uint256 redeemAmount, uint256 redeemTokens ) external; function borrowAllowed( address cToken, address borrower, uint256 borrowAmount ) external returns (uint256); function borrowVerify( address cToken, address borrower, uint256 borrowAmount ) external; function repayBorrowAllowed( address cToken, address payer, address borrower, uint256 repayAmount ) external returns (uint256); function repayBorrowVerify( address cToken, address payer, address borrower, uint256 repayAmount, uint256 borrowerIndex ) external; function liquidateBorrowAllowed( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint256 repayAmount ) external returns (uint256); function liquidateBorrowVerify( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint256 repayAmount, uint256 seizeTokens ) external; function seizeAllowed( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint256 seizeTokens ) external returns (uint256); function seizeVerify( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint256 seizeTokens ) external; function transferAllowed( address cToken, address src, address dst, uint256 transferTokens ) external returns (uint256); function transferVerify( address cToken, address src, address dst, uint256 transferTokens ) external; /*** Liquidity/Liquidation Calculations ***/ function liquidateCalculateSeizeTokens( address cTokenBorrowed, address cTokenCollateral, uint256 repayAmount ) external view returns (uint256, uint256); } interface ComptrollerInterfaceExtension { function checkMembership(address account, CToken cToken) external view returns (bool); function updateCTokenVersion(address cToken, ComptrollerV1Storage.Version version) external; function flashloanAllowed( address cToken, address receiver, uint256 amount, bytes calldata params ) external view returns (bool); function getAccountLiquidity(address account) external view returns ( uint256, uint256, uint256 ); function supplyCaps(address market) external view returns (uint256); } pragma solidity ^0.5.16; import "./CToken.sol"; import "./PriceOracle/PriceOracle.sol"; contract UnitrollerAdminStorage { /** * @notice Administrator for this contract */ address public admin; /** * @notice Pending administrator for this contract */ address public pendingAdmin; /** * @notice Active brains of Unitroller */ address public comptrollerImplementation; /** * @notice Pending brains of Unitroller */ address public pendingComptrollerImplementation; } contract ComptrollerV1Storage is UnitrollerAdminStorage { /** * @notice Oracle which gives the price of any given asset */ PriceOracle public oracle; /** * @notice Multiplier used to calculate the maximum repayAmount when liquidating a borrow */ uint256 public closeFactorMantissa; /** * @notice Multiplier representing the discount on collateral that a liquidator receives */ uint256 public liquidationIncentiveMantissa; /** * @notice Per-account mapping of "assets you are in" */ mapping(address => CToken[]) public accountAssets; enum Version { VANILLA, COLLATERALCAP, WRAPPEDNATIVE } struct Market { /// @notice Whether or not this market is listed bool isListed; /** * @notice Multiplier representing the most one can borrow against their collateral in this market. * For instance, 0.9 to allow borrowing 90% of collateral value. * Must be between 0 and 1, and stored as a mantissa. */ uint256 collateralFactorMantissa; /// @notice Per-market mapping of "accounts in this asset" mapping(address => bool) accountMembership; /// @notice CToken version Version version; } /** * @notice Official mapping of cTokens -> Market metadata * @dev Used e.g. to determine if a market is supported */ mapping(address => Market) public markets; /** * @notice The Pause Guardian can pause certain actions as a safety mechanism. * Actions which allow users to remove their own assets cannot be paused. * Liquidation / seizing / transfer can only be paused globally, not by market. */ address public pauseGuardian; bool public _mintGuardianPaused; bool public _borrowGuardianPaused; bool public transferGuardianPaused; bool public seizeGuardianPaused; mapping(address => bool) public mintGuardianPaused; mapping(address => bool) public borrowGuardianPaused; struct CompMarketState { /// @notice The market's last updated compBorrowIndex or compSupplyIndex uint224 index; /// @notice The block number the index was last updated at uint32 block; } /// @notice A list of all markets CToken[] public allMarkets; /// @notice The portion of compRate that each market currently receives /// @dev This storage is depreacted. mapping(address => uint256) public compSpeeds; /// @notice The COMP market supply state for each market /// @dev This storage is depreacted. mapping(address => CompMarketState) public compSupplyState; /// @notice The COMP market borrow state for each market /// @dev This storage is depreacted. mapping(address => CompMarketState) public compBorrowState; /// @notice The COMP borrow index for each market for each supplier as of the last time they accrued COMP /// @dev This storage is depreacted. mapping(address => mapping(address => uint256)) public compSupplierIndex; /// @notice The COMP borrow index for each market for each borrower as of the last time they accrued COMP /// @dev This storage is depreacted. mapping(address => mapping(address => uint256)) public compBorrowerIndex; /// @notice The COMP accrued but not yet transferred to each user /// @dev This storage is depreacted. mapping(address => uint256) public compAccrued; /// @notice The borrowCapGuardian can set borrowCaps to any number for any market. Lowering the borrow cap could disable borrowing on the given market. address public borrowCapGuardian; /// @notice Borrow caps enforced by borrowAllowed for each cToken address. Defaults to zero which corresponds to unlimited borrowing. mapping(address => uint256) public borrowCaps; /// @notice The supplyCapGuardian can set supplyCaps to any number for any market. Lowering the supply cap could disable supplying to the given market. address public supplyCapGuardian; /// @notice Supply caps enforced by mintAllowed for each cToken address. Defaults to zero which corresponds to unlimited supplying. mapping(address => uint256) public supplyCaps; /// @notice creditLimits allowed specific protocols to borrow and repay without collateral. /// @dev This storage is depreacted. mapping(address => uint256) internal _oldCreditLimits; /// @notice flashloanGuardianPaused can pause flash loan as a safety mechanism. mapping(address => bool) public flashloanGuardianPaused; /// @notice liquidityMining the liquidity mining module that handles the LM rewards distribution. address public liquidityMining; /// @notice creditLimits allowed specific protocols to borrow and repay specific markets without collateral. mapping(address => mapping(address => uint256)) internal _creditLimits; /// @notice isMarkertDelisted records the market which has been delisted by us. mapping(address => bool) public isMarkertDelisted; /// @notice creditLimitManager is the role who is in charge of increasing the credit limit. address public creditLimitManager; } pragma solidity ^0.5.16; /** * @title ERC 20 Token Standard Interface * https://eips.ethereum.org/EIPS/eip-20 */ interface EIP20Interface { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); /** * @notice Get the total number of tokens in circulation * @return The supply of tokens */ function totalSupply() external view returns (uint256); /** * @notice Gets the balance of the specified address * @param owner The address from which the balance will be retrieved * @return The balance */ function balanceOf(address owner) external view returns (uint256 balance); /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint256 amount) external returns (bool success); /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom( address src, address dst, uint256 amount ) external returns (bool success); /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param amount The number of tokens that are approved (-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint256 amount) external returns (bool success); /** * @notice Get the current allowance from `owner` for `spender` * @param owner The address of the account which owns the tokens to be spent * @param spender The address of the account which may transfer tokens * @return The number of tokens allowed to be spent (-1 means infinite) */ function allowance(address owner, address spender) external view returns (uint256 remaining); event Transfer(address indexed from, address indexed to, uint256 amount); event Approval(address indexed owner, address indexed spender, uint256 amount); } pragma solidity ^0.5.16; /** * @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 */ interface EIP20NonStandardInterface { /** * @notice Get the total number of tokens in circulation * @return The supply of tokens */ function totalSupply() external view returns (uint256); /** * @notice Gets the balance of the specified address * @param owner The address from which the balance will be retrieved * @return The balance */ function balanceOf(address owner) external view returns (uint256 balance); /// /// !!!!!!!!!!!!!! /// !!! NOTICE !!! `transfer` does not return a value, in violation of the ERC-20 specification /// !!!!!!!!!!!!!! /// /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer */ function transfer(address dst, uint256 amount) external; /// /// !!!!!!!!!!!!!! /// !!! NOTICE !!! `transferFrom` does not return a value, in violation of the ERC-20 specification /// !!!!!!!!!!!!!! /// /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param amount The number of tokens to transfer */ function transferFrom( address src, address dst, uint256 amount ) external; /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param amount The number of tokens that are approved * @return Whether or not the approval succeeded */ function approve(address spender, uint256 amount) external returns (bool success); /** * @notice Get the current allowance from `owner` for `spender` * @param owner The address of the account which owns the tokens to be spent * @param spender The address of the account which may transfer tokens * @return The number of tokens allowed to be spent */ function allowance(address owner, address spender) external view returns (uint256 remaining); event Transfer(address indexed from, address indexed to, uint256 amount); event Approval(address indexed owner, address indexed spender, uint256 amount); } pragma solidity ^0.5.16; interface ERC3156FlashBorrowerInterface { /** * @dev Receive a flash loan. * @param initiator The initiator of the loan. * @param token The loan currency. * @param amount The amount of tokens lent. * @param fee The additional amount of tokens to repay. * @param data Arbitrary data structure, intended to contain user-defined parameters. * @return The keccak256 hash of "ERC3156FlashBorrower.onFlashLoan" */ function onFlashLoan( address initiator, address token, uint256 amount, uint256 fee, bytes calldata data ) external returns (bytes32); } pragma solidity ^0.5.16; contract ComptrollerErrorReporter { enum Error { NO_ERROR, UNAUTHORIZED, COMPTROLLER_MISMATCH, INSUFFICIENT_SHORTFALL, INSUFFICIENT_LIQUIDITY, INVALID_CLOSE_FACTOR, INVALID_COLLATERAL_FACTOR, INVALID_LIQUIDATION_INCENTIVE, MARKET_NOT_ENTERED, // no longer possible MARKET_NOT_LISTED, MARKET_ALREADY_LISTED, MATH_ERROR, NONZERO_BORROW_BALANCE, PRICE_ERROR, REJECTION, SNAPSHOT_ERROR, TOO_MANY_ASSETS, TOO_MUCH_REPAY } enum FailureInfo { ACCEPT_ADMIN_PENDING_ADMIN_CHECK, ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK, EXIT_MARKET_BALANCE_OWED, EXIT_MARKET_REJECTION, SET_CLOSE_FACTOR_OWNER_CHECK, SET_CLOSE_FACTOR_VALIDATION, SET_COLLATERAL_FACTOR_OWNER_CHECK, SET_COLLATERAL_FACTOR_NO_EXISTS, SET_COLLATERAL_FACTOR_VALIDATION, SET_COLLATERAL_FACTOR_WITHOUT_PRICE, SET_IMPLEMENTATION_OWNER_CHECK, SET_LIQUIDATION_INCENTIVE_OWNER_CHECK, SET_LIQUIDATION_INCENTIVE_VALIDATION, SET_MAX_ASSETS_OWNER_CHECK, SET_PENDING_ADMIN_OWNER_CHECK, SET_PENDING_IMPLEMENTATION_OWNER_CHECK, SET_PRICE_ORACLE_OWNER_CHECK, SUPPORT_MARKET_EXISTS, SUPPORT_MARKET_OWNER_CHECK, SET_PAUSE_GUARDIAN_OWNER_CHECK } /** * @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); /** * @dev use this when reporting a known error from the money market 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( Error err, FailureInfo info, uint256 opaqueError ) internal returns (uint256) { emit Failure(uint256(err), uint256(info), opaqueError); return uint256(err); } } contract TokenErrorReporter { enum Error { NO_ERROR, UNAUTHORIZED, BAD_INPUT, COMPTROLLER_REJECTION, COMPTROLLER_CALCULATION_ERROR, INTEREST_RATE_MODEL_ERROR, INVALID_ACCOUNT_PAIR, INVALID_CLOSE_AMOUNT_REQUESTED, INVALID_COLLATERAL_FACTOR, MATH_ERROR, MARKET_NOT_FRESH, MARKET_NOT_LISTED, TOKEN_INSUFFICIENT_ALLOWANCE, TOKEN_INSUFFICIENT_BALANCE, TOKEN_INSUFFICIENT_CASH, TOKEN_TRANSFER_IN_FAILED, TOKEN_TRANSFER_OUT_FAILED } /* * 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, ACCRUE_INTEREST_BORROW_RATE_CALCULATION_FAILED, BORROW_ACCRUE_INTEREST_FAILED, BORROW_CASH_NOT_AVAILABLE, BORROW_FRESHNESS_CHECK, BORROW_MARKET_NOT_LISTED, BORROW_COMPTROLLER_REJECTION, LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED, LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED, LIQUIDATE_COLLATERAL_FRESHNESS_CHECK, LIQUIDATE_COMPTROLLER_REJECTION, LIQUIDATE_COMPTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED, LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX, LIQUIDATE_CLOSE_AMOUNT_IS_ZERO, LIQUIDATE_FRESHNESS_CHECK, LIQUIDATE_LIQUIDATOR_IS_BORROWER, LIQUIDATE_REPAY_BORROW_FRESH_FAILED, LIQUIDATE_SEIZE_COMPTROLLER_REJECTION, LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER, LIQUIDATE_SEIZE_TOO_MUCH, MINT_ACCRUE_INTEREST_FAILED, MINT_COMPTROLLER_REJECTION, MINT_FRESHNESS_CHECK, MINT_TRANSFER_IN_FAILED, MINT_TRANSFER_IN_NOT_POSSIBLE, REDEEM_ACCRUE_INTEREST_FAILED, REDEEM_COMPTROLLER_REJECTION, REDEEM_FRESHNESS_CHECK, REDEEM_TRANSFER_OUT_NOT_POSSIBLE, REDUCE_RESERVES_ACCRUE_INTEREST_FAILED, REDUCE_RESERVES_ADMIN_CHECK, REDUCE_RESERVES_CASH_NOT_AVAILABLE, REDUCE_RESERVES_FRESH_CHECK, REDUCE_RESERVES_VALIDATION, REPAY_BEHALF_ACCRUE_INTEREST_FAILED, REPAY_BORROW_ACCRUE_INTEREST_FAILED, REPAY_BORROW_COMPTROLLER_REJECTION, REPAY_BORROW_FRESHNESS_CHECK, REPAY_BORROW_TRANSFER_IN_NOT_POSSIBLE, SET_COLLATERAL_FACTOR_OWNER_CHECK, SET_COLLATERAL_FACTOR_VALIDATION, SET_COMPTROLLER_OWNER_CHECK, SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED, SET_INTEREST_RATE_MODEL_FRESH_CHECK, SET_INTEREST_RATE_MODEL_OWNER_CHECK, SET_MAX_ASSETS_OWNER_CHECK, SET_ORACLE_MARKET_NOT_LISTED, SET_PENDING_ADMIN_OWNER_CHECK, SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED, SET_RESERVE_FACTOR_ADMIN_CHECK, SET_RESERVE_FACTOR_FRESH_CHECK, SET_RESERVE_FACTOR_BOUNDS_CHECK, TRANSFER_COMPTROLLER_REJECTION, TRANSFER_NOT_ALLOWED, ADD_RESERVES_ACCRUE_INTEREST_FAILED, ADD_RESERVES_FRESH_CHECK, ADD_RESERVES_TRANSFER_IN_NOT_POSSIBLE } /** * @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); /** * @dev use this when reporting a known error from the money market 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( Error err, FailureInfo info, uint256 opaqueError ) internal returns (uint256) { emit Failure(uint256(err), uint256(info), opaqueError); return uint256(err); } } pragma solidity ^0.5.16; import "./CarefulMath.sol"; /** * @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 Exponential is CarefulMath { 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 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 (MathError, Exp memory) { (MathError err0, uint256 scaledNumerator) = mulUInt(num, expScale); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } (MathError err1, uint256 rational) = divUInt(scaledNumerator, denom); if (err1 != MathError.NO_ERROR) { return (err1, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: rational})); } /** * @dev Adds two exponentials, returning a new exponential. */ function addExp(Exp memory a, Exp memory b) internal pure returns (MathError, Exp memory) { (MathError error, uint256 result) = addUInt(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 (MathError, Exp memory) { (MathError error, uint256 result) = subUInt(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 (MathError, Exp memory) { (MathError err0, uint256 scaledMantissa) = mulUInt(a.mantissa, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: scaledMantissa})); } /** * @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer. */ function mulScalarTruncate(Exp memory a, uint256 scalar) internal pure returns (MathError, uint256) { (MathError err, Exp memory product) = mulScalar(a, scalar); if (err != MathError.NO_ERROR) { return (err, 0); } return (MathError.NO_ERROR, truncate(product)); } /** * @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer. */ function mulScalarTruncateAddUInt( Exp memory a, uint256 scalar, uint256 addend ) internal pure returns (MathError, uint256) { (MathError err, Exp memory product) = mulScalar(a, scalar); if (err != MathError.NO_ERROR) { return (err, 0); } return addUInt(truncate(product), addend); } /** * @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 Divide an Exp by a scalar, returning a new Exp. */ function divScalar(Exp memory a, uint256 scalar) internal pure returns (MathError, Exp memory) { (MathError err0, uint256 descaledMantissa) = divUInt(a.mantissa, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: descaledMantissa})); } /** * @dev Divide a scalar by an Exp, returning a new Exp. */ function divScalarByExp(uint256 scalar, Exp memory divisor) internal pure returns (MathError, Exp memory) { /* We are doing this as: getExp(mulUInt(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` */ (MathError err0, uint256 numerator) = mulUInt(expScale, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return getExp(numerator, divisor.mantissa); } /** * @dev Divide a scalar by an Exp, then truncate to return an unsigned integer. */ function divScalarByExpTruncate(uint256 scalar, Exp memory divisor) internal pure returns (MathError, uint256) { (MathError err, Exp memory fraction) = divScalarByExp(scalar, divisor); if (err != MathError.NO_ERROR) { return (err, 0); } return (MathError.NO_ERROR, truncate(fraction)); } /** * @dev Divide a scalar by an Exp, returning a new Exp. */ function div_ScalarByExp(uint256 scalar, Exp memory divisor) internal pure returns (Exp memory) { /* We are doing this as: getExp(mulUInt(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` */ uint256 numerator = mul_(expScale, scalar); return Exp({mantissa: div_(numerator, divisor)}); } /** * @dev Divide a scalar by an Exp, then truncate to return an unsigned integer. */ function div_ScalarByExpTruncate(uint256 scalar, Exp memory divisor) internal pure returns (uint256) { Exp memory fraction = div_ScalarByExp(scalar, divisor); return truncate(fraction); } /** * @dev Multiplies two exponentials, returning a new exponential. */ function mulExp(Exp memory a, Exp memory b) internal pure returns (MathError, Exp memory) { (MathError err0, uint256 doubleScaledProduct) = mulUInt(a.mantissa, b.mantissa); if (err0 != MathError.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. (MathError err1, uint256 doubleScaledProductWithHalfScale) = addUInt(halfExpScale, doubleScaledProduct); if (err1 != MathError.NO_ERROR) { return (err1, Exp({mantissa: 0})); } (MathError err2, uint256 product) = divUInt(doubleScaledProductWithHalfScale, expScale); // The only error `div` can return is MathError.DIVISION_BY_ZERO but we control `expScale` and it is not zero. assert(err2 == MathError.NO_ERROR); return (MathError.NO_ERROR, Exp({mantissa: product})); } /** * @dev Multiplies two exponentials given their mantissas, returning a new exponential. */ function mulExp(uint256 a, uint256 b) internal pure returns (MathError, Exp memory) { return mulExp(Exp({mantissa: a}), Exp({mantissa: b})); } /** * @dev Multiplies three exponentials, returning a new exponential. */ function mulExp3( Exp memory a, Exp memory b, Exp memory c ) internal pure returns (MathError, Exp memory) { (MathError err, Exp memory ab) = mulExp(a, b); if (err != MathError.NO_ERROR) { return (err, ab); } return mulExp(ab, c); } /** * @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 (MathError, Exp memory) { return getExp(a.mantissa, b.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 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 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)}); } // implementation from https://github.com/Uniswap/uniswap-lib/commit/99f3f28770640ba1bb1ff460ac7c5292fb8291a0 // original implementation: https://github.com/abdk-consulting/abdk-libraries-solidity/blob/master/ABDKMath64x64.sol#L687 function sqrt(uint256 x) internal pure returns (uint256) { if (x == 0) return 0; 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 (r < r1 ? r : r1); } } pragma solidity ^0.5.16; contract Comp { /// @notice EIP-20 token name for this token string public constant name = "Cream"; /// @notice EIP-20 token symbol for this token string public constant symbol = "CREAM"; /// @notice EIP-20 token decimals for this token uint8 public constant decimals = 18; /// @notice Total number of tokens in circulation uint256 public constant totalSupply = 9000000e18; // 9 million Comp /// @notice Allowance amounts on behalf of others mapping(address => mapping(address => uint96)) internal allowances; /// @notice Official record of token balances for each account mapping(address => uint96) internal balances; /// @notice A record of each accounts delegate mapping(address => address) public delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint96 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 => uint256) 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, uint256 previousBalance, uint256 newBalance); /// @notice The standard EIP-20 transfer event event Transfer(address indexed from, address indexed to, uint256 amount); /// @notice The standard EIP-20 approval event event Approval(address indexed owner, address indexed spender, uint256 amount); /** * @notice Construct a new Comp token * @param account The initial account to grant all the tokens */ constructor(address account) public { balances[account] = uint96(totalSupply); emit Transfer(address(0), account, totalSupply); } /** * @notice Get the number of tokens `spender` is approved to spend on behalf of `account` * @param account The address of the account holding the funds * @param spender The address of the account spending the funds * @return The number of tokens approved */ function allowance(address account, address spender) external view returns (uint256) { return allowances[account][spender]; } /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param rawAmount The number of tokens that are approved (2^256-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint256 rawAmount) external returns (bool) { uint96 amount; if (rawAmount == uint256(-1)) { amount = uint96(-1); } else { amount = safe96(rawAmount, "Comp::approve: amount exceeds 96 bits"); } allowances[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; } /** * @notice Get the number of tokens held by the `account` * @param account The address of the account to get the balance of * @return The number of tokens held */ function balanceOf(address account) external view returns (uint256) { return balances[account]; } /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param rawAmount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint256 rawAmount) external returns (bool) { uint96 amount = safe96(rawAmount, "Comp::transfer: amount exceeds 96 bits"); _transferTokens(msg.sender, dst, amount); return true; } /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param rawAmount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom( address src, address dst, uint256 rawAmount ) external returns (bool) { address spender = msg.sender; uint96 spenderAllowance = allowances[src][spender]; uint96 amount = safe96(rawAmount, "Comp::approve: amount exceeds 96 bits"); if (spender != src && spenderAllowance != uint96(-1)) { uint96 newAllowance = sub96( spenderAllowance, amount, "Comp::transferFrom: transfer amount exceeds spender allowance" ); allowances[src][spender] = newAllowance; emit Approval(src, spender, newAllowance); } _transferTokens(src, dst, amount); return true; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) public { 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, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s ) public { 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), "Comp::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "Comp::delegateBySig: invalid nonce"); require(now <= expiry, "Comp::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 (uint96) { 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, uint256 blockNumber) public view returns (uint96) { require(blockNumber < block.number, "Comp::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]; uint96 delegatorBalance = balances[delegator]; delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _transferTokens( address src, address dst, uint96 amount ) internal { require(src != address(0), "Comp::_transferTokens: cannot transfer from the zero address"); require(dst != address(0), "Comp::_transferTokens: cannot transfer to the zero address"); balances[src] = sub96(balances[src], amount, "Comp::_transferTokens: transfer amount exceeds balance"); balances[dst] = add96(balances[dst], amount, "Comp::_transferTokens: transfer amount overflows"); emit Transfer(src, dst, amount); _moveDelegates(delegates[src], delegates[dst], amount); } function _moveDelegates( address srcRep, address dstRep, uint96 amount ) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { uint32 srcRepNum = numCheckpoints[srcRep]; uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint96 srcRepNew = sub96(srcRepOld, amount, "Comp::_moveVotes: vote amount underflows"); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { uint32 dstRepNum = numCheckpoints[dstRep]; uint96 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint96 dstRepNew = add96(dstRepOld, amount, "Comp::_moveVotes: vote amount overflows"); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes ) internal { uint32 blockNumber = safe32(block.number, "Comp::_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(uint256 n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function safe96(uint256 n, string memory errorMessage) internal pure returns (uint96) { require(n < 2**96, errorMessage); return uint96(n); } function add96( uint96 a, uint96 b, string memory errorMessage ) internal pure returns (uint96) { uint96 c = a + b; require(c >= a, errorMessage); return c; } function sub96( uint96 a, uint96 b, string memory errorMessage ) internal pure returns (uint96) { require(b <= a, errorMessage); return a - b; } function getChainId() internal pure returns (uint256) { uint256 chainId; assembly { chainId := chainid() } return chainId; } } pragma solidity ^0.5.16; /** * @title Compound's InterestRateModel Interface * @author Compound */ contract InterestRateModel { /// @notice Indicator that this is an InterestRateModel contract (for inspection) bool public constant isInterestRateModel = true; /** * @notice Calculates the current borrow interest rate per block * @param cash The total amount of cash the market has * @param borrows The total amount of borrows the market has outstanding * @param reserves The total amnount of reserves the market has * @return The borrow rate per block (as a percentage, and scaled by 1e18) */ function getBorrowRate( uint256 cash, uint256 borrows, uint256 reserves ) external view returns (uint256); /** * @notice Calculates the current supply interest rate per block * @param cash The total amount of cash the market has * @param borrows The total amount of borrows the market has outstanding * @param reserves The total amnount of reserves the market has * @param reserveFactorMantissa The current reserve factor the market has * @return The supply rate per block (as a percentage, and scaled by 1e18) */ function getSupplyRate( uint256 cash, uint256 borrows, uint256 reserves, uint256 reserveFactorMantissa ) external view returns (uint256); } pragma solidity ^0.5.16; contract LiquidityMiningInterface { function comptroller() external view returns (address); function updateSupplyIndex(address cToken, address[] calldata accounts) external; function updateBorrowIndex(address cToken, address[] calldata accounts) external; } pragma solidity ^0.5.16; import "../CToken.sol"; contract PriceOracle { /** * @notice Get the underlying price of a cToken asset * @param cToken The cToken to get the underlying price of * @return The underlying asset price mantissa (scaled by 1e18). * Zero means the price is unavailable. */ function getUnderlyingPrice(CToken cToken) external view returns (uint256); } pragma solidity ^0.5.16; import "./ErrorReporter.sol"; import "./ComptrollerStorage.sol"; /** * @title ComptrollerCore * @dev Storage for the comptroller is at this address, while execution is delegated to the `comptrollerImplementation`. * CTokens should reference this contract as their comptroller. */ contract Unitroller is UnitrollerAdminStorage, ComptrollerErrorReporter { /** * @notice Emitted when pendingComptrollerImplementation is changed */ event NewPendingImplementation(address oldPendingImplementation, address newPendingImplementation); /** * @notice Emitted when pendingComptrollerImplementation is accepted, which means comptroller implementation is updated */ event NewImplementation(address oldImplementation, address newImplementation); /** * @notice Emitted when pendingAdmin is changed */ event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin); /** * @notice Emitted when pendingAdmin is accepted, which means admin is updated */ event NewAdmin(address oldAdmin, address newAdmin); constructor() public { // Set admin to caller admin = msg.sender; } /*** Admin Functions ***/ function _setPendingImplementation(address newPendingImplementation) public returns (uint256) { if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_IMPLEMENTATION_OWNER_CHECK); } address oldPendingImplementation = pendingComptrollerImplementation; pendingComptrollerImplementation = newPendingImplementation; emit NewPendingImplementation(oldPendingImplementation, pendingComptrollerImplementation); return uint256(Error.NO_ERROR); } /** * @notice Accepts new implementation of comptroller. msg.sender must be pendingImplementation * @dev Admin function for new implementation to accept it's role as implementation * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _acceptImplementation() public returns (uint256) { // Check caller is pendingImplementation and pendingImplementation ≠ address(0) if (msg.sender != pendingComptrollerImplementation || pendingComptrollerImplementation == address(0)) { return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK); } // Save current values for inclusion in log address oldImplementation = comptrollerImplementation; address oldPendingImplementation = pendingComptrollerImplementation; comptrollerImplementation = pendingComptrollerImplementation; pendingComptrollerImplementation = address(0); emit NewImplementation(oldImplementation, comptrollerImplementation); emit NewPendingImplementation(oldPendingImplementation, pendingComptrollerImplementation); return uint256(Error.NO_ERROR); } /** * @notice Begins transfer of admin rights. 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. * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setPendingAdmin(address newPendingAdmin) public returns (uint256) { // Check caller = admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK); } // Save current value, if any, for inclusion in log address oldPendingAdmin = pendingAdmin; // Store pendingAdmin with value newPendingAdmin pendingAdmin = newPendingAdmin; // Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin) emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin); 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 is pendingAdmin and pendingAdmin ≠ address(0) if (msg.sender != pendingAdmin || msg.sender == address(0)) { return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_ADMIN_PENDING_ADMIN_CHECK); } // Save current values for inclusion in log address oldAdmin = admin; address oldPendingAdmin = pendingAdmin; // Store admin with value pendingAdmin admin = pendingAdmin; // Clear the pending value pendingAdmin = address(0); emit NewAdmin(oldAdmin, admin); emit NewPendingAdmin(oldPendingAdmin, pendingAdmin); return uint256(Error.NO_ERROR); } /** * @dev Delegates execution to an implementation contract. * It returns to the external caller whatever the implementation returns * or forwards reverts. */ function() external payable { // delegate all other functions to current implementation (bool success, ) = comptrollerImplementation.delegatecall(msg.data); assembly { let free_mem_ptr := mload(0x40) returndatacopy(free_mem_ptr, 0, returndatasize) switch success case 0 { revert(free_mem_ptr, returndatasize) } default { return(free_mem_ptr, returndatasize) } } } }
Adds two exponentials, returning a new exponential./
function addExp(Exp memory a, Exp memory b) internal pure returns (MathError, Exp memory) { (MathError error, uint256 result) = addUInt(a.mantissa, b.mantissa); }
333,407
./full_match/80001/0x416E2d3E39dF69bBc30244eC90477fD042812E6B/sources/src/Interfaces/IHyphenRouter.sol
https:github.com/bcnmy/hyphen-contract/blob/master/contracts/hyphen/LiquidityPool.sol
interface IHyphenRouter { function depositErc20( uint256 toChainId, address tokenAddress, address receiver, uint256 amount, string calldata tag ) external; function depositNative( address receiver, uint256 toChainId, string calldata tag ) external payable; pragma solidity 0.8.17; }
5,585,594
./partial_match/1/0x266c0b1ae2320C0E32059aCCB44Fd4B606Ff77c5/sources/LabRevSharing.sol
claim wETH from Staking Contract
function claim() public { require(stakers[msg.sender].stakedAmount > 0, "No staked amount"); require(!stakers[msg.sender].claimed, "Already claimed"); require(stakers[msg.sender].shilled, "Not enough shilling"); require(block.timestamp >= stakers[msg.sender].stakingTime + minStakingDuration, "Minimum staking duration not reached"); require(block.timestamp >= endTime, "Staking duration is not ended yet."); uint256 reward = calculateReward(msg.sender); wETH.safeTransfer(address(msg.sender), reward); stakers[msg.sender].claimed = true; }
2,666,274
// SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import {IERC20} from './interfaces/IERC20.sol'; import {ILendingPoolConfiguratorV2} from './interfaces/ILendingPoolConfiguratorV2.sol'; import {IOverlyingAsset} from './interfaces/IOverlyingAsset.sol'; import {ILendingPoolAddressesProvider} from './interfaces/ILendingPoolAddressesProvider.sol'; import {IAAMPL} from './interfaces/IAAMPL.sol'; import {ILendingPool, DataTypes} from './interfaces/ILendingPool.sol'; /** * @title AssetListingProposalGenericExecutor * @notice Proposal payload to be executed by the Aave Governance contract via DELEGATECALL * @author Aave **/ contract AIP12AMPL { event ProposalExecuted(); // Mainnet ILendingPoolAddressesProvider public constant LENDING_POOL_ADDRESSES_PROVIDER = ILendingPoolAddressesProvider(0xB53C1a33016B2DC2fF3653530bfF1848a515c8c5); address public constant token = 0xD46bA6D942050d489DBd938a2C909A5d5039A161; address public constant aToken = 0x6fBC3BE5ee5273598d1491D41bB45F6d05a7541A; address public constant stableDebtToken = 0x0e8f4fc4c261d454b13C74507Bce8C38AA990361; address public constant variableDebtToken = 0x3A38bbc6438d2CE2a9e8F116F315a23433755947; address public constant interestStrategy = 0x9A8CA7e1d64AFfF2664443B3803f280345F5336B; uint256 public constant ltv = 0; uint256 public constant liquidationThreshold = 0; uint256 public constant liquidationBonus = 0; uint256 public constant reserveFactor = 2000; uint8 public constant decimals = 9; // Kovan // ILendingPoolAddressesProvider public constant LENDING_POOL_ADDRESSES_PROVIDER = // ILendingPoolAddressesProvider(0x88757f2f99175387aB4C6a4b3067c77A695b0349); // // address public constant token = 0x3E0437898a5667a4769B1Ca5A34aAB1ae7E81377; // address public constant aToken = 0x6421504aBFE7B17d0B751fba13FF5F7D1e2Dd3F9; // address public constant stableDebtToken = 0x0C6f0690462165c6CB7Ebb0BE54502Df21E6aEAe; // address public constant variableDebtToken = 0x66FD8b4a795E99AfCDED8aa81DC68E2019b0863d; // address public constant interestStrategy = 0x3aD3116f2426C213d19CA8563bA90cA2a3650238; // uint256 public constant ltv = 0; // uint256 public constant liquidationThreshold = 0; // uint256 public constant liquidationBonus = 0; // uint256 public constant reserveFactor = 2000; // uint8 public constant decimals = 9; /** * @dev Payload execution function, called once a proposal passed in the Aave governance */ function execute() external { ILendingPoolConfiguratorV2 LENDING_POOL_CONFIGURATOR_V2 = ILendingPoolConfiguratorV2(LENDING_POOL_ADDRESSES_PROVIDER.getLendingPoolConfigurator()); require( token == IOverlyingAsset(aToken).UNDERLYING_ASSET_ADDRESS(), 'ATOKEN: WRONG_UNDERLYING_TOKEN' ); require( token == IOverlyingAsset(stableDebtToken).UNDERLYING_ASSET_ADDRESS(), 'STABLE_DEBT: WRONG_UNDERLYING_TOKEN' ); require( token == IOverlyingAsset(variableDebtToken).UNDERLYING_ASSET_ADDRESS(), 'VARIABLE_DEBT: WRONG_UNDERLYING_TOKEN' ); LENDING_POOL_CONFIGURATOR_V2.initReserve( aToken, stableDebtToken, variableDebtToken, decimals, interestStrategy ); LENDING_POOL_CONFIGURATOR_V2.enableBorrowingOnReserve(token, false); LENDING_POOL_CONFIGURATOR_V2.setReserveFactor(token, reserveFactor); ILendingPool pool = ILendingPool(LENDING_POOL_ADDRESSES_PROVIDER.getLendingPool()); DataTypes.ReserveData memory reserve = pool.getReserveData(token); IAAMPL(reserve.aTokenAddress).initializeDebtTokens(); emit ProposalExecuted(); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; /** * @dev Interface of the ERC20 standard as defined in the EIP. * From https://github.com/OpenZeppelin/openzeppelin-contracts */ 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); function decimals() external view returns (uint8); /** * @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: AGPL-3.0 pragma solidity 0.6.12; interface ILendingPoolConfiguratorV2 { /** * @dev Initializes a reserve * @param aTokenImpl The address of the aToken contract implementation * @param stableDebtTokenImpl The address of the stable debt token contract * @param variableDebtTokenImpl The address of the variable debt token contract * @param underlyingAssetDecimals The decimals of the reserve underlying asset * @param interestRateStrategyAddress The address of the interest rate strategy contract for this reserve **/ function initReserve( address aTokenImpl, address stableDebtTokenImpl, address variableDebtTokenImpl, uint8 underlyingAssetDecimals, address interestRateStrategyAddress ) external; /** * @dev Configures the reserve collateralization parameters * all the values are expressed in percentages with two decimals of precision. A valid value is 10000, which means 100.00% * @param asset The address of the underlying asset of the reserve * @param ltv The loan to value of the asset when used as collateral * @param liquidationThreshold The threshold at which loans using this asset as collateral will be considered undercollateralized * @param liquidationBonus The bonus liquidators receive to liquidate this asset. The values is always above 100%. A value of 105% * means the liquidator will receive a 5% bonus **/ function configureReserveAsCollateral( address asset, uint256 ltv, uint256 liquidationThreshold, uint256 liquidationBonus ) external; /** * @dev Enables borrowing on a reserve * @param asset The address of the underlying asset of the reserve * @param stableBorrowRateEnabled True if stable borrow rate needs to be enabled by default on this reserve **/ function enableBorrowingOnReserve(address asset, bool stableBorrowRateEnabled) external; /** * @dev Updates the reserve factor of a reserve * @param asset The address of the underlying asset of the reserve * @param reserveFactor The new reserve factor of the reserve **/ function setReserveFactor(address asset, uint256 reserveFactor) external; /** * @dev Sets the interest rate strategy of a reserve * @param asset The address of the underlying asset of the reserve * @param rateStrategyAddress The new address of the interest strategy contract **/ function setReserveInterestRateStrategyAddress(address asset, address rateStrategyAddress) external; } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.6.12; interface IOverlyingAsset { function UNDERLYING_ASSET_ADDRESS() external view returns (address); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; /** * @title LendingPoolAddressesProvider contract * @dev Main registry of addresses part of or connected to the protocol, including permissioned roles * - Acting also as factory of proxies and admin of those, so with right to change its implementations * - Owned by the Aave Governance * @author Aave **/ interface ILendingPoolAddressesProvider { event MarketIdSet(string newMarketId); event LendingPoolUpdated(address indexed newAddress); event ConfigurationAdminUpdated(address indexed newAddress); event EmergencyAdminUpdated(address indexed newAddress); event LendingPoolConfiguratorUpdated(address indexed newAddress); event LendingPoolCollateralManagerUpdated(address indexed newAddress); event PriceOracleUpdated(address indexed newAddress); event LendingRateOracleUpdated(address indexed newAddress); event ProxyCreated(bytes32 id, address indexed newAddress); event AddressSet(bytes32 id, address indexed newAddress, bool hasProxy); function getMarketId() external view returns (string memory); function setMarketId(string calldata marketId) external; function setAddress(bytes32 id, address newAddress) external; function setAddressAsProxy(bytes32 id, address impl) external; function getAddress(bytes32 id) external view returns (address); function getLendingPool() external view returns (address); function setLendingPoolImpl(address pool) external; function getLendingPoolConfigurator() external view returns (address); function setLendingPoolConfiguratorImpl(address configurator) external; function getLendingPoolCollateralManager() external view returns (address); function setLendingPoolCollateralManager(address manager) external; function getPoolAdmin() external view returns (address); function setPoolAdmin(address admin) external; function getEmergencyAdmin() external view returns (address); function setEmergencyAdmin(address admin) external; function getPriceOracle() external view returns (address); function setPriceOracle(address priceOracle) external; function getLendingRateOracle() external view returns (address); function setLendingRateOracle(address lendingRateOracle) external; } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; interface IAAMPL { function initializeDebtTokens() external; } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import {ILendingPoolAddressesProvider} from './ILendingPoolAddressesProvider.sol'; import {DataTypes} from '../lib/DataTypes.sol'; interface ILendingPool { /** * @dev Emitted on deposit() * @param reserve The address of the underlying asset of the reserve * @param user The address initiating the deposit * @param onBehalfOf The beneficiary of the deposit, receiving the aTokens * @param amount The amount deposited * @param referral The referral code used **/ event Deposit( address indexed reserve, address user, address indexed onBehalfOf, uint256 amount, uint16 indexed referral ); /** * @dev Emitted on withdraw() * @param reserve The address of the underlyng asset being withdrawn * @param user The address initiating the withdrawal, owner of aTokens * @param to Address that will receive the underlying * @param amount The amount to be withdrawn **/ event Withdraw(address indexed reserve, address indexed user, address indexed to, uint256 amount); /** * @dev Emitted on borrow() and flashLoan() when debt needs to be opened * @param reserve The address of the underlying asset being borrowed * @param user The address of the user initiating the borrow(), receiving the funds on borrow() or just * initiator of the transaction on flashLoan() * @param onBehalfOf The address that will be getting the debt * @param amount The amount borrowed out * @param borrowRateMode The rate mode: 1 for Stable, 2 for Variable * @param borrowRate The numeric rate at which the user has borrowed * @param referral The referral code used **/ event Borrow( address indexed reserve, address user, address indexed onBehalfOf, uint256 amount, uint256 borrowRateMode, uint256 borrowRate, uint16 indexed referral ); /** * @dev Emitted on repay() * @param reserve The address of the underlying asset of the reserve * @param user The beneficiary of the repayment, getting his debt reduced * @param repayer The address of the user initiating the repay(), providing the funds * @param amount The amount repaid **/ event Repay( address indexed reserve, address indexed user, address indexed repayer, uint256 amount ); /** * @dev Emitted on swapBorrowRateMode() * @param reserve The address of the underlying asset of the reserve * @param user The address of the user swapping his rate mode * @param rateMode The rate mode that the user wants to swap to **/ event Swap(address indexed reserve, address indexed user, uint256 rateMode); /** * @dev Emitted on setUserUseReserveAsCollateral() * @param reserve The address of the underlying asset of the reserve * @param user The address of the user enabling the usage as collateral **/ event ReserveUsedAsCollateralEnabled(address indexed reserve, address indexed user); /** * @dev Emitted on setUserUseReserveAsCollateral() * @param reserve The address of the underlying asset of the reserve * @param user The address of the user enabling the usage as collateral **/ event ReserveUsedAsCollateralDisabled(address indexed reserve, address indexed user); /** * @dev Emitted on rebalanceStableBorrowRate() * @param reserve The address of the underlying asset of the reserve * @param user The address of the user for which the rebalance has been executed **/ event RebalanceStableBorrowRate(address indexed reserve, address indexed user); /** * @dev Emitted on flashLoan() * @param target The address of the flash loan receiver contract * @param initiator The address initiating the flash loan * @param asset The address of the asset being flash borrowed * @param amount The amount flash borrowed * @param premium The fee flash borrowed * @param referralCode The referral code used **/ event FlashLoan( address indexed target, address indexed initiator, address indexed asset, uint256 amount, uint256 premium, uint16 referralCode ); /** * @dev Emitted when the pause is triggered. */ event Paused(); /** * @dev Emitted when the pause is lifted. */ event Unpaused(); /** * @dev Emitted when a borrower is liquidated. This event is emitted by the LendingPool via * LendingPoolCollateral manager using a DELEGATECALL * This allows to have the events in the generated ABI for LendingPool. * @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation * @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation * @param user The address of the borrower getting liquidated * @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover * @param liquidatedCollateralAmount The amount of collateral received by the liiquidator * @param liquidator The address of the liquidator * @param receiveAToken `true` if the liquidators wants to receive the collateral aTokens, `false` if he wants * to receive the underlying collateral asset directly **/ event LiquidationCall( address indexed collateralAsset, address indexed debtAsset, address indexed user, uint256 debtToCover, uint256 liquidatedCollateralAmount, address liquidator, bool receiveAToken ); /** * @dev Emitted when the state of a reserve is updated. NOTE: This event is actually declared * in the ReserveLogic library and emitted in the updateInterestRates() function. Since the function is internal, * the event will actually be fired by the LendingPool contract. The event is therefore replicated here so it * gets added to the LendingPool ABI * @param reserve The address of the underlying asset of the reserve * @param liquidityRate The new liquidity rate * @param stableBorrowRate The new stable borrow rate * @param variableBorrowRate The new variable borrow rate * @param liquidityIndex The new liquidity index * @param variableBorrowIndex The new variable borrow index **/ event ReserveDataUpdated( address indexed reserve, uint256 liquidityRate, uint256 stableBorrowRate, uint256 variableBorrowRate, uint256 liquidityIndex, uint256 variableBorrowIndex ); /** * @dev Deposits an `amount` of underlying asset into the reserve, receiving in return overlying aTokens. * - E.g. User deposits 100 USDC and gets in return 100 aUSDC * @param asset The address of the underlying asset to deposit * @param amount The amount to be deposited * @param onBehalfOf The address that will receive the aTokens, same as msg.sender if the user * wants to receive them on his own wallet, or a different address if the beneficiary of aTokens * is a different wallet * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man **/ function deposit( address asset, uint256 amount, address onBehalfOf, uint16 referralCode ) external; /** * @dev Withdraws an `amount` of underlying asset from the reserve, burning the equivalent aTokens owned * E.g. User has 100 aUSDC, calls withdraw() and receives 100 USDC, burning the 100 aUSDC * @param asset The address of the underlying asset to withdraw * @param amount The underlying amount to be withdrawn * - Send the value type(uint256).max in order to withdraw the whole aToken balance * @param to Address that will receive the underlying, same as msg.sender if the user * wants to receive it on his own wallet, or a different address if the beneficiary is a * different wallet * @return The final amount withdrawn **/ function withdraw( address asset, uint256 amount, address to ) external returns (uint256); /** * @dev Allows users to borrow a specific `amount` of the reserve underlying asset, provided that the borrower * already deposited enough collateral, or he was given enough allowance by a credit delegator on the * corresponding debt token (StableDebtToken or VariableDebtToken) * - E.g. User borrows 100 USDC passing as `onBehalfOf` his own address, receiving the 100 USDC in his wallet * and 100 stable/variable debt tokens, depending on the `interestRateMode` * @param asset The address of the underlying asset to borrow * @param amount The amount to be borrowed * @param interestRateMode The interest rate mode at which the user wants to borrow: 1 for Stable, 2 for Variable * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man * @param onBehalfOf Address of the user who will receive the debt. Should be the address of the borrower itself * calling the function if he wants to borrow against his own collateral, or the address of the credit delegator * if he has been given credit delegation allowance **/ function borrow( address asset, uint256 amount, uint256 interestRateMode, uint16 referralCode, address onBehalfOf ) external; /** * @notice Repays a borrowed `amount` on a specific reserve, burning the equivalent debt tokens owned * - E.g. User repays 100 USDC, burning 100 variable/stable debt tokens of the `onBehalfOf` address * @param asset The address of the borrowed underlying asset previously borrowed * @param amount The amount to repay * - Send the value type(uint256).max in order to repay the whole debt for `asset` on the specific `debtMode` * @param rateMode The interest rate mode at of the debt the user wants to repay: 1 for Stable, 2 for Variable * @param onBehalfOf Address of the user who will get his debt reduced/removed. Should be the address of the * user calling the function if he wants to reduce/remove his own debt, or the address of any other * other borrower whose debt should be removed * @return The final amount repaid **/ function repay( address asset, uint256 amount, uint256 rateMode, address onBehalfOf ) external returns (uint256); /** * @dev Allows a borrower to swap his debt between stable and variable mode, or viceversa * @param asset The address of the underlying asset borrowed * @param rateMode The rate mode that the user wants to swap to **/ function swapBorrowRateMode(address asset, uint256 rateMode) external; /** * @dev Rebalances the stable interest rate of a user to the current stable rate defined on the reserve. * - Users can be rebalanced if the following conditions are satisfied: * 1. Usage ratio is above 95% * 2. the current deposit APY is below REBALANCE_UP_THRESHOLD * maxVariableBorrowRate, which means that too much has been * borrowed at a stable rate and depositors are not earning enough * @param asset The address of the underlying asset borrowed * @param user The address of the user to be rebalanced **/ function rebalanceStableBorrowRate(address asset, address user) external; /** * @dev Allows depositors to enable/disable a specific deposited asset as collateral * @param asset The address of the underlying asset deposited * @param useAsCollateral `true` if the user wants to use the deposit as collateral, `false` otherwise **/ function setUserUseReserveAsCollateral(address asset, bool useAsCollateral) external; /** * @dev Function to liquidate a non-healthy position collateral-wise, with Health Factor below 1 * - The caller (liquidator) covers `debtToCover` amount of debt of the user getting liquidated, and receives * a proportionally amount of the `collateralAsset` plus a bonus to cover market risk * @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation * @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation * @param user The address of the borrower getting liquidated * @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover * @param receiveAToken `true` if the liquidators wants to receive the collateral aTokens, `false` if he wants * to receive the underlying collateral asset directly **/ function liquidationCall( address collateralAsset, address debtAsset, address user, uint256 debtToCover, bool receiveAToken ) external; /** * @dev Allows smartcontracts to access the liquidity of the pool within one transaction, * as long as the amount taken plus a fee is returned. * IMPORTANT There are security concerns for developers of flashloan receiver contracts that must be kept into consideration. * For further details please visit https://developers.aave.com * @param receiverAddress The address of the contract receiving the funds, implementing the IFlashLoanReceiver interface * @param assets The addresses of the assets being flash-borrowed * @param amounts The amounts amounts being flash-borrowed * @param modes Types of the debt to open if the flash loan is not returned: * 0 -> Don't open any debt, just revert if funds can't be transferred from the receiver * 1 -> Open debt at stable rate for the value of the amount flash-borrowed to the `onBehalfOf` address * 2 -> Open debt at variable rate for the value of the amount flash-borrowed to the `onBehalfOf` address * @param onBehalfOf The address that will receive the debt in the case of using on `modes` 1 or 2 * @param params Variadic packed params to pass to the receiver as extra information * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man **/ function flashLoan( address receiverAddress, address[] calldata assets, uint256[] calldata amounts, uint256[] calldata modes, address onBehalfOf, bytes calldata params, uint16 referralCode ) external; /** * @dev Returns the user account data across all the reserves * @param user The address of the user * @return totalCollateralETH the total collateral in ETH of the user * @return totalDebtETH the total debt in ETH of the user * @return availableBorrowsETH the borrowing power left of the user * @return currentLiquidationThreshold the liquidation threshold of the user * @return ltv the loan to value of the user * @return healthFactor the current health factor of the user **/ function getUserAccountData(address user) external view returns ( uint256 totalCollateralETH, uint256 totalDebtETH, uint256 availableBorrowsETH, uint256 currentLiquidationThreshold, uint256 ltv, uint256 healthFactor ); function initReserve( address reserve, address aTokenAddress, address stableDebtAddress, address variableDebtAddress, address interestRateStrategyAddress ) external; function setReserveInterestRateStrategyAddress(address reserve, address rateStrategyAddress) external; function setConfiguration(address reserve, uint256 configuration) external; /** * @dev Returns the configuration of the reserve * @param asset The address of the underlying asset of the reserve * @return The configuration of the reserve **/ function getConfiguration(address asset) external view returns (DataTypes.ReserveConfigurationMap memory); /** * @dev Returns the configuration of the user across all the reserves * @param user The user address * @return The configuration of the user **/ function getUserConfiguration(address user) external view returns (DataTypes.UserConfigurationMap memory); /** * @dev Returns the normalized income normalized income of the reserve * @param asset The address of the underlying asset of the reserve * @return The reserve's normalized income */ function getReserveNormalizedIncome(address asset) external view returns (uint256); /** * @dev Returns the normalized variable debt per unit of asset * @param asset The address of the underlying asset of the reserve * @return The reserve normalized variable debt */ function getReserveNormalizedVariableDebt(address asset) external view returns (uint256); /** * @dev Returns the state and configuration of the reserve * @param asset The address of the underlying asset of the reserve * @return The state of the reserve **/ function getReserveData(address asset) external view returns (DataTypes.ReserveData memory); function finalizeTransfer( address asset, address from, address to, uint256 amount, uint256 balanceFromAfter, uint256 balanceToBefore ) external; function getReservesList() external view returns (address[] memory); function getAddressesProvider() external view returns (ILendingPoolAddressesProvider); function setPause(bool val) external; function paused() external view returns (bool); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; library DataTypes { // refer to the whitepaper, section 1.1 basic concepts for a formal description of these properties. struct ReserveData { //stores the reserve configuration ReserveConfigurationMap configuration; //the liquidity index. Expressed in ray uint128 liquidityIndex; //variable borrow index. Expressed in ray uint128 variableBorrowIndex; //the current supply rate. Expressed in ray uint128 currentLiquidityRate; //the current variable borrow rate. Expressed in ray uint128 currentVariableBorrowRate; //the current stable borrow rate. Expressed in ray uint128 currentStableBorrowRate; uint40 lastUpdateTimestamp; //tokens addresses address aTokenAddress; address stableDebtTokenAddress; address variableDebtTokenAddress; //address of the interest rate strategy address interestRateStrategyAddress; //the id of the reserve. Represents the position in the list of the active reserves uint8 id; } struct ReserveConfigurationMap { //bit 0-15: LTV //bit 16-31: Liq. threshold //bit 32-47: Liq. bonus //bit 48-55: Decimals //bit 56: Reserve is active //bit 57: reserve is frozen //bit 58: borrowing is enabled //bit 59: stable rate borrowing enabled //bit 60-63: reserved //bit 64-79: reserve factor uint256 data; } struct UserConfigurationMap { uint256 data; } enum InterestRateMode {NONE, STABLE, VARIABLE} } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import {IERC20} from './interfaces/IERC20.sol'; import {ILendingPoolConfiguratorV2} from './interfaces/ILendingPoolConfiguratorV2.sol'; import {IOverlyingAsset} from './interfaces/IOverlyingAsset.sol'; import {ILendingPoolAddressesProvider} from './interfaces/ILendingPoolAddressesProvider.sol'; import {IAAMPL} from './interfaces/IAAMPL.sol'; import {ILendingPool, DataTypes} from './interfaces/ILendingPool.sol'; /** * @title AssetListingProposalGenericExecutor * @notice Proposal payload to be executed by the Aave Governance contract via DELEGATECALL * @author Aave **/ contract AIP26AMPL { event ProposalExecuted(); // Mainnet ILendingPoolAddressesProvider public constant LENDING_POOL_ADDRESSES_PROVIDER = ILendingPoolAddressesProvider(0xB53C1a33016B2DC2fF3653530bfF1848a515c8c5); address public constant token = 0xD46bA6D942050d489DBd938a2C909A5d5039A161; address public constant interestStrategy = 0x509859687725398587147Dd7A2c88d7316f92b02; /** * @dev Payload execution function, called once a proposal passed in the Aave governance */ function execute() external { ILendingPoolConfiguratorV2 LENDING_POOL_CONFIGURATOR_V2 = ILendingPoolConfiguratorV2(LENDING_POOL_ADDRESSES_PROVIDER.getLendingPoolConfigurator()); LENDING_POOL_CONFIGURATOR_V2.setReserveInterestRateStrategyAddress(token, interestStrategy); emit ProposalExecuted(); } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.6.12; import {IERC20} from './interfaces/IERC20.sol'; import {ILendingPoolConfiguratorV2} from './interfaces/ILendingPoolConfiguratorV2.sol'; import {IProposalGenericExecutor} from './interfaces/IProposalGenericExecutor.sol'; import {IOverlyingAsset} from './interfaces/IOverlyingAsset.sol'; import {ILendingPoolAddressesProvider} from './interfaces/ILendingPoolAddressesProvider.sol'; /** * @title AssetListingProposalGenericExecutor * @notice Proposal payload to be executed by the Aave Governance contract via DELEGATECALL * @author Aave **/ contract AssetListingProposalGenericExecutor is IProposalGenericExecutor { event ProposalExecuted(); ILendingPoolAddressesProvider public constant LENDING_POOL_ADDRESSES_PROVIDER = ILendingPoolAddressesProvider(0xB53C1a33016B2DC2fF3653530bfF1848a515c8c5); /** * @dev Payload execution function, called once a proposal passed in the Aave governance */ function execute( address token, address aToken, address stableDebtToken, address variablDebtToken, address interestStrategy, uint256 ltv, uint256 liquidationThreshold, uint256 liquidationBonus, uint256 reserveFactor, uint8 decimals, bool enableBorrow, bool enableStableBorrow, bool enableAsCollateral ) external override { ILendingPoolConfiguratorV2 LENDING_POOL_CONFIGURATOR_V2 = ILendingPoolConfiguratorV2(LENDING_POOL_ADDRESSES_PROVIDER.getLendingPoolConfigurator()); require( token == IOverlyingAsset(aToken).UNDERLYING_ASSET_ADDRESS(), 'ATOKEN: WRONG_UNDERLYING_TOKEN' ); require( token == IOverlyingAsset(stableDebtToken).UNDERLYING_ASSET_ADDRESS(), 'STABLE_DEBT: WRONG_UNDERLYING_TOKEN' ); require( token == IOverlyingAsset(variablDebtToken).UNDERLYING_ASSET_ADDRESS(), 'VARIABLE_DEBT: WRONG_UNDERLYING_TOKEN' ); LENDING_POOL_CONFIGURATOR_V2.initReserve( aToken, stableDebtToken, variablDebtToken, decimals, interestStrategy ); if (enableBorrow) { LENDING_POOL_CONFIGURATOR_V2.enableBorrowingOnReserve(token, enableStableBorrow); } LENDING_POOL_CONFIGURATOR_V2.setReserveFactor(token, reserveFactor); if (enableAsCollateral) { LENDING_POOL_CONFIGURATOR_V2.configureReserveAsCollateral( token, ltv, liquidationThreshold, liquidationBonus ); } emit ProposalExecuted(); } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.6.12; interface IProposalGenericExecutor { function execute( address token, address aToken, address stableDebtToken, address variablDebtToken, address interestStrategy, uint256 ltv, uint256 liquidationThreshold, uint256 liquidationBonus, uint256 reserveFactor, uint8 decimals, bool enableBorrow, bool enableBorrowOnReserve, bool enableAsCollateral ) external; }
Interface of the ERC20 standard as defined in the EIP./
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); function decimals() external view returns (uint8); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); pragma solidity 0.6.12; }
5,711,934
// SPDX-License-Identifier: MIT pragma solidity ^0.8.11; // This is only kept for backward compatability / upgrading import {OwnableUpgradeable} from "../oz/access/OwnableUpgradeable.sol"; import {EnumerableMapUpgradeable, ERC721PausableUpgradeable, IERC721Upgradeable, ERC721Upgradeable} from "../oz/token/ERC721/ERC721PausableUpgradeable.sol"; import {IRegistrar} from "../interfaces/IRegistrar.sol"; import {StorageSlot} from "../oz/utils/StorageSlot.sol"; import {BeaconProxy} from "../oz/proxy/beacon/BeaconProxy.sol"; import {IZNSHub} from "../interfaces/IZNSHub.sol"; contract Registrar is IRegistrar, OwnableUpgradeable, ERC721PausableUpgradeable { using EnumerableMapUpgradeable for EnumerableMapUpgradeable.UintToAddressMap; // Data recorded for each domain struct DomainRecord { address minter; bool metadataLocked; address metadataLockedBy; address controller; uint256 royaltyAmount; uint256 parentId; address subdomainContract; } // A map of addresses that are authorised to register domains. mapping(address => bool) public controllers; // A mapping of domain id's to domain data // This essentially expands the internal ERC721's token storage to additional fields mapping(uint256 => DomainRecord) public records; /** * @dev Storage slot with the admin of the contract. */ bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; // The beacon address address public beacon; // If this is a subdomain contract these will be set uint256 public rootDomainId; address public parentRegistrar; // The event emitter IZNSHub public zNSHub; uint8 private test; // ignore uint256 private gap; // ignore function _getAdmin() internal view returns (address) { return StorageSlot.getAddressSlot(_ADMIN_SLOT).value; } modifier onlyController() { if (!controllers[msg.sender] && !zNSHub.isController(msg.sender)) { revert("ZR: Not controller"); } _; } modifier onlyOwnerOf(uint256 id) { require(ownerOf(id) == msg.sender, "ZR: Not owner"); _; } function initialize( address parentRegistrar_, uint256 rootDomainId_, string calldata collectionName, string calldata collectionSymbol, address zNSHub_ ) public initializer { // __Ownable_init(); // Purposely not initializing ownable since we override owner() if (parentRegistrar_ == address(0)) { // create the root domain _createDomain(0, 0, msg.sender, address(0)); } else { rootDomainId = rootDomainId_; parentRegistrar = parentRegistrar_; } zNSHub = IZNSHub(zNSHub_); __ERC721Pausable_init(); __ERC721_init(collectionName, collectionSymbol); } // Used to upgrade existing registrar to new registrar function upgradeFromNormalRegistrar(address zNSHub_) public { require(msg.sender == _getAdmin(), "Not Proxy Admin"); zNSHub = IZNSHub(zNSHub_); } function owner() public view override returns (address) { return zNSHub.owner(); } /* * External Methods */ /** * @notice Authorizes a controller to control the registrar * @param controller The address of the controller */ function addController(address controller) external { require( msg.sender == owner() || msg.sender == parentRegistrar, "ZR: Not authorized" ); require(!controllers[controller], "ZR: Controller is already added"); controllers[controller] = true; emit ControllerAdded(controller); } /** * @notice Unauthorizes a controller to control the registrar * @param controller The address of the controller */ function removeController(address controller) external override onlyOwner { require( msg.sender == owner() || msg.sender == parentRegistrar, "ZR: Not authorized" ); require(controllers[controller], "ZR: Controller does not exist"); controllers[controller] = false; emit ControllerRemoved(controller); } /** * @notice Pauses the registrar. Can only be done when not paused. */ function pause() external onlyOwner { _pause(); } /** * @notice Unpauses the registrar. Can only be done when not paused. */ function unpause() external onlyOwner { _unpause(); } /** * @notice Registers a new (sub) domain * @param parentId The parent domain * @param label The label of the domain * @param minter the minter of the new domain * @param metadataUri The uri of the metadata * @param royaltyAmount The amount of royalty this domain pays * @param locked Whether the domain is locked or not */ function registerDomain( uint256 parentId, string memory label, address minter, string memory metadataUri, uint256 royaltyAmount, bool locked ) external override onlyController returns (uint256) { return _registerDomain( parentId, label, minter, metadataUri, royaltyAmount, locked ); } function registerDomainAndSend( uint256 parentId, string memory label, address minter, string memory metadataUri, uint256 royaltyAmount, bool locked, address sendToUser ) external override onlyController returns (uint256) { // Register the domain uint256 id = _registerDomain( parentId, label, minter, metadataUri, royaltyAmount, locked ); // immediately send domain to user _safeTransfer(minter, sendToUser, id, ""); return id; } function registerSubdomainContract( uint256 parentId, string memory label, address minter, string memory metadataUri, uint256 royaltyAmount, bool locked, address sendToUser ) external onlyController returns (uint256) { // Register domain, `minter` is the minter uint256 id = _registerDomain( parentId, label, minter, metadataUri, royaltyAmount, locked ); // Create subdomain contract as a beacon proxy address subdomainContract = address( new BeaconProxy(zNSHub.registrarBeacon(), "") ); // More maintainable instead of using `data` in constructor Registrar(subdomainContract).initialize( address(this), id, "Zer0 Name Service", "ZNS", address(zNSHub) ); // Indicate that the subdomain has a contract records[id].subdomainContract = subdomainContract; zNSHub.addRegistrar(id, subdomainContract); // immediately send the domain to the user (from the minter) _safeTransfer(minter, sendToUser, id, ""); return id; } function _registerDomain( uint256 parentId, string memory label, address minter, string memory metadataUri, uint256 royaltyAmount, bool locked ) internal returns (uint256) { require(bytes(label).length > 0, "ZR: Empty name"); // subdomain cannot be minted on domains which are subdomain contracts require( records[parentId].subdomainContract == address(0), "ZR: Parent is subcontract" ); if (parentId != rootDomainId) { // Domain parents must exist require(_exists(parentId), "ZR: No parent"); } // Create the child domain under the parent domain uint256 labelHash = uint256(keccak256(bytes(label))); address controller = msg.sender; // Calculate the new domain's id and create it uint256 domainId = uint256( keccak256(abi.encodePacked(parentId, labelHash)) ); _createDomain(parentId, domainId, minter, controller); _setTokenURI(domainId, metadataUri); if (locked) { records[domainId].metadataLockedBy = minter; records[domainId].metadataLocked = true; } if (royaltyAmount > 0) { records[domainId].royaltyAmount = royaltyAmount; } zNSHub.domainCreated( domainId, label, labelHash, parentId, minter, controller, metadataUri, royaltyAmount ); return domainId; } /** * @notice Sets the domain royalty amount * @param id The domain to set on * @param amount The royalty amount */ function setDomainRoyaltyAmount(uint256 id, uint256 amount) external override onlyOwnerOf(id) { require(!isDomainMetadataLocked(id), "ZR: Metadata locked"); records[id].royaltyAmount = amount; zNSHub.royaltiesAmountChanged(id, amount); } /** * @notice Both sets and locks domain metadata uri in a single call * @param id The domain to lock * @param uri The uri to set */ function setAndLockDomainMetadata(uint256 id, string memory uri) external override onlyOwnerOf(id) { require(!isDomainMetadataLocked(id), "ZR: Metadata locked"); _setDomainMetadataUri(id, uri); _setDomainLock(id, msg.sender, true); } /** * @notice Sets the domain metadata uri * @param id The domain to set on * @param uri The uri to set */ function setDomainMetadataUri(uint256 id, string memory uri) external override onlyOwnerOf(id) { require(!isDomainMetadataLocked(id), "ZR: Metadata locked"); _setDomainMetadataUri(id, uri); } /** * @notice Locks a domains metadata uri * @param id The domain to lock * @param toLock whether the domain should be locked or not */ function lockDomainMetadata(uint256 id, bool toLock) external override { _validateLockDomainMetadata(id, toLock); _setDomainLock(id, msg.sender, toLock); } /* * Public View */ function ownerOf(uint256 tokenId) public view virtual override(ERC721Upgradeable, IERC721Upgradeable) returns (address) { // Check if the token is in this contract if (_tokenOwners.contains(tokenId)) { return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token"); } return zNSHub.ownerOf(tokenId); } /** * @notice Returns whether or not an account is a a controller registered on this contract * @param account Address of account to check */ function isController(address account) external view override returns (bool) { bool accountIsController = controllers[account]; return accountIsController; } /** * @notice Returns whether or not a domain is exists * @param id The domain */ function domainExists(uint256 id) public view override returns (bool) { bool domainNftExists = _exists(id); return domainNftExists; } /** * @notice Returns the original minter of a domain * @param id The domain */ function minterOf(uint256 id) public view override returns (address) { address minter = records[id].minter; return minter; } /** * @notice Returns whether or not a domain's metadata is locked * @param id The domain */ function isDomainMetadataLocked(uint256 id) public view override returns (bool) { bool isLocked = records[id].metadataLocked; return isLocked; } /** * @notice Returns who locked a domain's metadata * @param id The domain */ function domainMetadataLockedBy(uint256 id) public view override returns (address) { address lockedBy = records[id].metadataLockedBy; return lockedBy; } /** * @notice Returns the controller which created the domain on behalf of a user * @param id The domain */ function domainController(uint256 id) public view override returns (address) { address controller = records[id].controller; return controller; } /** * @notice Returns the current royalty amount for a domain * @param id The domain */ function domainRoyaltyAmount(uint256 id) public view override returns (uint256) { uint256 amount = records[id].royaltyAmount; return amount; } /** * @notice Returns the parent id of a domain. * @param id The domain */ function parentOf(uint256 id) public view override returns (uint256) { require(_exists(id), "ZR: Does not exist"); uint256 parentId = records[id].parentId; return parentId; } /* * Internal Methods */ function _transfer( address from, address to, uint256 tokenId ) internal virtual override { super._transfer(from, to, tokenId); // Need to emit transfer events on event emitter zNSHub.domainTransferred(from, to, tokenId); } function _setDomainMetadataUri(uint256 id, string memory uri) internal { _setTokenURI(id, uri); zNSHub.metadataChanged(id, uri); } function _validateLockDomainMetadata(uint256 id, bool toLock) internal view { if (toLock) { require(ownerOf(id) == msg.sender, "ZR: Not owner"); require(!isDomainMetadataLocked(id), "ZR: Metadata locked"); } else { require(isDomainMetadataLocked(id), "ZR: Not locked"); require(domainMetadataLockedBy(id) == msg.sender, "ZR: Not locker"); } } // internal - creates a domain function _createDomain( uint256 parentId, uint256 domainId, address minter, address controller ) internal { // Create the NFT and register the domain data _mint(minter, domainId); records[domainId] = DomainRecord({ parentId: parentId, minter: minter, metadataLocked: false, metadataLockedBy: address(0), controller: controller, royaltyAmount: 0, subdomainContract: address(0) }); } function _setDomainLock( uint256 id, address locker, bool lockStatus ) internal { records[id].metadataLockedBy = locker; records[id].metadataLocked = lockStatus; zNSHub.metadataLockChanged(id, locker, lockStatus); } function adminBurnToken(uint256 tokenId) external onlyOwner { _burn(tokenId); delete (records[tokenId]); } function adminTransfer( address from, address to, uint256 tokenId ) external onlyOwner { _transfer(from, to, tokenId); } function adminSetMetadataUri(uint256 id, string memory uri) external onlyOwner { _setDomainMetadataUri(id, uri); } function registerDomainAndSendBulk( uint256 parentId, uint256 namingOffset, // e.g., the IPFS node refers to the metadata as x. the zNS label will be x + namingOffset uint256 startingIndex, uint256 endingIndex, address minter, string memory folderWithIPFSPrefix, // e.g., ipfs://Qm.../ uint256 royaltyAmount, bool locked ) external onlyController { require(endingIndex - startingIndex > 0, "Invalid number of domains"); uint256 result; for (uint256 i = startingIndex; i < endingIndex; i++) { result = _registerDomain( parentId, uint2str(i + namingOffset), minter, string(abi.encodePacked(folderWithIPFSPrefix, uint2str(i))), royaltyAmount, locked ); } } function uint2str(uint256 _i) internal pure returns (string memory _uintAsString) { if (_i == 0) { return "0"; } uint256 j = _i; uint256 len; while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint256 k = len; while (_i != 0) { k = k - 1; uint8 temp = (48 + uint8(_i - (_i / 10) * 10)); bytes1 b1 = bytes1(temp); bstr[k] = b1; _i /= 10; } return string(bstr); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.9; import "../utils/ContextUpgradeable.sol"; import "../proxy/Initializable.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 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 initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { 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; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.9; import "./ERC721Upgradeable.sol"; import "../../utils/PausableUpgradeable.sol"; import "../../proxy/Initializable.sol"; /** * @dev ERC721 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 ERC721PausableUpgradeable is Initializable, ERC721Upgradeable, PausableUpgradeable { function __ERC721Pausable_init() internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __Pausable_init_unchained(); __ERC721Pausable_init_unchained(); } function __ERC721Pausable_init_unchained() internal initializer {} /** * @dev See {ERC721-_beforeTokenTransfer}. * * Requirements: * * - the contract must not be paused. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); require(!paused(), "ERC721Pausable: token transfer while paused"); } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.9; import "../oz/token/ERC721/IERC721EnumerableUpgradeable.sol"; import "../oz/token/ERC721/IERC721MetadataUpgradeable.sol"; interface IRegistrar is IERC721MetadataUpgradeable, IERC721EnumerableUpgradeable { // Emitted when a controller is removed event ControllerAdded(address indexed controller); // Emitted whenever a controller is removed event ControllerRemoved(address indexed controller); // Emitted whenever a new domain is created event DomainCreated( uint256 indexed id, string label, uint256 indexed labelHash, uint256 indexed parent, address minter, address controller, string metadataUri, uint256 royaltyAmount ); // Emitted whenever the metadata of a domain is locked event MetadataLockChanged(uint256 indexed id, address locker, bool isLocked); // Emitted whenever the metadata of a domain is changed event MetadataChanged(uint256 indexed id, string uri); // Emitted whenever the royalty amount is changed event RoyaltiesAmountChanged(uint256 indexed id, uint256 amount); // Authorises a controller, who can register domains. function addController(address controller) external; // Revoke controller permission for an address. function removeController(address controller) external; // Registers a new sub domain function registerDomain( uint256 parentId, string memory label, address minter, string memory metadataUri, uint256 royaltyAmount, bool locked ) external returns (uint256); function registerDomainAndSend( uint256 parentId, string memory label, address minter, string memory metadataUri, uint256 royaltyAmount, bool locked, address sendToUser ) external returns (uint256); function registerSubdomainContract( uint256 parentId, string memory label, address minter, string memory metadataUri, uint256 royaltyAmount, bool locked, address sendToUser ) external returns (uint256); // Set a domains metadata uri and lock that domain from being modified function setAndLockDomainMetadata(uint256 id, string memory uri) external; // Lock a domain's metadata so that it cannot be changed function lockDomainMetadata(uint256 id, bool toLock) external; // Update a domain's metadata uri function setDomainMetadataUri(uint256 id, string memory uri) external; // Sets the asked royalty amount on a domain (amount is a percentage with 5 decimal places) function setDomainRoyaltyAmount(uint256 id, uint256 amount) external; // Returns whether an address is a controller function isController(address account) external view returns (bool); // Checks whether or not a domain exists function domainExists(uint256 id) external view returns (bool); // Returns the original minter of a domain function minterOf(uint256 id) external view returns (address); // Checks if a domains metadata is locked function isDomainMetadataLocked(uint256 id) external view returns (bool); // Returns the address which locked the domain metadata function domainMetadataLockedBy(uint256 id) external view returns (address); // Gets the controller that registered a domain function domainController(uint256 id) external view returns (address); // Gets a domains current royalty amount function domainRoyaltyAmount(uint256 id) external view returns (uint256); // Returns the parent domain of a child domain function parentOf(uint256 id) external view returns (uint256); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/StorageSlot.sol) pragma solidity ^0.8.0; /** * @dev Library for reading and writing primitive types to specific storage slots. * * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts. * This library helps with reading and writing to such slots without the need for inline assembly. * * The functions in this library return Slot structs that contain a `value` member that can be used to read or write. * * Example usage to set ERC1967 implementation slot: * ``` * contract ERC1967 { * bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; * * function _getImplementation() internal view returns (address) { * return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value; * } * * function _setImplementation(address newImplementation) internal { * require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract"); * StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; * } * } * ``` * * _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._ */ library StorageSlot { struct AddressSlot { address value; } struct BooleanSlot { bool value; } struct Bytes32Slot { bytes32 value; } struct Uint256Slot { uint256 value; } /** * @dev Returns an `AddressSlot` with member `value` located at `slot`. */ function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `BooleanSlot` with member `value` located at `slot`. */ function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Bytes32Slot` with member `value` located at `slot`. */ function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Uint256Slot` with member `value` located at `slot`. */ function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) { assembly { r.slot := slot } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (proxy/beacon/BeaconProxy.sol) pragma solidity ^0.8.0; import "./IBeacon.sol"; import "../Proxy.sol"; import "../ERC1967/ERC1967Upgrade.sol"; /** * @dev This contract implements a proxy that gets the implementation address for each call from a {UpgradeableBeacon}. * * The beacon address is stored in storage slot `uint256(keccak256('eip1967.proxy.beacon')) - 1`, so that it doesn't * conflict with the storage layout of the implementation behind the proxy. * * _Available since v3.4._ */ contract BeaconProxy is Proxy, ERC1967Upgrade { /** * @dev Initializes the proxy with `beacon`. * * If `data` is nonempty, it's used as data in a delegate call to the implementation returned by the beacon. This * will typically be an encoded function call, and allows initializating the storage of the proxy like a Solidity * constructor. * * Requirements: * * - `beacon` must be a contract with the interface {IBeacon}. */ constructor(address beacon, bytes memory data) payable { assert( _BEACON_SLOT == bytes32(uint256(keccak256("eip1967.proxy.beacon")) - 1) ); _upgradeBeaconToAndCall(beacon, data, false); } /** * @dev Returns the current beacon address. */ function _beacon() internal view virtual returns (address) { return _getBeacon(); } /** * @dev Returns the current implementation address of the associated beacon. */ function _implementation() internal view virtual override returns (address) { return IBeacon(_getBeacon()).implementation(); } /** * @dev Changes the proxy to use a new beacon. Deprecated: see {_upgradeBeaconToAndCall}. * * If `data` is nonempty, it's used as data in a delegate call to the implementation returned by the beacon. * * Requirements: * * - `beacon` must be a contract. * - The implementation returned by `beacon` must be a contract. */ function _setBeacon(address beacon, bytes memory data) internal virtual { _upgradeBeaconToAndCall(beacon, data, false); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.9; import {IRegistrar} from "./IRegistrar.sol"; interface IZNSHub { function addRegistrar(uint256 rootDomainId, address registrar) external; function isController(address controller) external returns (bool); function getRegistrarForDomain(uint256 domainId) external view returns (IRegistrar); function ownerOf(uint256 domainId) external view returns (address); function domainExists(uint256 domainId) external view returns (bool); function owner() external view returns (address); function registrarBeacon() external view returns (address); function domainTransferred( address from, address to, uint256 tokenId ) external; function domainCreated( uint256 id, string calldata name, uint256 nameHash, uint256 parent, address minter, address controller, string calldata metadataUri, uint256 royaltyAmount ) external; function metadataLockChanged( uint256 id, address locker, bool isLocked ) external; function metadataChanged(uint256 id, string calldata uri) external; function royaltiesAmountChanged(uint256 id, uint256 amount) external; // Returns the parent domain of a child domain function parentOf(uint256 id) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.9; import "../proxy/Initializable.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 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 ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer {} function _msgSender() internal view virtual returns (address) { 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; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity ^0.8.9; import "../utils/AddressUpgradeable.sol"; /** * @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 {UpgradeableProxy-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 || _isConstructor() || !_initialized, "Initializable: contract is already 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) { return !AddressUpgradeable.isContract(address(this)); } } // SPDX-License-Identifier: MIT 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; // 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); } 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.8.9; import "../../utils/ContextUpgradeable.sol"; import "./IERC721Upgradeable.sol"; import "./IERC721MetadataUpgradeable.sol"; import "./IERC721EnumerableUpgradeable.sol"; import "./IERC721ReceiverUpgradeable.sol"; import "../../introspection/ERC165Upgradeable.sol"; import "../../math/SafeMathUpgradeable.sol"; import "../../utils/AddressUpgradeable.sol"; import "../../utils/EnumerableSetUpgradeable.sol"; import "../../utils/EnumerableMapUpgradeable.sol"; import "../../utils/StringsUpgradeable.sol"; import "../../proxy/Initializable.sol"; /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable, IERC721EnumerableUpgradeable { using SafeMathUpgradeable for uint256; using AddressUpgradeable for address; using EnumerableSetUpgradeable for EnumerableSetUpgradeable.UintSet; using EnumerableMapUpgradeable for EnumerableMapUpgradeable.UintToAddressMap; using StringsUpgradeable 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 => EnumerableSetUpgradeable.UintSet) private _holderTokens; // Enumerable mapping from token ids to their owners EnumerableMapUpgradeable.UintToAddressMap internal _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. */ function __ERC721_init(string memory name_, string memory symbol_) internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __ERC721_init_unchained(name_, symbol_); } function __ERC721_init_unchained(string memory name_, string memory symbol_) internal initializer { _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 = ERC721Upgradeable.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || ERC721Upgradeable.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 = ERC721Upgradeable.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || ERC721Upgradeable.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 = ERC721Upgradeable.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( ERC721Upgradeable.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( IERC721ReceiverUpgradeable(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(ERC721Upgradeable.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 {} uint256[41] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.9; import "./ContextUpgradeable.sol"; import "../proxy/Initializable.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 PausableUpgradeable is Initializable, ContextUpgradeable { /** * @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. */ function __Pausable_init() internal initializer { __Context_init_unchained(); __Pausable_init_unchained(); } function __Pausable_init_unchained() internal initializer { _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()); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.9; import "../../introspection/IERC165Upgradeable.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721Upgradeable is IERC165Upgradeable { /** * @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.9; import "./IERC721Upgradeable.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721MetadataUpgradeable is IERC721Upgradeable { /** * @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.9; import "./IERC721Upgradeable.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721EnumerableUpgradeable is IERC721Upgradeable { /** * @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.9; /** * @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.9; import "./IERC165Upgradeable.sol"; import "../proxy/Initializable.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable { /* * 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; function __ERC165_init() internal initializer { __ERC165_init_unchained(); } function __ERC165_init_unchained() internal initializer { // 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; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.9; /** * @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 SafeMathUpgradeable { /** * @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: MIT pragma solidity ^0.8.9; /** * @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 EnumerableSetUpgradeable { // 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.8.9; /** * @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 EnumerableMapUpgradeable { // 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)))); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.9; /** * @dev String operations. */ library StringsUpgradeable { /** * @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); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.9; /** * @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 IERC165Upgradeable { /** * @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 // OpenZeppelin Contracts v4.4.1 (proxy/beacon/IBeacon.sol) pragma solidity ^0.8.0; /** * @dev This is the interface that {BeaconProxy} expects of its beacon. */ interface IBeacon { /** * @dev Must return an address that can be used as a delegate call target. * * {BeaconProxy} will check that this address is a contract. */ function implementation() external view returns (address); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (proxy/Proxy.sol) pragma solidity ^0.8.0; /** * @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM * instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to * be specified by overriding the virtual {_implementation} function. * * Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a * different contract through the {_delegate} function. * * The success and return data of the delegated call will be returned back to the caller of the proxy. */ abstract contract Proxy { /** * @dev Delegates the current call to `implementation`. * * This function does not return to its internal call site, it will return directly to the external caller. */ function _delegate(address implementation) internal virtual { assembly { // Copy msg.data. We take full control of memory in this inline assembly // block because it will not return to Solidity code. We overwrite the // Solidity scratch pad at memory position 0. calldatacopy(0, 0, calldatasize()) // Call the implementation. // out and outsize are 0 because we don't know the size yet. let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0) // Copy the returned data. returndatacopy(0, 0, returndatasize()) switch result // delegatecall returns 0 on error. case 0 { revert(0, returndatasize()) } default { return(0, returndatasize()) } } } /** * @dev This is a virtual function that should be overriden so it returns the address to which the fallback function * and {_fallback} should delegate. */ function _implementation() internal view virtual returns (address); /** * @dev Delegates the current call to the address returned by `_implementation()`. * * This function does not return to its internall call site, it will return directly to the external caller. */ function _fallback() internal virtual { _beforeFallback(); _delegate(_implementation()); } /** * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other * function in the contract matches the call data. */ fallback() external payable virtual { _fallback(); } /** * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if call data * is empty. */ receive() external payable virtual { _fallback(); } /** * @dev Hook that is called before falling back to the implementation. Can happen as part of a manual `_fallback` * call, or as part of the Solidity `fallback` or `receive` functions. * * If overriden should call `super._beforeFallback()`. */ function _beforeFallback() internal virtual {} } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (proxy/ERC1967/ERC1967Upgrade.sol) pragma solidity ^0.8.2; import "../beacon/IBeacon.sol"; import "../../interfaces/draft-IERC1822.sol"; import "../../utils/Address.sol"; import "../../utils/StorageSlot.sol"; /** * @dev This abstract contract provides getters and event emitting update functions for * https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots. * * _Available since v4.1._ * * @custom:oz-upgrades-unsafe-allow delegatecall */ abstract contract ERC1967Upgrade { // This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1 bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143; /** * @dev Storage slot with the address of the current implementation. * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; /** * @dev Emitted when the implementation is upgraded. */ event Upgraded(address indexed implementation); /** * @dev Returns the current implementation address. */ function _getImplementation() internal view returns (address) { return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value; } /** * @dev Stores a new address in the EIP1967 implementation slot. */ function _setImplementation(address newImplementation) private { require( Address.isContract(newImplementation), "ERC1967: new implementation is not a contract" ); StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; } /** * @dev Perform implementation upgrade * * Emits an {Upgraded} event. */ function _upgradeTo(address newImplementation) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); } /** * @dev Perform implementation upgrade with additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCall( address newImplementation, bytes memory data, bool forceCall ) internal { _upgradeTo(newImplementation); if (data.length > 0 || forceCall) { Address.functionDelegateCall(newImplementation, data); } } /** * @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCallUUPS( address newImplementation, bytes memory data, bool forceCall ) internal { // Upgrades from old implementations will perform a rollback test. This test requires the new // implementation to upgrade back to the old, non-ERC1822 compliant, implementation. Removing // this special case will break upgrade paths from old UUPS implementation to new ones. if (StorageSlot.getBooleanSlot(_ROLLBACK_SLOT).value) { _setImplementation(newImplementation); } else { try IERC1822Proxiable(newImplementation).proxiableUUID() returns ( bytes32 slot ) { require( slot == _IMPLEMENTATION_SLOT, "ERC1967Upgrade: unsupported proxiableUUID" ); } catch { revert("ERC1967Upgrade: new implementation is not UUPS"); } _upgradeToAndCall(newImplementation, data, forceCall); } } /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; /** * @dev Emitted when the admin account has changed. */ event AdminChanged(address previousAdmin, address newAdmin); /** * @dev Returns the current admin. */ function _getAdmin() internal view returns (address) { return StorageSlot.getAddressSlot(_ADMIN_SLOT).value; } /** * @dev Stores a new address in the EIP1967 admin slot. */ function _setAdmin(address newAdmin) private { require(newAdmin != address(0), "ERC1967: new admin is the zero address"); StorageSlot.getAddressSlot(_ADMIN_SLOT).value = newAdmin; } /** * @dev Changes the admin of the proxy. * * Emits an {AdminChanged} event. */ function _changeAdmin(address newAdmin) internal { emit AdminChanged(_getAdmin(), newAdmin); _setAdmin(newAdmin); } /** * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy. * This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor. */ bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50; /** * @dev Emitted when the beacon is upgraded. */ event BeaconUpgraded(address indexed beacon); /** * @dev Returns the current beacon. */ function _getBeacon() internal view returns (address) { return StorageSlot.getAddressSlot(_BEACON_SLOT).value; } /** * @dev Stores a new beacon in the EIP1967 beacon slot. */ function _setBeacon(address newBeacon) private { require( Address.isContract(newBeacon), "ERC1967: new beacon is not a contract" ); require( Address.isContract(IBeacon(newBeacon).implementation()), "ERC1967: beacon implementation is not a contract" ); StorageSlot.getAddressSlot(_BEACON_SLOT).value = newBeacon; } /** * @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does * not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that). * * Emits a {BeaconUpgraded} event. */ function _upgradeBeaconToAndCall( address newBeacon, bytes memory data, bool forceCall ) internal { _setBeacon(newBeacon); emit BeaconUpgraded(newBeacon); if (data.length > 0 || forceCall) { Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data); } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (interfaces/draft-IERC1822.sol) pragma solidity ^0.8.0; /** * @dev ERC1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified * proxy whose upgrades are fully controlled by the current implementation. */ interface IERC1822Proxiable { /** * @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation * address. * * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this * function revert if invoked through a proxy. */ function proxiableUUID() external view returns (bytes32); } // 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); } } } }
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; }
143,825
//SPDX-License-Identifier: MIT pragma solidity =0.7.6; pragma abicoder v2; import {IERC721} from "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol"; import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; import {Address} from "@openzeppelin/contracts/utils/Address.sol"; import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import {IUniswapV3Pool} from "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol"; import {INonfungiblePositionManager} from "@uniswap/v3-periphery/contracts/interfaces/INonfungiblePositionManager.sol"; import {IWETH9} from "../interfaces/IWETH9.sol"; import {IWPowerPerp} from "../interfaces/IWPowerPerp.sol"; import {IShortPowerPerp} from "../interfaces/IShortPowerPerp.sol"; import {IOracle} from "../interfaces/IOracle.sol"; import {VaultLib} from "../libs/VaultLib.sol"; import {Uint256Casting} from "../libs/Uint256Casting.sol"; import {Power2Base} from "../libs/Power2Base.sol"; /** * * Error * C0: Paused * C1: Not paused * C2: Shutdown * C3: Not shutdown * C4: Invalid oracle address * C5: Invalid shortPowerPerp address * C6: Invalid wPowerPerp address * C7: Invalid weth address * C8: Invalid quote currency address * C9: Invalid eth:quoteCurrency pool address * C10: Invalid wPowerPerp:eth pool address * C11: Invalid Uniswap position manager * C12: Can not liquidate safe vault * C13: Invalid address * C14: Set fee recipient first * C15: Fee too high * C16: Paused too many times * C17: Pause time limit exceeded * C18: Not enough paused time has passed * C19: Cannot receive eth * C20: Invalid vault id * C21: Need full liquidation * C22: Dust vault left * C23: Invalid nft * C24: Invalid state * C25: Not allowed */ contract Controller is Ownable, ReentrancyGuard { using SafeMath for uint256; using Uint256Casting for uint256; using VaultLib for VaultLib.Vault; using Address for address payable; uint256 internal constant MIN_COLLATERAL = 0.5 ether; /// @dev system can only be paused for 182 days from deployment uint256 internal constant PAUSE_TIME_LIMIT = 182 days; uint256 internal constant FUNDING_PERIOD = 1 days; uint32 public constant TWAP_PERIOD = 5 minutes; //80% of index uint256 internal constant LOWER_MARK_RATIO = 8e17; //125% of index uint256 internal constant UPPER_MARK_RATIO = 125e16; // 10% uint256 internal constant LIQUIDATION_BOUNTY = 1e17; // 2% uint256 internal constant REDUCE_DEBT_BOUNTY = 2e16; /// @dev basic unit used for calculation uint256 private constant ONE = 1e18; uint256 private constant ONE_ONE = 1e36; address public immutable weth; address public immutable quoteCurrency; address public immutable ethQuoteCurrencyPool; /// @dev address of the powerPerp/weth pool address public immutable wPowerPerpPool; address internal immutable uniswapPositionManager; address public immutable shortPowerPerp; address public immutable wPowerPerp; address public immutable oracle; address public feeRecipient; uint256 internal immutable deployTimestamp; /// @dev fee rate in basis point. feeRate of 1 = 0.01% uint256 public feeRate; /// @dev the settlement price for each wPowerPerp for settlement uint256 public indexForSettlement; uint256 public pausesLeft = 4; uint256 public lastPauseTime; // these 2 parameters are always updated together. Use uint128 to batch read and write. uint128 public normalizationFactor; uint128 public lastFundingUpdateTimestamp; bool internal immutable isWethToken0; bool public isShutDown; bool public isSystemPaused; /// @dev vault data storage mapping(uint256 => VaultLib.Vault) public vaults; /// Events event OpenVault(address sender, uint256 vaultId); event DepositCollateral(address sender, uint256 vaultId, uint256 amount); event DepositUniPositionToken(address sender, uint256 vaultId, uint256 tokenId); event WithdrawCollateral(address sender, uint256 vaultId, uint256 amount); event WithdrawUniPositionToken(address sender, uint256 vaultId, uint256 tokenId); event MintShort(address sender, uint256 amount, uint256 vaultId); event BurnShort(address sender, uint256 amount, uint256 vaultId); event ReduceDebt( address sender, uint256 vaultId, uint256 ethRedeemed, uint256 wPowerPerpRedeemed, uint256 wPowerPerpBurned, uint256 wPowerPerpExcess, uint256 bounty ); event UpdateOperator(address sender, uint256 vaultId, address operator); event FeeRateUpdated(uint256 oldFee, uint256 newFee); event FeeRecipientUpdated(address oldFeeRecipient, address newFeeRecipient); event Liquidate(address liquidator, uint256 vaultId, uint256 debtAmount, uint256 collateralPaid); event NormalizationFactorUpdated( uint256 oldNormFactor, uint256 newNormFactor, uint256 lastModificationTimestamp, uint256 timestamp ); event Paused(uint256 pausesLeft); event UnPaused(address unpauser); event Shutdown(uint256 indexForSettlement); event RedeemLong(address sender, uint256 wPowerPerpAmount, uint256 payoutAmount); event RedeemShort(address sender, uint256 vauldId, uint256 collateralAmount); modifier notPaused() { require(!isSystemPaused, "C0"); _; } modifier isPaused() { require(isSystemPaused, "C1"); _; } modifier notShutdown() { require(!isShutDown, "C2"); _; } modifier isShutdown() { require(isShutDown, "C3"); _; } /** * @notice constructor * @param _oracle oracle address * @param _shortPowerPerp ERC721 token address representing the short position * @param _wPowerPerp ERC20 token address representing the long position * @param _weth weth address * @param _quoteCurrency quoteCurrency address * @param _ethQuoteCurrencyPool uniswap v3 pool for weth / quoteCurrency * @param _wPowerPerpPool uniswap v3 pool for wPowerPerp / weth * @param _uniPositionManager uniswap v3 position manager address */ constructor( address _oracle, address _shortPowerPerp, address _wPowerPerp, address _weth, address _quoteCurrency, address _ethQuoteCurrencyPool, address _wPowerPerpPool, address _uniPositionManager ) { require(_oracle != address(0), "C4"); require(_shortPowerPerp != address(0), "C5"); require(_wPowerPerp != address(0), "C6"); require(_weth != address(0), "C7"); require(_quoteCurrency != address(0), "C8"); require(_ethQuoteCurrencyPool != address(0), "C9"); require(_wPowerPerpPool != address(0), "C10"); require(_uniPositionManager != address(0), "C11"); oracle = _oracle; shortPowerPerp = _shortPowerPerp; wPowerPerp = _wPowerPerp; weth = _weth; quoteCurrency = _quoteCurrency; ethQuoteCurrencyPool = _ethQuoteCurrencyPool; wPowerPerpPool = _wPowerPerpPool; uniswapPositionManager = _uniPositionManager; isWethToken0 = _weth < _wPowerPerp; normalizationFactor = 1e18; deployTimestamp = block.timestamp; lastFundingUpdateTimestamp = block.timestamp.toUint128(); } /** * ====================== * | External Functions | * ====================== */ /** * @notice returns the expected normalization factor, if the funding is paid right now * @dev can be used for on-chain and off-chain calculations */ function getExpectedNormalizationFactor() external view returns (uint256) { return _getNewNormalizationFactor(); } /** * @notice get the index price of the powerPerp, scaled down * @dev the index price is scaled down by INDEX_SCALE in the associated PowerXBase library * @dev this is the index price used when calculating funding and for collateralization * @param _period period which you want to calculate twap with * @return index price denominated in $USD, scaled by 1e18 */ function getIndex(uint32 _period) external view returns (uint256) { return Power2Base._getIndex(_period, oracle, ethQuoteCurrencyPool, weth, quoteCurrency); } /** * @notice the unscaled index of the power perp in USD, scaled by 18 decimals * @dev this is the mark that would be be used for future funding after a new normalization factor is applied * @param _period period which you want to calculate twap with * @return index price denominated in $USD, scaled by 1e18 */ function getUnscaledIndex(uint32 _period) external view returns (uint256) { return Power2Base._getUnscaledIndex(_period, oracle, ethQuoteCurrencyPool, weth, quoteCurrency); } /** * @notice get the expected mark price of powerPerp after funding has been applied * @param _period period of time for the twap in seconds * @return mark price denominated in $USD, scaled by 1e18 */ function getDenormalizedMark(uint32 _period) external view returns (uint256) { return Power2Base._getDenormalizedMark( _period, oracle, wPowerPerpPool, ethQuoteCurrencyPool, weth, quoteCurrency, wPowerPerp, _getNewNormalizationFactor() ); } /** * @notice get the mark price of powerPerp before funding has been applied * @dev this is the mark that would be used to calculate a new normalization factor if funding was calculated now * @param _period period which you want to calculate twap with * @return mark price denominated in $USD, scaled by 1e18 */ function getDenormalizedMarkForFunding(uint32 _period) external view returns (uint256) { return Power2Base._getDenormalizedMark( _period, oracle, wPowerPerpPool, ethQuoteCurrencyPool, weth, quoteCurrency, wPowerPerp, normalizationFactor ); } /** * @dev return if the vault is properly collateralized * @param _vaultId id of the vault * @return true if the vault is properly collateralized */ function isVaultSafe(uint256 _vaultId) external view returns (bool) { VaultLib.Vault memory vault = vaults[_vaultId]; uint256 expectedNormalizationFactor = _getNewNormalizationFactor(); return _isVaultSafe(vault, expectedNormalizationFactor); } /** * @notice deposit collateral and mint wPowerPerp (non-rebasing) for specified powerPerp (rebasing) amount * @param _vaultId vault to mint wPowerPerp in * @param _powerPerpAmount amount of powerPerp to mint * @param _uniTokenId uniswap v3 position token id (additional collateral) * @return vaultId * @return amount of wPowerPerp minted */ function mintPowerPerpAmount( uint256 _vaultId, uint256 _powerPerpAmount, uint256 _uniTokenId ) external payable notPaused nonReentrant returns (uint256, uint256) { return _openDepositMint(msg.sender, _vaultId, _powerPerpAmount, msg.value, _uniTokenId, false); } /** * @notice deposit collateral and mint wPowerPerp * @param _vaultId vault to mint wPowerPerp in * @param _wPowerPerpAmount amount of wPowerPerp to mint * @param _uniTokenId uniswap v3 position token id (additional collateral) * @return vaultId */ function mintWPowerPerpAmount( uint256 _vaultId, uint256 _wPowerPerpAmount, uint256 _uniTokenId ) external payable notPaused nonReentrant returns (uint256) { (uint256 vaultId, ) = _openDepositMint(msg.sender, _vaultId, _wPowerPerpAmount, msg.value, _uniTokenId, true); return vaultId; } /** * @dev deposit collateral into a vault * @param _vaultId id of the vault */ function deposit(uint256 _vaultId) external payable notPaused nonReentrant { _checkVaultId(_vaultId); _applyFunding(); VaultLib.Vault memory cachedVault = vaults[_vaultId]; _addEthCollateral(cachedVault, _vaultId, msg.value); _writeVault(_vaultId, cachedVault); } /** * @notice deposit uniswap position token into a vault to increase collateral ratio * @param _vaultId id of the vault * @param _uniTokenId uniswap position token id */ function depositUniPositionToken(uint256 _vaultId, uint256 _uniTokenId) external notPaused nonReentrant { _checkVaultId(_vaultId); _applyFunding(); VaultLib.Vault memory cachedVault = vaults[_vaultId]; _depositUniPositionToken(cachedVault, msg.sender, _vaultId, _uniTokenId); _writeVault(_vaultId, cachedVault); } /** * @notice withdraw collateral from a vault * @param _vaultId id of the vault * @param _amount amount of eth to withdraw */ function withdraw(uint256 _vaultId, uint256 _amount) external notPaused nonReentrant { uint256 cachedNormFactor = _applyFunding(); VaultLib.Vault memory cachedVault = vaults[_vaultId]; _withdrawCollateral(cachedVault, msg.sender, _vaultId, _amount); _checkVault(cachedVault, cachedNormFactor); _writeVault(_vaultId, cachedVault); payable(msg.sender).sendValue(_amount); } /** * @notice withdraw uniswap v3 position token from a vault * @param _vaultId id of the vault */ function withdrawUniPositionToken(uint256 _vaultId) external notPaused nonReentrant { uint256 cachedNormFactor = _applyFunding(); VaultLib.Vault memory cachedVault = vaults[_vaultId]; _withdrawUniPositionToken(cachedVault, msg.sender, _vaultId); _checkVault(cachedVault, cachedNormFactor); _writeVault(_vaultId, cachedVault); } /** * @notice burn wPowerPerp and remove collateral from a vault * @param _vaultId id of the vault * @param _wPowerPerpAmount amount of wPowerPerp to burn * @param _withdrawAmount amount of eth to withdraw */ function burnWPowerPerpAmount( uint256 _vaultId, uint256 _wPowerPerpAmount, uint256 _withdrawAmount ) external notPaused nonReentrant { _burnAndWithdraw(msg.sender, _vaultId, _wPowerPerpAmount, _withdrawAmount, true); } /** * @notice burn powerPerp and remove collateral from a vault * @param _vaultId id of the vault * @param _powerPerpAmount amount of powerPerp to burn * @param _withdrawAmount amount of eth to withdraw * @return amount of wPowerPerp burned */ function burnPowerPerpAmount( uint256 _vaultId, uint256 _powerPerpAmount, uint256 _withdrawAmount ) external notPaused nonReentrant returns (uint256) { return _burnAndWithdraw(msg.sender, _vaultId, _powerPerpAmount, _withdrawAmount, false); } /** * @notice after the system is shutdown, insolvent vaults need to be have their uniswap v3 token assets withdrawn by force * @notice if a vault has a uniswap v3 position in it, anyone can call to withdraw uniswap v3 token assets, reducing debt and increasing collateral in the vault * @dev the caller won't get any bounty. this is expected to be used for insolvent vaults in shutdown * @param _vaultId vault containing uniswap v3 position to liquidate */ function reduceDebtShutdown(uint256 _vaultId) external isShutdown nonReentrant { VaultLib.Vault memory cachedVault = vaults[_vaultId]; _reduceDebt( cachedVault, IShortPowerPerp(shortPowerPerp).ownerOf(_vaultId), _vaultId, normalizationFactor, false ); _writeVault(_vaultId, cachedVault); } /** * @notice withdraw assets from uniswap v3 position, reducing debt and increasing collateral in the vault * @dev the caller won't get any bounty. this is expected to be used by vault owner * @param _vaultId target vault */ function reduceDebt(uint256 _vaultId) external notPaused nonReentrant { _checkCanModifyVault(_vaultId, msg.sender); uint256 cachedNormFactor = _applyFunding(); VaultLib.Vault memory cachedVault = vaults[_vaultId]; _reduceDebt(cachedVault, IShortPowerPerp(shortPowerPerp).ownerOf(_vaultId), _vaultId, cachedNormFactor, false); _writeVault(_vaultId, cachedVault); } /** * @notice if a vault is under the 150% collateral ratio, anyone can liquidate the vault by burning wPowerPerp * @dev liquidator can get back (wPowerPerp burned) * (index price) * (normalizationFactor) * 110% in collateral * @dev normally can only liquidate 50% of a vault's debt * @dev if a vault is under dust limit after a liquidation can fully liquidate * @dev will attempt to reduceDebt first, and can earn a bounty if sucessful * @param _vaultId vault to liquidate * @param _maxDebtAmount max amount of wPowerPerpetual to repay * @return amount of wPowerPerp repaid */ function liquidate(uint256 _vaultId, uint256 _maxDebtAmount) external notPaused nonReentrant returns (uint256) { _checkVaultId(_vaultId); uint256 cachedNormFactor = _applyFunding(); VaultLib.Vault memory cachedVault = vaults[_vaultId]; require(!_isVaultSafe(cachedVault, cachedNormFactor), "C12"); // try to save target vault before liquidation by reducing debt uint256 bounty = _reduceDebt( cachedVault, IShortPowerPerp(shortPowerPerp).ownerOf(_vaultId), _vaultId, cachedNormFactor, true ); // if vault is safe after saving, pay bounty and return early if (_isVaultSafe(cachedVault, cachedNormFactor)) { _writeVault(_vaultId, cachedVault); payable(msg.sender).sendValue(bounty); return 0; } // add back the bounty amount, liquidators onlly get reward from liquidation cachedVault.addEthCollateral(bounty); // if the vault is still not safe after saving, liquidate it (uint256 debtAmount, uint256 collateralPaid) = _liquidate( cachedVault, _maxDebtAmount, cachedNormFactor, msg.sender ); emit Liquidate(msg.sender, _vaultId, debtAmount, collateralPaid); _writeVault(_vaultId, cachedVault); // pay the liquidator payable(msg.sender).sendValue(collateralPaid); return debtAmount; } /** * @notice authorize an address to modify the vault * @dev can be revoke by setting address to 0 * @param _vaultId id of the vault * @param _operator new operator address */ function updateOperator(uint256 _vaultId, address _operator) external { require(IShortPowerPerp(shortPowerPerp).ownerOf(_vaultId) == msg.sender, "C25"); vaults[_vaultId].operator = _operator; emit UpdateOperator(msg.sender, _vaultId, _operator); } /** * @notice set the recipient who will receive the fee * @dev this should be a contract handling insurance * @param _newFeeRecipient new fee recipient */ function setFeeRecipient(address _newFeeRecipient) external onlyOwner { require(_newFeeRecipient != address(0), "C13"); emit FeeRecipientUpdated(feeRecipient, _newFeeRecipient); feeRecipient = _newFeeRecipient; } /** * @notice set the fee rate when user mints * @dev this function cannot be called if the feeRecipient is still un-set * @param _newFeeRate new fee rate in basis points. can't be higher than 1% */ function setFeeRate(uint256 _newFeeRate) external onlyOwner { require(feeRecipient != address(0), "C14"); require(_newFeeRate <= 100, "C15"); emit FeeRateUpdated(feeRate, _newFeeRate); feeRate = _newFeeRate; } /** * @notice pause (if not paused) and then immediately shutdown the system, can be called when paused already * @dev this bypasses the check on number of pauses or time based checks, but is irreversible and enables emergency settlement */ function shutDown() external onlyOwner notShutdown { isSystemPaused = true; isShutDown = true; indexForSettlement = Power2Base._getScaledTwap( oracle, ethQuoteCurrencyPool, weth, quoteCurrency, TWAP_PERIOD, false ); } /** * @notice pause the system for up to 24 hours after which any one can unpause * @dev can only be called for 365 days since the contract was launched or 4 times */ function pause() external onlyOwner notShutdown notPaused { require(pausesLeft > 0, "C16"); uint256 timeSinceDeploy = block.timestamp.sub(deployTimestamp); require(timeSinceDeploy < PAUSE_TIME_LIMIT, "C17"); isSystemPaused = true; pausesLeft -= 1; lastPauseTime = block.timestamp; emit Paused(pausesLeft); } /** * @notice unpause the contract * @dev anyone can unpause the contract after 24 hours */ function unPauseAnyone() external isPaused notShutdown { require(block.timestamp > (lastPauseTime + 1 days), "C18"); isSystemPaused = false; emit UnPaused(msg.sender); } /** * @notice unpause the contract * @dev owner can unpause at any time */ function unPauseOwner() external onlyOwner isPaused notShutdown { isSystemPaused = false; emit UnPaused(msg.sender); } /** * @notice redeem wPowerPerp for (settlement index value) * normalizationFactor when the system is shutdown * @param _wPerpAmount amount of wPowerPerp to burn */ function redeemLong(uint256 _wPerpAmount) external isShutdown nonReentrant { IWPowerPerp(wPowerPerp).burn(msg.sender, _wPerpAmount); uint256 longValue = Power2Base._getLongSettlementValue(_wPerpAmount, indexForSettlement, normalizationFactor); payable(msg.sender).sendValue(longValue); emit RedeemLong(msg.sender, _wPerpAmount, longValue); } /** * @notice redeem short position when the system is shutdown * @dev short position is redeemed by valuing the debt at the (settlement index value) * normalizationFactor * @param _vaultId vault id */ function redeemShort(uint256 _vaultId) external isShutdown nonReentrant { _checkCanModifyVault(_vaultId, msg.sender); VaultLib.Vault memory cachedVault = vaults[_vaultId]; uint256 cachedNormFactor = normalizationFactor; _reduceDebt(cachedVault, msg.sender, _vaultId, cachedNormFactor, false); uint256 debt = Power2Base._getLongSettlementValue( cachedVault.shortAmount, indexForSettlement, cachedNormFactor ); // if the debt is more than collateral, this line will revert uint256 excess = uint256(cachedVault.collateralAmount).sub(debt); // reset the vault but don't burn the nft, just because people may want to keep it cachedVault.shortAmount = 0; cachedVault.collateralAmount = 0; _writeVault(_vaultId, cachedVault); payable(msg.sender).sendValue(excess); emit RedeemShort(msg.sender, _vaultId, excess); } /** * @notice update the normalization factor as a way to pay funding */ function applyFunding() external notPaused { _applyFunding(); } /** * @notice add eth into a contract. used in case contract has insufficient eth to pay for settlement transactions */ function donate() external payable isShutdown {} /** * @notice fallback function to accept eth */ receive() external payable { require(msg.sender == weth, "C19"); } /* * ====================== * | Internal Functions | * ====================== */ /** * @notice check if a vaultId is valid, reverts if it's not valid * @param _vaultId the id to check */ function _checkVaultId(uint256 _vaultId) internal view { require(_vaultId > 0 && _vaultId < IShortPowerPerp(shortPowerPerp).nextId(), "C20"); } /** * @notice check if an address can modify a vault * @param _vaultId the id of the vault to check if can be modified by _account * @param _account the address to check if can modify the vault */ function _checkCanModifyVault(uint256 _vaultId, address _account) internal view { require( IShortPowerPerp(shortPowerPerp).ownerOf(_vaultId) == _account || vaults[_vaultId].operator == _account, "C25" ); } /** * @notice wrapper function which open a vault, add collateral and mint wPowerPerp * @param _account account to receive wPowerPerp * @param _vaultId id of the vault * @param _mintAmount amount to mint * @param _depositAmount amount of eth as collateral * @param _uniTokenId id of uniswap v3 position token * @param _isWAmount if the input amount is wPowerPerp (as opposed to rebasing powerPerp) * @return vaultId * @return total minted wPowerPower amount */ function _openDepositMint( address _account, uint256 _vaultId, uint256 _mintAmount, uint256 _depositAmount, uint256 _uniTokenId, bool _isWAmount ) internal returns (uint256, uint256) { uint256 cachedNormFactor = _applyFunding(); uint256 depositAmountWithFee = _depositAmount; uint256 wPowerPerpAmount = _isWAmount ? _mintAmount : _mintAmount.mul(ONE).div(cachedNormFactor); uint256 feeAmount; VaultLib.Vault memory cachedVault; // load vault or create new a new one if (_vaultId == 0) { (_vaultId, cachedVault) = _openVault(_account); } else { // make sure we're not accessing an unexistent vault. _checkVaultId(_vaultId); cachedVault = vaults[_vaultId]; } if (wPowerPerpAmount > 0) { (feeAmount, depositAmountWithFee) = _getFee( cachedVault, wPowerPerpAmount, _depositAmount, cachedNormFactor ); _mintWPowerPerp(cachedVault, _account, _vaultId, wPowerPerpAmount); } if (_depositAmount > 0) _addEthCollateral(cachedVault, _vaultId, depositAmountWithFee); if (_uniTokenId != 0) _depositUniPositionToken(cachedVault, _account, _vaultId, _uniTokenId); _checkVault(cachedVault, cachedNormFactor); _writeVault(_vaultId, cachedVault); // pay insurance fee if (feeAmount > 0) payable(feeRecipient).sendValue(feeAmount); return (_vaultId, wPowerPerpAmount); } /** * @notice wrapper function to burn wPowerPerp and redeem collateral * @param _account who should receive collateral * @param _vaultId id of the vault * @param _burnAmount amount of wPowerPerp to burn * @param _withdrawAmount amount of eth collateral to withdraw * @param _isWAmount true if the amount is wPowerPerp (as opposed to rebasing powerPerp) * @return total burned wPowerPower amount */ function _burnAndWithdraw( address _account, uint256 _vaultId, uint256 _burnAmount, uint256 _withdrawAmount, bool _isWAmount ) internal returns (uint256) { _checkVaultId(_vaultId); uint256 cachedNormFactor = _applyFunding(); uint256 wBurnAmount = _isWAmount ? _burnAmount : _burnAmount.mul(ONE).div(cachedNormFactor); VaultLib.Vault memory cachedVault = vaults[_vaultId]; if (wBurnAmount > 0) _burnWPowerPerp(cachedVault, _account, _vaultId, wBurnAmount); if (_withdrawAmount > 0) _withdrawCollateral(cachedVault, _account, _vaultId, _withdrawAmount); _checkVault(cachedVault, cachedNormFactor); _writeVault(_vaultId, cachedVault); if (_withdrawAmount > 0) payable(msg.sender).sendValue(_withdrawAmount); return wBurnAmount; } /** * @notice open a new vault * @dev create a new vault and bind it with a new short vault id * @param _recipient owner of new vault * @return id of the new vault * @return new in-memory vault */ function _openVault(address _recipient) internal returns (uint256, VaultLib.Vault memory) { uint256 vaultId = IShortPowerPerp(shortPowerPerp).mintNFT(_recipient); VaultLib.Vault memory vault = VaultLib.Vault({ NftCollateralId: 0, collateralAmount: 0, shortAmount: 0, operator: address(0) }); emit OpenVault(msg.sender, vaultId); return (vaultId, vault); } /** * @notice deposit uniswap v3 position token into a vault * @dev this function will update the vault memory in-place * @param _vault the Vault memory to update * @param _account account to transfer the uniswap v3 position from * @param _vaultId id of the vault * @param _uniTokenId uniswap position token id */ function _depositUniPositionToken( VaultLib.Vault memory _vault, address _account, uint256 _vaultId, uint256 _uniTokenId ) internal { //get tokens for uniswap NFT (, , address token0, address token1, , , , , , , , ) = INonfungiblePositionManager(uniswapPositionManager) .positions(_uniTokenId); // only check token0 and token1, ignore fee // if there are multiple wPowerPerp/weth pools with different fee rate, accept position tokens from any of them require((token0 == wPowerPerp && token1 == weth) || (token1 == wPowerPerp && token0 == weth), "C23"); _vault.addUniNftCollateral(_uniTokenId); INonfungiblePositionManager(uniswapPositionManager).transferFrom(_account, address(this), _uniTokenId); emit DepositUniPositionToken(msg.sender, _vaultId, _uniTokenId); } /** * @notice add eth collateral into a vault * @dev this function will update the vault memory in-place * @param _vault the Vault memory to update. * @param _amount amount of eth adding to the vault */ function _addEthCollateral( VaultLib.Vault memory _vault, uint256 _vaultId, uint256 _amount ) internal { _vault.addEthCollateral(_amount); emit DepositCollateral(msg.sender, _vaultId, _amount); } /** * @notice remove uniswap v3 position token from the vault * @dev this function will update the vault memory in-place * @param _vault the Vault memory to update * @param _account where to send the uni position token to * @param _vaultId id of the vault */ function _withdrawUniPositionToken( VaultLib.Vault memory _vault, address _account, uint256 _vaultId ) internal { _checkCanModifyVault(_vaultId, _account); uint256 tokenId = _vault.NftCollateralId; _vault.removeUniNftCollateral(); INonfungiblePositionManager(uniswapPositionManager).transferFrom(address(this), _account, tokenId); emit WithdrawUniPositionToken(msg.sender, _vaultId, tokenId); } /** * @notice remove eth collateral from the vault * @dev this function will update the vault memory in-place * @param _vault the Vault memory to update * @param _account where to send collateral to * @param _vaultId id of the vault * @param _amount amount of eth to withdraw */ function _withdrawCollateral( VaultLib.Vault memory _vault, address _account, uint256 _vaultId, uint256 _amount ) internal { _checkCanModifyVault(_vaultId, _account); _vault.removeEthCollateral(_amount); emit WithdrawCollateral(msg.sender, _vaultId, _amount); } /** * @notice mint wPowerPerp (ERC20) to an account * @dev this function will update the vault memory in-place * @param _vault the Vault memory to update * @param _account account to receive wPowerPerp * @param _vaultId id of the vault * @param _wPowerPerpAmount wPowerPerp amount to mint */ function _mintWPowerPerp( VaultLib.Vault memory _vault, address _account, uint256 _vaultId, uint256 _wPowerPerpAmount ) internal { _checkCanModifyVault(_vaultId, _account); _vault.addShort(_wPowerPerpAmount); IWPowerPerp(wPowerPerp).mint(_account, _wPowerPerpAmount); emit MintShort(msg.sender, _wPowerPerpAmount, _vaultId); } /** * @notice burn wPowerPerp (ERC20) from an account * @dev this function will update the vault memory in-place * @param _vault the Vault memory to update * @param _account account burning the wPowerPerp * @param _vaultId id of the vault * @param _wPowerPerpAmount wPowerPerp amount to burn */ function _burnWPowerPerp( VaultLib.Vault memory _vault, address _account, uint256 _vaultId, uint256 _wPowerPerpAmount ) internal { _vault.removeShort(_wPowerPerpAmount); IWPowerPerp(wPowerPerp).burn(_account, _wPowerPerpAmount); emit BurnShort(msg.sender, _wPowerPerpAmount, _vaultId); } /** * @notice liquidate a vault, pay the liquidator * @dev liquidator can only liquidate at most 1/2 of the vault in 1 transaction * @dev this function will update the vault memory in-place * @param _vault the Vault memory to update * @param _maxWPowerPerpAmount maximum debt amount liquidator is willing to repay * @param _normalizationFactor current normalization factor * @param _liquidator liquidator address to receive eth * @return debtAmount amount of wPowerPerp repaid (burn from the vault) * @return collateralToPay amount of collateral paid to liquidator */ function _liquidate( VaultLib.Vault memory _vault, uint256 _maxWPowerPerpAmount, uint256 _normalizationFactor, address _liquidator ) internal returns (uint256, uint256) { (uint256 liquidateAmount, uint256 collateralToPay) = _getLiquidationResult( _maxWPowerPerpAmount, uint256(_vault.shortAmount), uint256(_vault.collateralAmount), _normalizationFactor ); // if the liquidator didn't specify enough wPowerPerp to burn, revert. require(_maxWPowerPerpAmount >= liquidateAmount, "C21"); IWPowerPerp(wPowerPerp).burn(_liquidator, liquidateAmount); _vault.removeShort(liquidateAmount); _vault.removeEthCollateral(collateralToPay); (, bool isDust) = _getVaultStatus(_vault, _normalizationFactor); require(!isDust, "C22"); return (liquidateAmount, collateralToPay); } /** * @notice redeem uniswap v3 position in a vault for its constituent eth and wSqueeth * @notice this will increase vault collateral by the amount of eth, and decrease debt by the amount of wSqueeth * @dev will be executed before liquidation if there's an NFT in the vault * @dev pays a 2% bounty to the liquidator if called by liquidate() * @dev will update the vault memory in-place * @param _vault the Vault memory to update * @param _owner account to send any excess * @param _payBounty true if paying caller 2% bounty * @return bounty amount of bounty paid for liquidator */ function _reduceDebt( VaultLib.Vault memory _vault, address _owner, uint256 _vaultId, uint256 _normalizationFactor, bool _payBounty ) internal returns (uint256) { uint256 nftId = _vault.NftCollateralId; if (nftId == 0) return 0; (uint256 withdrawnEthAmount, uint256 withdrawnWPowerPerpAmount) = _redeemUniToken(nftId); // change weth back to eth if (withdrawnEthAmount > 0) IWETH9(weth).withdraw(withdrawnEthAmount); (uint256 burnAmount, uint256 excess, uint256 bounty) = _getReduceDebtResultInVault( _vault, withdrawnEthAmount, withdrawnWPowerPerpAmount, _normalizationFactor, _payBounty ); if (excess > 0) IWPowerPerp(wPowerPerp).transfer(_owner, excess); if (burnAmount > 0) IWPowerPerp(wPowerPerp).burn(address(this), burnAmount); emit ReduceDebt( msg.sender, _vaultId, withdrawnEthAmount, withdrawnWPowerPerpAmount, burnAmount, excess, bounty ); return bounty; } /** * @notice pay fee recipient * @dev pay in eth from either the vault or the deposit amount * @param _vault the Vault memory to update * @param _wSqueethAmount the amount of wSqueeth minting * @param _depositAmount the amount of eth depositing or withdrawing * @param _normalizationFactor current normalization factor * @return the amount of actual deposited eth into the vault, this is less than the original amount if a fee was taken */ function _getFee( VaultLib.Vault memory _vault, uint256 _wSqueethAmount, uint256 _depositAmount, uint256 _normalizationFactor ) internal view returns (uint256, uint256) { uint256 cachedFeeRate = feeRate; if (cachedFeeRate == 0) return (uint256(0), _depositAmount); uint256 depositAmountAfterFee; uint256 ethEquivalentMinted = Power2Base._getDebtValueInEth( _wSqueethAmount, oracle, ethQuoteCurrencyPool, weth, quoteCurrency, _normalizationFactor ); uint256 feeAmount = ethEquivalentMinted.mul(cachedFeeRate).div(10000); // if fee can be paid from deposited collateral, pay from _depositAmount if (_depositAmount > feeAmount) { depositAmountAfterFee = _depositAmount.sub(feeAmount); // if not, adjust the vault to pay from the vault collateral } else { _vault.removeEthCollateral(feeAmount); depositAmountAfterFee = _depositAmount; } //return the fee and deposit amount, which has only been reduced by a fee if it is paid out of the deposit amount return (feeAmount, depositAmountAfterFee); } /** * @notice write vault to storage * @dev writes to vaults mapping */ function _writeVault(uint256 _vaultId, VaultLib.Vault memory _vault) private { vaults[_vaultId] = _vault; } /** * @dev redeem a uni position token and get back wPowerPerp and eth * @param _uniTokenId uniswap v3 position token id * @return wethAmount amount of weth withdrawn from uniswap * @return wPowerPerpAmount amount of wPowerPerp withdrawn from uniswap */ function _redeemUniToken(uint256 _uniTokenId) internal returns (uint256, uint256) { INonfungiblePositionManager positionManager = INonfungiblePositionManager(uniswapPositionManager); (, , uint128 liquidity, , ) = VaultLib._getUniswapPositionInfo(uniswapPositionManager, _uniTokenId); // prepare parameters to withdraw liquidity from uniswap v3 position manager INonfungiblePositionManager.DecreaseLiquidityParams memory decreaseParams = INonfungiblePositionManager .DecreaseLiquidityParams({ tokenId: _uniTokenId, liquidity: liquidity, amount0Min: 0, amount1Min: 0, deadline: block.timestamp }); positionManager.decreaseLiquidity(decreaseParams); // withdraw max amount of weth and wPowerPerp from uniswap INonfungiblePositionManager.CollectParams memory collectParams = INonfungiblePositionManager.CollectParams({ tokenId: _uniTokenId, recipient: address(this), amount0Max: uint128(-1), amount1Max: uint128(-1) }); (uint256 collectedToken0, uint256 collectedToken1) = positionManager.collect(collectParams); return isWethToken0 ? (collectedToken0, collectedToken1) : (collectedToken1, collectedToken0); } /** * @notice update the normalization factor as a way to pay in-kind funding * @dev the normalization factor scales amount of debt that must be repaid, effecting an interest rate paid between long and short positions * @return new normalization factor **/ function _applyFunding() internal returns (uint256) { // only update the norm factor once per block if (lastFundingUpdateTimestamp == block.timestamp) return normalizationFactor; uint256 newNormalizationFactor = _getNewNormalizationFactor(); emit NormalizationFactorUpdated( normalizationFactor, newNormalizationFactor, lastFundingUpdateTimestamp, block.timestamp ); // the following will be batch into 1 SSTORE because of type uint128 normalizationFactor = newNormalizationFactor.toUint128(); lastFundingUpdateTimestamp = block.timestamp.toUint128(); return newNormalizationFactor; } /** * @dev calculate new normalization factor base on the current timestamp * @return new normalization factor if funding happens in the current block */ function _getNewNormalizationFactor() internal view returns (uint256) { uint32 period = block.timestamp.sub(lastFundingUpdateTimestamp).toUint32(); if (period == 0) { return normalizationFactor; } // make sure we use the same period for mark and index uint32 periodForOracle = _getConsistentPeriodForOracle(period); // avoid reading normalizationFactor from storage multiple times uint256 cacheNormFactor = normalizationFactor; uint256 mark = Power2Base._getDenormalizedMark( periodForOracle, oracle, wPowerPerpPool, ethQuoteCurrencyPool, weth, quoteCurrency, wPowerPerp, cacheNormFactor ); uint256 index = Power2Base._getIndex(periodForOracle, oracle, ethQuoteCurrencyPool, weth, quoteCurrency); uint256 rFunding = (ONE.mul(uint256(period))).div(FUNDING_PERIOD); // floor mark to be at least LOWER_MARK_RATIO of index uint256 lowerBound = index.mul(LOWER_MARK_RATIO).div(ONE); if (mark < lowerBound) { mark = lowerBound; } else { // cap mark to be at most UPPER_MARK_RATIO of index uint256 upperBound = index.mul(UPPER_MARK_RATIO).div(ONE); if (mark > upperBound) mark = upperBound; } // newNormFactor = (mark / ( (1+rFunding) * mark - index * rFunding )) * oldNormaFactor uint256 multiplier = mark.mul(ONE_ONE).div((ONE.add(rFunding)).mul(mark).sub(index.mul(rFunding))); // multiply by 1e36 to keep multiplier in 18 decimals return cacheNormFactor.mul(multiplier).div(ONE); } /** * @notice check if vault has enough collateral and is not a dust vault * @dev revert if vault has insufficient collateral or is a dust vault * @param _vault the Vault memory to update * @param _normalizationFactor normalization factor */ function _checkVault(VaultLib.Vault memory _vault, uint256 _normalizationFactor) internal view { (bool isSafe, bool isDust) = _getVaultStatus(_vault, _normalizationFactor); require(isSafe, "C24"); require(!isDust, "C22"); } /** * @notice check that the vault has enough collateral * @param _vault in-memory vault * @param _normalizationFactor normalization factor * @return true if the vault is properly collateralized */ function _isVaultSafe(VaultLib.Vault memory _vault, uint256 _normalizationFactor) internal view returns (bool) { (bool isSafe, ) = _getVaultStatus(_vault, _normalizationFactor); return isSafe; } /** * @notice return if the vault is properly collateralized and if it is a dust vault * @param _vault the Vault memory to update * @param _normalizationFactor normalization factor * @return true if the vault is safe * @return true if the vault is a dust vault */ function _getVaultStatus(VaultLib.Vault memory _vault, uint256 _normalizationFactor) internal view returns (bool, bool) { uint256 scaledEthPrice = Power2Base._getScaledTwap( oracle, ethQuoteCurrencyPool, weth, quoteCurrency, TWAP_PERIOD, true // do not call more than maximum period so it does not revert ); return VaultLib.getVaultStatus( _vault, uniswapPositionManager, _normalizationFactor, scaledEthPrice, MIN_COLLATERAL, IOracle(oracle).getTimeWeightedAverageTickSafe(wPowerPerpPool, TWAP_PERIOD), isWethToken0 ); } /** * @notice get the expected excess, burnAmount and bounty if Uniswap position token got burned * @dev this function will update the vault memory in-place * @return burnAmount amount of wSqueeth that should be burned * @return wPowerPerpExcess amount of wSqueeth that should be send to the vault owner * @return bounty amount of bounty should be paid out to caller */ function _getReduceDebtResultInVault( VaultLib.Vault memory _vault, uint256 nftEthAmount, uint256 nftWPowerperpAmount, uint256 _normalizationFactor, bool _payBounty ) internal view returns ( uint256, uint256, uint256 ) { uint256 bounty; if (_payBounty) bounty = _getReduceDebtBounty(nftEthAmount, nftWPowerperpAmount, _normalizationFactor); uint256 burnAmount = nftWPowerperpAmount; uint256 wPowerPerpExcess; if (nftWPowerperpAmount > _vault.shortAmount) { wPowerPerpExcess = nftWPowerperpAmount.sub(_vault.shortAmount); burnAmount = _vault.shortAmount; } _vault.removeShort(burnAmount); _vault.removeUniNftCollateral(); _vault.addEthCollateral(nftEthAmount); _vault.removeEthCollateral(bounty); return (burnAmount, wPowerPerpExcess, bounty); } /** * @notice get how much bounty you can get by helping a vault reducing the debt. * @dev bounty is 2% of the total value of the position token * @param _ethWithdrawn amount of eth withdrawn from uniswap by redeeming the position token * @param _wPowerPerpReduced amount of wPowerPerp withdrawn from uniswap by redeeming the position token * @param _normalizationFactor normalization factor */ function _getReduceDebtBounty( uint256 _ethWithdrawn, uint256 _wPowerPerpReduced, uint256 _normalizationFactor ) internal view returns (uint256) { return Power2Base ._getDebtValueInEth( _wPowerPerpReduced, oracle, ethQuoteCurrencyPool, weth, quoteCurrency, _normalizationFactor ) .add(_ethWithdrawn) .mul(REDUCE_DEBT_BOUNTY) .div(ONE); } /** * @notice get the expected wPowerPerp needed to liquidate a vault. * @dev a liquidator cannot liquidate more than half of a vault, unless only liquidating half of the debt will make the vault a "dust vault" * @dev a liquidator cannot take out more collateral than the vault holds * @param _maxWPowerPerpAmount the max amount of wPowerPerp willing to pay * @param _vaultShortAmount the amount of short in the vault * @param _maxWPowerPerpAmount the amount of collateral in the vault * @param _normalizationFactor normalization factor * @return finalLiquidateAmount the amount that should be liquidated. This amount can be higher than _maxWPowerPerpAmount, which should be checked * @return collateralToPay final amount of collateral paying out to the liquidator */ function _getLiquidationResult( uint256 _maxWPowerPerpAmount, uint256 _vaultShortAmount, uint256 _vaultCollateralAmount, uint256 _normalizationFactor ) internal view returns (uint256, uint256) { // try limiting liquidation amount to half of the vault debt (uint256 finalLiquidateAmount, uint256 collateralToPay) = _getSingleLiquidationAmount( _maxWPowerPerpAmount, _vaultShortAmount.div(2), _normalizationFactor ); if (_vaultCollateralAmount > collateralToPay) { if (_vaultCollateralAmount.sub(collateralToPay) < MIN_COLLATERAL) { // the vault is left with dust after liquidation, allow liquidating full vault // calculate the new liquidation amount and collateral again based on the new limit (finalLiquidateAmount, collateralToPay) = _getSingleLiquidationAmount( _maxWPowerPerpAmount, _vaultShortAmount, _normalizationFactor ); } } // check if final collateral to pay is greater than vault amount. // if so the system only pays out the amount the vault has, which may not be profitable if (collateralToPay > _vaultCollateralAmount) { // force liquidator to pay full debt amount finalLiquidateAmount = _vaultShortAmount; collateralToPay = _vaultCollateralAmount; } return (finalLiquidateAmount, collateralToPay); } /** * @notice determine how much wPowerPerp to liquidate, and how much collateral to return * @param _maxInputWAmount maximum wPowerPerp amount liquidator is willing to repay * @param _maxLiquidatableWAmount maximum wPowerPerp amount a liquidator is allowed to repay * @param _normalizationFactor normalization factor * @return finalWAmountToLiquidate amount of wPowerPerp the liquidator will burn * @return collateralToPay total collateral the liquidator will get */ function _getSingleLiquidationAmount( uint256 _maxInputWAmount, uint256 _maxLiquidatableWAmount, uint256 _normalizationFactor ) internal view returns (uint256, uint256) { uint256 finalWAmountToLiquidate = _maxInputWAmount > _maxLiquidatableWAmount ? _maxLiquidatableWAmount : _maxInputWAmount; uint256 collateralToPay = Power2Base._getDebtValueInEth( finalWAmountToLiquidate, oracle, ethQuoteCurrencyPool, weth, quoteCurrency, _normalizationFactor ); // add 10% bonus for liquidators collateralToPay = collateralToPay.add(collateralToPay.mul(LIQUIDATION_BOUNTY).div(ONE)); return (finalWAmountToLiquidate, collateralToPay); } /** * @notice get a period can be used to request a twap for 2 uniswap v3 pools * @dev if the period is greater than min(max_pool_1, max_pool_2), return min(max_pool_1, max_pool_2) * @param _period max period that we intend to use * @return fair period not greator than _period to be used for both pools. */ function _getConsistentPeriodForOracle(uint32 _period) internal view returns (uint32) { uint32 maxPeriodPool1 = IOracle(oracle).getMaxPeriod(ethQuoteCurrencyPool); uint32 maxPeriodPool2 = IOracle(oracle).getMaxPeriod(wPowerPerpPool); uint32 maxSafePeriod = maxPeriodPool1 > maxPeriodPool2 ? maxPeriodPool2 : maxPeriodPool1; return _period > maxSafePeriod ? maxSafePeriod : _period; } }
get the expected excess, burnAmount and bounty if Uniswap position token got burned this function will update the vault memory in-place return burnAmount amount of wSqueeth that should be burned return wPowerPerpExcess amount of wSqueeth that should be send to the vault owner return bounty amount of bounty should be paid out to caller/
function _getReduceDebtResultInVault( VaultLib.Vault memory _vault, uint256 nftEthAmount, uint256 nftWPowerperpAmount, uint256 _normalizationFactor, bool _payBounty ) internal view returns ( uint256, uint256, uint256 ) { uint256 bounty; if (_payBounty) bounty = _getReduceDebtBounty(nftEthAmount, nftWPowerperpAmount, _normalizationFactor); uint256 burnAmount = nftWPowerperpAmount; uint256 wPowerPerpExcess; if (nftWPowerperpAmount > _vault.shortAmount) { wPowerPerpExcess = nftWPowerperpAmount.sub(_vault.shortAmount); burnAmount = _vault.shortAmount; } _vault.removeShort(burnAmount); _vault.removeUniNftCollateral(); _vault.addEthCollateral(nftEthAmount); _vault.removeEthCollateral(bounty); return (burnAmount, wPowerPerpExcess, bounty); }
13,123,615
// SPDX-License-Identifier: MIT pragma solidity 0.8.2; /// @title: David Ariew X Tatler China import "../ERC721ProjectUpgradeable.sol"; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // '########:::::'###::::'##::::'##:'####:'########::::::::'###::::'########::'####:'########:'##:::::'##::::'##::::'##::::'########::::'###::::'########:'##:::::::'########:'########::::::'######::'##::::'##:'####:'##::: ##::::'###:::: // // ##.... ##:::'## ##::: ##:::: ##:. ##:: ##.... ##::::::'## ##::: ##.... ##:. ##:: ##.....:: ##:'##: ##::::. ##::'##:::::... ##..::::'## ##:::... ##..:: ##::::::: ##.....:: ##.... ##::::'##... ##: ##:::: ##:. ##:: ###:: ##:::'## ##::: // // ##:::: ##::'##:. ##:: ##:::: ##:: ##:: ##:::: ##:::::'##:. ##:: ##:::: ##:: ##:: ##::::::: ##: ##: ##:::::. ##'##::::::::: ##:::::'##:. ##::::: ##:::: ##::::::: ##::::::: ##:::: ##:::: ##:::..:: ##:::: ##:: ##:: ####: ##::'##:. ##:: // // ##:::: ##:'##:::. ##: ##:::: ##:: ##:: ##:::: ##::::'##:::. ##: ########::: ##:: ######::: ##: ##: ##::::::. ###:::::::::: ##::::'##:::. ##:::: ##:::: ##::::::: ######::: ########::::: ##::::::: #########:: ##:: ## ## ##:'##:::. ##: // // ##:::: ##: #########:. ##:: ##::: ##:: ##:::: ##:::: #########: ##.. ##:::: ##:: ##...:::: ##: ##: ##:::::: ## ##::::::::: ##:::: #########:::: ##:::: ##::::::: ##...:::: ##.. ##:::::: ##::::::: ##.... ##:: ##:: ##. ####: #########: // // ##:::: ##: ##.... ##::. ## ##:::: ##:: ##:::: ##:::: ##.... ##: ##::. ##::: ##:: ##::::::: ##: ##: ##::::: ##:. ##:::::::: ##:::: ##.... ##:::: ##:::: ##::::::: ##::::::: ##::. ##::::: ##::: ##: ##:::: ##:: ##:: ##:. ###: ##.... ##: // // ########:: ##:::: ##:::. ###::::'####: ########::::: ##:::: ##: ##:::. ##:'####: ########:. ###. ###::::: ##:::. ##::::::: ##:::: ##:::: ##:::: ##:::: ########: ########: ##:::. ##::::. ######:: ##:::: ##:'####: ##::. ##: ##:::: ##: // // ........:::..:::::..:::::...:::::....::........::::::..:::::..::..:::::..::....::........:::...::...::::::..:::::..::::::::..:::::..:::::..:::::..:::::........::........::..:::::..::::::......:::..:::::..::....::..::::..::..:::::..:: // /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// contract DavidAriewXTatlerChina is ERC721ProjectUpgradeable { /// @custom:oz-upgrades-unsafe-allow constructor constructor() initializer {} function initialize() public initializer { _initialize("David Ariew X Tatler China", "DavidAriewXTatlerChina"); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.2; import "@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol"; import "./access/AdminControlUpgradeable.sol"; import "./core/ERC721ProjectCoreUpgradeable.sol"; /** * @dev ERC721Project implementation */ abstract contract ERC721ProjectUpgradeable is Initializable, AdminControlUpgradeable, ERC721Upgradeable, ERC721ProjectCoreUpgradeable, UUPSUpgradeable { function _initialize(string memory _name, string memory _symbol) internal initializer { __AdminControl_init(); __ERC721_init(_name, _symbol); __ERC721ProjectCore_init(); __UUPSUpgradeable_init(); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(AdminControlUpgradeable, ERC721Upgradeable, ERC721ProjectCoreUpgradeable) returns (bool) { return super.supportsInterface(interfaceId); } function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { _approveTransfer(from, to, tokenId); super._beforeTokenTransfer(from, to, tokenId); } /** * @dev See {IProjectCore-registerManager}. */ function registerManager(address manager, string calldata baseURI) external override adminRequired nonBlacklistRequired(manager) { _registerManager(manager, baseURI, false); } /** * @dev See {IProjectCore-registerManager}. */ function registerManager( address manager, string calldata baseURI, bool baseURIIdentical ) external override adminRequired nonBlacklistRequired(manager) { _registerManager(manager, baseURI, baseURIIdentical); } /** * @dev See {IProjectCore-unregisterManager}. */ function unregisterManager(address manager) external override adminRequired { _unregisterManager(manager); } /** * @dev See {IProjectCore-blacklistManager}. */ function blacklistManager(address manager) external override adminRequired { _blacklistManager(manager); } /** * @dev See {IProjectCore-managerSetBaseTokenURI}. */ function managerSetBaseTokenURI(string calldata uri) external override managerRequired { _managerSetBaseTokenURI(uri, false); } /** * @dev See {IProjectCore-managerSetBaseTokenURI}. */ function managerSetBaseTokenURI(string calldata uri, bool identical) external override managerRequired { _managerSetBaseTokenURI(uri, identical); } /** * @dev See {IProjectCore-managerSetTokenURIPrefix}. */ function managerSetTokenURIPrefix(string calldata prefix) external override managerRequired { _managerSetTokenURIPrefix(prefix); } /** * @dev See {IProjectCore-managerSetTokenURI}. */ function managerSetTokenURI(uint256 tokenId, string calldata uri) external override managerRequired { _managerSetTokenURI(tokenId, uri); } /** * @dev See {IProjectCore-managerSetTokenURI}. */ function managerSetTokenURI(uint256[] calldata tokenIds, string[] calldata uris) external override managerRequired { require(tokenIds.length == uris.length, "Invalid input"); for (uint256 i = 0; i < tokenIds.length; i++) { _managerSetTokenURI(tokenIds[i], uris[i]); } } /** * @dev See {IProjectCore-setBaseTokenURI}. */ function setBaseTokenURI(string calldata uri) external override adminRequired { _setBaseTokenURI(uri); } /** * @dev See {IProjectCore-setTokenURIPrefix}. */ function setTokenURIPrefix(string calldata prefix) external override adminRequired { _setTokenURIPrefix(prefix); } /** * @dev See {IProjectCore-setTokenURI}. */ function setTokenURI(uint256 tokenId, string calldata uri) external override adminRequired { _setTokenURI(tokenId, uri); } /** * @dev See {IProjectCore-setTokenURI}. */ function setTokenURI(uint256[] calldata tokenIds, string[] calldata uris) external override adminRequired { require(tokenIds.length == uris.length, "Invalid input"); for (uint256 i = 0; i < tokenIds.length; i++) { _setTokenURI(tokenIds[i], uris[i]); } } /** * @dev See {IProjectCore-setMintPermissions}. */ function setMintPermissions(address manager, address permissions) external override adminRequired { _setMintPermissions(manager, permissions); } /** * @dev See {IERC721ProjectCore-adminMint}. */ function adminMint(address to, string calldata uri) external virtual override nonReentrant adminRequired returns (uint256) { return _adminMint(to, uri); } /** * @dev See {IERC721ProjectCore-adminMintBatch}. */ function adminMintBatch(address to, uint16 count) external virtual override nonReentrant adminRequired returns (uint256[] memory tokenIds) { tokenIds = new uint256[](count); for (uint16 i = 0; i < count; i++) { tokenIds[i] = _adminMint(to, ""); } return tokenIds; } /** * @dev See {IERC721ProjectCore-adminMintBatch}. */ function adminMintBatch(address to, string[] calldata uris) external virtual override nonReentrant adminRequired returns (uint256[] memory tokenIds) { tokenIds = new uint256[](uris.length); for (uint256 i = 0; i < uris.length; i++) { tokenIds[i] = _adminMint(to, uris[i]); } return tokenIds; } /** * @dev Mint token with no manager */ function _adminMint(address to, string memory uri) internal virtual returns (uint256 tokenId) { _tokenCount++; tokenId = _tokenCount; // Track the manager that minted the token _tokensManager[tokenId] = address(this); _safeMint(to, tokenId); if (bytes(uri).length > 0) { _tokenURIs[tokenId] = uri; } // Call post mint _postMintBase(to, tokenId); return tokenId; } /** * @dev See {IERC721ProjectCore-managerMint}. */ function managerMint(address to, string calldata uri) external virtual override nonReentrant managerRequired returns (uint256) { return _managerMint(to, uri); } /** * @dev See {IERC721ProjectCore-managerMintBatch}. */ function managerMintBatch(address to, uint16 count) external virtual override nonReentrant managerRequired returns (uint256[] memory tokenIds) { tokenIds = new uint256[](count); for (uint16 i = 0; i < count; i++) { tokenIds[i] = _managerMint(to, ""); } return tokenIds; } /** * @dev See {IERC721ProjectCore-managerMintBatch}. */ function managerMintBatch(address to, string[] calldata uris) external virtual override nonReentrant managerRequired returns (uint256[] memory tokenIds) { tokenIds = new uint256[](uris.length); for (uint256 i = 0; i < uris.length; i++) { tokenIds[i] = _managerMint(to, uris[i]); } } /** * @dev Mint token via manager */ function _managerMint(address to, string memory uri) internal virtual returns (uint256 tokenId) { _tokenCount++; tokenId = _tokenCount; _checkMintPermissions(to, tokenId); // Track the manager that minted the token _tokensManager[tokenId] = msg.sender; _safeMint(to, tokenId); if (bytes(uri).length > 0) { _tokenURIs[tokenId] = uri; } // Call post mint _postMintManager(to, tokenId); return tokenId; } /** * @dev See {IERC721ProjectCore-tokenManager}. */ function tokenManager(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "Nonexistent token"); return _tokenManager(tokenId); } /** * @dev See {IERC721ProjectCore-burn}. */ function burn(uint256 tokenId) public virtual override nonReentrant { require(_isApprovedOrOwner(msg.sender, tokenId), "Caller is not owner nor approved"); address owner = ownerOf(tokenId); _burn(tokenId); _postBurn(owner, tokenId); } /** * @dev See {IProjectCore-setRoyalties}. */ function setRoyalties(address payable[] calldata receivers, uint256[] calldata basisPoints) external override adminRequired { _setRoyaltiesManager(address(this), receivers, basisPoints); } /** * @dev See {IProjectCore-setRoyalties}. */ function setRoyalties( uint256 tokenId, address payable[] calldata receivers, uint256[] calldata basisPoints ) external override adminRequired { require(_exists(tokenId), "Nonexistent token"); _setRoyalties(tokenId, receivers, basisPoints); } /** * @dev See {IProjectCore-setRoyaltiesManager}. */ function setRoyaltiesManager( address manager, address payable[] calldata receivers, uint256[] calldata basisPoints ) external override adminRequired { _setRoyaltiesManager(manager, receivers, basisPoints); } /** * @dev {See IProjectCore-getRoyalties}. */ function getRoyalties(uint256 tokenId) external view virtual override returns (address payable[] memory, uint256[] memory) { require(_exists(tokenId), "Nonexistent token"); return _getRoyalties(tokenId); } /** * @dev {See IProjectCore-getFees}. */ function getFees(uint256 tokenId) external view virtual override returns (address payable[] memory, uint256[] memory) { require(_exists(tokenId), "Nonexistent token"); return _getRoyalties(tokenId); } /** * @dev {See IProjectCore-getFeeRecipients}. */ function getFeeRecipients(uint256 tokenId) external view virtual override returns (address payable[] memory) { require(_exists(tokenId), "Nonexistent token"); return _getRoyaltyReceivers(tokenId); } /** * @dev {See IProjectCore-getFeeBps}. */ function getFeeBps(uint256 tokenId) external view virtual override returns (uint256[] memory) { require(_exists(tokenId), "Nonexistent token"); return _getRoyaltyBPS(tokenId); } /** * @dev {See IProjectCore-royaltyInfo}. */ function royaltyInfo( uint256 tokenId, uint256 value, bytes calldata ) external view virtual override returns ( address, uint256, bytes memory ) { require(_exists(tokenId), "Nonexistent token"); return _getRoyaltyInfo(tokenId, value); } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "Nonexistent token"); return _tokenURI(tokenId); } function _authorizeUpgrade(address newImplementation) internal override onlyOwner {} uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC721Upgradeable.sol"; import "./IERC721ReceiverUpgradeable.sol"; import "./extensions/IERC721MetadataUpgradeable.sol"; import "../../utils/AddressUpgradeable.sol"; import "../../utils/ContextUpgradeable.sol"; import "../../utils/StringsUpgradeable.sol"; import "../../utils/introspection/ERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @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 ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable { using AddressUpgradeable for address; using StringsUpgradeable 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. */ function __ERC721_init(string memory name_, string memory symbol_) internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __ERC721_init_unchained(name_, symbol_); } function __ERC721_init_unchained(string memory name_, string memory symbol_) internal initializer { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) { return interfaceId == type(IERC721Upgradeable).interfaceId || interfaceId == type(IERC721MetadataUpgradeable).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}. 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 = ERC721Upgradeable.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 { 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 _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 = ERC721Upgradeable.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); } /** * @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 = ERC721Upgradeable.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); } /** * @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(ERC721Upgradeable.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); 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); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721Upgradeable.ownerOf(tokenId), to, tokenId); } /** * @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 IERC721ReceiverUpgradeable(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721ReceiverUpgradeable(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { // solhint-disable-next-line no-inline-assembly 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` 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 { } uint256[44] private __gap; } // 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; import "../ERC1967/ERC1967UpgradeUpgradeable.sol"; import "./Initializable.sol"; /** * @dev Base contract for building openzeppelin-upgrades compatible implementations for the {ERC1967Proxy}. It includes * publicly available upgrade functions that are called by the plugin and by the secure upgrade mechanism to verify * continuation of the upgradability. * * The {_authorizeUpgrade} function MUST be overridden to include access restriction to the upgrade mechanism. * * _Available since v4.1._ */ abstract contract UUPSUpgradeable is Initializable, ERC1967UpgradeUpgradeable { function __UUPSUpgradeable_init() internal initializer { __ERC1967Upgrade_init_unchained(); __UUPSUpgradeable_init_unchained(); } function __UUPSUpgradeable_init_unchained() internal initializer { } function upgradeTo(address newImplementation) external virtual { _authorizeUpgrade(newImplementation); _upgradeToAndCallSecure(newImplementation, bytes(""), false); } function upgradeToAndCall(address newImplementation, bytes memory data) external payable virtual { _authorizeUpgrade(newImplementation); _upgradeToAndCallSecure(newImplementation, data, true); } function _authorizeUpgrade(address newImplementation) internal virtual; uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity 0.8.2; import "@openzeppelin/contracts-upgradeable/utils/introspection/IERC165Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/introspection/ERC165Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/structs/EnumerableSetUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "./IAdminControlUpgradeable.sol"; abstract contract AdminControlUpgradeable is Initializable, OwnableUpgradeable, IAdminControlUpgradeable, ERC165Upgradeable { using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet; // Track registered admins EnumerableSetUpgradeable.AddressSet private _admins; /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __AdminControl_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); __ERC165_init_unchained(); __AdminControl_init_unchained(); } function __AdminControl_init_unchained() internal initializer {} /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) { return interfaceId == type(IAdminControlUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Only allows approved admins to call the specified function */ modifier adminRequired() { require(isAdmin(_msgSender()), "AdminControl: Must be owner or admin"); _; } /** * @dev See {IAdminControl-getAdmins}. */ function getAdmins() external view override returns (address[] memory admins) { admins = new address[](_admins.length()); for (uint256 i = 0; i < _admins.length(); i++) { admins[i] = _admins.at(i); } return admins; } /** * @dev See {IAdminControl-approveAdmin}. */ function approveAdmin(address admin) external override onlyOwner { if (_admins.add(admin)) { emit AdminApproved(admin, msg.sender); } } /** * @dev See {IAdminControl-revokeAdmin}. */ function revokeAdmin(address admin) external override onlyOwner { if (_admins.remove(admin)) { emit AdminRevoked(admin, msg.sender); } } /** * @dev See {IAdminControl-isAdmin}. */ function isAdmin(address admin) public view override returns (bool) { return (owner() == admin || _admins.contains(admin)); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity 0.8.2; import "@openzeppelin/contracts-upgradeable/utils/structs/EnumerableSetUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "../managers/ERC721/IERC721ProjectApproveTransferManager.sol"; import "../managers/ERC721/IERC721ProjectBurnableManager.sol"; import "../permissions/ERC721/IERC721ProjectMintPermissions.sol"; import "./IERC721ProjectCoreUpgradeable.sol"; import "./ProjectCoreUpgradeable.sol"; /** * @dev Core ERC721 project implementation */ abstract contract ERC721ProjectCoreUpgradeable is Initializable, ProjectCoreUpgradeable, IERC721ProjectCoreUpgradeable { using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet; /** * @dev initializer */ function __ERC721ProjectCore_init() internal initializer { __ProjectCore_init_unchained(); __ReentrancyGuard_init_unchained(); __ERC165_init_unchained(); __ERC721ProjectCore_init_unchained(); } function __ERC721ProjectCore_init_unchained() internal initializer {} /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ProjectCoreUpgradeable, IERC165Upgradeable) returns (bool) { return interfaceId == type(IERC721ProjectCoreUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IProjectCore-managerSetApproveTransfer}. */ function managerSetApproveTransfer(bool enabled) external override managerRequired { require( !enabled || ERC165CheckerUpgradeable.supportsInterface( msg.sender, type(IERC721ProjectApproveTransferManager).interfaceId ), "Manager must implement IERC721ProjectApproveTransferManager" ); if (_managerApproveTransfers[msg.sender] != enabled) { _managerApproveTransfers[msg.sender] = enabled; emit ManagerApproveTransferUpdated(msg.sender, enabled); } } /** * @dev Set mint permissions for an manager */ function _setMintPermissions(address manager, address permissions) internal { require(_managers.contains(manager), "ProjectCore: Invalid manager"); require( permissions == address(0x0) || ERC165CheckerUpgradeable.supportsInterface( permissions, type(IERC721ProjectMintPermissions).interfaceId ), "Invalid address" ); if (_managerPermissions[manager] != permissions) { _managerPermissions[manager] = permissions; emit MintPermissionsUpdated(manager, permissions, msg.sender); } } /** * Check if an manager can mint */ function _checkMintPermissions(address to, uint256 tokenId) internal { if (_managerPermissions[msg.sender] != address(0x0)) { IERC721ProjectMintPermissions(_managerPermissions[msg.sender]).approveMint(msg.sender, to, tokenId); } } /** * Override for post mint actions */ function _postMintBase(address, uint256) internal virtual {} /** * Override for post mint actions */ function _postMintManager(address, uint256) internal virtual {} /** * Post-burning callback and metadata cleanup */ function _postBurn(address owner, uint256 tokenId) internal virtual { // Callback to originating manager if needed if (_tokensManager[tokenId] != address(this)) { if ( ERC165CheckerUpgradeable.supportsInterface( _tokensManager[tokenId], type(IERC721ProjectBurnableManager).interfaceId ) ) { IERC721ProjectBurnableManager(_tokensManager[tokenId]).onBurn(owner, tokenId); } } // Clear metadata (if any) if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } // Delete token origin manager tracking delete _tokensManager[tokenId]; } /** * Approve a transfer */ function _approveTransfer( address from, address to, uint256 tokenId ) internal { if (_managerApproveTransfers[_tokensManager[tokenId]]) { require( IERC721ProjectApproveTransferManager(_tokensManager[tokenId]).approveTransfer(from, to, tokenId), "ERC721Project: Manager approval failure" ); } } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165Upgradeable.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721Upgradeable is IERC165Upgradeable { /** * @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; /** * @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 "../IERC721Upgradeable.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721MetadataUpgradeable is IERC721Upgradeable { /** * @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.0; /** * @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; // 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); } 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.8.0; import "../proxy/utils/Initializable.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 ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } 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; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library StringsUpgradeable { 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); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.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 ERC165Upgradeable is Initializable, IERC165Upgradeable { function __ERC165_init() internal initializer { __ERC165_init_unchained(); } function __ERC165_init_unchained() internal initializer { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165Upgradeable).interfaceId; } uint256[50] private __gap; } // 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 IERC165Upgradeable { /** * @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.2; import "../beacon/IBeaconUpgradeable.sol"; import "../../utils/AddressUpgradeable.sol"; import "../../utils/StorageSlotUpgradeable.sol"; import "../utils/Initializable.sol"; /** * @dev This abstract contract provides getters and event emitting update functions for * https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots. * * _Available since v4.1._ * * @custom:oz-upgrades-unsafe-allow delegatecall */ abstract contract ERC1967UpgradeUpgradeable is Initializable { function __ERC1967Upgrade_init() internal initializer { __ERC1967Upgrade_init_unchained(); } function __ERC1967Upgrade_init_unchained() internal initializer { } // This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1 bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143; /** * @dev Storage slot with the address of the current implementation. * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; /** * @dev Emitted when the implementation is upgraded. */ event Upgraded(address indexed implementation); /** * @dev Returns the current implementation address. */ function _getImplementation() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value; } /** * @dev Stores a new address in the EIP1967 implementation slot. */ function _setImplementation(address newImplementation) private { require(AddressUpgradeable.isContract(newImplementation), "ERC1967: new implementation is not a contract"); StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; } /** * @dev Perform implementation upgrade * * Emits an {Upgraded} event. */ function _upgradeTo(address newImplementation) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); } /** * @dev Perform implementation upgrade with additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCall(address newImplementation, bytes memory data, bool forceCall) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); if (data.length > 0 || forceCall) { _functionDelegateCall(newImplementation, data); } } /** * @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCallSecure(address newImplementation, bytes memory data, bool forceCall) internal { address oldImplementation = _getImplementation(); // Initial upgrade and setup call _setImplementation(newImplementation); if (data.length > 0 || forceCall) { _functionDelegateCall(newImplementation, data); } // Perform rollback test if not already in progress StorageSlotUpgradeable.BooleanSlot storage rollbackTesting = StorageSlotUpgradeable.getBooleanSlot(_ROLLBACK_SLOT); if (!rollbackTesting.value) { // Trigger rollback using upgradeTo from the new implementation rollbackTesting.value = true; _functionDelegateCall( newImplementation, abi.encodeWithSignature( "upgradeTo(address)", oldImplementation ) ); rollbackTesting.value = false; // Check rollback was effective require(oldImplementation == _getImplementation(), "ERC1967Upgrade: upgrade breaks further upgrades"); // Finally reset to the new implementation and log the upgrade _setImplementation(newImplementation); emit Upgraded(newImplementation); } } /** * @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does * not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that). * * Emits a {BeaconUpgraded} event. */ function _upgradeBeaconToAndCall(address newBeacon, bytes memory data, bool forceCall) internal { _setBeacon(newBeacon); emit BeaconUpgraded(newBeacon); if (data.length > 0 || forceCall) { _functionDelegateCall(IBeaconUpgradeable(newBeacon).implementation(), data); } } /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; /** * @dev Emitted when the admin account has changed. */ event AdminChanged(address previousAdmin, address newAdmin); /** * @dev Returns the current admin. */ function _getAdmin() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value; } /** * @dev Stores a new address in the EIP1967 admin slot. */ function _setAdmin(address newAdmin) private { require(newAdmin != address(0), "ERC1967: new admin is the zero address"); StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value = newAdmin; } /** * @dev Changes the admin of the proxy. * * Emits an {AdminChanged} event. */ function _changeAdmin(address newAdmin) internal { emit AdminChanged(_getAdmin(), newAdmin); _setAdmin(newAdmin); } /** * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy. * This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor. */ bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50; /** * @dev Emitted when the beacon is upgraded. */ event BeaconUpgraded(address indexed beacon); /** * @dev Returns the current beacon. */ function _getBeacon() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value; } /** * @dev Stores a new beacon in the EIP1967 beacon slot. */ function _setBeacon(address newBeacon) private { require( AddressUpgradeable.isContract(newBeacon), "ERC1967: new beacon is not a contract" ); require( AddressUpgradeable.isContract(IBeaconUpgradeable(newBeacon).implementation()), "ERC1967: beacon implementation is not a contract" ); StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value = newBeacon; } /* * @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) private returns (bytes memory) { require(AddressUpgradeable.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, "Address: low-level delegate call failed"); } 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); } } } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev This is the interface that {BeaconProxy} expects of its beacon. */ interface IBeaconUpgradeable { /** * @dev Must return an address that can be used as a delegate call target. * * {BeaconProxy} will check that this address is a contract. */ function implementation() external view returns (address); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Library for reading and writing primitive types to specific storage slots. * * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts. * This library helps with reading and writing to such slots without the need for inline assembly. * * The functions in this library return Slot structs that contain a `value` member that can be used to read or write. * * Example usage to set ERC1967 implementation slot: * ``` * contract ERC1967 { * bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; * * function _getImplementation() internal view returns (address) { * return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value; * } * * function _setImplementation(address newImplementation) internal { * require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract"); * StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; * } * } * ``` * * _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._ */ library StorageSlotUpgradeable { struct AddressSlot { address value; } struct BooleanSlot { bool value; } struct Bytes32Slot { bytes32 value; } struct Uint256Slot { uint256 value; } /** * @dev Returns an `AddressSlot` with member `value` located at `slot`. */ function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `BooleanSlot` with member `value` located at `slot`. */ function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Bytes32Slot` with member `value` located at `slot`. */ function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Uint256Slot` with member `value` located at `slot`. */ function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) { assembly { r.slot := slot } } } // 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 EnumerableSetUpgradeable { // 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] = 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) { 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.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.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 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 initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { 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; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity 0.8.2; import "@openzeppelin/contracts-upgradeable/utils/introspection/IERC165Upgradeable.sol"; /** * @dev Interface for admin control */ interface IAdminControlUpgradeable is IERC165Upgradeable { event AdminApproved(address indexed account, address indexed sender); event AdminRevoked(address indexed account, address indexed sender); /** * @dev gets address of all admins */ function getAdmins() external view returns (address[] memory); /** * @dev add an admin. Can only be called by contract owner. */ function approveAdmin(address admin) external; /** * @dev remove an admin. Can only be called by contract owner. */ function revokeAdmin(address admin) external; /** * @dev checks whether or not given address is an admin * Returns True if they are */ function isAdmin(address admin) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity 0.8.2; import "@openzeppelin/contracts/utils/introspection/IERC165.sol"; /** * Implement this if you want your manager to approve a transfer */ interface IERC721ProjectApproveTransferManager is IERC165 { /** * @dev Set whether or not the project will check the manager for approval of token transfer */ function setApproveTransfer(address project, bool enabled) external; /** * @dev Called by project contract to approve a transfer */ function approveTransfer( address from, address to, uint256 tokenId ) external returns (bool); } // SPDX-License-Identifier: MIT pragma solidity 0.8.2; import "@openzeppelin/contracts/utils/introspection/IERC165.sol"; /** * @dev Your manager is required to implement this interface if it wishes * to receive the onBurn callback whenever a token the manager created is * burned */ interface IERC721ProjectBurnableManager is IERC165 { /** * @dev callback handler for burn events */ function onBurn(address owner, uint256 tokenId) external; } // SPDX-License-Identifier: MIT pragma solidity 0.8.2; import "@openzeppelin/contracts/utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721Project compliant manager contracts. */ interface IERC721ProjectMintPermissions is IERC165 { /** * @dev get approval to mint */ function approveMint( address manager, address to, uint256 tokenId ) external; } // SPDX-License-Identifier: MIT pragma solidity 0.8.2; import "./IProjectCoreUpgradeable.sol"; /** * @dev Core ERC721 project interface */ interface IERC721ProjectCoreUpgradeable is IProjectCoreUpgradeable { /** * @dev mint a token with no manager. Can only be called by an admin. set uri to empty string to use default uri. * Returns tokenId minted */ function adminMint(address to, string calldata uri) external returns (uint256); /** * @dev batch mint a token with no manager. Can only be called by an admin. * Returns tokenId minted */ function adminMintBatch(address to, uint16 count) external returns (uint256[] memory); /** * @dev batch mint a token with no manager. Can only be called by an admin. * Returns tokenId minted */ function adminMintBatch(address to, string[] calldata uris) external returns (uint256[] memory); /** * @dev mint a token. Can only be called by a registered manager. set uri to "" to use default uri * Returns tokenId minted */ function managerMint(address to, string calldata uri) external returns (uint256); /** * @dev batch mint a token. Can only be called by a registered manager. * Returns tokenIds minted */ function managerMintBatch(address to, uint16 count) external returns (uint256[] memory); /** * @dev batch mint a token. Can only be called by a registered manager. * Returns tokenId minted */ function managerMintBatch(address to, string[] calldata uris) external returns (uint256[] memory); /** * @dev burn a token. Can only be called by token owner or approved address. * On burn, calls back to the registered manager's onBurn method */ function burn(uint256 tokenId) external; } // SPDX-License-Identifier: MIT pragma solidity 0.8.2; import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/StringsUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/introspection/ERC165Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/introspection/ERC165CheckerUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/structs/EnumerableSetUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "../managers/ProjectTokenURIManager/IProjectTokenURIManager.sol"; import "./IProjectCoreUpgradeable.sol"; /** * @dev Core project implementation */ abstract contract ProjectCoreUpgradeable is Initializable, IProjectCoreUpgradeable, ReentrancyGuardUpgradeable, ERC165Upgradeable { using StringsUpgradeable for uint256; using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet; using AddressUpgradeable for address; /** * External interface identifiers for royalties */ /** * @dev ProjectCore * * bytes4(keccak256('getRoyalties(uint256)')) == 0xbb3bafd6 * * => 0xbb3bafd6 = 0xbb3bafd6 */ bytes4 private constant _INTERFACE_ID_ROYALTIES_PROJECTCORE = 0xbb3bafd6; /** * @dev Rarible: RoyaltiesV1 * * bytes4(keccak256('getFeeRecipients(uint256)')) == 0xb9c4d9fb * bytes4(keccak256('getFeeBps(uint256)')) == 0x0ebd4c7f * * => 0xb9c4d9fb ^ 0x0ebd4c7f = 0xb7799584 */ bytes4 private constant _INTERFACE_ID_ROYALTIES_RARIBLE = 0xb7799584; /** * @dev Foundation * * bytes4(keccak256('getFees(uint256)')) == 0xd5a06d4c * * => 0xd5a06d4c = 0xd5a06d4c */ bytes4 private constant _INTERFACE_ID_ROYALTIES_FOUNDATION = 0xd5a06d4c; /** * @dev EIP-2981 * * bytes4(keccak256("royaltyInfo(uint256,uint256,bytes)")) == 0x6057361d * * => 0x6057361d = 0x6057361d */ bytes4 private constant _INTERFACE_ID_ROYALTIES_EIP2981 = 0x6057361d; uint256 _tokenCount; // Track registered managers data EnumerableSetUpgradeable.AddressSet internal _managers; EnumerableSetUpgradeable.AddressSet internal _blacklistedManagers; mapping(address => address) internal _managerPermissions; mapping(address => bool) internal _managerApproveTransfers; // For tracking which manager a token was minted by mapping(uint256 => address) internal _tokensManager; // The baseURI for a given manager mapping(address => string) private _managerBaseURI; mapping(address => bool) private _managerBaseURIIdentical; // The prefix for any tokens with a uri configured mapping(address => string) private _managerURIPrefix; // Mapping for individual token URIs mapping(uint256 => string) internal _tokenURIs; // Royalty configurations mapping(address => address payable[]) internal _managerRoyaltyReceivers; mapping(address => uint256[]) internal _managerRoyaltyBPS; mapping(uint256 => address payable[]) internal _tokenRoyaltyReceivers; mapping(uint256 => uint256[]) internal _tokenRoyaltyBPS; /** * @dev initializer */ function __ProjectCore_init() internal initializer { __ReentrancyGuard_init_unchained(); __ERC165_init_unchained(); __ProjectCore_init_unchained(); _tokenCount = 0; } function __ProjectCore_init_unchained() internal initializer {} /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) { return interfaceId == type(IProjectCoreUpgradeable).interfaceId || super.supportsInterface(interfaceId) || interfaceId == _INTERFACE_ID_ROYALTIES_PROJECTCORE || interfaceId == _INTERFACE_ID_ROYALTIES_RARIBLE || interfaceId == _INTERFACE_ID_ROYALTIES_FOUNDATION || interfaceId == _INTERFACE_ID_ROYALTIES_EIP2981; } /** * @dev Only allows registered managers to call the specified function */ modifier managerRequired() { require(_managers.contains(msg.sender), "Must be registered manager"); _; } /** * @dev Only allows non-blacklisted managers */ modifier nonBlacklistRequired(address manager) { require(!_blacklistedManagers.contains(manager), "Manager blacklisted"); _; } /** * @dev totalSupply */ function totalSupply() public view override returns (uint256) { return _tokenCount; } /** * @dev See {IProjectCore-getManagers}. */ function getManagers() external view override returns (address[] memory managers) { managers = new address[](_managers.length()); for (uint256 i = 0; i < _managers.length(); i++) { managers[i] = _managers.at(i); } return managers; } /** * @dev Register an manager */ function _registerManager( address manager, string calldata baseURI, bool baseURIIdentical ) internal { require(manager != address(this), "Project: Invalid"); require(manager.isContract(), "Project: Manager must be a contract"); if (_managers.add(manager)) { _managerBaseURI[manager] = baseURI; _managerBaseURIIdentical[manager] = baseURIIdentical; emit ManagerRegistered(manager, msg.sender); } } /** * @dev Unregister an manager */ function _unregisterManager(address manager) internal { if (_managers.remove(manager)) { emit ManagerUnregistered(manager, msg.sender); } } /** * @dev Blacklist an manager */ function _blacklistManager(address manager) internal { require(manager != address(this), "Cannot blacklist yourself"); if (_managers.remove(manager)) { emit ManagerUnregistered(manager, msg.sender); } if (_blacklistedManagers.add(manager)) { emit ManagerBlacklisted(manager, msg.sender); } } /** * @dev Set base token uri for an manager */ function _managerSetBaseTokenURI(string calldata uri, bool identical) internal { _managerBaseURI[msg.sender] = uri; _managerBaseURIIdentical[msg.sender] = identical; } /** * @dev Set token uri prefix for an manager */ function _managerSetTokenURIPrefix(string calldata prefix) internal { _managerURIPrefix[msg.sender] = prefix; } /** * @dev Set token uri for a token of an manager */ function _managerSetTokenURI(uint256 tokenId, string calldata uri) internal { require(_tokensManager[tokenId] == msg.sender, "Invalid token"); _tokenURIs[tokenId] = uri; } /** * @dev Set base token uri for tokens with no manager */ function _setBaseTokenURI(string memory uri) internal { _managerBaseURI[address(this)] = uri; } /** * @dev Set token uri prefix for tokens with no manager */ function _setTokenURIPrefix(string calldata prefix) internal { _managerURIPrefix[address(this)] = prefix; } /** * @dev Set token uri for a token with no manager */ function _setTokenURI(uint256 tokenId, string calldata uri) internal { require(_tokensManager[tokenId] == address(this), "Invalid token"); _tokenURIs[tokenId] = uri; } /** * @dev Retrieve a token's URI */ function _tokenURI(uint256 tokenId) internal view returns (string memory) { address manager = _tokensManager[tokenId]; require(!_blacklistedManagers.contains(manager), "Manager blacklisted"); // 1. if tokenURI is stored in this contract, use it with managerURIPrefix if any if (bytes(_tokenURIs[tokenId]).length != 0) { if (bytes(_managerURIPrefix[manager]).length != 0) { return string(abi.encodePacked(_managerURIPrefix[manager], _tokenURIs[tokenId])); } return _tokenURIs[tokenId]; } // 2. if URI is controlled by manager, retrieve it from manager if (ERC165CheckerUpgradeable.supportsInterface(manager, type(IProjectTokenURIManager).interfaceId)) { return IProjectTokenURIManager(manager).tokenURI(address(this), tokenId); } // 3. use managerBaseURI with id or not if (!_managerBaseURIIdentical[manager]) { return string(abi.encodePacked(_managerBaseURI[manager], tokenId.toString())); } else { return _managerBaseURI[manager]; } } /** * Get token manager */ function _tokenManager(uint256 tokenId) internal view returns (address manager) { manager = _tokensManager[tokenId]; require(manager != address(this), "No manager for token"); require(!_blacklistedManagers.contains(manager), "Manager blacklisted"); return manager; } /** * Helper to get royalties for a token */ function _getRoyalties(uint256 tokenId) internal view returns (address payable[] storage, uint256[] storage) { return (_getRoyaltyReceivers(tokenId), _getRoyaltyBPS(tokenId)); } /** * Helper to get royalty receivers for a token */ function _getRoyaltyReceivers(uint256 tokenId) internal view returns (address payable[] storage) { if (_tokenRoyaltyReceivers[tokenId].length > 0) { return _tokenRoyaltyReceivers[tokenId]; } else if (_managerRoyaltyReceivers[_tokensManager[tokenId]].length > 0) { return _managerRoyaltyReceivers[_tokensManager[tokenId]]; } return _managerRoyaltyReceivers[address(this)]; } /** * Helper to get royalty basis points for a token */ function _getRoyaltyBPS(uint256 tokenId) internal view returns (uint256[] storage) { if (_tokenRoyaltyBPS[tokenId].length > 0) { return _tokenRoyaltyBPS[tokenId]; } else if (_managerRoyaltyBPS[_tokensManager[tokenId]].length > 0) { return _managerRoyaltyBPS[_tokensManager[tokenId]]; } return _managerRoyaltyBPS[address(this)]; } function _getRoyaltyInfo(uint256 tokenId, uint256 value) internal view returns ( address receiver, uint256 amount, bytes memory data ) { address payable[] storage receivers = _getRoyaltyReceivers(tokenId); require(receivers.length <= 1, "More than 1 royalty receiver"); if (receivers.length == 0) { return (address(this), 0, data); } return (receivers[0], (_getRoyaltyBPS(tokenId)[0] * value) / 10000, data); } /** * Set royalties for a token */ function _setRoyalties( uint256 tokenId, address payable[] calldata receivers, uint256[] calldata basisPoints ) internal { require(receivers.length == basisPoints.length, "Invalid input"); uint256 totalBasisPoints; for (uint256 i = 0; i < basisPoints.length; i++) { totalBasisPoints += basisPoints[i]; } require(totalBasisPoints < 10000, "Invalid total royalties"); _tokenRoyaltyReceivers[tokenId] = receivers; _tokenRoyaltyBPS[tokenId] = basisPoints; emit RoyaltiesUpdated(tokenId, receivers, basisPoints); } /** * Set royalties for all tokens of an manager */ function _setRoyaltiesManager( address manager, address payable[] calldata receivers, uint256[] calldata basisPoints ) internal { require(receivers.length == basisPoints.length, "Invalid input"); uint256 totalBasisPoints; for (uint256 i = 0; i < basisPoints.length; i++) { totalBasisPoints += basisPoints[i]; } require(totalBasisPoints < 10000, "Invalid total royalties"); _managerRoyaltyReceivers[manager] = receivers; _managerRoyaltyBPS[manager] = basisPoints; if (manager == address(this)) { emit DefaultRoyaltiesUpdated(receivers, basisPoints); } else { emit ManagerRoyaltiesUpdated(manager, receivers, basisPoints); } } uint256[36] private __gap; } // 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.2; import "@openzeppelin/contracts-upgradeable/utils/introspection/IERC165Upgradeable.sol"; /** * @dev Core project interface */ interface IProjectCoreUpgradeable is IERC165Upgradeable { event ManagerRegistered(address indexed manager, address indexed sender); event ManagerUnregistered(address indexed manager, address indexed sender); event ManagerBlacklisted(address indexed manager, address indexed sender); event MintPermissionsUpdated(address indexed manager, address indexed permissions, address indexed sender); event RoyaltiesUpdated(uint256 indexed tokenId, address payable[] receivers, uint256[] basisPoints); event DefaultRoyaltiesUpdated(address payable[] receivers, uint256[] basisPoints); event ManagerRoyaltiesUpdated(address indexed manager, address payable[] receivers, uint256[] basisPoints); event ManagerApproveTransferUpdated(address indexed manager, bool enabled); /** * @dev totalSupply */ function totalSupply() external view returns (uint256); /** * @dev gets address of all managers */ function getManagers() external view returns (address[] memory); /** * @dev add an manager. Can only be called by contract owner or admin. * manager address must point to a contract implementing IProjectManager. * Returns True if newly added, False if already added. */ function registerManager(address manager, string calldata baseURI) external; /** * @dev add an manager. Can only be called by contract owner or admin. * manager address must point to a contract implementing IProjectManager. * Returns True if newly added, False if already added. */ function registerManager( address manager, string calldata baseURI, bool baseURIIdentical ) external; /** * @dev add an manager. Can only be called by contract owner or admin. * Returns True if removed, False if already removed. */ function unregisterManager(address manager) external; /** * @dev blacklist an manager. Can only be called by contract owner or admin. * This function will destroy all ability to reference the metadata of any tokens created * by the specified manager. It will also unregister the manager if needed. * Returns True if removed, False if already removed. */ function blacklistManager(address manager) external; /** * @dev set the baseTokenURI of an manager. Can only be called by manager. */ function managerSetBaseTokenURI(string calldata uri) external; /** * @dev set the baseTokenURI of an manager. Can only be called by manager. * For tokens with no uri configured, tokenURI will return "uri+tokenId" */ function managerSetBaseTokenURI(string calldata uri, bool identical) external; /** * @dev set the common prefix of an manager. Can only be called by manager. * If configured, and a token has a uri set, tokenURI will return "prefixURI+tokenURI" * Useful if you want to use ipfs/arweave */ function managerSetTokenURIPrefix(string calldata prefix) external; /** * @dev set the tokenURI of a token manager. Can only be called by manager that minted token. */ function managerSetTokenURI(uint256 tokenId, string calldata uri) external; /** * @dev set the tokenURI of a token manager for multiple tokens. Can only be called by manager that minted token. */ function managerSetTokenURI(uint256[] calldata tokenId, string[] calldata uri) external; /** * @dev set the baseTokenURI for tokens with no manager. Can only be called by owner/admin. * For tokens with no uri configured, tokenURI will return "uri+tokenId" */ function setBaseTokenURI(string calldata uri) external; /** * @dev set the common prefix for tokens with no manager. Can only be called by owner/admin. * If configured, and a token has a uri set, tokenURI will return "prefixURI+tokenURI" * Useful if you want to use ipfs/arweave */ function setTokenURIPrefix(string calldata prefix) external; /** * @dev set the tokenURI of a token with no manager. Can only be called by owner/admin. */ function setTokenURI(uint256 tokenId, string calldata uri) external; /** * @dev set the tokenURI of multiple tokens with no manager. Can only be called by owner/admin. */ function setTokenURI(uint256[] calldata tokenIds, string[] calldata uris) external; /** * @dev set a permissions contract for an manager. Used to control minting. */ function setMintPermissions(address manager, address permissions) external; /** * @dev Configure so transfers of tokens created by the caller (must be manager) gets approval * from the manager before transferring */ function managerSetApproveTransfer(bool enabled) external; /** * @dev get the manager of a given token */ function tokenManager(uint256 tokenId) external view returns (address); /** * @dev Set default royalties */ function setRoyalties(address payable[] calldata receivers, uint256[] calldata basisPoints) external; /** * @dev Set royalties of a token */ function setRoyalties( uint256 tokenId, address payable[] calldata receivers, uint256[] calldata basisPoints ) external; /** * @dev Set royalties of an manager */ function setRoyaltiesManager( address manager, address payable[] calldata receivers, uint256[] calldata basisPoints ) external; /** * @dev Get royalites of a token. Returns list of receivers and basisPoints */ function getRoyalties(uint256 tokenId) external view returns (address payable[] memory, uint256[] memory); // Royalty support for various other standards function getFeeRecipients(uint256 tokenId) external view returns (address payable[] memory); function getFeeBps(uint256 tokenId) external view returns (uint256[] memory); function getFees(uint256 tokenId) external view returns (address payable[] memory, uint256[] memory); function royaltyInfo( uint256 tokenId, uint256 value, bytes calldata data ) external view returns ( address, uint256, bytes memory ); } // 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 "./IERC165Upgradeable.sol"; /** * @dev Library used to query support of an interface declared via {IERC165}. * * Note that these functions return the actual result of the query: they do not * `revert` if an interface is not supported. It is up to the caller to decide * what to do in these cases. */ library ERC165CheckerUpgradeable { // As per the EIP-165 spec, no interface should ever match 0xffffffff bytes4 private constant _INTERFACE_ID_INVALID = 0xffffffff; /** * @dev Returns true if `account` supports the {IERC165} interface, */ function supportsERC165(address account) internal view returns (bool) { // Any contract that implements ERC165 must explicitly indicate support of // InterfaceId_ERC165 and explicitly indicate non-support of InterfaceId_Invalid return _supportsERC165Interface(account, type(IERC165Upgradeable).interfaceId) && !_supportsERC165Interface(account, _INTERFACE_ID_INVALID); } /** * @dev Returns true if `account` supports the interface defined by * `interfaceId`. Support for {IERC165} itself is queried automatically. * * See {IERC165-supportsInterface}. */ function supportsInterface(address account, bytes4 interfaceId) internal view returns (bool) { // query support of both ERC165 as per the spec and support of _interfaceId return supportsERC165(account) && _supportsERC165Interface(account, interfaceId); } /** * @dev Returns a boolean array where each value corresponds to the * interfaces passed in and whether they're supported or not. This allows * you to batch check interfaces for a contract where your expectation * is that some interfaces may not be supported. * * See {IERC165-supportsInterface}. * * _Available since v3.4._ */ function getSupportedInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool[] memory) { // an array of booleans corresponding to interfaceIds and whether they're supported or not bool[] memory interfaceIdsSupported = new bool[](interfaceIds.length); // query support of ERC165 itself if (supportsERC165(account)) { // query support of each interface in interfaceIds for (uint256 i = 0; i < interfaceIds.length; i++) { interfaceIdsSupported[i] = _supportsERC165Interface(account, interfaceIds[i]); } } return interfaceIdsSupported; } /** * @dev Returns true if `account` supports all the interfaces defined in * `interfaceIds`. Support for {IERC165} itself is queried automatically. * * Batch-querying can lead to gas savings by skipping repeated checks for * {IERC165} support. * * See {IERC165-supportsInterface}. */ function supportsAllInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool) { // query support of ERC165 itself if (!supportsERC165(account)) { return false; } // query support of each interface in _interfaceIds for (uint256 i = 0; i < interfaceIds.length; i++) { if (!_supportsERC165Interface(account, interfaceIds[i])) { return false; } } // all interfaces supported return true; } /** * @notice Query if a contract implements an interface, does not check ERC165 support * @param account The address of the contract to query for support of an interface * @param interfaceId The interface identifier, as specified in ERC-165 * @return true if the contract at account indicates support of the interface with * identifier interfaceId, false otherwise * @dev Assumes that account contains a contract that supports ERC165, otherwise * the behavior of this method is undefined. This precondition can be checked * with {supportsERC165}. * Interface identification is specified in ERC-165. */ function _supportsERC165Interface(address account, bytes4 interfaceId) private view returns (bool) { bytes memory encodedParams = abi.encodeWithSelector(IERC165Upgradeable(account).supportsInterface.selector, interfaceId); (bool success, bytes memory result) = account.staticcall{ gas: 30000 }(encodedParams); if (result.length < 32) return false; return success && abi.decode(result, (bool)); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.2; import "@openzeppelin/contracts/utils/introspection/IERC165.sol"; /** * @dev Implement this if you want your manager to have overloadable URI's */ interface IProjectTokenURIManager is IERC165 { /** * Get the uri for a given project/tokenId */ function tokenURI(address project, uint256 tokenId) external view returns (string memory); }
See {IProjectCore-registerManager}./
function registerManager(address manager, string calldata baseURI) external override adminRequired nonBlacklistRequired(manager) { _registerManager(manager, baseURI, false); }
12,006,203
pragma solidity ^0.5.10; /** @title A contract for generating unique identifiers * * @notice A contract that provides an identifier generation scheme, * guaranteeing uniqueness across all contracts that inherit from it, * as well as the unpredictability of future identifiers. * * @dev This contract is intended to be inherited by any contract that * implements the callback software pattern for cooperative custodianship. * */ contract LockRequestable { // MEMBERS /// @notice the count of all invocations of `generateLockId`. uint256 public lockRequestCount; // CONSTRUCTOR constructor() public { lockRequestCount = 0; } // FUNCTIONS /** @notice Returns a fresh unique identifier. * * @dev the generation scheme uses three components. * First, the blockhash of the previous block. * Second, the deployed address. * Third, the next value of the counter. * This ensures that identifiers are unique across all contracts * following this scheme, and that future identifiers are * unpredictable. * * @return a 32-byte unique identifier. */ function generateLockId() internal returns (bytes32 lockId) { return keccak256(abi.encodePacked(blockhash(block.number - 1), address(this), ++lockRequestCount)); } } contract ERC20Interface { // METHODS // NOTE: // public getter functions are not currently recognised as an // implementation of the matching abstract function by the compiler. // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#name // function name() public view returns (string); // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#symbol // function symbol() public view returns (string); // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#totalsupply // function decimals() public view returns (uint8); // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#totalsupply function totalSupply() public view returns (uint256); // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#balanceof function balanceOf(address _owner) public view returns (uint256 balance); // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#transfer function transfer(address _to, uint256 _value) public returns (bool success); // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#transferfrom function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#approve function approve(address _spender, uint256 _value) public returns (bool success); // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#allowance function allowance(address _owner, address _spender) public view returns (uint256 remaining); // EVENTS // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#transfer-1 event Transfer(address indexed _from, address indexed _to, uint256 _value); // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#approval event Approval(address indexed _owner, address indexed _spender, uint256 _value); } /** @title A dual control contract. * * @notice A general-purpose contract that implements dual control over * co-operating contracts through a callback mechanism. * * @dev This contract implements dual control through a 2-of-N * threshold multi-signature scheme. The contract recognizes a set of N signers, * and will unlock requests with signatures from any distinct pair of them. * This contract signals the unlocking through a co-operative callback * scheme. * This contract also provides time lock and revocation features. * Requests made by a 'primary' account have a default time lock applied. * All other requests must pay a 1 ETH stake and have an extended time lock * applied. * A request that is completed will prevent all previous pending requests * that share the same callback from being completed: this is the * revocation feature. * */ contract Custodian { // TYPES /** @dev The `Request` struct stores a pending unlocking. * `callbackAddress` and `callbackSelector` are the data required to * make a callback. The custodian completes the process by * calling `callbackAddress.call(callbackSelector, lockId)`, which * signals to the contract co-operating with the Custodian that * the 2-of-N signatures have been provided and verified. */ struct Request { bytes32 lockId; bytes4 callbackSelector; // bytes4 and address can be packed into 1 word address callbackAddress; uint256 idx; uint256 timestamp; bool extended; } // EVENTS /// @dev Emitted by successful `requestUnlock` calls. event Requested( bytes32 _lockId, address _callbackAddress, bytes4 _callbackSelector, uint256 _nonce, address _whitelistedAddress, bytes32 _requestMsgHash, uint256 _timeLockExpiry ); /// @dev Emitted by `completeUnlock` calls on requests in the time-locked state. event TimeLocked( uint256 _timeLockExpiry, bytes32 _requestMsgHash ); /// @dev Emitted by successful `completeUnlock` calls. event Completed( bytes32 _lockId, bytes32 _requestMsgHash, address _signer1, address _signer2 ); /// @dev Emitted by `completeUnlock` calls where the callback failed. event Failed( bytes32 _lockId, bytes32 _requestMsgHash, address _signer1, address _signer2 ); /// @dev Emitted by successful `extendRequestTimeLock` calls. event TimeLockExtended( uint256 _timeLockExpiry, bytes32 _requestMsgHash ); // MEMBERS /** @dev The count of all requests. * This value is used as a nonce, incorporated into the request hash. */ uint256 public requestCount; /// @dev The set of signers: signatures from two signers unlock a pending request. mapping (address => bool) public signerSet; /// @dev The map of request hashes to pending requests. mapping (bytes32 => Request) public requestMap; /// @dev The map of callback addresses to callback selectors to request indexes. mapping (address => mapping (bytes4 => uint256)) public lastCompletedIdxs; /** @dev The default period (in seconds) to time-lock requests. * All requests will be subject to this default time lock, and the duration * is fixed at contract creation. */ uint256 public defaultTimeLock; /** @dev The extended period (in seconds) to time-lock requests. * Requests not from the primary account are subject to this time lock. * The primary account may also elect to extend the time lock on requests * that originally received the default. */ uint256 public extendedTimeLock; /// @dev The primary account is the privileged account for making requests. address public primary; // CONSTRUCTOR constructor( address[] memory _signers, uint256 _defaultTimeLock, uint256 _extendedTimeLock, address _primary ) public { // check for at least two `_signers` require(_signers.length >= 2, "at least two `_signers`"); // validate time lock params require(_defaultTimeLock <= _extendedTimeLock, "valid timelock params"); defaultTimeLock = _defaultTimeLock; extendedTimeLock = _extendedTimeLock; primary = _primary; // explicitly initialize `requestCount` to zero requestCount = 0; // turn the array into a set for (uint i = 0; i < _signers.length; i++) { // no zero addresses or duplicates require(_signers[i] != address(0) && !signerSet[_signers[i]], "no zero addresses or duplicates"); signerSet[_signers[i]] = true; } } // MODIFIERS modifier onlyPrimary { require(msg.sender == primary, "only primary"); _; } modifier onlySigner { require(signerSet[msg.sender], "only signer"); _; } // METHODS /** @notice Requests an unlocking with a lock identifier and a callback. * * @dev If called by an account other than the primary a 1 ETH stake * must be paid. When the request is unlocked stake will be transferred to the message sender. * This is an anti-spam measure. As well as the callback * and the lock identifier parameters a 'whitelisted address' is required * for compatibility with existing signature schemes. * * @param _lockId The identifier of a pending request in a co-operating contract. * @param _callbackAddress The address of a co-operating contract. * @param _callbackSelector The function selector of a function within * the co-operating contract at address `_callbackAddress`. * @param _whitelistedAddress An address whitelisted in existing * offline control protocols. * * @return requestMsgHash The hash of a request message to be signed. */ function requestUnlock( bytes32 _lockId, address _callbackAddress, bytes4 _callbackSelector, address _whitelistedAddress ) public payable returns (bytes32 requestMsgHash) { require(msg.sender == primary || msg.value >= 1 ether, "sender is primary or stake is paid"); // disallow using a zero value for the callback address require(_callbackAddress != address(0), "no zero value for callback address"); uint256 requestIdx = ++requestCount; // compute a nonce value // - the blockhash prevents prediction of future nonces // - the address of this contract prevents conflicts with co-operating contracts using this scheme // - the counter prevents conflicts arising from multiple txs within the same block uint256 nonce = uint256(keccak256(abi.encodePacked(blockhash(block.number - 1), address(this), requestIdx))); requestMsgHash = keccak256( abi.encodePacked( nonce, _whitelistedAddress, uint256(0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) ) ); requestMap[requestMsgHash] = Request({ lockId: _lockId, callbackSelector: _callbackSelector, callbackAddress: _callbackAddress, idx: requestIdx, timestamp: block.timestamp, extended: false }); // compute the expiry time uint256 timeLockExpiry = block.timestamp; if (msg.sender == primary) { timeLockExpiry += defaultTimeLock; } else { timeLockExpiry += extendedTimeLock; // any sender that is not the creator will get the extended time lock requestMap[requestMsgHash].extended = true; } emit Requested(_lockId, _callbackAddress, _callbackSelector, nonce, _whitelistedAddress, requestMsgHash, timeLockExpiry); } /** @notice Completes a pending unlocking with two signatures. * * @dev Given a request message hash as two signatures of it from * two distinct signers in the signer set, this function completes the * unlocking of the pending request by executing the callback. * * @param _requestMsgHash The request message hash of a pending request. * @param _recoveryByte1 The public key recovery byte (27 or 28) * @param _ecdsaR1 The R component of an ECDSA signature (R, S) pair * @param _ecdsaS1 The S component of an ECDSA signature (R, S) pair * @param _recoveryByte2 The public key recovery byte (27 or 28) * @param _ecdsaR2 The R component of an ECDSA signature (R, S) pair * @param _ecdsaS2 The S component of an ECDSA signature (R, S) pair * * @return success True if the callback successfully executed. */ function completeUnlock( bytes32 _requestMsgHash, uint8 _recoveryByte1, bytes32 _ecdsaR1, bytes32 _ecdsaS1, uint8 _recoveryByte2, bytes32 _ecdsaR2, bytes32 _ecdsaS2 ) public onlySigner returns (bool success) { Request storage request = requestMap[_requestMsgHash]; // copy storage to locals before `delete` bytes32 lockId = request.lockId; address callbackAddress = request.callbackAddress; bytes4 callbackSelector = request.callbackSelector; // failing case of the lookup if the callback address is zero require(callbackAddress != address(0), "no zero value for callback address"); // reject confirms of earlier withdrawals buried under later confirmed withdrawals require(request.idx > lastCompletedIdxs[callbackAddress][callbackSelector], "reject confirms of earlier withdrawals buried under later confirmed withdrawals"); address signer1 = ecrecover( keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", _requestMsgHash)), _recoveryByte1, _ecdsaR1, _ecdsaS1 ); require(signerSet[signer1], "signer is set"); address signer2 = ecrecover( keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", _requestMsgHash)), _recoveryByte2, _ecdsaR2, _ecdsaS2 ); require(signerSet[signer2], "signer is set"); require(signer1 != signer2, "signers are different"); if (request.extended && ((block.timestamp - request.timestamp) < extendedTimeLock)) { emit TimeLocked(request.timestamp + extendedTimeLock, _requestMsgHash); return false; } else if ((block.timestamp - request.timestamp) < defaultTimeLock) { emit TimeLocked(request.timestamp + defaultTimeLock, _requestMsgHash); return false; } else { if (address(this).balance > 0) { // reward sender with anti-spam payments msg.sender.transfer(address(this).balance); } // raise the waterline for the last completed unlocking lastCompletedIdxs[callbackAddress][callbackSelector] = request.idx; // and delete the request delete requestMap[_requestMsgHash]; // invoke callback (success,) = (false, bytes(msg.data)); callbackAddress.call(abi.encodeWithSelector(callbackSelector, lockId)); //inject UNHANDLED EXCEPTION if (success) { emit Completed(lockId, _requestMsgHash, signer1, signer2); } else { emit Failed(lockId, _requestMsgHash, signer1, signer2); } } } /** @notice Reclaim the storage of a pending request that is uncompletable. * * @dev If a pending request shares the callback (address and selector) of * a later request has been completed, then the request can no longer * be completed. This function will reclaim the contract storage of the * pending request. * * @param _requestMsgHash The request message hash of a pending request. */ function deleteUncompletableRequest(bytes32 _requestMsgHash) public { Request storage request = requestMap[_requestMsgHash]; uint256 idx = request.idx; require(0 < idx && idx < lastCompletedIdxs[request.callbackAddress][request.callbackSelector], "there must be a completed latter request with same callback"); delete requestMap[_requestMsgHash]; } /** @notice Extend the time lock of a pending request. * * @dev Requests made by the primary account receive the default time lock. * This function allows the primary account to apply the extended time lock * to one its own requests. * * @param _requestMsgHash The request message hash of a pending request. */ function extendRequestTimeLock(bytes32 _requestMsgHash) public onlyPrimary { Request storage request = requestMap[_requestMsgHash]; // reject 1null1 results from the map lookup // this can only be the case if an unknown `_requestMsgHash` is received require(request.callbackAddress != address(0), "reject 1null1 results from the map lookup"); // `extendRequestTimeLock` must be idempotent require(request.extended != true, "`extendRequestTimeLock` must be idempotent"); // set the `extended` flag; note that this is never unset request.extended = true; emit TimeLockExtended(request.timestamp + extendedTimeLock, _requestMsgHash); } } /** @title A contract to inherit upgradeable custodianship. * * @notice A contract that provides re-usable code for upgradeable * custodianship. That custodian may be an account or another contract. * * @dev This contract is intended to be inherited by any contract * requiring a custodian to control some aspect of its functionality. * This contract provides the mechanism for that custodianship to be * passed from one custodian to the next. * */ contract CustodianUpgradeable is LockRequestable { // TYPES /// @dev The struct type for pending custodian changes. struct CustodianChangeRequest { address proposedNew; } // MEMBERS /// @dev The address of the account or contract that acts as the custodian. address public custodian; /// @dev The map of lock ids to pending custodian changes. mapping (bytes32 => CustodianChangeRequest) public custodianChangeReqs; // CONSTRUCTOR constructor( address _custodian ) LockRequestable() public { custodian = _custodian; } // MODIFIERS modifier onlyCustodian { require(msg.sender == custodian, "only custodian"); _; } // PUBLIC FUNCTIONS // (UPGRADE) /** @notice Requests a change of the custodian associated with this contract. * * @dev Returns a unique lock id associated with the request. * Anyone can call this function, but confirming the request is authorized * by the custodian. * * @param _proposedCustodian The address of the new custodian. * @return lockId A unique identifier for this request. */ function requestCustodianChange(address _proposedCustodian) public returns (bytes32 lockId) { require(_proposedCustodian != address(0), "no null value for `_proposedCustodian`"); lockId = generateLockId(); custodianChangeReqs[lockId] = CustodianChangeRequest({ proposedNew: _proposedCustodian }); emit CustodianChangeRequested(lockId, msg.sender, _proposedCustodian); } /** @notice Confirms a pending change of the custodian associated with this contract. * * @dev When called by the current custodian with a lock id associated with a * pending custodian change, the `address custodian` member will be updated with the * requested address. * * @param _lockId The identifier of a pending change request. */ function confirmCustodianChange(bytes32 _lockId) public onlyCustodian { custodian = getCustodianChangeReq(_lockId); delete custodianChangeReqs[_lockId]; emit CustodianChangeConfirmed(_lockId, custodian); } // PRIVATE FUNCTIONS function getCustodianChangeReq(bytes32 _lockId) private view returns (address _proposedNew) { CustodianChangeRequest storage changeRequest = custodianChangeReqs[_lockId]; // reject 1null1 results from the map lookup // this can only be the case if an unknown `_lockId` is received require(changeRequest.proposedNew != address(0), "reject 1null1 results from the map lookup"); return changeRequest.proposedNew; } //EVENTS /// @dev Emitted by successful `requestCustodianChange` calls. event CustodianChangeRequested( bytes32 _lockId, address _msgSender, address _proposedCustodian ); /// @dev Emitted by successful `confirmCustodianChange` calls. event CustodianChangeConfirmed(bytes32 _lockId, address _newCustodian); } /** @title A contract to inherit upgradeable token implementations. * * @notice A contract that provides re-usable code for upgradeable * token implementations. It itself inherits from `CustodianUpgradable` * as the upgrade process is controlled by the custodian. * * @dev This contract is intended to be inherited by any contract * requiring a reference to the active token implementation, either * to delegate calls to it, or authorize calls from it. This contract * provides the mechanism for that implementation to be replaced, * which constitutes an implementation upgrade. * */ contract ERC20ImplUpgradeable is CustodianUpgradeable { // TYPES /// @dev The struct type for pending implementation changes. struct ImplChangeRequest { address proposedNew; } // MEMBERS // @dev The reference to the active token implementation. ERC20Impl public erc20Impl; /// @dev The map of lock ids to pending implementation changes. mapping (bytes32 => ImplChangeRequest) public implChangeReqs; // CONSTRUCTOR constructor(address _custodian) CustodianUpgradeable(_custodian) public { erc20Impl = ERC20Impl(0x0); } // MODIFIERS modifier onlyImpl { require(msg.sender == address(erc20Impl), "only ERC20Impl"); _; } // PUBLIC FUNCTIONS // (UPGRADE) /** @notice Requests a change of the active implementation associated * with this contract. * * @dev Returns a unique lock id associated with the request. * Anyone can call this function, but confirming the request is authorized * by the custodian. * * @param _proposedImpl The address of the new active implementation. * @return lockId A unique identifier for this request. */ function requestImplChange(address _proposedImpl) public returns (bytes32 lockId) { require(_proposedImpl != address(0), "no null value for `_proposedImpl`"); lockId = generateLockId(); implChangeReqs[lockId] = ImplChangeRequest({ proposedNew: _proposedImpl }); emit ImplChangeRequested(lockId, msg.sender, _proposedImpl); } /** @notice Confirms a pending change of the active implementation * associated with this contract. * * @dev When called by the custodian with a lock id associated with a * pending change, the `ERC20Impl erc20Impl` member will be updated * with the requested address. * * @param _lockId The identifier of a pending change request. */ function confirmImplChange(bytes32 _lockId) public onlyCustodian { erc20Impl = getImplChangeReq(_lockId); delete implChangeReqs[_lockId]; emit ImplChangeConfirmed(_lockId, address(erc20Impl)); } // PRIVATE FUNCTIONS function getImplChangeReq(bytes32 _lockId) private view returns (ERC20Impl _proposedNew) { ImplChangeRequest storage changeRequest = implChangeReqs[_lockId]; // reject 1null1 results from the map lookup // this can only be the case if an unknown `_lockId` is received require(changeRequest.proposedNew != address(0), "reject 1null1 results from the map lookup"); return ERC20Impl(changeRequest.proposedNew); } //EVENTS /// @dev Emitted by successful `requestImplChange` calls. event ImplChangeRequested( bytes32 _lockId, address _msgSender, address _proposedImpl ); /// @dev Emitted by successful `confirmImplChange` calls. event ImplChangeConfirmed(bytes32 _lockId, address _newImpl); } /** @title Public interface to ERC20 compliant token. * * @notice This contract is a permanent entry point to an ERC20 compliant * system of contracts. * * @dev This contract contains no business logic and instead * delegates to an instance of ERC20Impl. This contract also has no storage * that constitutes the operational state of the token. This contract is * upgradeable in the sense that the `custodian` can update the * `erc20Impl` address, thus redirecting the delegation of business logic. * The `custodian` is also authorized to pass custodianship. * */ contract ERC20Proxy is ERC20Interface, ERC20ImplUpgradeable { // MEMBERS /// @notice Returns the name of the token. string public name; /// @notice Returns the symbol of the token. string public symbol; /// @notice Returns the number of decimals the token uses. uint8 public decimals; // CONSTRUCTOR constructor( string memory _name, string memory _symbol, uint8 _decimals, address _custodian ) ERC20ImplUpgradeable(_custodian) public { name = _name; symbol = _symbol; decimals = _decimals; } // PUBLIC FUNCTIONS // (ERC20Interface) /** @notice Returns the total token supply. * * @return the total token supply. */ function totalSupply() public view returns (uint256) { return erc20Impl.totalSupply(); } /** @notice Returns the account balance of another account with an address * `_owner`. * * @return balance the balance of account with address `_owner`. */ function balanceOf(address _owner) public view returns (uint256 balance) { return erc20Impl.balanceOf(_owner); } /** @dev Internal use only. */ function emitTransfer(address _from, address _to, uint256 _value) public onlyImpl { emit Transfer(_from, _to, _value); } /** @notice Transfers `_value` amount of tokens to address `_to`. * * @dev Will fire the `Transfer` event. Will revert if the `_from` * account balance does not have enough tokens to spend. * * @return success true if transfer completes. */ function transfer(address _to, uint256 _value) public returns (bool success) { return erc20Impl.transferWithSender(msg.sender, _to, _value); } /** @notice Transfers `_value` amount of tokens from address `_from` * to address `_to`. * * @dev Will fire the `Transfer` event. Will revert unless the `_from` * account has deliberately authorized the sender of the message * via some mechanism. * * @return success true if transfer completes. */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { return erc20Impl.transferFromWithSender(msg.sender, _from, _to, _value); } /** @dev Internal use only. */ function emitApproval(address _owner, address _spender, uint256 _value) public onlyImpl { emit Approval(_owner, _spender, _value); } /** @notice Allows `_spender` to withdraw from your account multiple times, * up to the `_value` amount. If this function is called again it * overwrites the current allowance with _value. * * @dev Will fire the `Approval` event. * * @return success true if approval completes. */ function approve(address _spender, uint256 _value) public returns (bool success) { return erc20Impl.approveWithSender(msg.sender, _spender, _value); } /** @notice Increases the amount `_spender` is allowed to withdraw from * your account. * This function is implemented to avoid the race condition in standard * ERC20 contracts surrounding the `approve` method. * * @dev Will fire the `Approval` event. This function should be used instead of * `approve`. * * @return success true if approval completes. */ function increaseApproval(address _spender, uint256 _addedValue) public returns (bool success) { return erc20Impl.increaseApprovalWithSender(msg.sender, _spender, _addedValue); } /** @notice Decreases the amount `_spender` is allowed to withdraw from * your account. This function is implemented to avoid the race * condition in standard ERC20 contracts surrounding the `approve` method. * * @dev Will fire the `Approval` event. This function should be used * instead of `approve`. * * @return success true if approval completes. */ function decreaseApproval(address _spender, uint256 _subtractedValue) public returns (bool success) { return erc20Impl.decreaseApprovalWithSender(msg.sender, _spender, _subtractedValue); } /** @notice Returns how much `_spender` is currently allowed to spend from * `_owner`'s balance. * * @return remaining the remaining allowance. */ function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return erc20Impl.allowance(_owner, _spender); } } /** @title ERC20 compliant token balance store. * * @notice This contract serves as the store of balances, allowances, and * supply for the ERC20 compliant token. No business logic exists here. * * @dev This contract contains no business logic and instead * is the final destination for any change in balances, allowances, or token * supply. This contract is upgradeable in the sense that its custodian can * update the `erc20Impl` address, thus redirecting the source of logic that * determines how the balances will be updated. * */ contract ERC20Store is ERC20ImplUpgradeable { // MEMBERS /// @dev The total token supply. uint256 public totalSupply; /// @dev The mapping of balances. mapping (address => uint256) public balances; /// @dev The mapping of allowances. mapping (address => mapping (address => uint256)) public allowed; // CONSTRUCTOR constructor(address _custodian) ERC20ImplUpgradeable(_custodian) public { totalSupply = 0; } // PUBLIC FUNCTIONS // (ERC20 Ledger) /** @notice The function to set the total supply of tokens. * * @dev Intended for use by token implementation functions * that update the total supply. The only authorized caller * is the active implementation. * * @param _newTotalSupply the value to set as the new total supply */ function setTotalSupply( uint256 _newTotalSupply ) public onlyImpl { totalSupply = _newTotalSupply; } /** @notice Sets how much `_owner` allows `_spender` to transfer on behalf * of `_owner`. * * @dev Intended for use by token implementation functions * that update spending allowances. The only authorized caller * is the active implementation. * * @param _owner The account that will allow an on-behalf-of spend. * @param _spender The account that will spend on behalf of the owner. * @param _value The limit of what can be spent. */ function setAllowance( address _owner, address _spender, uint256 _value ) public onlyImpl { allowed[_owner][_spender] = _value; } /** @notice Sets the balance of `_owner` to `_newBalance`. * * @dev Intended for use by token implementation functions * that update balances. The only authorized caller * is the active implementation. * * @param _owner The account that will hold a new balance. * @param _newBalance The balance to set. */ function setBalance( address _owner, uint256 _newBalance ) public onlyImpl { balances[_owner] = _newBalance; } /** @notice Adds `_balanceIncrease` to `_owner`'s balance. * * @dev Intended for use by token implementation functions * that update balances. The only authorized caller * is the active implementation. * WARNING: the caller is responsible for preventing overflow. * * @param _owner The account that will hold a new balance. * @param _balanceIncrease The balance to add. */ function addBalance( address _owner, uint256 _balanceIncrease ) public onlyImpl { balances[_owner] = balances[_owner] + _balanceIncrease; } } /** @title ERC20 compliant token intermediary contract holding core logic. * * @notice This contract serves as an intermediary between the exposed ERC20 * interface in ERC20Proxy and the store of balances in ERC20Store. This * contract contains core logic that the proxy can delegate to * and that the store is called by. * * @dev This contract contains the core logic to implement the * ERC20 specification as well as several extensions. * 1. Changes to the token supply. * 2. Batched transfers. * 3. Relative changes to spending approvals. * 4. Delegated transfer control ('sweeping'). * */ contract ERC20Impl is CustodianUpgradeable { // TYPES /// @dev The struct type for pending increases to the token supply (print). struct PendingPrint { address receiver; uint256 value; } // MEMBERS /// @dev The reference to the proxy. ERC20Proxy public erc20Proxy; /// @dev The reference to the store. ERC20Store public erc20Store; /// @dev The sole authorized caller of delegated transfer control ('sweeping'). address public sweeper; /** @dev The static message to be signed by an external account that * signifies their permission to forward their balance to any arbitrary * address. This is used to consolidate the control of all accounts * backed by a shared keychain into the control of a single key. * Initialized as the concatenation of the address of this contract * and the word "sweep". This concatenation is done to prevent a replay * attack in a subsequent contract, where the sweeping message could * potentially be replayed to re-enable sweeping ability. */ bytes32 public sweepMsg; /** @dev The mapping that stores whether the address in question has * enabled sweeping its contents to another account or not. * If an address maps to "true", it has already enabled sweeping, * and thus does not need to re-sign the `sweepMsg` to enact the sweep. */ mapping (address => bool) public sweptSet; /// @dev The map of lock ids to pending token increases. mapping (bytes32 => PendingPrint) public pendingPrintMap; /// @dev The map of blocked addresses. mapping (address => bool) public blocked; // CONSTRUCTOR constructor( address _erc20Proxy, address _erc20Store, address _custodian, address _sweeper ) CustodianUpgradeable(_custodian) public { require(_sweeper != address(0), "no null value for `_sweeper`"); erc20Proxy = ERC20Proxy(_erc20Proxy); erc20Store = ERC20Store(_erc20Store); sweeper = _sweeper; sweepMsg = keccak256(abi.encodePacked(address(this), "sweep")); } // MODIFIERS modifier onlyProxy { require(msg.sender == address(erc20Proxy), "only ERC20Proxy"); _; } modifier onlySweeper { require(msg.sender == sweeper, "only sweeper"); _; } /** @notice Core logic of the ERC20 `approve` function. * * @dev This function can only be called by the referenced proxy, * which has an `approve` function. * Every argument passed to that function as well as the original * `msg.sender` gets passed to this function. * NOTE: approvals for the zero address (unspendable) are disallowed. * * @param _sender The address initiating the approval in a proxy. */ function approveWithSender( address _sender, address _spender, uint256 _value ) public onlyProxy returns (bool success) { require(_spender != address(0), "no null value for `_spender`"); require(blocked[_sender] != true, "_sender must not be blocked"); require(blocked[_spender] != true, "_spender must not be blocked"); erc20Store.setAllowance(_sender, _spender, _value); erc20Proxy.emitApproval(_sender, _spender, _value); return true; } /** @notice Core logic of the `increaseApproval` function. * * @dev This function can only be called by the referenced proxy, * which has an `increaseApproval` function. * Every argument passed to that function as well as the original * `msg.sender` gets passed to this function. * NOTE: approvals for the zero address (unspendable) are disallowed. * * @param _sender The address initiating the approval. */ function increaseApprovalWithSender( address _sender, address _spender, uint256 _addedValue ) public onlyProxy returns (bool success) { require(_spender != address(0),"no null value for_spender"); require(blocked[_sender] != true, "_sender must not be blocked"); require(blocked[_spender] != true, "_spender must not be blocked"); uint256 currentAllowance = erc20Store.allowed(_sender, _spender); uint256 newAllowance = currentAllowance + _addedValue; require(newAllowance >= currentAllowance, "new allowance must not be smaller than previous"); erc20Store.setAllowance(_sender, _spender, newAllowance); erc20Proxy.emitApproval(_sender, _spender, newAllowance); return true; } /** @notice Core logic of the `decreaseApproval` function. * * @dev This function can only be called by the referenced proxy, * which has a `decreaseApproval` function. * Every argument passed to that function as well as the original * `msg.sender` gets passed to this function. * NOTE: approvals for the zero address (unspendable) are disallowed. * * @param _sender The address initiating the approval. */ function decreaseApprovalWithSender( address _sender, address _spender, uint256 _subtractedValue ) public onlyProxy returns (bool success) { require(_spender != address(0), "no unspendable approvals"); // disallow unspendable approvals require(blocked[_sender] != true, "_sender must not be blocked"); require(blocked[_spender] != true, "_spender must not be blocked"); uint256 currentAllowance = erc20Store.allowed(_sender, _spender); uint256 newAllowance = currentAllowance - _subtractedValue; require(newAllowance <= currentAllowance, "new allowance must not be smaller than previous"); erc20Store.setAllowance(_sender, _spender, newAllowance); erc20Proxy.emitApproval(_sender, _spender, newAllowance); return true; } /** @notice Requests an increase in the token supply, with the newly created * tokens to be added to the balance of the specified account. * * @dev Returns a unique lock id associated with the request. * Anyone can call this function, but confirming the request is authorized * by the custodian. * NOTE: printing to the zero address is disallowed. * * @param _receiver The receiving address of the print, if confirmed. * @param _value The number of tokens to add to the total supply and the * balance of the receiving address, if confirmed. * * @return lockId A unique identifier for this request. */ function requestPrint(address _receiver, uint256 _value) public returns (bytes32 lockId) { require(_receiver != address(0), "no null value for `_receiver`"); require(blocked[msg.sender] != true, "account blocked"); require(blocked[_receiver] != true, "_receiver must not be blocked"); lockId = generateLockId(); pendingPrintMap[lockId] = PendingPrint({ receiver: _receiver, value: _value }); emit PrintingLocked(lockId, _receiver, _value); } /** @notice Confirms a pending increase in the token supply. * * @dev When called by the custodian with a lock id associated with a * pending increase, the amount requested to be printed in the print request * is printed to the receiving address specified in that same request. * NOTE: this function will not execute any print that would overflow the * total supply, but it will not revert either. * * @param _lockId The identifier of a pending print request. */ function confirmPrint(bytes32 _lockId) public onlyCustodian { PendingPrint storage print = pendingPrintMap[_lockId]; // reject 1null1 results from the map lookup // this can only be the case if an unknown `_lockId` is received address receiver = print.receiver; require (receiver != address(0), "unknown `_lockId`"); uint256 value = print.value; delete pendingPrintMap[_lockId]; uint256 supply = erc20Store.totalSupply(); uint256 newSupply = supply + value; if (newSupply >= supply) { erc20Store.setTotalSupply(newSupply); erc20Store.addBalance(receiver, value); emit PrintingConfirmed(_lockId, receiver, value); erc20Proxy.emitTransfer(address(0), receiver, value); } } /** @notice Burns the specified value from the sender's balance. * * @dev Sender's balanced is subtracted by the amount they wish to burn. * * @param _value The amount to burn. * * @return success true if the burn succeeded. */ function burn(uint256 _value) public returns (bool success) { require(blocked[msg.sender] != true, "account blocked"); uint256 balanceOfSender = erc20Store.balances(msg.sender); require(_value <= balanceOfSender, "disallow burning more, than amount of the balance"); erc20Store.setBalance(msg.sender, balanceOfSender - _value); erc20Store.setTotalSupply(erc20Store.totalSupply() - _value); erc20Proxy.emitTransfer(msg.sender, address(0), _value); return true; } /** @notice Burns the specified value from the balance in question. * * @dev Suspected balance is subtracted by the amount which will be burnt. * * @dev If the suspected balance has less than the amount requested, it will be set to 0. * * @param _from The address of suspected balance. * * @param _value The amount to burn. * * @return success true if the burn succeeded. */ function burn(address _from, uint256 _value) public onlyCustodian returns (bool success) { uint256 balance = erc20Store.balances(_from); if(_value <= balance){ erc20Store.setBalance(_from, balance - _value); erc20Store.setTotalSupply(erc20Store.totalSupply() - _value); erc20Proxy.emitTransfer(_from, address(0), _value); emit Wiped(_from, _value, _value, balance - _value); } else { erc20Store.setBalance(_from,0); erc20Store.setTotalSupply(erc20Store.totalSupply() - balance); erc20Proxy.emitTransfer(_from, address(0), balance); emit Wiped(_from, _value, balance, 0); } return true; } /** @notice A function for a sender to issue multiple transfers to multiple * different addresses at once. This function is implemented for gas * considerations when someone wishes to transfer, as one transaction is * cheaper than issuing several distinct individual `transfer` transactions. * * @dev By specifying a set of destination addresses and values, the * sender can issue one transaction to transfer multiple amounts to * distinct addresses, rather than issuing each as a separate * transaction. The `_tos` and `_values` arrays must be equal length, and * an index in one array corresponds to the same index in the other array * (e.g. `_tos[0]` will receive `_values[0]`, `_tos[1]` will receive * `_values[1]`, and so on.) * NOTE: transfers to the zero address are disallowed. * * @param _tos The destination addresses to receive the transfers. * @param _values The values for each destination address. * @return success If transfers succeeded. */ function batchTransfer(address[] memory _tos, uint256[] memory _values) public returns (bool success) { require(_tos.length == _values.length, "_tos and _values must be the same length"); require(blocked[msg.sender] != true, "account blocked"); uint256 numTransfers = _tos.length; uint256 senderBalance = erc20Store.balances(msg.sender); for (uint256 i = 0; i < numTransfers; i++) { address to = _tos[i]; require(to != address(0), "no null values for _tos"); require(blocked[to] != true, "_tos must not be blocked"); uint256 v = _values[i]; require(senderBalance >= v, "insufficient funds"); if (msg.sender != to) { senderBalance -= v; erc20Store.addBalance(to, v); } erc20Proxy.emitTransfer(msg.sender, to, v); } erc20Store.setBalance(msg.sender, senderBalance); return true; } /** @notice Enables the delegation of transfer control for many * accounts to the sweeper account, transferring any balances * as well to the given destination. * * @dev An account delegates transfer control by signing the * value of `sweepMsg`. The sweeper account is the only authorized * caller of this function, so it must relay signatures on behalf * of accounts that delegate transfer control to it. Enabling * delegation is idempotent and permanent. If the account has a * balance at the time of enabling delegation, its balance is * also transferred to the given destination account `_to`. * NOTE: transfers to the zero address are disallowed. * * @param _vs The array of recovery byte components of the ECDSA signatures. * @param _rs The array of 'R' components of the ECDSA signatures. * @param _ss The array of 'S' components of the ECDSA signatures. * @param _to The destination for swept balances. */ function enableSweep(uint8[] memory _vs, bytes32[] memory _rs, bytes32[] memory _ss, address _to) public onlySweeper { require(_to != address(0), "no null value for `_to`"); require(blocked[_to] != true, "_to must not be blocked"); require((_vs.length == _rs.length) && (_vs.length == _ss.length), "_vs[], _rs[], _ss lengths are different"); uint256 numSignatures = _vs.length; uint256 sweptBalance = 0; for (uint256 i = 0; i < numSignatures; ++i) { address from = ecrecover(keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32",sweepMsg)), _vs[i], _rs[i], _ss[i]); require(blocked[from] != true, "_froms must not be blocked"); // ecrecover returns 0 on malformed input if (from != address(0)) { sweptSet[from] = true; uint256 fromBalance = erc20Store.balances(from); if (fromBalance > 0) { sweptBalance += fromBalance; erc20Store.setBalance(from, 0); erc20Proxy.emitTransfer(from, _to, fromBalance); } } } if (sweptBalance > 0) { erc20Store.addBalance(_to, sweptBalance); } } /** @notice For accounts that have delegated, transfer control * to the sweeper, this function transfers their balances to the given * destination. * * @dev The sweeper account is the only authorized caller of * this function. This function accepts an array of addresses to have their * balances transferred for gas efficiency purposes. * NOTE: any address for an account that has not been previously enabled * will be ignored. * NOTE: transfers to the zero address are disallowed. * * @param _froms The addresses to have their balances swept. * @param _to The destination address of all these transfers. */ function replaySweep(address[] memory _froms, address _to) public onlySweeper { require(_to != address(0), "no null value for `_to`"); require(blocked[_to] != true, "_to must not be blocked"); uint256 lenFroms = _froms.length; uint256 sweptBalance = 0; for (uint256 i = 0; i < lenFroms; ++i) { address from = _froms[i]; require(blocked[from] != true, "_froms must not be blocked"); if (sweptSet[from]) { uint256 fromBalance = erc20Store.balances(from); if (fromBalance > 0) { sweptBalance += fromBalance; erc20Store.setBalance(from, 0); erc20Proxy.emitTransfer(from, _to, fromBalance); } } } if (sweptBalance > 0) { erc20Store.addBalance(_to, sweptBalance); } } /** @notice Core logic of the ERC20 `transferFrom` function. * * @dev This function can only be called by the referenced proxy, * which has a `transferFrom` function. * Every argument passed to that function as well as the original * `msg.sender` gets passed to this function. * NOTE: transfers to the zero address are disallowed. * * @param _sender The address initiating the transfer in a proxy. */ function transferFromWithSender( address _sender, address _from, address _to, uint256 _value ) public onlyProxy returns (bool success) { require(_to != address(0), "no null values for `_to`"); require(blocked[_sender] != true, "_sender must not be blocked"); require(blocked[_from] != true, "_from must not be blocked"); require(blocked[_to] != true, "_to must not be blocked"); uint256 balanceOfFrom = erc20Store.balances(_from); require(_value <= balanceOfFrom, "insufficient funds on `_from` balance"); uint256 senderAllowance = erc20Store.allowed(_from, _sender); require(_value <= senderAllowance, "insufficient allowance amount"); erc20Store.setBalance(_from, balanceOfFrom - _value); erc20Store.addBalance(_to, _value); erc20Store.setAllowance(_from, _sender, senderAllowance - _value); erc20Proxy.emitTransfer(_from, _to, _value); return true; } /** @notice Core logic of the ERC20 `transfer` function. * * @dev This function can only be called by the referenced proxy, * which has a `transfer` function. * Every argument passed to that function as well as the original * `msg.sender` gets passed to this function. * NOTE: transfers to the zero address are disallowed. * * @param _sender The address initiating the transfer in a proxy. */ function transferWithSender( address _sender, address _to, uint256 _value ) public onlyProxy returns (bool success) { require(_to != address(0), "no null value for `_to`"); require(blocked[_sender] != true, "_sender must not be blocked"); require(blocked[_to] != true, "_to must not be blocked"); uint256 balanceOfSender = erc20Store.balances(_sender); require(_value <= balanceOfSender, "insufficient funds"); erc20Store.setBalance(_sender, balanceOfSender - _value); erc20Store.addBalance(_to, _value); erc20Proxy.emitTransfer(_sender, _to, _value); return true; } /** @notice Transfers the specified value from the balance in question. * * @dev Suspected balance is subtracted by the amount which will be transferred. * * @dev If the suspected balance has less than the amount requested, it will be set to 0. * * @param _from The address of suspected balance. * * @param _value The amount to transfer. * * @return success true if the transfer succeeded. */ function forceTransfer( address _from, address _to, uint256 _value ) public onlyCustodian returns (bool success) { require(_to != address(0), "no null value for `_to`"); uint256 balanceOfSender = erc20Store.balances(_from); if(_value <= balanceOfSender) { erc20Store.setBalance(_from, balanceOfSender - _value); erc20Store.addBalance(_to, _value); erc20Proxy.emitTransfer(_from, _to, _value); } else { erc20Store.setBalance(_from, 0); erc20Store.addBalance(_to, balanceOfSender); erc20Proxy.emitTransfer(_from, _to, balanceOfSender); } return true; } // METHODS (ERC20 sub interface impl.) /// @notice Core logic of the ERC20 `totalSupply` function. function totalSupply() public view returns (uint256) { return erc20Store.totalSupply(); } /// @notice Core logic of the ERC20 `balanceOf` function. function balanceOf(address _owner) public view returns (uint256 balance) { return erc20Store.balances(_owner); } /// @notice Core logic of the ERC20 `allowance` function. function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return erc20Store.allowed(_owner, _spender); } /// @dev internal use only. function blockWallet(address wallet) public onlyCustodian returns (bool success) { blocked[wallet] = true; return true; } /// @dev internal use only. function unblockWallet(address wallet) public onlyCustodian returns (bool success) { blocked[wallet] = false; return true; } // EVENTS /// @dev Emitted by successful `requestPrint` calls. event PrintingLocked(bytes32 _lockId, address _receiver, uint256 _value); /// @dev Emitted by successful `confirmPrint` calls. event PrintingConfirmed(bytes32 _lockId, address _receiver, uint256 _value); /** @dev Emitted by successful `confirmWipe` calls. * * @param _value Amount requested to be burned. * * @param _burned Amount which was burned. * * @param _balance Amount left on account after burn. * * @param _from Account which balance was burned. */ event Wiped(address _from, uint256 _value, uint256 _burned, uint _balance); } /** @title A contact to govern hybrid control over increases to the token supply and managing accounts. * * @notice A contract that acts as a custodian of the active token * implementation, and an intermediary between it and the 1true1 custodian. * It preserves the functionality of direct custodianship as well as granting * limited control of token supply increases to an additional key. * * @dev This contract is a layer of indirection between an instance of * ERC20Impl and a custodian. The functionality of the custodianship over * the token implementation is preserved (printing and custodian changes), * but this contract adds the ability for an additional key * (the 'controller') to increase the token supply up to a ceiling, * and this supply ceiling can only be raised by the custodian. * */ contract Controller is LockRequestable { // TYPES /// @dev The struct type for pending ceiling raises. struct PendingCeilingRaise { uint256 raiseBy; } /// @dev The struct type for pending wipes. struct wipeAddress { uint256 value; address from; } /// @dev The struct type for pending force transfer requests. struct forceTransferRequest { uint256 value; address from; address to; } // MEMBERS /// @dev The reference to the active token implementation. ERC20Impl public erc20Impl; /// @dev The address of the account or contract that acts as the custodian. Custodian public custodian; /** @dev The sole authorized caller of limited printing. * This account is also authorized to lower the supply ceiling and * wiping suspected accounts or force transferring funds from them. */ address public controller; /** @dev The maximum that the token supply can be increased to * through the use of the limited printing feature. * The difference between the current total supply and the supply * ceiling is what is available to the 'controller' account. * The value of the ceiling can only be increased by the custodian. */ uint256 public totalSupplyCeiling; /// @dev The map of lock ids to pending ceiling raises. mapping (bytes32 => PendingCeilingRaise) public pendingRaiseMap; /// @dev The map of lock ids to pending wipes. mapping (bytes32 => wipeAddress[]) public pendingWipeMap; /// @dev The map of lock ids to pending force transfer requests. mapping (bytes32 => forceTransferRequest) public pendingForceTransferRequestMap; // CONSTRUCTOR constructor( address _erc20Impl, address _custodian, address _controller, uint256 _initialCeiling ) public { erc20Impl = ERC20Impl(_erc20Impl); custodian = Custodian(_custodian); controller = _controller; totalSupplyCeiling = _initialCeiling; } // MODIFIERS modifier onlyCustodian { require(msg.sender == address(custodian), "only custodian"); _; } modifier onlyController { require(msg.sender == controller, "only controller"); _; } modifier onlySigner { require(custodian.signerSet(msg.sender) == true, "only signer"); _; } /** @notice Increases the token supply, with the newly created tokens * being added to the balance of the specified account. * * @dev The function checks that the value to print does not * exceed the supply ceiling when added to the current total supply. * NOTE: printing to the zero address is disallowed. * * @param _receiver The receiving address of the print. * @param _value The number of tokens to add to the total supply and the * balance of the receiving address. */ function limitedPrint(address _receiver, uint256 _value) public onlyController { uint256 totalSupply = erc20Impl.totalSupply(); uint256 newTotalSupply = totalSupply + _value; require(newTotalSupply >= totalSupply, "new total supply overflow"); require(newTotalSupply <= totalSupplyCeiling, "total supply ceiling overflow"); erc20Impl.confirmPrint(erc20Impl.requestPrint(_receiver, _value)); } /** @notice Requests wipe of suspected accounts. * * @dev Returns a unique lock id associated with the request. * Only controller can call this function, and only the custodian * can confirm the request. * * @param _froms The array of suspected accounts. * * @param _values array of amounts by which suspected accounts will be wiped. * * @return lockId A unique identifier for this request. */ function requestWipe(address[] memory _froms, uint256[] memory _values) public onlyController returns (bytes32 lockId) { require(_froms.length == _values.length, "_froms[] and _values[] must be same length"); lockId = generateLockId(); uint256 amount = _froms.length; for(uint256 i = 0; i < amount; i++) { address from = _froms[i]; uint256 value = _values[i]; pendingWipeMap[lockId].push(wipeAddress(value, from)); } emit WipeRequested(lockId); return lockId; } /** @notice Confirms a pending wipe of suspected accounts. * * @dev When called by the custodian with a lock id associated with a * pending wipe, the amount requested is burned from the suspected accounts. * * @param _lockId The identifier of a pending wipe request. */ function confirmWipe(bytes32 _lockId) public onlyCustodian { uint256 amount = pendingWipeMap[_lockId].length; for(uint256 i = 0; i < amount; i++) { wipeAddress memory addr = pendingWipeMap[_lockId][i]; address from = addr.from; uint256 value = addr.value; erc20Impl.burn(from, value); } delete pendingWipeMap[_lockId]; emit WipeCompleted(_lockId); } /** @notice Requests force transfer from the suspected account. * * @dev Returns a unique lock id associated with the request. * Only controller can call this function, and only the custodian * can confirm the request. * * @param _from address of suspected account. * * @param _to address of reciever. * * @param _value amount which will be transferred. * * @return lockId A unique identifier for this request. */ function requestForceTransfer(address _from, address _to, uint256 _value) public onlyController returns (bytes32 lockId) { lockId = generateLockId(); require (_value != 0, "no zero value transfers"); pendingForceTransferRequestMap[lockId] = forceTransferRequest(_value, _from, _to); emit ForceTransferRequested(lockId, _from, _to, _value); return lockId; } /** @notice Confirms a pending force transfer request. * * @dev When called by the custodian with a lock id associated with a * pending transfer request, the amount requested is transferred from the suspected account. * * @param _lockId The identifier of a pending transfer request. */ function confirmForceTransfer(bytes32 _lockId) public onlyCustodian { address from = pendingForceTransferRequestMap[_lockId].from; address to = pendingForceTransferRequestMap[_lockId].to; uint256 value = pendingForceTransferRequestMap[_lockId].value; delete pendingForceTransferRequestMap[_lockId]; erc20Impl.forceTransfer(from, to, value); emit ForceTransferCompleted(_lockId, from, to, value); } /** @notice Requests an increase to the supply ceiling. * * @dev Returns a unique lock id associated with the request. * Anyone can call this function, but confirming the request is authorized * by the custodian. * * @param _raiseBy The amount by which to raise the ceiling. * * @return lockId A unique identifier for this request. */ function requestCeilingRaise(uint256 _raiseBy) public returns (bytes32 lockId) { require(_raiseBy != 0, "no zero ceiling raise"); lockId = generateLockId(); pendingRaiseMap[lockId] = PendingCeilingRaise({ raiseBy: _raiseBy }); emit CeilingRaiseLocked(lockId, _raiseBy); } /** @notice Confirms a pending increase in the token supply. * * @dev When called by the custodian with a lock id associated with a * pending ceiling increase, the amount requested is added to the * current supply ceiling. * NOTE: this function will not execute any raise that would overflow the * supply ceiling, but it will not revert either. * * @param _lockId The identifier of a pending ceiling raise request. */ function confirmCeilingRaise(bytes32 _lockId) public onlyCustodian { PendingCeilingRaise storage pendingRaise = pendingRaiseMap[_lockId]; // copy locals of references to struct members uint256 raiseBy = pendingRaise.raiseBy; // accounts for a gibberish _lockId require(raiseBy != 0, "no gibberish _lockId"); delete pendingRaiseMap[_lockId]; uint256 newCeiling = totalSupplyCeiling + raiseBy; // overflow check if (newCeiling >= totalSupplyCeiling) { totalSupplyCeiling = newCeiling; emit CeilingRaiseConfirmed(_lockId, raiseBy, newCeiling); } } /** @notice Lowers the supply ceiling, further constraining the bound of * what can be printed by the controller. * * @dev The controller is the sole authorized caller of this function, * so it is the only account that can elect to lower its limit to increase * the token supply. * * @param _lowerBy The amount by which to lower the supply ceiling. */ function lowerCeiling(uint256 _lowerBy) public onlyController { uint256 newCeiling = totalSupplyCeiling - _lowerBy; // overflow check require(newCeiling <= totalSupplyCeiling, "totalSupplyCeiling overflow"); totalSupplyCeiling = newCeiling; emit CeilingLowered(_lowerBy, newCeiling); } /** @notice Pass-through control of print confirmation, allowing this * contract's custodian to act as the custodian of the associated * active token implementation. * * @dev This contract is the direct custodian of the active token * implementation, but this function allows this contract's custodian * to act as though it were the direct custodian of the active * token implementation. Therefore the custodian retains control of * unlimited printing. * * @param _lockId The identifier of a pending print request in * the associated active token implementation. */ function confirmPrintProxy(bytes32 _lockId) public onlyCustodian { erc20Impl.confirmPrint(_lockId); } /** @notice Pass-through control of custodian change confirmation, * allowing this contract's custodian to act as the custodian of * the associated active token implementation. * * @dev This contract is the direct custodian of the active token * implementation, but this function allows this contract's custodian * to act as though it were the direct custodian of the active * token implementation. Therefore the custodian retains control of * custodian changes. * * @param _lockId The identifier of a pending custodian change request * in the associated active token implementation. */ function confirmCustodianChangeProxy(bytes32 _lockId) public onlyCustodian { erc20Impl.confirmCustodianChange(_lockId); } /** @notice Blocks all transactions with a wallet. * * @dev Only signers from custodian are authorized to call this function * * @param wallet account which will be blocked. */ function blockWallet(address wallet) public onlySigner { erc20Impl.blockWallet(wallet); emit Blocked(wallet); } /** @notice Unblocks all transactions with a wallet. * * @dev Only signers from custodian are authorized to call this function * * @param wallet account which will be unblocked. */ function unblockWallet(address wallet) public onlySigner { erc20Impl.unblockWallet(wallet); emit Unblocked(wallet); } // EVENTS /// @dev Emitted by successful `requestCeilingRaise` calls. event CeilingRaiseLocked(bytes32 _lockId, uint256 _raiseBy); /// @dev Emitted by successful `confirmCeilingRaise` calls. event CeilingRaiseConfirmed(bytes32 _lockId, uint256 _raiseBy, uint256 _newCeiling); /// @dev Emitted by successful `lowerCeiling` calls. event CeilingLowered(uint256 _lowerBy, uint256 _newCeiling); /// @dev Emitted by successful `blockWallet` calls. event Blocked(address _wallet); /// @dev Emitted by successful `unblockWallet` calls. event Unblocked(address _wallet); /// @dev Emitted by successful `requestForceTransfer` calls. event ForceTransferRequested(bytes32 _lockId, address _from, address _to, uint256 _value); /// @dev Emitted by successful `confirmForceTransfer` calls. event ForceTransferCompleted(bytes32 _lockId, address _from, address _to, uint256 _value); /// @dev Emitted by successful `requestWipe` calls. event WipeRequested(bytes32 _lockId); /// @dev Emitted by successful `confirmWipe` calls. event WipeCompleted(bytes32 _lockId); }
PRIVATE FUNCTIONS reject 1null1 results from the map lookup this can only be the case if an unknown `_lockId` is received
function getImplChangeReq(bytes32 _lockId) private view returns (ERC20Impl _proposedNew) { ImplChangeRequest storage changeRequest = implChangeReqs[_lockId]; require(changeRequest.proposedNew != address(0), "reject 1null1 results from the map lookup"); return ERC20Impl(changeRequest.proposedNew); } bytes32 _lockId, address _msgSender, address _proposedImpl );
12,961,502
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./ERC165.sol"; import "./interfaces/IERC721.sol"; /* Minting Function: a. nft to point to an address b. keep track of the token ids c. keep track of token owners addresses to token ids d. keep track of how many tokens an owner address has e. create an event that emits a transfer log - contract address, where it is being minted to, the id */ contract ERC721 is ERC165, IERC721 { // Mapping from token id to the owner; mapping(uint256 => address) private _tokenOwner; // Mapping from owner to number of ownder tokens; mapping(address => uint256) private _ownedTokensCount; // Mapping from token id to approved addresses mapping(uint256 => address) private _tokenApprovals; constructor() { _registerInterface( bytes4(keccak256("balanceOf(bytes4)")) ^ bytes4(keccak256("ownerOf(bytes4)")) ^ bytes4(keccak256("transferFrom(bytes4)")) ); } function _exists_check(uint256 tokenId) internal view returns (bool) { address owner = _tokenOwner[tokenId]; return owner != address(0); } // requires that the token does not already exist modifier _exists(uint256 tokenId) { require(!_exists_check(tokenId), "ERC721: Token already minted"); _; } // Invalid token for address or invalid address modifier _invalid_address(address _owner) { require( _owner != address(0), "ERC721: Invalid token for address or invalid address" ); _; } // Can't transfer a token the address does not own modifier _token_exists_for_owner(uint256 _tokenId, address _owner) { require( this.ownerOf(_tokenId) == _owner, "ERC721: Can't transfer a token the address does not own." ); _; } function _mint(address to, uint256 tokenId) internal virtual _exists(tokenId) { // requires address to be not zero require(to != address(0), "ERC721: mininting to the zero address"); // adding new address with token id for minting _tokenOwner[tokenId] = to; // keeping track of each address that is minting _ownedTokensCount[to] += 1; emit Transfer(address(0), to, tokenId); } /// @notice Transfer ownership of an NFT -- THE CALLER IS RESPONSIBLE /// TO CONFIRM THAT `_to` IS CAPABLE OF RECEIVING NFTS OR ELSE /// THEY MAY BE PERMANENTLY LOST /// @dev Throws unless `msg.sender` is the current owner, an authorized /// operator, or the approved address for this NFT. Throws if `_from` is /// not the current owner. Throws if `_to` is the zero address. Throws if /// `_tokenId` is not a valid NFT. /// @param _from The current owner of the NFT /// @param _to The new owner /// @param _tokenId The NFT to transfer function _transferFrom( address _from, address _to, uint256 _tokenId ) internal _token_exists_for_owner(_tokenId, _from) _invalid_address(_to) { _ownedTokensCount[_from] -= 1; _ownedTokensCount[_to] += 1; _tokenOwner[_tokenId] = _to; emit Transfer(_from, _to, _tokenId); } /// @notice Transfer ownership of an NFT -- THE CALLER IS RESPONSIBLE /// TO CONFIRM THAT `_to` IS CAPABLE OF RECEIVING NFTS OR ELSE /// THEY MAY BE PERMANENTLY LOST /// @dev Throws unless `msg.sender` is the current owner, an authorized /// operator, or the approved address for this NFT. Throws if `_from` is /// not the current owner. Throws if `_to` is the zero address. Throws if /// `_tokenId` is not a valid NFT. /// @param _from The current owner of the NFT /// @param _to The new owner /// @param _tokenId The NFT to transfer function transferFrom( address _from, address _to, uint256 _tokenId ) public override _token_exists_for_owner(_tokenId, _from) _invalid_address(_to) { _transferFrom(_from, _to, _tokenId); } /// @notice Count all NFT's assigned to an owner /// @dev NFTs assgined to the zero address are considered invaild /// function throws for queries about the zero address /// @param _owner An address for whom to query the balance /// @return The number of NFT's owned by '_owner', possibly zero function balanceOf(address _owner) public view _invalid_address(_owner) returns (uint256) { return _ownedTokensCount[_owner]; } /// @notice Find the owner of an NFT /// @dev NFTs assigned to zero address are considered invalid, and queries /// about them do throw. /// @param _tokenId The identifier for an NFT /// @return The address of the owner of the NFT function ownerOf(uint256 _tokenId) external view _invalid_address(_tokenOwner[_tokenId]) returns (address) { return _tokenOwner[_tokenId]; } }
Find the owner of an NFT NFTs assigned to zero address are considered invalid, and queries about them do throw. _tokenId The identifier for an NFT return The address of the owner of the NFT
function ownerOf(uint256 _tokenId) external view _invalid_address(_tokenOwner[_tokenId]) returns (address) { return _tokenOwner[_tokenId]; }
12,814,723
// Contracts by dYdX Foundation. Individual files are released under different licenses. // // https://dydx.community // https://github.com/dydxfoundation/governance-contracts // // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeERC20 } from '../../dependencies/open-zeppelin/SafeERC20.sol'; import { IERC20 } from '../../interfaces/IERC20.sol'; import { SM1Admin } from '../v1_1/impl/SM1Admin.sol'; import { SM1Getters } from '../v1_1/impl/SM1Getters.sol'; import { SM1Operators } from '../v1_1/impl/SM1Operators.sol'; import { SM1Slashing } from '../v1_1/impl/SM1Slashing.sol'; import { SM1Staking } from '../v1_1/impl/SM1Staking.sol'; /** * @title SafetyModuleV2 * @author dYdX * * @notice Contract for staking tokens, which may be slashed by the permissioned slasher. * * NOTE: Most functions will revert if epoch zero has not started. */ contract SafetyModuleV2 is SM1Slashing, SM1Operators, SM1Admin, SM1Getters { using SafeERC20 for IERC20; // ============ Constants ============ string public constant EIP712_DOMAIN_NAME = 'dYdX Safety Module'; string public constant EIP712_DOMAIN_VERSION = '1'; bytes32 public constant EIP712_DOMAIN_SCHEMA_HASH = keccak256( 'EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)' ); // ============ Constructor ============ constructor( IERC20 stakedToken, IERC20 rewardsToken, address rewardsTreasury, uint256 distributionStart, uint256 distributionEnd ) SM1Staking(stakedToken, rewardsToken, rewardsTreasury, distributionStart, distributionEnd) {} // ============ External Functions ============ /** * @notice Initializer for v2, intended to fix the deployment bug that affected v1. * * Responsible for the following: * * 1. Funds recovery and staker compensation: * - Transfer all Safety Module DYDX to the recovery contract. * - Transfer compensation amount from the rewards treasury to the recovery contract. * * 2. Storage recovery and cleanup: * - Set the _EXCHANGE_RATE_ to EXCHANGE_RATE_BASE. * - Clean up invalid storage values at slots 115 and 125. * * @param recoveryContract The address of the contract which will distribute * recovered funds to stakers. * @param recoveryCompensationAmount Amount to transfer out of the rewards treasury, for staker * compensation, on top of the return of staked funds. */ function initialize( address recoveryContract, uint256 recoveryCompensationAmount ) external initializer { // Funds recovery and staker compensation. uint256 balance = STAKED_TOKEN.balanceOf(address(this)); STAKED_TOKEN.safeTransfer(recoveryContract, balance); REWARDS_TOKEN.safeTransferFrom(REWARDS_TREASURY, recoveryContract, recoveryCompensationAmount); // Storage recovery and cleanup. __SM1ExchangeRate_init(); // solhint-disable-next-line no-inline-assembly assembly { sstore(115, 0) sstore(125, 0) } } // ============ Internal Functions ============ /** * @dev Returns the revision of the implementation contract. * * @return The revision number. */ function getRevision() internal pure override returns (uint256) { return 2; } } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; import { IERC20 } from '../../interfaces/IERC20.sol'; import { SafeMath } from './SafeMath.sol'; import { Address } from './Address.sol'; /** * @title SafeERC20 * @dev From https://github.com/OpenZeppelin/openzeppelin-contracts * 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)); } 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 callOptionalReturn(IERC20 token, bytes memory data) private { 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'); } } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.5; /** * @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: AGPL-3.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { SM1Types } from '../lib/SM1Types.sol'; import { SM1Roles } from './SM1Roles.sol'; import { SM1StakedBalances } from './SM1StakedBalances.sol'; /** * @title SM1Admin * @author dYdX * * @dev Admin-only functions. */ abstract contract SM1Admin is SM1StakedBalances, SM1Roles { using SafeMath for uint256; // ============ External Functions ============ /** * @notice Set the parameters defining the function from timestamp to epoch number. * * The formula used is `n = floor((t - b) / a)` where: * - `n` is the epoch number * - `t` is the timestamp (in seconds) * - `b` is a non-negative offset, indicating the start of epoch zero (in seconds) * - `a` is the length of an epoch, a.k.a. the interval (in seconds) * * Reverts if epoch zero already started, and the new parameters would change the current epoch. * Reverts if epoch zero has not started, but would have had started under the new parameters. * * @param interval The length `a` of an epoch, in seconds. * @param offset The offset `b`, i.e. the start of epoch zero, in seconds. */ function setEpochParameters( uint256 interval, uint256 offset ) external onlyRole(EPOCH_PARAMETERS_ROLE) nonReentrant { if (!hasEpochZeroStarted()) { require( block.timestamp < offset, 'SM1Admin: Started epoch zero' ); _setEpochParameters(interval, offset); return; } // We must settle the total active balance to ensure the index is recorded at the epoch // boundary as needed, before we make any changes to the epoch formula. _settleTotalActiveBalance(); // Update the epoch parameters. Require that the current epoch number is unchanged. uint256 originalCurrentEpoch = getCurrentEpoch(); _setEpochParameters(interval, offset); uint256 newCurrentEpoch = getCurrentEpoch(); require( originalCurrentEpoch == newCurrentEpoch, 'SM1Admin: Changed epochs' ); } /** * @notice Set the blackout window, during which one cannot request withdrawals of staked funds. */ function setBlackoutWindow( uint256 blackoutWindow ) external onlyRole(EPOCH_PARAMETERS_ROLE) nonReentrant { _setBlackoutWindow(blackoutWindow); } /** * @notice Set the emission rate of rewards. * * @param emissionPerSecond The new number of rewards tokens given out per second. */ function setRewardsPerSecond( uint256 emissionPerSecond ) external onlyRole(REWARDS_RATE_ROLE) nonReentrant { uint256 totalStaked = 0; if (hasEpochZeroStarted()) { // We must settle the total active balance to ensure the index is recorded at the epoch // boundary as needed, before we make any changes to the emission rate. totalStaked = _settleTotalActiveBalance(); } _setRewardsPerSecond(emissionPerSecond, totalStaked); } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { Math } from '../../../utils/Math.sol'; import { SM1Types } from '../lib/SM1Types.sol'; import { SM1Storage } from './SM1Storage.sol'; /** * @title SM1Getters * @author dYdX * * @dev Some external getter functions. */ abstract contract SM1Getters is SM1Storage { using SafeMath for uint256; // ============ External Functions ============ /** * @notice The parameters specifying the function from timestamp to epoch number. * * @return The parameters struct with `interval` and `offset` fields. */ function getEpochParameters() external view returns (SM1Types.EpochParameters memory) { return _EPOCH_PARAMETERS_; } /** * @notice The period of time at the end of each epoch in which withdrawals cannot be requested. * * @return The blackout window duration, in seconds. */ function getBlackoutWindow() external view returns (uint256) { return _BLACKOUT_WINDOW_; } /** * @notice Get the domain separator used for EIP-712 signatures. * * @return The EIP-712 domain separator. */ function getDomainSeparator() external view returns (bytes32) { return _DOMAIN_SEPARATOR_; } /** * @notice The value of one underlying token, in the units used for staked balances, denominated * as a mutiple of EXCHANGE_RATE_BASE for additional precision. * * To convert from an underlying amount to a staked amount, multiply by the exchange rate. * * @return The exchange rate. */ function getExchangeRate() external view returns (uint256) { return _EXCHANGE_RATE_; } /** * @notice Get an exchange rate snapshot. * * @param index The index number of the exchange rate snapshot. * * @return The snapshot struct with `blockNumber` and `value` fields. */ function getExchangeRateSnapshot( uint256 index ) external view returns (SM1Types.Snapshot memory) { return _EXCHANGE_RATE_SNAPSHOTS_[index]; } /** * @notice Get the number of exchange rate snapshots. * * @return The number of snapshots that have been taken of the exchange rate. */ function getExchangeRateSnapshotCount() external view returns (uint256) { return _EXCHANGE_RATE_SNAPSHOT_COUNT_; } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { SM1Roles } from './SM1Roles.sol'; import { SM1Staking } from './SM1Staking.sol'; /** * @title SM1Operators * @author dYdX * * @dev Actions which may be called by authorized operators, nominated by the contract owner. * * There are two types of operators. These should be smart contracts, which can be used to * provide additional functionality to users: * * STAKE_OPERATOR_ROLE: * * This operator is allowed to request withdrawals and withdraw funds on behalf of stakers. This * role could be used by a smart contract to provide a staking interface with additional * features, for example, optional lock-up periods that pay out additional rewards (from a * separate rewards pool). * * CLAIM_OPERATOR_ROLE: * * This operator is allowed to claim rewards on behalf of stakers. This role could be used by a * smart contract to provide an interface for claiming rewards from multiple incentive programs * at once. */ abstract contract SM1Operators is SM1Staking, SM1Roles { using SafeMath for uint256; // ============ Events ============ event OperatorStakedFor( address indexed staker, uint256 amount, address operator ); event OperatorWithdrawalRequestedFor( address indexed staker, uint256 amount, address operator ); event OperatorWithdrewStakeFor( address indexed staker, address recipient, uint256 amount, address operator ); event OperatorClaimedRewardsFor( address indexed staker, address recipient, uint256 claimedRewards, address operator ); // ============ External Functions ============ /** * @notice Request a withdrawal on behalf of a staker. * * Reverts if we are currently in the blackout window. * * @param staker The staker whose stake to request a withdrawal for. * @param stakeAmount The amount of stake to move from the active to the inactive balance. */ function requestWithdrawalFor( address staker, uint256 stakeAmount ) external onlyRole(STAKE_OPERATOR_ROLE) nonReentrant { _requestWithdrawal(staker, stakeAmount); emit OperatorWithdrawalRequestedFor(staker, stakeAmount, msg.sender); } /** * @notice Withdraw a staker's stake, and send to the specified recipient. * * @param staker The staker whose stake to withdraw. * @param recipient The address that should receive the funds. * @param stakeAmount The amount of stake to withdraw from the staker's inactive balance. */ function withdrawStakeFor( address staker, address recipient, uint256 stakeAmount ) external onlyRole(STAKE_OPERATOR_ROLE) nonReentrant { _withdrawStake(staker, recipient, stakeAmount); emit OperatorWithdrewStakeFor(staker, recipient, stakeAmount, msg.sender); } /** * @notice Claim rewards on behalf of a staker, and send them to the specified recipient. * * @param staker The staker whose rewards to claim. * @param recipient The address that should receive the funds. * * @return The number of rewards tokens claimed. */ function claimRewardsFor( address staker, address recipient ) external onlyRole(CLAIM_OPERATOR_ROLE) nonReentrant returns (uint256) { uint256 rewards = _settleAndClaimRewards(staker, recipient); // Emits an event internally. emit OperatorClaimedRewardsFor(staker, recipient, rewards, msg.sender); return rewards; } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeERC20 } from '../../../dependencies/open-zeppelin/SafeERC20.sol'; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { IERC20 } from '../../../interfaces/IERC20.sol'; import { Math } from '../../../utils/Math.sol'; import { SM1Types } from '../lib/SM1Types.sol'; import { SM1Roles } from './SM1Roles.sol'; import { SM1Staking } from './SM1Staking.sol'; /** * @title SM1Slashing * @author dYdX * * @dev Provides the slashing function for removing funds from the contract. * * SLASHING: * * All funds in the contract, active or inactive, are slashable. Slashes are recorded by updating * the exchange rate, and to simplify the technical implementation, we disallow full slashes. * To reduce the possibility of overflow in the exchange rate, we place an upper bound on the * fraction of funds that may be slashed in a single slash. * * Warning: Slashing is not possible if the slash would cause the exchange rate to overflow. * * REWARDS AND GOVERNANCE POWER ACCOUNTING: * * Since all slashes are accounted for by a global exchange rate, slashes do not require any * update to staked balances. The earning of rewards is unaffected by slashes. * * Governance power takes slashes into account by using snapshots of the exchange rate inside * the getPowerAtBlock() function. Note that getPowerAtBlock() returns the governance power as of * the end of the specified block. */ abstract contract SM1Slashing is SM1Staking, SM1Roles { using SafeERC20 for IERC20; using SafeMath for uint256; // ============ Constants ============ /// @notice The maximum fraction of funds that may be slashed in a single slash (numerator). uint256 public constant MAX_SLASH_NUMERATOR = 95; /// @notice The maximum fraction of funds that may be slashed in a single slash (denominator). uint256 public constant MAX_SLASH_DENOMINATOR = 100; // ============ Events ============ event Slashed( uint256 amount, address recipient, uint256 newExchangeRate ); // ============ External Functions ============ /** * @notice Slash staked token balances and withdraw those funds to the specified address. * * @param requestedSlashAmount The request slash amount, denominated in the underlying token. * @param recipient The address to receive the slashed tokens. * * @return The amount slashed, denominated in the underlying token. */ function slash( uint256 requestedSlashAmount, address recipient ) external onlyRole(SLASHER_ROLE) nonReentrant returns (uint256) { uint256 underlyingBalance = STAKED_TOKEN.balanceOf(address(this)); if (underlyingBalance == 0) { return 0; } // Get the slash amount and remaining amount. Note that remainingAfterSlash is nonzero. uint256 maxSlashAmount = underlyingBalance.mul(MAX_SLASH_NUMERATOR).div(MAX_SLASH_DENOMINATOR); uint256 slashAmount = Math.min(requestedSlashAmount, maxSlashAmount); uint256 remainingAfterSlash = underlyingBalance.sub(slashAmount); if (slashAmount == 0) { return 0; } // Update the exchange rate. // // Warning: Can revert if the max exchange rate is exceeded. uint256 newExchangeRate = updateExchangeRate(underlyingBalance, remainingAfterSlash); // Transfer the slashed token. STAKED_TOKEN.safeTransfer(recipient, slashAmount); emit Slashed(slashAmount, recipient, newExchangeRate); return slashAmount; } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeERC20 } from '../../../dependencies/open-zeppelin/SafeERC20.sol'; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { IERC20 } from '../../../interfaces/IERC20.sol'; import { Math } from '../../../utils/Math.sol'; import { SM1Types } from '../lib/SM1Types.sol'; import { SM1ERC20 } from './SM1ERC20.sol'; import { SM1StakedBalances } from './SM1StakedBalances.sol'; /** * @title SM1Staking * @author dYdX * * @dev External functions for stakers. See SM1StakedBalances for details on staker accounting. * * UNDERLYING AND STAKED AMOUNTS: * * We distinguish between underlying amounts and stake amounts. An underlying amount is denoted * in the original units of the token being staked. A stake amount is adjusted by the exchange * rate, which can increase due to slashing. Before any slashes have occurred, the exchange rate * is equal to one. */ abstract contract SM1Staking is SM1StakedBalances, SM1ERC20 { using SafeERC20 for IERC20; using SafeMath for uint256; // ============ Events ============ event Staked( address indexed staker, address spender, uint256 underlyingAmount, uint256 stakeAmount ); event WithdrawalRequested( address indexed staker, uint256 stakeAmount ); event WithdrewStake( address indexed staker, address recipient, uint256 underlyingAmount, uint256 stakeAmount ); // ============ Constants ============ IERC20 public immutable STAKED_TOKEN; // ============ Constructor ============ constructor( IERC20 stakedToken, IERC20 rewardsToken, address rewardsTreasury, uint256 distributionStart, uint256 distributionEnd ) SM1StakedBalances(rewardsToken, rewardsTreasury, distributionStart, distributionEnd) { STAKED_TOKEN = stakedToken; } // ============ External Functions ============ /** * @notice Deposit and stake funds. These funds are active and start earning rewards immediately. * * @param underlyingAmount The amount of underlying token to stake. */ function stake( uint256 underlyingAmount ) external nonReentrant { _stake(msg.sender, underlyingAmount); } /** * @notice Deposit and stake on behalf of another address. * * @param staker The staker who will receive the stake. * @param underlyingAmount The amount of underlying token to stake. */ function stakeFor( address staker, uint256 underlyingAmount ) external nonReentrant { _stake(staker, underlyingAmount); } /** * @notice Request to withdraw funds. Starting in the next epoch, the funds will be “inactive” * and available for withdrawal. Inactive funds do not earn rewards. * * Reverts if we are currently in the blackout window. * * @param stakeAmount The amount of stake to move from the active to the inactive balance. */ function requestWithdrawal( uint256 stakeAmount ) external nonReentrant { _requestWithdrawal(msg.sender, stakeAmount); } /** * @notice Withdraw the sender's inactive funds, and send to the specified recipient. * * @param recipient The address that should receive the funds. * @param stakeAmount The amount of stake to withdraw from the sender's inactive balance. */ function withdrawStake( address recipient, uint256 stakeAmount ) external nonReentrant { _withdrawStake(msg.sender, recipient, stakeAmount); } /** * @notice Withdraw the max available inactive funds, and send to the specified recipient. * * This is less gas-efficient than querying the max via eth_call and calling withdrawStake(). * * @param recipient The address that should receive the funds. * * @return The withdrawn amount. */ function withdrawMaxStake( address recipient ) external nonReentrant returns (uint256) { uint256 stakeAmount = getStakeAvailableToWithdraw(msg.sender); _withdrawStake(msg.sender, recipient, stakeAmount); return stakeAmount; } /** * @notice Settle and claim all rewards, and send them to the specified recipient. * * Call this function with eth_call to query the claimable rewards balance. * * @param recipient The address that should receive the funds. * * @return The number of rewards tokens claimed. */ function claimRewards( address recipient ) external nonReentrant returns (uint256) { return _settleAndClaimRewards(msg.sender, recipient); // Emits an event internally. } // ============ Public Functions ============ /** * @notice Get the amount of stake available for a given staker to withdraw. * * @param staker The address whose balance to check. * * @return The staker's stake amount that is inactive and available to withdraw. */ function getStakeAvailableToWithdraw( address staker ) public view returns (uint256) { // Note that the next epoch inactive balance is always at least that of the current epoch. return getInactiveBalanceCurrentEpoch(staker); } // ============ Internal Functions ============ function _stake( address staker, uint256 underlyingAmount ) internal { // Convert using the exchange rate. uint256 stakeAmount = stakeAmountFromUnderlyingAmount(underlyingAmount); // Update staked balances and delegate snapshots. _increaseCurrentAndNextActiveBalance(staker, stakeAmount); _moveDelegatesForTransfer(address(0), staker, stakeAmount); // Transfer token from the sender. STAKED_TOKEN.safeTransferFrom(msg.sender, address(this), underlyingAmount); emit Staked(staker, msg.sender, underlyingAmount, stakeAmount); emit Transfer(address(0), msg.sender, stakeAmount); } function _requestWithdrawal( address staker, uint256 stakeAmount ) internal { require( !inBlackoutWindow(), 'SM1Staking: Withdraw requests restricted in the blackout window' ); // Get the staker's requestable amount and revert if there is not enough to request withdrawal. uint256 requestableBalance = getActiveBalanceNextEpoch(staker); require( stakeAmount <= requestableBalance, 'SM1Staking: Withdraw request exceeds next active balance' ); // Move amount from active to inactive in the next epoch. _moveNextBalanceActiveToInactive(staker, stakeAmount); emit WithdrawalRequested(staker, stakeAmount); } function _withdrawStake( address staker, address recipient, uint256 stakeAmount ) internal { // Get staker withdrawable balance and revert if there is not enough to withdraw. uint256 withdrawableBalance = getInactiveBalanceCurrentEpoch(staker); require( stakeAmount <= withdrawableBalance, 'SM1Staking: Withdraw amount exceeds staker inactive balance' ); // Update staked balances and delegate snapshots. _decreaseCurrentAndNextInactiveBalance(staker, stakeAmount); _moveDelegatesForTransfer(staker, address(0), stakeAmount); // Convert using the exchange rate. uint256 underlyingAmount = underlyingAmountFromStakeAmount(stakeAmount); // Transfer token to the recipient. STAKED_TOKEN.safeTransfer(recipient, underlyingAmount); emit Transfer(msg.sender, address(0), stakeAmount); emit WithdrewStake(staker, recipient, underlyingAmount, stakeAmount); } } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; /** * @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) { // 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. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; /** * @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'); } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.5; pragma abicoder v2; library SM1Types { /** * @dev The parameters used to convert a timestamp to an epoch number. */ struct EpochParameters { uint128 interval; uint128 offset; } /** * @dev Snapshot of a value at a specific block, used to track historical governance power. */ struct Snapshot { uint256 blockNumber; uint256 value; } /** * @dev A balance, possibly with a change scheduled for the next epoch. * * @param currentEpoch The epoch in which the balance was last updated. * @param currentEpochBalance The balance at epoch `currentEpoch`. * @param nextEpochBalance The balance at epoch `currentEpoch + 1`. */ struct StoredBalance { uint16 currentEpoch; uint240 currentEpochBalance; uint240 nextEpochBalance; } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma abicoder v2; import { SM1Storage } from './SM1Storage.sol'; /** * @title SM1Roles * @author dYdX * * @dev Defines roles used in the SafetyModuleV1 contract. The hierarchy of roles and powers * of each role are described below. * * Roles: * * OWNER_ROLE * | -> May add or remove addresses from any of the roles below. * | * +-- SLASHER_ROLE * | -> Can slash staked token balances and withdraw those funds. * | * +-- EPOCH_PARAMETERS_ROLE * | -> May set epoch parameters such as the interval, offset, and blackout window. * | * +-- REWARDS_RATE_ROLE * | -> May set the emission rate of rewards. * | * +-- CLAIM_OPERATOR_ROLE * | -> May claim rewards on behalf of a user. * | * +-- STAKE_OPERATOR_ROLE * -> May manipulate user's staked funds (e.g. perform withdrawals on behalf of a user). */ abstract contract SM1Roles is SM1Storage { bytes32 public constant OWNER_ROLE = keccak256('OWNER_ROLE'); bytes32 public constant SLASHER_ROLE = keccak256('SLASHER_ROLE'); bytes32 public constant EPOCH_PARAMETERS_ROLE = keccak256('EPOCH_PARAMETERS_ROLE'); bytes32 public constant REWARDS_RATE_ROLE = keccak256('REWARDS_RATE_ROLE'); bytes32 public constant CLAIM_OPERATOR_ROLE = keccak256('CLAIM_OPERATOR_ROLE'); bytes32 public constant STAKE_OPERATOR_ROLE = keccak256('STAKE_OPERATOR_ROLE'); function __SM1Roles_init() internal { // Assign roles to the sender. // // The STAKE_OPERATOR_ROLE and CLAIM_OPERATOR_ROLE roles are not initially assigned. // These can be assigned to other smart contracts to provide additional functionality for users. _setupRole(OWNER_ROLE, msg.sender); _setupRole(SLASHER_ROLE, msg.sender); _setupRole(EPOCH_PARAMETERS_ROLE, msg.sender); _setupRole(REWARDS_RATE_ROLE, msg.sender); // Set OWNER_ROLE as the admin of all roles. _setRoleAdmin(OWNER_ROLE, OWNER_ROLE); _setRoleAdmin(SLASHER_ROLE, OWNER_ROLE); _setRoleAdmin(EPOCH_PARAMETERS_ROLE, OWNER_ROLE); _setRoleAdmin(REWARDS_RATE_ROLE, OWNER_ROLE); _setRoleAdmin(CLAIM_OPERATOR_ROLE, OWNER_ROLE); _setRoleAdmin(STAKE_OPERATOR_ROLE, OWNER_ROLE); } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { IERC20 } from '../../../interfaces/IERC20.sol'; import { SafeCast } from '../lib/SafeCast.sol'; import { SM1Types } from '../lib/SM1Types.sol'; import { SM1Rewards } from './SM1Rewards.sol'; /** * @title SM1StakedBalances * @author dYdX * * @dev Accounting of staked balances. * * NOTE: Functions may revert if epoch zero has not started. * * NOTE: All amounts dealt with in this file are denominated in staked units, which because of the * exchange rate, may not correspond one-to-one with the underlying token. See SM1Staking.sol. * * STAKED BALANCE ACCOUNTING: * * A staked balance is in one of two states: * - active: Earning staking rewards; cannot be withdrawn by staker; may be slashed. * - inactive: Not earning rewards; can be withdrawn by the staker; may be slashed. * * A staker may have a combination of active and inactive balances. The following operations * affect staked balances as follows: * - deposit: Increase active balance. * - request withdrawal: At the end of the current epoch, move some active funds to inactive. * - withdraw: Decrease inactive balance. * - transfer: Move some active funds to another staker. * * To encode the fact that a balance may be scheduled to change at the end of a certain epoch, we * store each balance as a struct of three fields: currentEpoch, currentEpochBalance, and * nextEpochBalance. * * REWARDS ACCOUNTING: * * Active funds earn rewards for the period of time that they remain active. This means, after * requesting a withdrawal of some funds, those funds will continue to earn rewards until the end * of the epoch. For example: * * epoch: n n + 1 n + 2 n + 3 * | | | | * +----------+----------+----------+-----... * ^ t_0: User makes a deposit. * ^ t_1: User requests a withdrawal of all funds. * ^ t_2: The funds change state from active to inactive. * * In the above scenario, the user would earn rewards for the period from t_0 to t_2, varying * with the total staked balance in that period. If the user only request a withdrawal for a part * of their balance, then the remaining balance would continue earning rewards beyond t_2. * * User rewards must be settled via SM1Rewards any time a user's active balance changes. Special * attention is paid to the the epoch boundaries, where funds may have transitioned from active * to inactive. * * SETTLEMENT DETAILS: * * Internally, this module uses the following types of operations on stored balances: * - Load: Loads a balance, while applying settlement logic internally to get the * up-to-date result. Returns settlement results without updating state. * - Store: Stores a balance. * - Load-for-update: Performs a load and applies updates as needed to rewards accounting. * Since this is state-changing, it must be followed by a store operation. * - Settle: Performs load-for-update and store operations. * * This module is responsible for maintaining the following invariants to ensure rewards are * calculated correctly: * - When an active balance is loaded for update, if a rollover occurs from one epoch to the * next, the rewards index must be settled up to the boundary at which the rollover occurs. * - Because the global rewards index is needed to update the user rewards index, the total * active balance must be settled before any staker balances are settled or loaded for update. * - A staker's balance must be settled before their rewards are settled. */ abstract contract SM1StakedBalances is SM1Rewards { using SafeCast for uint256; using SafeMath for uint256; // ============ Constructor ============ constructor( IERC20 rewardsToken, address rewardsTreasury, uint256 distributionStart, uint256 distributionEnd ) SM1Rewards(rewardsToken, rewardsTreasury, distributionStart, distributionEnd) {} // ============ Public Functions ============ /** * @notice Get the current active balance of a staker. */ function getActiveBalanceCurrentEpoch( address staker ) public view returns (uint256) { if (!hasEpochZeroStarted()) { return 0; } (SM1Types.StoredBalance memory balance, , , ) = _loadActiveBalance( _ACTIVE_BALANCES_[staker] ); return uint256(balance.currentEpochBalance); } /** * @notice Get the next epoch active balance of a staker. */ function getActiveBalanceNextEpoch( address staker ) public view returns (uint256) { if (!hasEpochZeroStarted()) { return 0; } (SM1Types.StoredBalance memory balance, , , ) = _loadActiveBalance( _ACTIVE_BALANCES_[staker] ); return uint256(balance.nextEpochBalance); } /** * @notice Get the current total active balance. */ function getTotalActiveBalanceCurrentEpoch() public view returns (uint256) { if (!hasEpochZeroStarted()) { return 0; } (SM1Types.StoredBalance memory balance, , , ) = _loadActiveBalance( _TOTAL_ACTIVE_BALANCE_ ); return uint256(balance.currentEpochBalance); } /** * @notice Get the next epoch total active balance. */ function getTotalActiveBalanceNextEpoch() public view returns (uint256) { if (!hasEpochZeroStarted()) { return 0; } (SM1Types.StoredBalance memory balance, , , ) = _loadActiveBalance( _TOTAL_ACTIVE_BALANCE_ ); return uint256(balance.nextEpochBalance); } /** * @notice Get the current inactive balance of a staker. * @dev The balance is converted via the index to token units. */ function getInactiveBalanceCurrentEpoch( address staker ) public view returns (uint256) { if (!hasEpochZeroStarted()) { return 0; } SM1Types.StoredBalance memory balance = _loadInactiveBalance(_INACTIVE_BALANCES_[staker]); return uint256(balance.currentEpochBalance); } /** * @notice Get the next epoch inactive balance of a staker. * @dev The balance is converted via the index to token units. */ function getInactiveBalanceNextEpoch( address staker ) public view returns (uint256) { if (!hasEpochZeroStarted()) { return 0; } SM1Types.StoredBalance memory balance = _loadInactiveBalance(_INACTIVE_BALANCES_[staker]); return uint256(balance.nextEpochBalance); } /** * @notice Get the current total inactive balance. */ function getTotalInactiveBalanceCurrentEpoch() public view returns (uint256) { if (!hasEpochZeroStarted()) { return 0; } SM1Types.StoredBalance memory balance = _loadInactiveBalance(_TOTAL_INACTIVE_BALANCE_); return uint256(balance.currentEpochBalance); } /** * @notice Get the next epoch total inactive balance. */ function getTotalInactiveBalanceNextEpoch() public view returns (uint256) { if (!hasEpochZeroStarted()) { return 0; } SM1Types.StoredBalance memory balance = _loadInactiveBalance(_TOTAL_INACTIVE_BALANCE_); return uint256(balance.nextEpochBalance); } /** * @notice Get the current transferable balance for a user. The user can * only transfer their balance that is not currently inactive or going to be * inactive in the next epoch. Note that this means the user's transferable funds * are their active balance of the next epoch. * * @param account The account to get the transferable balance of. * * @return The user's transferable balance. */ function getTransferableBalance( address account ) public view returns (uint256) { return getActiveBalanceNextEpoch(account); } // ============ Internal Functions ============ function _increaseCurrentAndNextActiveBalance( address staker, uint256 amount ) internal { // Always settle total active balance before settling a staker active balance. uint256 oldTotalBalance = _increaseCurrentAndNextBalances(address(0), true, amount); uint256 oldUserBalance = _increaseCurrentAndNextBalances(staker, true, amount); // When an active balance changes at current timestamp, settle rewards to the current timestamp. _settleUserRewardsUpToNow(staker, oldUserBalance, oldTotalBalance); } function _moveNextBalanceActiveToInactive( address staker, uint256 amount ) internal { // Decrease the active balance for the next epoch. // Always settle total active balance before settling a staker active balance. _decreaseNextBalance(address(0), true, amount); _decreaseNextBalance(staker, true, amount); // Increase the inactive balance for the next epoch. _increaseNextBalance(address(0), false, amount); _increaseNextBalance(staker, false, amount); // Note that we don't need to settle rewards since the current active balance did not change. } function _transferCurrentAndNextActiveBalance( address sender, address recipient, uint256 amount ) internal { // Always settle total active balance before settling a staker active balance. uint256 totalBalance = _settleTotalActiveBalance(); // Move current and next active balances from sender to recipient. uint256 oldSenderBalance = _decreaseCurrentAndNextBalances(sender, true, amount); uint256 oldRecipientBalance = _increaseCurrentAndNextBalances(recipient, true, amount); // When an active balance changes at current timestamp, settle rewards to the current timestamp. _settleUserRewardsUpToNow(sender, oldSenderBalance, totalBalance); _settleUserRewardsUpToNow(recipient, oldRecipientBalance, totalBalance); } function _decreaseCurrentAndNextInactiveBalance( address staker, uint256 amount ) internal { // Decrease the inactive balance for the next epoch. _decreaseCurrentAndNextBalances(address(0), false, amount); _decreaseCurrentAndNextBalances(staker, false, amount); // Note that we don't settle rewards since active balances are not affected. } function _settleTotalActiveBalance() internal returns (uint256) { return _settleBalance(address(0), true); } function _settleAndClaimRewards( address staker, address recipient ) internal returns (uint256) { // Always settle total active balance before settling a staker active balance. uint256 totalBalance = _settleTotalActiveBalance(); // Always settle staker active balance before settling staker rewards. uint256 userBalance = _settleBalance(staker, true); // Settle rewards balance since we want to claim the full accrued amount. _settleUserRewardsUpToNow(staker, userBalance, totalBalance); // Claim rewards balance. return _claimRewards(staker, recipient); } // ============ Private Functions ============ /** * @dev Load a balance for update and then store it. */ function _settleBalance( address maybeStaker, bool isActiveBalance ) private returns (uint256) { SM1Types.StoredBalance storage balancePtr = _getBalancePtr(maybeStaker, isActiveBalance); SM1Types.StoredBalance memory balance = _loadBalanceForUpdate(balancePtr, maybeStaker, isActiveBalance); uint256 currentBalance = uint256(balance.currentEpochBalance); _storeBalance(balancePtr, balance); return currentBalance; } /** * @dev Settle a balance while applying an increase. */ function _increaseCurrentAndNextBalances( address maybeStaker, bool isActiveBalance, uint256 amount ) private returns (uint256) { SM1Types.StoredBalance storage balancePtr = _getBalancePtr(maybeStaker, isActiveBalance); SM1Types.StoredBalance memory balance = _loadBalanceForUpdate(balancePtr, maybeStaker, isActiveBalance); uint256 originalCurrentBalance = uint256(balance.currentEpochBalance); balance.currentEpochBalance = originalCurrentBalance.add(amount).toUint240(); balance.nextEpochBalance = uint256(balance.nextEpochBalance).add(amount).toUint240(); _storeBalance(balancePtr, balance); return originalCurrentBalance; } /** * @dev Settle a balance while applying a decrease. */ function _decreaseCurrentAndNextBalances( address maybeStaker, bool isActiveBalance, uint256 amount ) private returns (uint256) { SM1Types.StoredBalance storage balancePtr = _getBalancePtr(maybeStaker, isActiveBalance); SM1Types.StoredBalance memory balance = _loadBalanceForUpdate(balancePtr, maybeStaker, isActiveBalance); uint256 originalCurrentBalance = uint256(balance.currentEpochBalance); balance.currentEpochBalance = originalCurrentBalance.sub(amount).toUint240(); balance.nextEpochBalance = uint256(balance.nextEpochBalance).sub(amount).toUint240(); _storeBalance(balancePtr, balance); return originalCurrentBalance; } /** * @dev Settle a balance while applying an increase. */ function _increaseNextBalance( address maybeStaker, bool isActiveBalance, uint256 amount ) private { SM1Types.StoredBalance storage balancePtr = _getBalancePtr(maybeStaker, isActiveBalance); SM1Types.StoredBalance memory balance = _loadBalanceForUpdate(balancePtr, maybeStaker, isActiveBalance); balance.nextEpochBalance = uint256(balance.nextEpochBalance).add(amount).toUint240(); _storeBalance(balancePtr, balance); } /** * @dev Settle a balance while applying a decrease. */ function _decreaseNextBalance( address maybeStaker, bool isActiveBalance, uint256 amount ) private { SM1Types.StoredBalance storage balancePtr = _getBalancePtr(maybeStaker, isActiveBalance); SM1Types.StoredBalance memory balance = _loadBalanceForUpdate(balancePtr, maybeStaker, isActiveBalance); balance.nextEpochBalance = uint256(balance.nextEpochBalance).sub(amount).toUint240(); _storeBalance(balancePtr, balance); } function _getBalancePtr( address maybeStaker, bool isActiveBalance ) private view returns (SM1Types.StoredBalance storage) { // Active. if (isActiveBalance) { if (maybeStaker != address(0)) { return _ACTIVE_BALANCES_[maybeStaker]; } return _TOTAL_ACTIVE_BALANCE_; } // Inactive. if (maybeStaker != address(0)) { return _INACTIVE_BALANCES_[maybeStaker]; } return _TOTAL_INACTIVE_BALANCE_; } /** * @dev Load a balance for updating. * * IMPORTANT: This function may modify state, and so the balance MUST be stored afterwards. * - For active balances: * - If a rollover occurs, rewards are settled up to the epoch boundary. * * @param balancePtr A storage pointer to the balance. * @param maybeStaker The user address, or address(0) to update total balance. * @param isActiveBalance Whether the balance is an active balance. */ function _loadBalanceForUpdate( SM1Types.StoredBalance storage balancePtr, address maybeStaker, bool isActiveBalance ) private returns (SM1Types.StoredBalance memory) { // Active balance. if (isActiveBalance) { ( SM1Types.StoredBalance memory balance, uint256 beforeRolloverEpoch, uint256 beforeRolloverBalance, bool didRolloverOccur ) = _loadActiveBalance(balancePtr); if (didRolloverOccur) { // Handle the effect of the balance rollover on rewards. We must partially settle the index // up to the epoch boundary where the change in balance occurred. We pass in the balance // from before the boundary. if (maybeStaker == address(0)) { // If it's the total active balance... _settleGlobalIndexUpToEpoch(beforeRolloverBalance, beforeRolloverEpoch); } else { // If it's a user active balance... _settleUserRewardsUpToEpoch(maybeStaker, beforeRolloverBalance, beforeRolloverEpoch); } } return balance; } // Inactive balance. return _loadInactiveBalance(balancePtr); } function _loadActiveBalance( SM1Types.StoredBalance storage balancePtr ) private view returns ( SM1Types.StoredBalance memory, uint256, uint256, bool ) { SM1Types.StoredBalance memory balance = balancePtr; // Return these as they may be needed for rewards settlement. uint256 beforeRolloverEpoch = uint256(balance.currentEpoch); uint256 beforeRolloverBalance = uint256(balance.currentEpochBalance); bool didRolloverOccur = false; // Roll the balance forward if needed. uint256 currentEpoch = getCurrentEpoch(); if (currentEpoch > uint256(balance.currentEpoch)) { didRolloverOccur = balance.currentEpochBalance != balance.nextEpochBalance; balance.currentEpoch = currentEpoch.toUint16(); balance.currentEpochBalance = balance.nextEpochBalance; } return (balance, beforeRolloverEpoch, beforeRolloverBalance, didRolloverOccur); } function _loadInactiveBalance( SM1Types.StoredBalance storage balancePtr ) private view returns (SM1Types.StoredBalance memory) { SM1Types.StoredBalance memory balance = balancePtr; // Roll the balance forward if needed. uint256 currentEpoch = getCurrentEpoch(); if (currentEpoch > uint256(balance.currentEpoch)) { balance.currentEpoch = currentEpoch.toUint16(); balance.currentEpochBalance = balance.nextEpochBalance; } return balance; } /** * @dev Store a balance. */ function _storeBalance( SM1Types.StoredBalance storage balancePtr, SM1Types.StoredBalance memory balance ) private { // Note: This should use a single `sstore` when compiler optimizations are enabled. balancePtr.currentEpoch = balance.currentEpoch; balancePtr.currentEpochBalance = balance.currentEpochBalance; balancePtr.nextEpochBalance = balance.nextEpochBalance; } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma abicoder v2; import { AccessControlUpgradeable } from '../../../dependencies/open-zeppelin/AccessControlUpgradeable.sol'; import { ReentrancyGuard } from '../../../utils/ReentrancyGuard.sol'; import { VersionedInitializable } from '../../../utils/VersionedInitializable.sol'; import { SM1Types } from '../lib/SM1Types.sol'; /** * @title SM1Storage * @author dYdX * * @dev Storage contract. Contains or inherits from all contract with storage. */ abstract contract SM1Storage is AccessControlUpgradeable, ReentrancyGuard, VersionedInitializable { // ============ Epoch Schedule ============ /// @dev The parameters specifying the function from timestamp to epoch number. SM1Types.EpochParameters internal _EPOCH_PARAMETERS_; /// @dev The period of time at the end of each epoch in which withdrawals cannot be requested. uint256 internal _BLACKOUT_WINDOW_; // ============ Staked Token ERC20 ============ /// @dev Allowances for ERC-20 transfers. mapping(address => mapping(address => uint256)) internal _ALLOWANCES_; // ============ Governance Power Delegation ============ /// @dev Domain separator for EIP-712 signatures. bytes32 internal _DOMAIN_SEPARATOR_; /// @dev Mapping from (owner) => (next valid nonce) for EIP-712 signatures. mapping(address => uint256) internal _NONCES_; /// @dev Snapshots and delegates for governance voting power. mapping(address => mapping(uint256 => SM1Types.Snapshot)) internal _VOTING_SNAPSHOTS_; mapping(address => uint256) internal _VOTING_SNAPSHOT_COUNTS_; mapping(address => address) internal _VOTING_DELEGATES_; /// @dev Snapshots and delegates for governance proposition power. mapping(address => mapping(uint256 => SM1Types.Snapshot)) internal _PROPOSITION_SNAPSHOTS_; mapping(address => uint256) internal _PROPOSITION_SNAPSHOT_COUNTS_; mapping(address => address) internal _PROPOSITION_DELEGATES_; // ============ Rewards Accounting ============ /// @dev The emission rate of rewards. uint256 internal _REWARDS_PER_SECOND_; /// @dev The cumulative rewards earned per staked token. (Shared storage slot.) uint224 internal _GLOBAL_INDEX_; /// @dev The timestamp at which the global index was last updated. (Shared storage slot.) uint32 internal _GLOBAL_INDEX_TIMESTAMP_; /// @dev The value of the global index when the user's staked balance was last updated. mapping(address => uint256) internal _USER_INDEXES_; /// @dev The user's accrued, unclaimed rewards (as of the last update to the user index). mapping(address => uint256) internal _USER_REWARDS_BALANCES_; /// @dev The value of the global index at the end of a given epoch. mapping(uint256 => uint256) internal _EPOCH_INDEXES_; // ============ Staker Accounting ============ /// @dev The active balance by staker. mapping(address => SM1Types.StoredBalance) internal _ACTIVE_BALANCES_; /// @dev The total active balance of stakers. SM1Types.StoredBalance internal _TOTAL_ACTIVE_BALANCE_; /// @dev The inactive balance by staker. mapping(address => SM1Types.StoredBalance) internal _INACTIVE_BALANCES_; /// @dev The total inactive balance of stakers. SM1Types.StoredBalance internal _TOTAL_INACTIVE_BALANCE_; // ============ Exchange Rate ============ /// @dev The value of one underlying token, in the units used for staked balances, denominated /// as a mutiple of EXCHANGE_RATE_BASE for additional precision. uint256 internal _EXCHANGE_RATE_; /// @dev Historical snapshots of the exchange rate, in each block that it has changed. mapping(uint256 => SM1Types.Snapshot) internal _EXCHANGE_RATE_SNAPSHOTS_; /// @dev Number of snapshots of the exchange rate. uint256 internal _EXCHANGE_RATE_SNAPSHOT_COUNT_; } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; import './Context.sol'; import './Strings.sol'; import './ERC165.sol'; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControlUpgradeable { function hasRole(bytes32 role, address account) external view returns (bool); function getRoleAdmin(bytes32 role) external view returns (bytes32); function grantRole(bytes32 role, address account) external; function revokeRole(bytes32 role, address account) external; function renounceRole(bytes32 role, address account) external; } /** * @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 AccessControlUpgradeable is Context, IAccessControlUpgradeable, ERC165 { struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @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 {_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 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]{20}) is missing role (0x[0-9a-f]{32})$/ * * _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(IAccessControlUpgradeable).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]{20}) is missing role (0x[0-9a-f]{32})$/ */ 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 { emit RoleAdminChanged(role, getRoleAdmin(role), adminRole); _roles[role].adminRole = 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()); } } uint256[49] private __gap; } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.5; pragma abicoder v2; /** * @title ReentrancyGuard * @author dYdX * * @dev Updated ReentrancyGuard library designed to be used with Proxy Contracts. */ abstract contract ReentrancyGuard { uint256 private constant NOT_ENTERED = 1; uint256 private constant ENTERED = uint256(int256(-1)); uint256 private _STATUS_; constructor() internal { _STATUS_ = NOT_ENTERED; } modifier nonReentrant() { require(_STATUS_ != ENTERED, 'ReentrancyGuard: reentrant call'); _STATUS_ = ENTERED; _; _STATUS_ = NOT_ENTERED; } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; /** * @title VersionedInitializable * @author Aave, inspired by the OpenZeppelin Initializable contract * * @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. * */ abstract contract VersionedInitializable { /** * @dev Indicates that the contract has been initialized. */ uint256 internal lastInitializedRevision = 0; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { uint256 revision = getRevision(); require(revision > lastInitializedRevision, "Contract instance has already been initialized"); lastInitializedRevision = revision; _; } /// @dev returns the revision number of the contract. /// Needs to be defined in the inherited class as a constant. function getRevision() internal pure virtual returns(uint256); // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; /* * @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; } } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; /** * @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); } } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; 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.7.5; /** * @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: Apache-2.0 pragma solidity 0.7.5; pragma abicoder v2; /** * @dev Methods for downcasting unsigned integers, reverting on overflow. */ library SafeCast { /** * @dev Downcast to a uint16, reverting on overflow. */ function toUint16( uint256 a ) internal pure returns (uint16) { uint16 b = uint16(a); require( uint256(b) == a, 'SafeCast: toUint16 overflow' ); return b; } /** * @dev Downcast to a uint32, reverting on overflow. */ function toUint32( uint256 a ) internal pure returns (uint32) { uint32 b = uint32(a); require( uint256(b) == a, 'SafeCast: toUint32 overflow' ); return b; } /** * @dev Downcast to a uint128, reverting on overflow. */ function toUint128( uint256 a ) internal pure returns (uint128) { uint128 b = uint128(a); require( uint256(b) == a, 'SafeCast: toUint128 overflow' ); return b; } /** * @dev Downcast to a uint224, reverting on overflow. */ function toUint224( uint256 a ) internal pure returns (uint224) { uint224 b = uint224(a); require( uint256(b) == a, 'SafeCast: toUint224 overflow' ); return b; } /** * @dev Downcast to a uint240, reverting on overflow. */ function toUint240( uint256 a ) internal pure returns (uint240) { uint240 b = uint240(a); require( uint256(b) == a, 'SafeCast: toUint240 overflow' ); return b; } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeERC20 } from '../../../dependencies/open-zeppelin/SafeERC20.sol'; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { IERC20 } from '../../../interfaces/IERC20.sol'; import { Math } from '../../../utils/Math.sol'; import { SafeCast } from '../lib/SafeCast.sol'; import { SM1EpochSchedule } from './SM1EpochSchedule.sol'; /** * @title SM1Rewards * @author dYdX * * @dev Manages the distribution of token rewards. * * Rewards are distributed continuously. After each second, an account earns rewards `r` according * to the following formula: * * r = R * s / S * * Where: * - `R` is the rewards distributed globally each second, also called the “emission rate.” * - `s` is the account's staked balance in that second (technically, it is measured at the * end of the second) * - `S` is the sum total of all staked balances in that second (again, measured at the end of * the second) * * The parameter `R` can be configured by the contract owner. For every second that elapses, * exactly `R` tokens will accrue to users, save for rounding errors, and with the exception that * while the total staked balance is zero, no tokens will accrue to anyone. * * The accounting works as follows: A global index is stored which represents the cumulative * number of rewards tokens earned per staked token since the start of the distribution. * The value of this index increases over time, and there are two factors affecting the rate of * increase: * 1) The emission rate (in the numerator) * 2) The total number of staked tokens (in the denominator) * * Whenever either factor changes, in some timestamp T, we settle the global index up to T by * calculating the increase in the index since the last update using the OLD values of the factors: * * indexDelta = timeDelta * emissionPerSecond * INDEX_BASE / totalStaked * * Where `INDEX_BASE` is a scaling factor used to allow more precision in the storage of the index. * * For each user we store an accrued rewards balance, as well as a user index, which is a cache of * the global index at the time that the user's accrued rewards balance was last updated. Then at * any point in time, a user's claimable rewards are represented by the following: * * rewards = _USER_REWARDS_BALANCES_[user] + userStaked * ( * settledGlobalIndex - _USER_INDEXES_[user] * ) / INDEX_BASE */ abstract contract SM1Rewards is SM1EpochSchedule { using SafeCast for uint256; using SafeERC20 for IERC20; using SafeMath for uint256; // ============ Constants ============ /// @dev Additional precision used to represent the global and user index values. uint256 private constant INDEX_BASE = 10**18; /// @notice The rewards token. IERC20 public immutable REWARDS_TOKEN; /// @notice Address to pull rewards from. Must have provided an allowance to this contract. address public immutable REWARDS_TREASURY; /// @notice Start timestamp (inclusive) of the period in which rewards can be earned. uint256 public immutable DISTRIBUTION_START; /// @notice End timestamp (exclusive) of the period in which rewards can be earned. uint256 public immutable DISTRIBUTION_END; // ============ Events ============ event RewardsPerSecondUpdated( uint256 emissionPerSecond ); event GlobalIndexUpdated( uint256 index ); event UserIndexUpdated( address indexed user, uint256 index, uint256 unclaimedRewards ); event ClaimedRewards( address indexed user, address recipient, uint256 claimedRewards ); // ============ Constructor ============ constructor( IERC20 rewardsToken, address rewardsTreasury, uint256 distributionStart, uint256 distributionEnd ) { require( distributionEnd >= distributionStart, 'SM1Rewards: Invalid parameters' ); REWARDS_TOKEN = rewardsToken; REWARDS_TREASURY = rewardsTreasury; DISTRIBUTION_START = distributionStart; DISTRIBUTION_END = distributionEnd; } // ============ External Functions ============ /** * @notice The current emission rate of rewards. * * @return The number of rewards tokens issued globally each second. */ function getRewardsPerSecond() external view returns (uint256) { return _REWARDS_PER_SECOND_; } // ============ Internal Functions ============ /** * @dev Initialize the contract. */ function __SM1Rewards_init() internal { _GLOBAL_INDEX_TIMESTAMP_ = Math.max(block.timestamp, DISTRIBUTION_START).toUint32(); } /** * @dev Set the emission rate of rewards. * * IMPORTANT: Do not call this function without settling the total staked balance first, to * ensure that the index is settled up to the epoch boundaries. * * @param emissionPerSecond The new number of rewards tokens to give out each second. * @param totalStaked The total staked balance. */ function _setRewardsPerSecond( uint256 emissionPerSecond, uint256 totalStaked ) internal { _settleGlobalIndexUpToNow(totalStaked); _REWARDS_PER_SECOND_ = emissionPerSecond; emit RewardsPerSecondUpdated(emissionPerSecond); } /** * @dev Claim tokens, sending them to the specified recipient. * * Note: In order to claim all accrued rewards, the total and user staked balances must first be * settled before calling this function. * * @param user The user's address. * @param recipient The address to send rewards to. * * @return The number of rewards tokens claimed. */ function _claimRewards( address user, address recipient ) internal returns (uint256) { uint256 accruedRewards = _USER_REWARDS_BALANCES_[user]; _USER_REWARDS_BALANCES_[user] = 0; REWARDS_TOKEN.safeTransferFrom(REWARDS_TREASURY, recipient, accruedRewards); emit ClaimedRewards(user, recipient, accruedRewards); return accruedRewards; } /** * @dev Settle a user's rewards up to the latest global index as of `block.timestamp`. Triggers a * settlement of the global index up to `block.timestamp`. Should be called with the OLD user * and total balances. * * @param user The user's address. * @param userStaked Tokens staked by the user during the period since the last user index * update. * @param totalStaked Total tokens staked by all users during the period since the last global * index update. * * @return The user's accrued rewards, including past unclaimed rewards. */ function _settleUserRewardsUpToNow( address user, uint256 userStaked, uint256 totalStaked ) internal returns (uint256) { uint256 globalIndex = _settleGlobalIndexUpToNow(totalStaked); return _settleUserRewardsUpToIndex(user, userStaked, globalIndex); } /** * @dev Settle a user's rewards up to an epoch boundary. Should be used to partially settle a * user's rewards if their balance was known to have changed on that epoch boundary. * * @param user The user's address. * @param userStaked Tokens staked by the user. Should be accurate for the time period * since the last update to this user and up to the end of the * specified epoch. * @param epochNumber Settle the user's rewards up to the end of this epoch. * * @return The user's accrued rewards, including past unclaimed rewards, up to the end of the * specified epoch. */ function _settleUserRewardsUpToEpoch( address user, uint256 userStaked, uint256 epochNumber ) internal returns (uint256) { uint256 globalIndex = _EPOCH_INDEXES_[epochNumber]; return _settleUserRewardsUpToIndex(user, userStaked, globalIndex); } /** * @dev Settle the global index up to the end of the given epoch. * * IMPORTANT: This function should only be called under conditions which ensure the following: * - `epochNumber` < the current epoch number * - `_GLOBAL_INDEX_TIMESTAMP_ < settleUpToTimestamp` * - `_EPOCH_INDEXES_[epochNumber] = 0` */ function _settleGlobalIndexUpToEpoch( uint256 totalStaked, uint256 epochNumber ) internal returns (uint256) { uint256 settleUpToTimestamp = getStartOfEpoch(epochNumber.add(1)); uint256 globalIndex = _settleGlobalIndexUpToTimestamp(totalStaked, settleUpToTimestamp); _EPOCH_INDEXES_[epochNumber] = globalIndex; return globalIndex; } // ============ Private Functions ============ /** * @dev Updates the global index, reflecting cumulative rewards given out per staked token. * * @param totalStaked The total staked balance, which should be constant in the interval * since the last update to the global index. * * @return The new global index. */ function _settleGlobalIndexUpToNow( uint256 totalStaked ) private returns (uint256) { return _settleGlobalIndexUpToTimestamp(totalStaked, block.timestamp); } /** * @dev Helper function which settles a user's rewards up to a global index. Should be called * any time a user's staked balance changes, with the OLD user and total balances. * * @param user The user's address. * @param userStaked Tokens staked by the user during the period since the last user index * update. * @param newGlobalIndex The new index value to bring the user index up to. MUST NOT be less * than the user's index. * * @return The user's accrued rewards, including past unclaimed rewards. */ function _settleUserRewardsUpToIndex( address user, uint256 userStaked, uint256 newGlobalIndex ) private returns (uint256) { uint256 oldAccruedRewards = _USER_REWARDS_BALANCES_[user]; uint256 oldUserIndex = _USER_INDEXES_[user]; if (oldUserIndex == newGlobalIndex) { return oldAccruedRewards; } uint256 newAccruedRewards; if (userStaked == 0) { // Note: Even if the user's staked balance is zero, we still need to update the user index. newAccruedRewards = oldAccruedRewards; } else { // Calculate newly accrued rewards since the last update to the user's index. uint256 indexDelta = newGlobalIndex.sub(oldUserIndex); uint256 accruedRewardsDelta = userStaked.mul(indexDelta).div(INDEX_BASE); newAccruedRewards = oldAccruedRewards.add(accruedRewardsDelta); // Update the user's rewards. _USER_REWARDS_BALANCES_[user] = newAccruedRewards; } // Update the user's index. _USER_INDEXES_[user] = newGlobalIndex; emit UserIndexUpdated(user, newGlobalIndex, newAccruedRewards); return newAccruedRewards; } /** * @dev Updates the global index, reflecting cumulative rewards given out per staked token. * * @param totalStaked The total staked balance, which should be constant in the interval * (_GLOBAL_INDEX_TIMESTAMP_, settleUpToTimestamp). * @param settleUpToTimestamp The timestamp up to which to settle rewards. It MUST satisfy * `settleUpToTimestamp <= block.timestamp`. * * @return The new global index. */ function _settleGlobalIndexUpToTimestamp( uint256 totalStaked, uint256 settleUpToTimestamp ) private returns (uint256) { uint256 oldGlobalIndex = uint256(_GLOBAL_INDEX_); // The goal of this function is to calculate rewards earned since the last global index update. // These rewards are earned over the time interval which is the intersection of the intervals // [_GLOBAL_INDEX_TIMESTAMP_, settleUpToTimestamp] and [DISTRIBUTION_START, DISTRIBUTION_END]. // // We can simplify a bit based on the assumption: // `_GLOBAL_INDEX_TIMESTAMP_ >= DISTRIBUTION_START` // // Get the start and end of the time interval under consideration. uint256 intervalStart = uint256(_GLOBAL_INDEX_TIMESTAMP_); uint256 intervalEnd = Math.min(settleUpToTimestamp, DISTRIBUTION_END); // Return early if the interval has length zero (incl. case where intervalEnd < intervalStart). if (intervalEnd <= intervalStart) { return oldGlobalIndex; } // Note: If we reach this point, we must update _GLOBAL_INDEX_TIMESTAMP_. uint256 emissionPerSecond = _REWARDS_PER_SECOND_; if (emissionPerSecond == 0 || totalStaked == 0) { // Ensure a log is emitted if the timestamp changed, even if the index does not change. _GLOBAL_INDEX_TIMESTAMP_ = intervalEnd.toUint32(); emit GlobalIndexUpdated(oldGlobalIndex); return oldGlobalIndex; } // Calculate the change in index over the interval. uint256 timeDelta = intervalEnd.sub(intervalStart); uint256 indexDelta = timeDelta.mul(emissionPerSecond).mul(INDEX_BASE).div(totalStaked); // Calculate, update, and return the new global index. uint256 newGlobalIndex = oldGlobalIndex.add(indexDelta); // Update storage. (Shared storage slot.) _GLOBAL_INDEX_TIMESTAMP_ = intervalEnd.toUint32(); _GLOBAL_INDEX_ = newGlobalIndex.toUint224(); emit GlobalIndexUpdated(newGlobalIndex); return newGlobalIndex; } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeMath } from '../dependencies/open-zeppelin/SafeMath.sol'; /** * @title Math * @author dYdX * * @dev Library for non-standard Math functions. */ library Math { using SafeMath for uint256; // ============ Library Functions ============ /** * @dev Return `ceil(numerator / denominator)`. */ function divRoundUp( uint256 numerator, uint256 denominator ) internal pure returns (uint256) { if (numerator == 0) { // SafeMath will check for zero denominator return SafeMath.div(0, denominator); } return numerator.sub(1).div(denominator).add(1); } /** * @dev Returns the minimum between a and b. */ function min( uint256 a, uint256 b ) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the maximum between a and b. */ function max( uint256 a, uint256 b ) internal pure returns (uint256) { return a > b ? a : b; } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { SafeCast } from '../lib/SafeCast.sol'; import { SM1Types } from '../lib/SM1Types.sol'; import { SM1Storage } from './SM1Storage.sol'; /** * @title SM1EpochSchedule * @author dYdX * * @dev Defines a function from block timestamp to epoch number. * * The formula used is `n = floor((t - b) / a)` where: * - `n` is the epoch number * - `t` is the timestamp (in seconds) * - `b` is a non-negative offset, indicating the start of epoch zero (in seconds) * - `a` is the length of an epoch, a.k.a. the interval (in seconds) * * Note that by restricting `b` to be non-negative, we limit ourselves to functions in which epoch * zero starts at a non-negative timestamp. * * The recommended epoch length and blackout window are 28 and 7 days respectively; however, these * are modifiable by the admin, within the specified bounds. */ abstract contract SM1EpochSchedule is SM1Storage { using SafeCast for uint256; using SafeMath for uint256; // ============ Events ============ event EpochParametersChanged( SM1Types.EpochParameters epochParameters ); event BlackoutWindowChanged( uint256 blackoutWindow ); // ============ Initializer ============ function __SM1EpochSchedule_init( uint256 interval, uint256 offset, uint256 blackoutWindow ) internal { require( block.timestamp < offset, 'SM1EpochSchedule: Epoch zero must start after initialization' ); _setBlackoutWindow(blackoutWindow); _setEpochParameters(interval, offset); } // ============ Public Functions ============ /** * @notice Get the epoch at the current block timestamp. * * NOTE: Reverts if epoch zero has not started. * * @return The current epoch number. */ function getCurrentEpoch() public view returns (uint256) { (uint256 interval, uint256 offsetTimestamp) = _getIntervalAndOffsetTimestamp(); return offsetTimestamp.div(interval); } /** * @notice Get the time remaining in the current epoch. * * NOTE: Reverts if epoch zero has not started. * * @return The number of seconds until the next epoch. */ function getTimeRemainingInCurrentEpoch() public view returns (uint256) { (uint256 interval, uint256 offsetTimestamp) = _getIntervalAndOffsetTimestamp(); uint256 timeElapsedInEpoch = offsetTimestamp.mod(interval); return interval.sub(timeElapsedInEpoch); } /** * @notice Given an epoch number, get the start of that epoch. Calculated as `t = (n * a) + b`. * * @return The timestamp in seconds representing the start of that epoch. */ function getStartOfEpoch( uint256 epochNumber ) public view returns (uint256) { SM1Types.EpochParameters memory epochParameters = _EPOCH_PARAMETERS_; uint256 interval = uint256(epochParameters.interval); uint256 offset = uint256(epochParameters.offset); return epochNumber.mul(interval).add(offset); } /** * @notice Check whether we are at or past the start of epoch zero. * * @return Boolean `true` if the current timestamp is at least the start of epoch zero, * otherwise `false`. */ function hasEpochZeroStarted() public view returns (bool) { SM1Types.EpochParameters memory epochParameters = _EPOCH_PARAMETERS_; uint256 offset = uint256(epochParameters.offset); return block.timestamp >= offset; } /** * @notice Check whether we are in a blackout window, where withdrawal requests are restricted. * Note that before epoch zero has started, there are no blackout windows. * * @return Boolean `true` if we are in a blackout window, otherwise `false`. */ function inBlackoutWindow() public view returns (bool) { return hasEpochZeroStarted() && getTimeRemainingInCurrentEpoch() <= _BLACKOUT_WINDOW_; } // ============ Internal Functions ============ function _setEpochParameters( uint256 interval, uint256 offset ) internal { SM1Types.EpochParameters memory epochParameters = SM1Types.EpochParameters({interval: interval.toUint128(), offset: offset.toUint128()}); _EPOCH_PARAMETERS_ = epochParameters; emit EpochParametersChanged(epochParameters); } function _setBlackoutWindow( uint256 blackoutWindow ) internal { _BLACKOUT_WINDOW_ = blackoutWindow; emit BlackoutWindowChanged(blackoutWindow); } // ============ Private Functions ============ /** * @dev Helper function to read params from storage and apply offset to the given timestamp. * Recall that the formula for epoch number is `n = (t - b) / a`. * * NOTE: Reverts if epoch zero has not started. * * @return The values `a` and `(t - b)`. */ function _getIntervalAndOffsetTimestamp() private view returns (uint256, uint256) { SM1Types.EpochParameters memory epochParameters = _EPOCH_PARAMETERS_; uint256 interval = uint256(epochParameters.interval); uint256 offset = uint256(epochParameters.offset); require( block.timestamp >= offset, 'SM1EpochSchedule: Epoch zero has not started' ); uint256 offsetTimestamp = block.timestamp.sub(offset); return (interval, offsetTimestamp); } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { IERC20 } from '../../../interfaces/IERC20.sol'; import { IERC20Detailed } from '../../../interfaces/IERC20Detailed.sol'; import { SM1Types } from '../lib/SM1Types.sol'; import { SM1GovernancePowerDelegation } from './SM1GovernancePowerDelegation.sol'; import { SM1StakedBalances } from './SM1StakedBalances.sol'; /** * @title SM1ERC20 * @author dYdX * * @dev ERC20 interface for staked tokens. Implements governance functionality for the tokens. * * Also allows a user with an active stake to transfer their staked tokens to another user, * even if they would otherwise be restricted from withdrawing. */ abstract contract SM1ERC20 is SM1StakedBalances, SM1GovernancePowerDelegation, IERC20Detailed { using SafeMath for uint256; // ============ Constants ============ /// @notice EIP-712 typehash for token approval via EIP-2612 permit. bytes32 public constant PERMIT_TYPEHASH = keccak256( 'Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)' ); // ============ External Functions ============ function name() external pure override returns (string memory) { return 'Staked DYDX'; } function symbol() external pure override returns (string memory) { return 'stkDYDX'; } function decimals() external pure override returns (uint8) { return 18; } /** * @notice Get the total supply of staked balances. * * Note that due to the exchange rate, this is different than querying the total balance of * underyling token staked to this contract. * * @return The sum of all staked balances. */ function totalSupply() external view override returns (uint256) { return getTotalActiveBalanceCurrentEpoch() + getTotalInactiveBalanceCurrentEpoch(); } /** * @notice Get a user's staked balance. * * Note that due to the exchange rate, one unit of staked balance may not be equivalent to one * unit of the underlying token. Also note that a user's staked balance is different from a * user's transferable balance. * * @param account The account to get the balance of. * * @return The user's staked balance. */ function balanceOf( address account ) public view override(SM1GovernancePowerDelegation, IERC20) returns (uint256) { return getActiveBalanceCurrentEpoch(account) + getInactiveBalanceCurrentEpoch(account); } function transfer( address recipient, uint256 amount ) external override nonReentrant returns (bool) { _transfer(msg.sender, recipient, amount); return true; } function allowance( address owner, address spender ) external view override returns (uint256) { return _ALLOWANCES_[owner][spender]; } function approve( address spender, uint256 amount ) external override returns (bool) { _approve(msg.sender, spender, amount); return true; } function transferFrom( address sender, address recipient, uint256 amount ) external override nonReentrant returns (bool) { _transfer(sender, recipient, amount); _approve( sender, msg.sender, _ALLOWANCES_[sender][msg.sender].sub(amount, 'SM1ERC20: transfer amount exceeds allowance') ); return true; } function increaseAllowance( address spender, uint256 addedValue ) external returns (bool) { _approve(msg.sender, spender, _ALLOWANCES_[msg.sender][spender].add(addedValue)); return true; } function decreaseAllowance( address spender, uint256 subtractedValue ) external returns (bool) { _approve( msg.sender, spender, _ALLOWANCES_[msg.sender][spender].sub( subtractedValue, 'SM1ERC20: Decreased allowance below zero' ) ); return true; } /** * @notice Implements the permit function as specified in EIP-2612. * * @param owner Address of the token owner. * @param spender Address of the spender. * @param value Amount of allowance. * @param deadline Expiration timestamp for the signature. * @param v Signature param. * @param r Signature param. * @param s Signature param. */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external { require( owner != address(0), 'SM1ERC20: INVALID_OWNER' ); require( block.timestamp <= deadline, 'SM1ERC20: INVALID_EXPIRATION' ); uint256 currentValidNonce = _NONCES_[owner]; bytes32 digest = keccak256( abi.encodePacked( '\x19\x01', _DOMAIN_SEPARATOR_, keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, currentValidNonce, deadline)) ) ); require( owner == ecrecover(digest, v, r, s), 'SM1ERC20: INVALID_SIGNATURE' ); _NONCES_[owner] = currentValidNonce.add(1); _approve(owner, spender, value); } // ============ Internal Functions ============ function _transfer( address sender, address recipient, uint256 amount ) internal { require( sender != address(0), 'SM1ERC20: Transfer from address(0)' ); require( recipient != address(0), 'SM1ERC20: Transfer to address(0)' ); require( getTransferableBalance(sender) >= amount, 'SM1ERC20: Transfer exceeds next epoch active balance' ); // Update staked balances and delegate snapshots. _transferCurrentAndNextActiveBalance(sender, recipient, amount); _moveDelegatesForTransfer(sender, recipient, amount); emit Transfer(sender, recipient, amount); } function _approve( address owner, address spender, uint256 amount ) internal { require( owner != address(0), 'SM1ERC20: Approve from address(0)' ); require( spender != address(0), 'SM1ERC20: Approve to address(0)' ); _ALLOWANCES_[owner][spender] = amount; emit Approval(owner, spender, amount); } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; import { IERC20 } from './IERC20.sol'; /** * @dev Interface for ERC20 including metadata **/ interface IERC20Detailed is IERC20 { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { IGovernancePowerDelegationERC20 } from '../../../interfaces/IGovernancePowerDelegationERC20.sol'; import { SM1Types } from '../lib/SM1Types.sol'; import { SM1ExchangeRate } from './SM1ExchangeRate.sol'; import { SM1Storage } from './SM1Storage.sol'; /** * @title SM1GovernancePowerDelegation * @author dYdX * * @dev Provides support for two types of governance powers which are separately delegatable. * Provides functions for delegation and for querying a user's power at a certain block number. * * Internally, makes use of staked balances denoted in staked units, but returns underlying token * units from the getPowerAtBlock() and getPowerCurrent() functions. * * This is based on, and is designed to match, Aave's implementation, which is used in their * governance token and staked token contracts. */ abstract contract SM1GovernancePowerDelegation is SM1ExchangeRate, IGovernancePowerDelegationERC20 { using SafeMath for uint256; // ============ Constants ============ /// @notice EIP-712 typehash for delegation by signature of a specific governance power type. bytes32 public constant DELEGATE_BY_TYPE_TYPEHASH = keccak256( 'DelegateByType(address delegatee,uint256 type,uint256 nonce,uint256 expiry)' ); /// @notice EIP-712 typehash for delegation by signature of all governance powers. bytes32 public constant DELEGATE_TYPEHASH = keccak256( 'Delegate(address delegatee,uint256 nonce,uint256 expiry)' ); // ============ External Functions ============ /** * @notice Delegates a specific governance power of the sender to a delegatee. * * @param delegatee The address to delegate power to. * @param delegationType The type of delegation (VOTING_POWER, PROPOSITION_POWER). */ function delegateByType( address delegatee, DelegationType delegationType ) external override { _delegateByType(msg.sender, delegatee, delegationType); } /** * @notice Delegates all governance powers of the sender to a delegatee. * * @param delegatee The address to delegate power to. */ function delegate( address delegatee ) external override { _delegateByType(msg.sender, delegatee, DelegationType.VOTING_POWER); _delegateByType(msg.sender, delegatee, DelegationType.PROPOSITION_POWER); } /** * @dev Delegates specific governance power from signer to `delegatee` using an EIP-712 signature. * * @param delegatee The address to delegate votes to. * @param delegationType The type of delegation (VOTING_POWER, PROPOSITION_POWER). * @param nonce The signer's nonce for EIP-712 signatures on this contract. * @param expiry Expiration timestamp for the signature. * @param v Signature param. * @param r Signature param. * @param s Signature param. */ function delegateByTypeBySig( address delegatee, DelegationType delegationType, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s ) external { bytes32 structHash = keccak256( abi.encode(DELEGATE_BY_TYPE_TYPEHASH, delegatee, uint256(delegationType), nonce, expiry) ); bytes32 digest = keccak256(abi.encodePacked('\x19\x01', _DOMAIN_SEPARATOR_, structHash)); address signer = ecrecover(digest, v, r, s); require( signer != address(0), 'SM1GovernancePowerDelegation: INVALID_SIGNATURE' ); require( nonce == _NONCES_[signer]++, 'SM1GovernancePowerDelegation: INVALID_NONCE' ); require( block.timestamp <= expiry, 'SM1GovernancePowerDelegation: INVALID_EXPIRATION' ); _delegateByType(signer, delegatee, delegationType); } /** * @dev Delegates both governance powers from signer to `delegatee` using an EIP-712 signature. * * @param delegatee The address to delegate votes to. * @param nonce The signer's nonce for EIP-712 signatures on this contract. * @param expiry Expiration timestamp for the signature. * @param v Signature param. * @param r Signature param. * @param s Signature param. */ function delegateBySig( address delegatee, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s ) external { bytes32 structHash = keccak256(abi.encode(DELEGATE_TYPEHASH, delegatee, nonce, expiry)); bytes32 digest = keccak256(abi.encodePacked('\x19\x01', _DOMAIN_SEPARATOR_, structHash)); address signer = ecrecover(digest, v, r, s); require( signer != address(0), 'SM1GovernancePowerDelegation: INVALID_SIGNATURE' ); require( nonce == _NONCES_[signer]++, 'SM1GovernancePowerDelegation: INVALID_NONCE' ); require( block.timestamp <= expiry, 'SM1GovernancePowerDelegation: INVALID_EXPIRATION' ); _delegateByType(signer, delegatee, DelegationType.VOTING_POWER); _delegateByType(signer, delegatee, DelegationType.PROPOSITION_POWER); } /** * @notice Returns the delegatee of a user. * * @param delegator The address of the delegator. * @param delegationType The type of delegation (VOTING_POWER, PROPOSITION_POWER). */ function getDelegateeByType( address delegator, DelegationType delegationType ) external override view returns (address) { (, , mapping(address => address) storage delegates) = _getDelegationDataByType(delegationType); return _getDelegatee(delegator, delegates); } /** * @notice Returns the current power of a user. The current power is the power delegated * at the time of the last snapshot. * * @param user The user whose power to query. * @param delegationType The type of power (VOTING_POWER, PROPOSITION_POWER). */ function getPowerCurrent( address user, DelegationType delegationType ) external override view returns (uint256) { return getPowerAtBlock(user, block.number, delegationType); } /** * @notice Get the next valid nonce for EIP-712 signatures. * * This nonce should be used when signing for any of the following functions: * - permit() * - delegateByTypeBySig() * - delegateBySig() */ function nonces( address owner ) external view returns (uint256) { return _NONCES_[owner]; } // ============ Public Functions ============ function balanceOf( address account ) public view virtual returns (uint256); /** * @notice Returns the power of a user at a certain block, denominated in underlying token units. * * @param user The user whose power to query. * @param blockNumber The block number at which to get the user's power. * @param delegationType The type of power (VOTING_POWER, PROPOSITION_POWER). * * @return The user's governance power of the specified type, in underlying token units. */ function getPowerAtBlock( address user, uint256 blockNumber, DelegationType delegationType ) public override view returns (uint256) { ( mapping(address => mapping(uint256 => SM1Types.Snapshot)) storage snapshots, mapping(address => uint256) storage snapshotCounts, // unused: delegates ) = _getDelegationDataByType(delegationType); uint256 stakeAmount = _findValueAtBlock( snapshots[user], snapshotCounts[user], blockNumber, 0 ); uint256 exchangeRate = _findValueAtBlock( _EXCHANGE_RATE_SNAPSHOTS_, _EXCHANGE_RATE_SNAPSHOT_COUNT_, blockNumber, EXCHANGE_RATE_BASE ); return underlyingAmountFromStakeAmountWithExchangeRate(stakeAmount, exchangeRate); } // ============ Internal Functions ============ /** * @dev Delegates one specific power to a delegatee. * * @param delegator The user whose power to delegate. * @param delegatee The address to delegate power to. * @param delegationType The type of power (VOTING_POWER, PROPOSITION_POWER). */ function _delegateByType( address delegator, address delegatee, DelegationType delegationType ) internal { require( delegatee != address(0), 'SM1GovernancePowerDelegation: INVALID_DELEGATEE' ); (, , mapping(address => address) storage delegates) = _getDelegationDataByType(delegationType); uint256 delegatorBalance = balanceOf(delegator); address previousDelegatee = _getDelegatee(delegator, delegates); delegates[delegator] = delegatee; _moveDelegatesByType(previousDelegatee, delegatee, delegatorBalance, delegationType); emit DelegateChanged(delegator, delegatee, delegationType); } /** * @dev Update delegate snapshots whenever staked tokens are transfered, minted, or burned. * * @param from The sender. * @param to The recipient. * @param stakedAmount The amount being transfered, denominated in staked units. */ function _moveDelegatesForTransfer( address from, address to, uint256 stakedAmount ) internal { address votingPowerFromDelegatee = _getDelegatee(from, _VOTING_DELEGATES_); address votingPowerToDelegatee = _getDelegatee(to, _VOTING_DELEGATES_); _moveDelegatesByType( votingPowerFromDelegatee, votingPowerToDelegatee, stakedAmount, DelegationType.VOTING_POWER ); address propositionPowerFromDelegatee = _getDelegatee(from, _PROPOSITION_DELEGATES_); address propositionPowerToDelegatee = _getDelegatee(to, _PROPOSITION_DELEGATES_); _moveDelegatesByType( propositionPowerFromDelegatee, propositionPowerToDelegatee, stakedAmount, DelegationType.PROPOSITION_POWER ); } /** * @dev Moves power from one user to another. * * @param from The user from which delegated power is moved. * @param to The user that will receive the delegated power. * @param amount The amount of power to be moved. * @param delegationType The type of power (VOTING_POWER, PROPOSITION_POWER). */ function _moveDelegatesByType( address from, address to, uint256 amount, DelegationType delegationType ) internal { if (from == to) { return; } ( mapping(address => mapping(uint256 => SM1Types.Snapshot)) storage snapshots, mapping(address => uint256) storage snapshotCounts, // unused: delegates ) = _getDelegationDataByType(delegationType); if (from != address(0)) { mapping(uint256 => SM1Types.Snapshot) storage fromSnapshots = snapshots[from]; uint256 fromSnapshotCount = snapshotCounts[from]; uint256 previousBalance = 0; if (fromSnapshotCount != 0) { previousBalance = fromSnapshots[fromSnapshotCount - 1].value; } uint256 newBalance = previousBalance.sub(amount); snapshotCounts[from] = _writeSnapshot( fromSnapshots, fromSnapshotCount, newBalance ); emit DelegatedPowerChanged(from, newBalance, delegationType); } if (to != address(0)) { mapping(uint256 => SM1Types.Snapshot) storage toSnapshots = snapshots[to]; uint256 toSnapshotCount = snapshotCounts[to]; uint256 previousBalance = 0; if (toSnapshotCount != 0) { previousBalance = toSnapshots[toSnapshotCount - 1].value; } uint256 newBalance = previousBalance.add(amount); snapshotCounts[to] = _writeSnapshot( toSnapshots, toSnapshotCount, newBalance ); emit DelegatedPowerChanged(to, newBalance, delegationType); } } /** * @dev Returns delegation data (snapshot, snapshotCount, delegates) by delegation type. * * @param delegationType The type of power (VOTING_POWER, PROPOSITION_POWER). * * @return The mapping of each user to a mapping of snapshots. * @return The mapping of each user to the total number of snapshots for that user. * @return The mapping of each user to the user's delegate. */ function _getDelegationDataByType( DelegationType delegationType ) internal view returns ( mapping(address => mapping(uint256 => SM1Types.Snapshot)) storage, mapping(address => uint256) storage, mapping(address => address) storage ) { if (delegationType == DelegationType.VOTING_POWER) { return ( _VOTING_SNAPSHOTS_, _VOTING_SNAPSHOT_COUNTS_, _VOTING_DELEGATES_ ); } else { return ( _PROPOSITION_SNAPSHOTS_, _PROPOSITION_SNAPSHOT_COUNTS_, _PROPOSITION_DELEGATES_ ); } } /** * @dev Returns the delegatee of a user. If a user never performed any delegation, their * delegated address will be 0x0, in which case we return the user's own address. * * @param delegator The address of the user for which return the delegatee. * @param delegates The mapping of delegates for a particular type of delegation. */ function _getDelegatee( address delegator, mapping(address => address) storage delegates ) internal view returns (address) { address previousDelegatee = delegates[delegator]; if (previousDelegatee == address(0)) { return delegator; } return previousDelegatee; } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; interface IGovernancePowerDelegationERC20 { enum DelegationType { VOTING_POWER, PROPOSITION_POWER } /** * @dev Emitted when a user delegates governance power to another user. * * @param delegator The delegator. * @param delegatee The delegatee. * @param delegationType The type of delegation (VOTING_POWER, PROPOSITION_POWER). */ event DelegateChanged( address indexed delegator, address indexed delegatee, DelegationType delegationType ); /** * @dev Emitted when an action changes the delegated power of a user. * * @param user The user whose delegated power has changed. * @param amount The new amount of delegated power for the user. * @param delegationType The type of delegation (VOTING_POWER, PROPOSITION_POWER). */ event DelegatedPowerChanged(address indexed user, uint256 amount, DelegationType delegationType); /** * @dev Delegates a specific governance power to a delegatee. * * @param delegatee The address to delegate power to. * @param delegationType The type of delegation (VOTING_POWER, PROPOSITION_POWER). */ function delegateByType(address delegatee, DelegationType delegationType) external virtual; /** * @dev Delegates all governance powers to a delegatee. * * @param delegatee The user to which the power will be delegated. */ function delegate(address delegatee) external virtual; /** * @dev Returns the delegatee of an user. * * @param delegator The address of the delegator. * @param delegationType The type of delegation (VOTING_POWER, PROPOSITION_POWER). */ function getDelegateeByType(address delegator, DelegationType delegationType) external view virtual returns (address); /** * @dev Returns the current delegated power of a user. The current power is the power delegated * at the time of the last snapshot. * * @param user The user whose power to query. * @param delegationType The type of power (VOTING_POWER, PROPOSITION_POWER). */ function getPowerCurrent(address user, DelegationType delegationType) external view virtual returns (uint256); /** * @dev Returns the delegated power of a user at a certain block. * * @param user The user whose power to query. * @param blockNumber The block number at which to get the user's power. * @param delegationType The type of power (VOTING_POWER, PROPOSITION_POWER). */ function getPowerAtBlock( address user, uint256 blockNumber, DelegationType delegationType ) external view virtual returns (uint256); } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { SM1Snapshots } from './SM1Snapshots.sol'; import { SM1Storage } from './SM1Storage.sol'; /** * @title SM1ExchangeRate * @author dYdX * * @dev Performs math using the exchange rate, which converts between underlying units of the token * that was staked (e.g. STAKED_TOKEN.balanceOf(account)), and staked units, used by this contract * for all staked balances (e.g. this.balanceOf(account)). * * OVERVIEW: * * The exchange rate is stored as a multiple of EXCHANGE_RATE_BASE, and represents the number of * staked balance units that each unit of underlying token is worth. Before any slashes have * occurred, the exchange rate is equal to one. The exchange rate can increase with each slash, * indicating that staked balances are becoming less and less valuable, per unit, relative to the * underlying token. * * AVOIDING OVERFLOW AND UNDERFLOW: * * Staked balances are represented internally as uint240, so the result of an operation returning * a staked balances must return a value less than 2^240. Intermediate values in calcuations are * represented as uint256, so all operations within a calculation must return values under 2^256. * * In the functions below operating on the exchange rate, we are strategic in our choice of the * order of multiplication and division operations, in order to avoid both overflow and underflow. * * We use the following assumptions and principles to implement this module: * - (ASSUMPTION) An amount denoted in underlying token units is never greater than 10^28. * - If the exchange rate is greater than 10^46, then we may perform division on the exchange * rate before performing multiplication, provided that the denominator is not greater * than 10^28 (to ensure a result with at least 18 decimals of precision). Specifically, * we use EXCHANGE_RATE_MAY_OVERFLOW as the cutoff, which is a number greater than 10^46. * - Since staked balances are stored as uint240, we cap the exchange rate to ensure that a * staked balance can never overflow (using the assumption above). */ abstract contract SM1ExchangeRate is SM1Snapshots, SM1Storage { using SafeMath for uint256; // ============ Constants ============ /// @notice The assumed upper bound on the total supply of the staked token. uint256 public constant MAX_UNDERLYING_BALANCE = 1e28; /// @notice Base unit used to represent the exchange rate, for additional precision. uint256 public constant EXCHANGE_RATE_BASE = 1e18; /// @notice Cutoff where an exchange rate may overflow after multiplying by an underlying balance. /// @dev Approximately 1.2e49 uint256 public constant EXCHANGE_RATE_MAY_OVERFLOW = (2 ** 256 - 1) / MAX_UNDERLYING_BALANCE; /// @notice Cutoff where a stake amount may overflow after multiplying by EXCHANGE_RATE_BASE. /// @dev Approximately 1.2e59 uint256 public constant STAKE_AMOUNT_MAY_OVERFLOW = (2 ** 256 - 1) / EXCHANGE_RATE_BASE; /// @notice Max exchange rate. /// @dev Approximately 1.8e62 uint256 public constant MAX_EXCHANGE_RATE = ( ((2 ** 240 - 1) / MAX_UNDERLYING_BALANCE) * EXCHANGE_RATE_BASE ); // ============ Initializer ============ function __SM1ExchangeRate_init() internal { _EXCHANGE_RATE_ = EXCHANGE_RATE_BASE; } function stakeAmountFromUnderlyingAmount( uint256 underlyingAmount ) internal view returns (uint256) { uint256 exchangeRate = _EXCHANGE_RATE_; if (exchangeRate > EXCHANGE_RATE_MAY_OVERFLOW) { uint256 exchangeRateUnbased = exchangeRate.div(EXCHANGE_RATE_BASE); return underlyingAmount.mul(exchangeRateUnbased); } else { return underlyingAmount.mul(exchangeRate).div(EXCHANGE_RATE_BASE); } } function underlyingAmountFromStakeAmount( uint256 stakeAmount ) internal view returns (uint256) { return underlyingAmountFromStakeAmountWithExchangeRate(stakeAmount, _EXCHANGE_RATE_); } function underlyingAmountFromStakeAmountWithExchangeRate( uint256 stakeAmount, uint256 exchangeRate ) internal pure returns (uint256) { if (stakeAmount > STAKE_AMOUNT_MAY_OVERFLOW) { // Note that this case implies that exchangeRate > EXCHANGE_RATE_MAY_OVERFLOW. uint256 exchangeRateUnbased = exchangeRate.div(EXCHANGE_RATE_BASE); return stakeAmount.div(exchangeRateUnbased); } else { return stakeAmount.mul(EXCHANGE_RATE_BASE).div(exchangeRate); } } function updateExchangeRate( uint256 numerator, uint256 denominator ) internal returns (uint256) { uint256 oldExchangeRate = _EXCHANGE_RATE_; // Avoid overflow. // Note that the numerator and denominator are both denominated in underlying token units. uint256 newExchangeRate; if (oldExchangeRate > EXCHANGE_RATE_MAY_OVERFLOW) { newExchangeRate = oldExchangeRate.div(denominator).mul(numerator); } else { newExchangeRate = oldExchangeRate.mul(numerator).div(denominator); } require( newExchangeRate <= MAX_EXCHANGE_RATE, 'SM1ExchangeRate: Max exchange rate exceeded' ); _EXCHANGE_RATE_SNAPSHOT_COUNT_ = _writeSnapshot( _EXCHANGE_RATE_SNAPSHOTS_, _EXCHANGE_RATE_SNAPSHOT_COUNT_, newExchangeRate ); _EXCHANGE_RATE_ = newExchangeRate; return newExchangeRate; } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma abicoder v2; import { SM1Types } from '../lib/SM1Types.sol'; import { SM1Storage } from './SM1Storage.sol'; /** * @title SM1Snapshots * @author dYdX * * @dev Handles storage and retrieval of historical values by block number. * * Note that the snapshot stored at a given block number represents the value as of the end of * that block. */ abstract contract SM1Snapshots { /** * @dev Writes a snapshot of a value at the current block. * * @param snapshots Storage mapping from snapshot index to snapshot struct. * @param snapshotCount The total number of snapshots in the provided mapping. * @param newValue The new value to snapshot at the current block. * * @return The new snapshot count. */ function _writeSnapshot( mapping(uint256 => SM1Types.Snapshot) storage snapshots, uint256 snapshotCount, uint256 newValue ) internal returns (uint256) { uint256 currentBlock = block.number; if ( snapshotCount != 0 && snapshots[snapshotCount - 1].blockNumber == currentBlock ) { // If there was a previous snapshot for this block, overwrite it. snapshots[snapshotCount - 1].value = newValue; return snapshotCount; } else { snapshots[snapshotCount] = SM1Types.Snapshot(currentBlock, newValue); return snapshotCount + 1; } } /** * @dev Search for the snapshot value at a given block. Uses binary search. * * Reverts if `blockNumber` is greater than the current block number. * * @param snapshots Storage mapping from snapshot index to snapshot struct. * @param snapshotCount The total number of snapshots in the provided mapping. * @param blockNumber The block number to search for. * @param initialValue The value to return if `blockNumber` is before the earliest snapshot. * * @return The snapshot value at the specified block number. */ function _findValueAtBlock( mapping(uint256 => SM1Types.Snapshot) storage snapshots, uint256 snapshotCount, uint256 blockNumber, uint256 initialValue ) internal view returns (uint256) { require( blockNumber <= block.number, 'SM1Snapshots: INVALID_BLOCK_NUMBER' ); if (snapshotCount == 0) { return initialValue; } // Check earliest snapshot. if (blockNumber < snapshots[0].blockNumber) { return initialValue; } // Check latest snapshot. if (blockNumber >= snapshots[snapshotCount - 1].blockNumber) { return snapshots[snapshotCount - 1].value; } uint256 lower = 0; uint256 upper = snapshotCount - 1; while (upper > lower) { uint256 center = upper - (upper - lower) / 2; // Ceil, avoiding overflow. SM1Types.Snapshot memory snapshot = snapshots[center]; if (snapshot.blockNumber == blockNumber) { return snapshot.value; } else if (snapshot.blockNumber < blockNumber) { lower = center; } else { upper = center - 1; } } return snapshots[lower].value; } }
Returns the revision of the implementation contract. return The revision number./
function getRevision() internal pure override returns (uint256) { return 2; }
203,797
pragma solidity ^0.4.24; // // .#########' // .###############+ // ,#################### // `#######################+ // ;########################## // #############################. // ###############################, // +##################, ###########` // .################### .########### // ##############, .###########+ // #############` .############` // ###########+ ############ // ###########; ########### // ##########' ########### // '########## '#. `, ########## // ########## ####' ####. :#########; // `#########' :#####; ###### ########## // :######### #######: ####### :######### // +######### :#######.######## #########` // #########; ###############' #########: // ######### #############+ '########' // ######### ############ :######### // ######### ########## ,######### // ######### :######## ,######### // ######### ,########## ,######### // ######### ,############ :########+ // ######### .#############+ '########' // #########: `###############' #########, // +########+ ;#######`;####### ######### // ,######### '######` '###### :######### // #########; .#####` '##### ########## // ########## '###` +### :#########: // ;#########+ ` ########## // ##########, ########### // ###########; ############ // +############ .############` // ###########+ ,#############; // `########### ;++################# // :##########, ################### // '###########.'################### // +############################## // '############################` // .########################## // #######################: // ###################+ // +##############: // :#######+` // // // // Play0x.com (The ONLY gaming platform for all ERC20 Tokens) // ------------------------------------------------------------------------------------------------------- // * Multiple types of game platforms // * Build your own game zone - Not only playing games, but also allowing other players to join your game. // * Support all ERC20 tokens. // // // // 0xC Token (Contract address : 0x60d8234a662651e586173c17eb45ca9833a7aa6c) // ------------------------------------------------------------------------------------------------------- // * 0xC Token is an ERC20 Token specifically for digital entertainment. // * No ICO and private sales,fair access. // * There will be hundreds of games using 0xC as a game token. // * Token holders can permanently get ETH's profit sharing. // /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two numbers, 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 numbers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0); // Solidity only automatically asserts 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 Subtracts two numbers, 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 numbers, 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 numbers 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 ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 { function approve(address _spender, uint256 _value) public returns (bool success); function allowance(address owner, address spender) public constant returns (uint256); function balanceOf(address who) public constant returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function transfer(address _to, uint256 _value) public; event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } contract Play0x_LottoBall { using SafeMath for uint256; using SafeMath for uint128; using SafeMath for uint40; using SafeMath for uint8; uint public jackpotSize; uint public tokenJackpotSize; uint public MIN_BET; uint public MAX_BET; uint public MAX_AMOUNT; //Adjustable max bet profit. uint public maxProfit; uint public maxTokenProfit; //Fee percentage uint8 public platformFeePercentage = 15; uint8 public jackpotFeePercentage = 5; uint8 public ERC20rewardMultiple = 5; //Bets can be refunded via invoking refundBet. uint constant BetExpirationBlocks = 250; //Funds that are locked in potentially winning bets. uint public lockedInBets; uint public lockedTokenInBets; bytes32 bitComparisonMask = 0xF; //Standard contract ownership transfer. address public owner; address private nextOwner; address public manager; address private nextManager; //The address corresponding to a private key used to sign placeBet commits. address[] public secretSignerList; address public ERC20ContractAddres; address constant DUMMY_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; //Single bet. struct Bet { //Amount in wei. uint amount; //place tx Block number. uint40 placeBlockNumber; // Address of a gambler. address gambler; } //Mapping from commits mapping (uint => Bet) public bets; //Withdrawal mode data. uint32[] public withdrawalMode; //Admin Payment event ToManagerPayment(address indexed beneficiary, uint amount); event ToManagerFailedPayment(address indexed beneficiary, uint amount); event ToOwnerPayment(address indexed beneficiary, uint amount); event ToOwnerFailedPayment(address indexed beneficiary, uint amount); //Bet Payment event Payment(address indexed beneficiary, uint amount); event FailedPayment(address indexed beneficiary, uint amount); event TokenPayment(address indexed beneficiary, uint amount); //JACKPOT event JackpotBouns(address indexed beneficiary, uint amount); event TokenJackpotBouns(address indexed beneficiary, uint amount); // Events that are issued to make statistic recovery easier. event PlaceBetLog(address indexed player, uint amount,uint8 rotateTime); //Play0x_LottoBall_Event event BetRelatedData( address indexed player, uint playerBetAmount, uint playerGetAmount, bytes32 entropy, bytes32 entropy2, uint8 Uplimit, uint8 rotateTime ); // Constructor. Deliberately does not take any parameters. constructor () public { owner = msg.sender; manager = DUMMY_ADDRESS; ERC20ContractAddres = DUMMY_ADDRESS; } // Standard modifier on methods invokable only by contract owner. modifier onlyOwner { require (msg.sender == owner); _; } modifier onlyManager { require (msg.sender == manager); _; } //Init Parameter. function initialParameter(address _manager,address[] _secretSignerList,address _erc20tokenAddress ,uint _MIN_BET,uint _MAX_BET,uint _maxProfit,uint _maxTokenProfit, uint _MAX_AMOUNT, uint8 _platformFeePercentage,uint8 _jackpotFeePercentage,uint8 _ERC20rewardMultiple,uint32[] _withdrawalMode)external onlyOwner{ manager = _manager; secretSignerList = _secretSignerList; ERC20ContractAddres = _erc20tokenAddress; MIN_BET = _MIN_BET; MAX_BET = _MAX_BET; maxProfit = _maxProfit; maxTokenProfit = _maxTokenProfit; MAX_AMOUNT = _MAX_AMOUNT; platformFeePercentage = _platformFeePercentage; jackpotFeePercentage = _jackpotFeePercentage; ERC20rewardMultiple = _ERC20rewardMultiple; withdrawalMode = _withdrawalMode; } // Standard contract ownership transfer implementation, function approveNextOwner(address _nextOwner) external onlyOwner { require (_nextOwner != owner); nextOwner = _nextOwner; } function acceptNextOwner() external { require (msg.sender == nextOwner); owner = nextOwner; } // Standard contract ownership transfer implementation, function approveNextManager(address _nextManager) external onlyManager { require (_nextManager != manager); nextManager = _nextManager; } function acceptNextManager() external { require (msg.sender == nextManager); manager = nextManager; } // Fallback function deliberately left empty. function () public payable { } //Set signer. function setSecretSignerList(address[] newSecretSignerList) external onlyOwner { secretSignerList = newSecretSignerList; } //Set signer by index function setSecretSignerByIndex(address newSecretSigner,uint newSecretSignerIndex) external onlyOwner { secretSignerList[newSecretSignerIndex] = newSecretSigner; } //Set tokenAddress. function setTokenAddress(address _tokenAddress) external onlyManager { ERC20ContractAddres = _tokenAddress; } // Change max bet reward. Setting this to zero effectively disables betting. function setMaxProfit(uint _maxProfit) public onlyOwner { require (_maxProfit < MAX_AMOUNT); maxProfit = _maxProfit; } // Funds withdrawal. function withdrawFunds(address beneficiary, uint withdrawAmount) external onlyOwner { require (withdrawAmount <= address(this).balance); uint safetyAmount = jackpotSize.add(lockedInBets).add(withdrawAmount); safetyAmount = safetyAmount.add(withdrawAmount); require (safetyAmount <= address(this).balance); sendFunds(beneficiary, withdrawAmount, withdrawAmount); } // Token withdrawal. function withdrawToken(address beneficiary, uint withdrawAmount) external onlyOwner { require (withdrawAmount <= ERC20(ERC20ContractAddres).balanceOf(address(this))); uint safetyAmount = tokenJackpotSize.add(lockedTokenInBets); safetyAmount = safetyAmount.add(withdrawAmount); require (safetyAmount <= ERC20(ERC20ContractAddres).balanceOf(address(this))); ERC20(ERC20ContractAddres).transfer(beneficiary, withdrawAmount); emit TokenPayment(beneficiary, withdrawAmount); } //Recovery of funds function withdrawAllFunds(address beneficiary) external onlyOwner { if (beneficiary.send(address(this).balance)) { lockedInBets = 0; emit Payment(beneficiary, address(this).balance); } else { emit FailedPayment(beneficiary, address(this).balance); } } //Recovery of Token funds function withdrawAlltokenFunds(address beneficiary) external onlyOwner { ERC20(ERC20ContractAddres).transfer(beneficiary, ERC20(ERC20ContractAddres).balanceOf(address(this))); lockedTokenInBets = 0; emit TokenPayment(beneficiary, ERC20(ERC20ContractAddres).balanceOf(address(this))); } // Contract may be destroyed only when there are no ongoing bets, // either settled or refunded. All funds are transferred to contract owner. function kill() external onlyOwner { require (lockedInBets == 0); require (lockedTokenInBets == 0); selfdestruct(owner); } function getContractInformation()public view returns( uint _jackpotSize, uint _tokenJackpotSize, uint _MIN_BET, uint _MAX_BET, uint _MAX_AMOUNT, uint8 _platformFeePercentage, uint8 _jackpotFeePercentage, uint _maxProfit, uint _maxTokenProfit, uint _lockedInBets, uint _lockedTokenInBets, uint32[] _withdrawalMode){ _jackpotSize = jackpotSize; _tokenJackpotSize = tokenJackpotSize; _MIN_BET = MIN_BET; _MAX_BET = MAX_BET; _MAX_AMOUNT = MAX_AMOUNT; _platformFeePercentage = platformFeePercentage; _jackpotFeePercentage = jackpotFeePercentage; _maxProfit = maxProfit; _maxTokenProfit = maxTokenProfit; _lockedInBets = lockedInBets; _lockedTokenInBets = lockedTokenInBets; _withdrawalMode = withdrawalMode; } function getContractAddress()public view returns( address _owner, address _manager, address[] _secretSignerList, address _ERC20ContractAddres ){ _owner = owner; _manager= manager; _secretSignerList = secretSignerList; _ERC20ContractAddres = ERC20ContractAddres; } // Settlement transaction enum PlaceParam { RotateTime, possibleWinAmount, secretSignerIndex } //Bet by ether: Commits are signed with a block limit to ensure that they are used at most once. function placeBet(uint[] placParameter, bytes32 _signatureHash , uint _commitLastBlock, uint _commit, bytes32 r, bytes32 s, uint8 v) external payable { require (uint8(placParameter[uint8(PlaceParam.RotateTime)]) != 0); require (block.number <= _commitLastBlock ); require (secretSignerList[placParameter[uint8(PlaceParam.secretSignerIndex)]] == ecrecover(_signatureHash, v, r, s)); // Check that the bet is in 'clean' state. Bet storage bet = bets[_commit]; require (bet.gambler == address(0)); //Ether balanceet lockedInBets = lockedInBets.add(uint(placParameter[uint8(PlaceParam.possibleWinAmount)])); require (uint(placParameter[uint8(PlaceParam.possibleWinAmount)]) <= msg.value.add(maxProfit)); require (lockedInBets <= address(this).balance); // Store bet parameters on blockchain. bet.amount = msg.value; bet.placeBlockNumber = uint40(block.number); bet.gambler = msg.sender; emit PlaceBetLog(msg.sender, msg.value, uint8(placParameter[uint8(PlaceParam.RotateTime)])); } function placeTokenBet(uint[] placParameter,bytes32 _signatureHash , uint _commitLastBlock, uint _commit, bytes32 r, bytes32 s, uint8 v,uint _amount,address _playerAddress) external { require (placParameter[uint8(PlaceParam.RotateTime)] != 0); require (block.number <= _commitLastBlock ); require (secretSignerList[placParameter[uint8(PlaceParam.secretSignerIndex)]] == ecrecover(_signatureHash, v, r, s)); // Check that the bet is in 'clean' state. Bet storage bet = bets[_commit]; require (bet.gambler == address(0)); //Token bet lockedTokenInBets = lockedTokenInBets.add(uint(placParameter[uint8(PlaceParam.possibleWinAmount)])); require (uint(placParameter[uint8(PlaceParam.possibleWinAmount)]) <= _amount.add(maxTokenProfit)); require (lockedTokenInBets <= ERC20(ERC20ContractAddres).balanceOf(address(this))); // Store bet parameters on blockchain. bet.amount = _amount; bet.placeBlockNumber = uint40(block.number); bet.gambler = _playerAddress; emit PlaceBetLog(_playerAddress, _amount, uint8(placParameter[uint8(PlaceParam.RotateTime)])); } //Estimated maximum award amount function getBonusPercentageByMachineMode(uint8 machineMode)public view returns( uint upperLimit,uint maxWithdrawalPercentage ){ uint limitIndex = machineMode.mul(2); upperLimit = withdrawalMode[limitIndex]; maxWithdrawalPercentage = withdrawalMode[(limitIndex.add(1))]; } // Settlement transaction enum SettleParam { Uplimit, BonusPercentage, RotateTime, CurrencyType, MachineMode, PerWinAmount, PerBetAmount, PossibleWinAmount, LuckySeed, jackpotFee, secretSignerIndex, Reveal } enum TotalParam { TotalAmount, TotalTokenAmount, TotalJackpotWin } function settleBet(uint[] combinationParameter, bytes32 blockHash ) external{ // "commit" for bet settlement can only be obtained by hashing a "reveal". uint commit = uint(keccak256(abi.encodePacked(combinationParameter[uint8(SettleParam.Reveal)]))); // Fetch bet parameters into local variables (to save gas). Bet storage bet = bets[commit]; // Check that bet is in 'active' state and check that bet has not expired yet. require (bet.amount != 0); require (block.number <= bet.placeBlockNumber.add(BetExpirationBlocks)); require (blockhash(bet.placeBlockNumber) == blockHash); //The RNG - combine "reveal" and blockhash of LuckySeed using Keccak256. bytes32 _entropy = keccak256( abi.encodePacked( uint( keccak256( abi.encodePacked( combinationParameter[uint8(SettleParam.Reveal)], combinationParameter[uint8(SettleParam.LuckySeed)] ) ) ), blockHash ) ); uint totalAmount = 0; uint totalTokenAmount = 0; uint totalJackpotWin = 0; (totalAmount,totalTokenAmount,totalJackpotWin) = runRotateTime( combinationParameter, _entropy, keccak256( abi.encodePacked(uint(_entropy), combinationParameter[uint8(SettleParam.LuckySeed)]) ) ); // Add ether JackpotBouns if (totalJackpotWin > 0 && combinationParameter[uint8(SettleParam.CurrencyType)] == 0) { emit JackpotBouns(bet.gambler,totalJackpotWin); totalAmount = totalAmount.add(totalJackpotWin); jackpotSize = uint128(jackpotSize.sub(totalJackpotWin)); }else if (totalJackpotWin > 0 && combinationParameter[uint8(SettleParam.CurrencyType)] == 1) { // Add token TokenJackpotBouns emit TokenJackpotBouns(bet.gambler,totalJackpotWin); totalAmount = totalAmount.add(totalJackpotWin); tokenJackpotSize = uint128(tokenJackpotSize.sub(totalJackpotWin)); } emit BetRelatedData( bet.gambler, bet.amount, totalAmount, _entropy, keccak256(abi.encodePacked(uint(_entropy), combinationParameter[uint8(SettleParam.LuckySeed)])), uint8(combinationParameter[uint8(SettleParam.Uplimit)]), uint8(combinationParameter[uint8(SettleParam.RotateTime)]) ); if (combinationParameter[uint8(SettleParam.CurrencyType)] == 0) { //Ether game if (totalAmount != 0){ sendFunds(bet.gambler, totalAmount , totalAmount); } //Send ERC20 Token if (totalTokenAmount != 0){ if(ERC20(ERC20ContractAddres).balanceOf(address(this)) > 0){ ERC20(ERC20ContractAddres).transfer(bet.gambler, totalTokenAmount); emit TokenPayment(bet.gambler, totalTokenAmount); } } }else if(combinationParameter[uint8(SettleParam.CurrencyType)] == 1){ //ERC20 game //Send ERC20 Token if (totalAmount != 0){ if(ERC20(ERC20ContractAddres).balanceOf(address(this)) > 0){ ERC20(ERC20ContractAddres).transfer(bet.gambler, totalAmount); emit TokenPayment(bet.gambler, totalAmount); } } } // Unlock the bet amount, regardless of the outcome. if (combinationParameter[uint8(SettleParam.CurrencyType)] == 0) { lockedInBets = lockedInBets.sub(combinationParameter[uint8(SettleParam.PossibleWinAmount)]); } else if (combinationParameter[uint8(SettleParam.CurrencyType)] == 1){ lockedTokenInBets = lockedTokenInBets.sub(combinationParameter[uint8(SettleParam.PossibleWinAmount)]); } //Move bet into 'processed' state already. bet.amount = 0; //Save jackpotSize if (uint16(combinationParameter[uint8(SettleParam.CurrencyType)]) == 0) { jackpotSize = jackpotSize.add(uint(combinationParameter[uint8(SettleParam.jackpotFee)])); }else if (uint16(combinationParameter[uint8(SettleParam.CurrencyType)]) == 1) { tokenJackpotSize = tokenJackpotSize.add(uint(combinationParameter[uint8(SettleParam.jackpotFee)])); } } function runRotateTime ( uint[] combinationParameter, bytes32 _entropy ,bytes32 _entropy2)private view returns(uint totalAmount,uint totalTokenAmount,uint totalJackpotWin) { bytes32 resultMask = 0xF000000000000000000000000000000000000000000000000000000000000000; bytes32 tmp_entropy; bytes32 tmp_Mask = resultMask; bool isGetJackpot = false; for (uint8 i = 0; i < combinationParameter[uint8(SettleParam.RotateTime)]; i++) { if (i < 64){ tmp_entropy = _entropy & tmp_Mask; tmp_entropy = tmp_entropy >> (4*(64 - (i.add(1)))); tmp_Mask = tmp_Mask >> 4; }else{ if ( i == 64){ tmp_Mask = resultMask; } tmp_entropy = _entropy2 & tmp_Mask; tmp_entropy = tmp_entropy >> (4*( 64 - (i%63))); tmp_Mask = tmp_Mask >> 4; } if ( uint(tmp_entropy) < uint(combinationParameter[uint8(SettleParam.Uplimit)]) ){ //bet win totalAmount = totalAmount.add(combinationParameter[uint8(SettleParam.PerWinAmount)]); //Platform fee determination:Ether Game Winning players must pay platform fees uint platformFees = combinationParameter[uint8(SettleParam.PerBetAmount)].mul(platformFeePercentage); platformFees = platformFees.div(1000); totalAmount = totalAmount.sub(platformFees); }else{ //bet lose if (uint(combinationParameter[uint8(SettleParam.CurrencyType)]) == 0){ if(ERC20(ERC20ContractAddres).balanceOf(address(this)) > 0){ //get token reward uint rewardAmount = uint(combinationParameter[uint8(SettleParam.PerBetAmount)]).mul(ERC20rewardMultiple); totalTokenAmount = totalTokenAmount.add(rewardAmount); } } } //Get jackpotWin Result if (isGetJackpot == false){ isGetJackpot = getJackpotWinBonus(i,_entropy,_entropy2); } } if (isGetJackpot == true && combinationParameter[uint8(SettleParam.CurrencyType)] == 0) { //gambler get ether bonus. totalJackpotWin = jackpotSize; }else if (isGetJackpot == true && combinationParameter[uint8(SettleParam.CurrencyType)] == 1) { //gambler get token bonus. totalJackpotWin = tokenJackpotSize; } } function getJackpotWinBonus (uint8 i,bytes32 entropy,bytes32 entropy2) private pure returns (bool isGetJackpot) { bytes32 one; bytes32 two; bytes32 three; bytes32 four; bytes32 resultMask = 0xF000000000000000000000000000000000000000000000000000000000000000; bytes32 jackpo_Mask = resultMask; if (i < 61){ one = (entropy & jackpo_Mask) >> 4*(64 - (i + 1)); jackpo_Mask = jackpo_Mask >> 4; two = (entropy & jackpo_Mask) >> (4*(64 - (i + 2))); jackpo_Mask = jackpo_Mask >> 4; three = (entropy & jackpo_Mask) >> (4*(64 - (i + 3))); jackpo_Mask = jackpo_Mask >> 4; four = (entropy & jackpo_Mask) >> (4*(64 - (i + 4))); jackpo_Mask = jackpo_Mask << 8; } else if(i >= 61){ if(i == 61){ one = (entropy & jackpo_Mask) >> 4*(64 - (i + 1)); jackpo_Mask = jackpo_Mask >> 4; two = (entropy & jackpo_Mask) >> (4*(64 - (i + 2))); jackpo_Mask = jackpo_Mask >> 4; three = (entropy & jackpo_Mask) >> (4*(64 - (i + 3))); jackpo_Mask = jackpo_Mask << 4; four = (entropy2 & 0xF000000000000000000000000000000000000000000000000000000000000000) >> 4*63; } else if(i == 62){ one = (entropy & jackpo_Mask) >> 4*(64 - (i + 1)); jackpo_Mask = jackpo_Mask >> 4; two = (entropy & jackpo_Mask) >> (4*(64 - (i + 2))); three = (entropy2 & 0xF000000000000000000000000000000000000000000000000000000000000000) >> 4*63; four = (entropy2 & 0x0F00000000000000000000000000000000000000000000000000000000000000) >> 4*62; } else if(i == 63){ one = (entropy & jackpo_Mask) >> 4*(64 - (i + 1)); two = (entropy2 & 0xF000000000000000000000000000000000000000000000000000000000000000) >> 4*63; jackpo_Mask = jackpo_Mask >> 4; three = (entropy2 & 0x0F00000000000000000000000000000000000000000000000000000000000000) >> 4*62; jackpo_Mask = jackpo_Mask << 4; four = (entropy2 & 0x00F0000000000000000000000000000000000000000000000000000000000000) >> 4*61; jackpo_Mask = 0xF000000000000000000000000000000000000000000000000000000000000000; } else { one = (entropy2 & jackpo_Mask) >> (4*( 64 - (i%64 + 1))); jackpo_Mask = jackpo_Mask >> 4; two = (entropy2 & jackpo_Mask) >> (4*( 64 - (i%64 + 2))) ; jackpo_Mask = jackpo_Mask >> 4; three = (entropy2 & jackpo_Mask) >> (4*( 64 - (i%64 + 3))) ; jackpo_Mask = jackpo_Mask >> 4; four = (entropy2 & jackpo_Mask) >>(4*( 64 - (i%64 + 4))); jackpo_Mask = jackpo_Mask << 8; } } if ((one ^ 0xF) == 0 && (two ^ 0xF) == 0 && (three ^ 0xF) == 0 && (four ^ 0xF) == 0){ isGetJackpot = true; } } //Get deductedBalance function getPossibleWinAmount(uint bonusPercentage,uint senderValue)public view returns (uint platformFee,uint jackpotFee,uint possibleWinAmount) { //Platform Fee uint prePlatformFee = (senderValue).mul(platformFeePercentage); platformFee = (prePlatformFee).div(1000); //Get jackpotFee uint preJackpotFee = (senderValue).mul(jackpotFeePercentage); jackpotFee = (preJackpotFee).div(1000); //Win Amount uint preUserGetAmount = senderValue.mul(bonusPercentage); possibleWinAmount = preUserGetAmount.div(10000); } function settleBetVerifi(uint[] combinationParameter,bytes32 blockHash )external view returns(uint totalAmount,uint totalTokenAmount,uint totalJackpotWin,bytes32 _entropy,bytes32 _entropy2) { require (secretSignerList[combinationParameter[uint8(SettleParam.secretSignerIndex)]] == msg.sender); //The RNG - combine "reveal" and blockhash of LuckySeed using Keccak256. _entropy = keccak256( abi.encodePacked( uint( keccak256( abi.encodePacked( combinationParameter[uint8(SettleParam.Reveal)], combinationParameter[uint8(SettleParam.LuckySeed)] ) ) ), blockHash ) ); _entropy2 = keccak256( abi.encodePacked( uint(_entropy), combinationParameter[uint8(SettleParam.LuckySeed)] ) ); (totalAmount,totalTokenAmount,totalJackpotWin) = runRotateTime(combinationParameter,_entropy,_entropy2); } // Refund transaction function refundBet(uint commit,uint8 machineMode) external { // Check that bet is in 'active' state. Bet storage bet = bets[commit]; uint amount = bet.amount; require (amount != 0, "Bet should be in an 'active' state"); // Check that bet has already expired. require (block.number > bet.placeBlockNumber.add(BetExpirationBlocks)); // Move bet into 'processed' state, release funds. bet.amount = 0; //Maximum amount to be confirmed uint platformFee; uint jackpotFee; uint possibleWinAmount; uint upperLimit; uint maxWithdrawalPercentage; (upperLimit,maxWithdrawalPercentage) = getBonusPercentageByMachineMode(machineMode); (platformFee, jackpotFee, possibleWinAmount) = getPossibleWinAmount(maxWithdrawalPercentage,amount); //Amount unlock lockedInBets = lockedInBets.sub(possibleWinAmount); //Refund sendFunds(bet.gambler, amount, amount); } function refundTokenBet(uint commit,uint8 machineMode) external { // Check that bet is in 'active' state. Bet storage bet = bets[commit]; uint amount = bet.amount; require (amount != 0, "Bet should be in an 'active' state"); // Check that bet has already expired. require (block.number > bet.placeBlockNumber.add(BetExpirationBlocks)); // Move bet into 'processed' state, release funds. bet.amount = 0; //Maximum amount to be confirmed uint platformFee; uint jackpotFee; uint possibleWinAmount; uint upperLimit; uint maxWithdrawalPercentage; (upperLimit,maxWithdrawalPercentage) = getBonusPercentageByMachineMode(machineMode); (platformFee, jackpotFee, possibleWinAmount) = getPossibleWinAmount(maxWithdrawalPercentage,amount); //Amount unlock lockedTokenInBets = uint128(lockedTokenInBets.sub(possibleWinAmount)); //Refund ERC20(ERC20ContractAddres).transfer(bet.gambler, amount); emit TokenPayment(bet.gambler, amount); } // A helper routine to bulk clean the storage. function clearStorage(uint[] cleanCommits) external { uint length = cleanCommits.length; for (uint i = 0; i < length; i++) { clearProcessedBet(cleanCommits[i]); } } // Helper routine to move 'processed' bets into 'clean' state. function clearProcessedBet(uint commit) private { Bet storage bet = bets[commit]; // Do not overwrite active bets with zeros if (bet.amount != 0 || block.number <= bet.placeBlockNumber + BetExpirationBlocks) { return; } // Zero out the remaining storage bet.placeBlockNumber = 0; bet.gambler = address(0); } // Helper routine to process the payment. function sendFunds(address beneficiary, uint amount, uint successLogAmount) private { if (beneficiary.send(amount)) { emit Payment(beneficiary, successLogAmount); } else { emit FailedPayment(beneficiary, amount); } } function sendFundsToManager(uint amount) external onlyOwner { if (manager.send(amount)) { emit ToManagerPayment(manager, amount); } else { emit ToManagerFailedPayment(manager, amount); } } function sendTokenFundsToManager( uint amount) external onlyOwner { ERC20(ERC20ContractAddres).transfer(manager, amount); emit TokenPayment(manager, amount); } function sendFundsToOwner(address beneficiary, uint amount) external onlyOwner { if (beneficiary.send(amount)) { emit ToOwnerPayment(beneficiary, amount); } else { emit ToOwnerFailedPayment(beneficiary, amount); } } //Update function updateMIN_BET(uint _uintNumber)public onlyManager { MIN_BET = _uintNumber; } function updateMAX_BET(uint _uintNumber)public onlyManager { MAX_BET = _uintNumber; } function updateMAX_AMOUNT(uint _uintNumber)public onlyManager { MAX_AMOUNT = _uintNumber; } function updateWithdrawalModeByIndex(uint8 _index, uint32 _value) public onlyManager{ withdrawalMode[_index] = _value; } function updateWithdrawalMode( uint32[] _withdrawalMode) public onlyManager{ withdrawalMode = _withdrawalMode; } function updateBitComparisonMask(bytes32 _newBitComparisonMask ) public onlyOwner{ bitComparisonMask = _newBitComparisonMask; } function updatePlatformFeePercentage(uint8 _platformFeePercentage ) public onlyOwner{ platformFeePercentage = _platformFeePercentage; } function updateJackpotFeePercentage(uint8 _jackpotFeePercentage ) public onlyOwner{ jackpotFeePercentage = _jackpotFeePercentage; } function updateERC20rewardMultiple(uint8 _ERC20rewardMultiple ) public onlyManager{ ERC20rewardMultiple = _ERC20rewardMultiple; } }
Refund transaction Check that bet is in 'active' state. Check that bet has already expired. Move bet into 'processed' state, release funds.Maximum amount to be confirmedAmount unlockRefund
function refundBet(uint commit,uint8 machineMode) external { Bet storage bet = bets[commit]; uint amount = bet.amount; require (amount != 0, "Bet should be in an 'active' state"); require (block.number > bet.placeBlockNumber.add(BetExpirationBlocks)); bet.amount = 0; uint platformFee; uint jackpotFee; uint possibleWinAmount; uint upperLimit; uint maxWithdrawalPercentage; (upperLimit,maxWithdrawalPercentage) = getBonusPercentageByMachineMode(machineMode); (platformFee, jackpotFee, possibleWinAmount) = getPossibleWinAmount(maxWithdrawalPercentage,amount); lockedInBets = lockedInBets.sub(possibleWinAmount); sendFunds(bet.gambler, amount, amount); }
12,761,206
./full_match/3/0xAbDf627E4ce02F8204d8312c22812E6f0c158fad/sources/contracts/SigmoidLoan.sol
uint256 len=0; targetAuction[len] = auctionList[i];
function getWalletInfo(uint256 _auctionType) view public returns(AUCTION[] memory) { for (uint256 i = 0; i < auctionList.length; i++) { if(_auctionType2 == myLoan[i].auctionType){ len++; } } uint256 f = 0; for (uint256 j = 0; j < myLoan.length; j++) { if(myLoan[j].auctionType == _auctionType2 && myLoan[j].seller == msg.sender && myLoan[j].auctionStatus == false ){ walletAuction[f] = myLoan[j]; f++; } } */ return (myLoan); }
8,178,684
pragma solidity ^0.4.24; pragma experimental "v0.5.0"; import {IndexedOrderedSetLib} from "./IndexedOrderedSetLib.sol"; import {Authorized} from "./Authority.sol"; /// @title Database contract for a package index package data. /// @author Tim Coulter <[email protected]>, Piper Merriam <[email protected]> contract PackageDB is Authorized { using IndexedOrderedSetLib for IndexedOrderedSetLib.IndexedOrderedSet; struct Package { bool exists; uint createdAt; uint updatedAt; string name; address owner; } // Package Data: (nameHash => value) mapping (bytes32 => Package) _recordedPackages; IndexedOrderedSetLib.IndexedOrderedSet _allPackageNameHashes; // Events event PackageReleaseAdd(bytes32 indexed nameHash, bytes32 indexed releaseHash); event PackageReleaseRemove(bytes32 indexed nameHash, bytes32 indexed releaseHash); event PackageCreate(bytes32 indexed nameHash); event PackageDelete(bytes32 indexed nameHash, string reason); event PackageOwnerUpdate(bytes32 indexed nameHash, address indexed oldOwner, address indexed newOwner); /* * Modifiers */ modifier onlyIfPackageExists(bytes32 nameHash) { require(packageExists(nameHash), "escape:PackageDB:package-not-found"); _; } // // +-------------+ // | Write API | // +-------------+ // /// @dev Creates or updates a release for a package. Returns success. /// @param name Package name function setPackage(string name) public auth returns (bool) { // Hash the name and the version for storing data bytes32 nameHash = hashName(name); Package storage package = _recordedPackages[nameHash]; // Mark the package as existing if it isn't already tracked. if (!packageExists(nameHash)) { // Set package data package.exists = true; package.createdAt = block.timestamp; // solium-disable-line security/no-block-members package.name = name; // Add the nameHash to the list of all package nameHashes. _allPackageNameHashes.add(nameHash); emit PackageCreate(nameHash); } package.updatedAt = block.timestamp; // solium-disable-line security/no-block-members return true; } /// @dev Removes a package from the package db. Packages with existing releases may not be removed. Returns success. /// @param nameHash The name hash of a package. function removePackage(bytes32 nameHash, string reason) public auth onlyIfPackageExists(nameHash) returns (bool) { emit PackageDelete(nameHash, reason); delete _recordedPackages[nameHash]; _allPackageNameHashes.remove(nameHash); return true; } /// @dev Sets the owner of a package to the provided address. Returns success. /// @param nameHash The name hash of a package. /// @param newPackageOwner The address of the new owner. function setPackageOwner(bytes32 nameHash, address newPackageOwner) public auth onlyIfPackageExists(nameHash) returns (bool) { emit PackageOwnerUpdate(nameHash, _recordedPackages[nameHash].owner, newPackageOwner); _recordedPackages[nameHash].owner = newPackageOwner; _recordedPackages[nameHash].updatedAt = block.timestamp; // solium-disable-line security/no-block-members return true; } // // +------------+ // | Read API | // +------------+ // /// @dev Query the existence of a package with the given name. Returns boolean indicating whether the package exists. /// @param nameHash The name hash of a package. function packageExists(bytes32 nameHash) public view returns (bool) { return _recordedPackages[nameHash].exists; } /// @dev Return the total number of packages function getNumPackages() public view returns (uint) { return _allPackageNameHashes.size(); } /// @dev Returns package namehash at the provided index from the set of all known name hashes. /// @param idx The index of the package name hash to retrieve. function getPackageNameHash(uint idx) public view returns (bytes32) { return _allPackageNameHashes.get(idx); } /// @dev Returns information about the package. /// @param nameHash The name hash to look up. function getPackageData(bytes32 nameHash) public view onlyIfPackageExists(nameHash) returns ( address packageOwner, uint createdAt, uint updatedAt ) { Package storage package = _recordedPackages[nameHash]; return (package.owner, package.createdAt, package.updatedAt); } /// @dev Returns the package name for the given namehash /// @param nameHash The name hash to look up. function getPackageName(bytes32 nameHash) public view onlyIfPackageExists(nameHash) returns (string) { return _recordedPackages[nameHash].name; } /// @dev Returns a slice of the array of all package hashes for the named package. /// @param offset The starting index for the slice. /// @param limit The length of the slice function getAllPackageIds(uint _offset, uint limit) public view returns ( bytes32[] packageIds, uint offset ) { bytes32[] memory hashes; // Array of package ids to return uint cursor = _offset; // Index counter to traverse DB array uint remaining; // Counter to collect `limit` packages uint totalPackages = getNumPackages(); // Total number of packages in registry // Is request within range? if (cursor < totalPackages){ // Get total remaining records remaining = totalPackages - cursor; // Number of records to collect is lesser of `remaining` and `limit` if (remaining > limit ){ remaining = limit; } // Allocate return array hashes = new bytes32[](remaining); // Collect records. (IndexedOrderedSet manages deletions.) while(remaining > 0){ bytes32 hash = getPackageNameHash(cursor); hashes[remaining - 1] = hash; remaining--; cursor++; } } return (hashes, cursor); } /* * Hash Functions */ /// @dev Returns name hash for a given package name. /// @param name Package name function hashName(string name) public pure returns (bytes32) { return keccak256(abi.encodePacked(name)); } }
Hash Functions/ Returns name hash for a given package name. name Package name
function hashName(string name) public pure returns (bytes32) { return keccak256(abi.encodePacked(name)); }
1,039,829
// File: @openzeppelin/contracts/GSN/Context.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.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/access/Ownable.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.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. */ 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 { 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; } } // File: @openzeppelin/contracts/math/SafeMath.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.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. */ 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; } } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.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); } // File: @openzeppelin/contracts/utils/ReentrancyGuard.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.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]. */ 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; } } // File: contracts/IAlohaNFT.sol pragma solidity ^0.6.6; interface IAlohaNFT { function awardItem( address wallet, uint256 tokenImage, uint256 tokenRarity, uint256 tokenBackground ) external returns (uint256); function transferFrom(address from, address to, uint256 tokenId) external; function tokenRarity(uint256 tokenId) external returns (uint256); function tokenImage(uint256 tokenId) external returns (uint256); function tokenBackground(uint256 tokenId) external returns (uint256); } // File: contracts/AlohaStaking.sol pragma solidity 0.6.6; pragma experimental ABIEncoderV2; contract AlohaStakingV2 is Ownable, ReentrancyGuard { using SafeMath for uint256; using SafeMath for uint8; /* Events */ event SettedPool( uint256 indexed alohaAmount, uint256 indexed erc20Amount, uint256 duration, uint256 rarity, uint256 date ); event Staked( address indexed wallet, address indexed erc20Address, uint256 rarity, uint256 endDate, uint256 tokenImage, uint256 tokenBackground, uint256 alohaAmount, uint256 erc20Amount, uint256 date ); event Withdrawal( address indexed wallet, address indexed erc20Address, uint256 rarity, uint256 originalAlohaAmount, uint256 originalErc20Amount, uint256 receivedAlohaAmount, uint256 receivedErc20Amount, uint256 erc721Id, uint256 date ); event Transfered( address indexed wallet, address indexed erc20Address, uint256 amount, uint256 date ); /* Vars */ uint256 public fee; address public alohaERC20; address public alohaERC721; uint256 public backgrounds; address[] public feesDestinators; uint256[] public feesPercentages; struct Pool { uint256 alohaAmount; uint256 erc20Amount; // 0 when is not a PairPool uint256 duration; uint256 rarity; } struct Stake { uint256 endDate; uint256 tokenImage; uint256 tokenBackground; uint256 alohaAmount; uint256 erc20Amount; // 0 when is not a PairPool } // image => rarity mapping (uint256 => uint256) public rewardsMap; // rarity => [image] mapping (uint256 => uint256[]) public rarityByImages; // rarity => totalImages mapping (uint256 => uint256) public rarityByImagesTotal; // image => rarity => limit mapping (uint256 => mapping(uint256 => uint256)) public limitByRarityAndImage; // image => rarity => totalTokens mapping (uint256 => mapping(uint256 => uint256)) public totalTokensByRarityAndImage; // erc20Address => rarity => Pool mapping (address => mapping(uint256 => Pool)) public poolsMap; // userAddress => erc20Address => rarity => Stake mapping (address => mapping(address => mapping(uint256 => Stake))) public stakingsMap; // erc20Address => totalStaked mapping (address => uint256) public totalStaked; /* Modifiers */ modifier imageNotExists(uint256 _image) { require( !_existsReward(_image), "AlohaStaking: Image for reward already exists" ); _; } modifier validRarity(uint256 _rarity) { require( _rarity >= 1 && _rarity <= 3, "AlohaStaking: Rarity must be 1, 2 or 3" ); _; } modifier poolExists(address _erc20, uint256 _rarity) { require( _existsPool(_erc20, _rarity), "AlohaStaking: Pool for ERC20 Token and rarity not exists" ); _; } modifier rarityAvailable(uint256 _rarity) { require( !(rarityByImagesTotal[_rarity] == 0), "AlohaStaking: Rarity not available" ); _; } modifier addressNotInStake(address _userAddress, address _erc20, uint256 _rarity) { require( (stakingsMap[msg.sender][_erc20][_rarity].endDate == 0), "AlohaStaking: Address already stakes in this pool" ); _; } modifier addressInStake(address _userAddress, address _erc20, uint256 _rarity) { require( !(stakingsMap[msg.sender][_erc20][_rarity].endDate == 0), "AlohaStaking: Address not stakes in this pool" ); _; } modifier stakeEnded(address _userAddress, address _erc20, uint256 _rarity) { require( (_getTime() > stakingsMap[msg.sender][_erc20][_rarity].endDate), "AlohaStaking: Stake duration has not ended yet" ); _; } /* Public Functions */ constructor( address _alohaERC20, address _alohaERC721, uint256 _backgrounds, uint256 _fee ) public { require(address(_alohaERC20) != address(0)); require(address(_alohaERC721) != address(0)); alohaERC20 = _alohaERC20; alohaERC721 = _alohaERC721; backgrounds = _backgrounds; fee = _fee; } /** * @dev Stake ALOHA to get a random token of the selected rarity */ function simpleStake( uint256 _tokenRarity ) public { pairStake(alohaERC20, _tokenRarity); } /** * @dev Stake ALOHA/TOKEN to get a random token of the selected rarity */ function pairStake( address _erc20Token, uint256 _tokenRarity ) public rarityAvailable(_tokenRarity) poolExists(_erc20Token, _tokenRarity) addressNotInStake(msg.sender, _erc20Token, _tokenRarity) { uint256 randomImage = _getRandomImage(_tokenRarity); uint256 _endDate = _getTime() + poolsMap[_erc20Token][_tokenRarity].duration; uint256 randomBackground = _randomB(backgrounds); uint256 alohaAmount = poolsMap[_erc20Token][_tokenRarity].alohaAmount; uint256 erc20Amount = poolsMap[_erc20Token][_tokenRarity].erc20Amount; _transferStake(msg.sender, alohaERC20, alohaAmount); totalStaked[alohaERC20] += alohaAmount; if (_erc20Token != alohaERC20) { _transferStake(msg.sender, _erc20Token, erc20Amount); totalStaked[_erc20Token] += erc20Amount; } stakingsMap[msg.sender][_erc20Token][_tokenRarity] = Stake({ endDate: _endDate, tokenImage: randomImage, tokenBackground: randomBackground, alohaAmount: alohaAmount, erc20Amount: erc20Amount }); emit Staked( msg.sender, _erc20Token, _tokenRarity, _endDate, randomImage, randomBackground, alohaAmount, erc20Amount, _getTime() ); } /** * @dev Withdraw ALOHA and claim your random NFT for the selected rarity */ function simpleWithdraw( uint256 _tokenRarity ) public { pairWithdraw(alohaERC20, _tokenRarity); } /** * @dev Withdraw ALOHA/TOKEN and claim your random NFT for the selected rarity */ function pairWithdraw( address _erc20Token, uint256 _tokenRarity ) public nonReentrant() addressInStake(msg.sender, _erc20Token, _tokenRarity) stakeEnded(msg.sender, _erc20Token, _tokenRarity) { _withdraw(_erc20Token, _tokenRarity, true); } /** * @dev Withdra ALOHA without generating your NFT. This can be done before release time is reached. */ function forceSimpleWithdraw( uint256 _tokenRarity ) public { forcePairWithdraw(alohaERC20, _tokenRarity); } /** * @dev Withdraw ALOHA/TOKEN without generating your NFT. This can be done before release time is reached. */ function forcePairWithdraw( address _erc20Token, uint256 _tokenRarity ) public nonReentrant() addressInStake(msg.sender, _erc20Token, _tokenRarity) { _withdraw(_erc20Token, _tokenRarity, false); } /** * @dev Returns how many fees we collected from withdraws of one token. */ function getAcumulatedFees(address _erc20Token) public view returns (uint256) { uint256 balance = IERC20(_erc20Token).balanceOf(address(this)); if (balance > 0) { return balance.sub(totalStaked[_erc20Token]); } return 0; } /** * @dev Send all the acumulated fees for one token to the fee destinators. */ function withdrawAcumulatedFees(address _erc20Token) public { uint256 total = getAcumulatedFees(_erc20Token); for (uint8 i = 0; i < feesDestinators.length; i++) { IERC20(_erc20Token).transfer( feesDestinators[i], total.mul(feesPercentages[i]).div(100) ); } } /* Governance Functions */ /** * @dev Sets the fee for every withdraw. */ function setFee(uint256 _fee) public onlyOwner() { fee = _fee; } /** * @dev Adds a new NFT to the pools, so users can stake for it. */ function createReward( uint256 _tokenImage, uint256 _tokenRarity, uint256 _limit ) public onlyOwner() imageNotExists(_tokenImage) validRarity(_tokenRarity) { rewardsMap[_tokenImage] = _tokenRarity; rarityByImages[_tokenRarity].push(_tokenImage); rarityByImagesTotal[_tokenRarity] += 1; limitByRarityAndImage[_tokenImage][_tokenRarity] = _limit; } /** * @dev Configure staking time and amount in ALOHA pool for one rarity. */ function setSimplePool( uint256 _alohaAmount, uint256 _duration, uint256 _tokenRarity ) public onlyOwner() rarityAvailable(_tokenRarity) { poolsMap[alohaERC20][_tokenRarity] = Pool({ alohaAmount: _alohaAmount, erc20Amount: 0, duration: _duration, rarity: _tokenRarity }); emit SettedPool( _alohaAmount, 0, _duration, _tokenRarity, _getTime() ); } /** * @dev Configure staking time and amount in ALOHA/TOKEN pool for one rarity. */ function setPairPool( uint256 _alohaAmount, address _erc20Address, uint256 _erc20Amount, uint256 _duration, uint256 _tokenRarity ) public onlyOwner() rarityAvailable(_tokenRarity) { require(address(_erc20Address) != address(0)); poolsMap[_erc20Address][_tokenRarity] = Pool({ alohaAmount: _alohaAmount, erc20Amount: _erc20Amount, duration: _duration, rarity: _tokenRarity }); emit SettedPool( _alohaAmount, _erc20Amount, _duration, _tokenRarity, _getTime() ); } /** * @dev Creates a new background for NFTs. New stakers could get this background. */ function addBackground(uint8 increase) public onlyOwner() { backgrounds += increase; } /** * @dev Configure how to distribute the fees for user's withdraws. */ function setFeesDestinatorsWithPercentages( address[] memory _destinators, uint256[] memory _percentages ) public onlyOwner() { require(_destinators.length <= 3, "AlohaStaking: Destinators lenght more then 3"); require(_percentages.length <= 3, "AlohaStaking: Percentages lenght more then 3"); require(_destinators.length == _percentages.length, "AlohaStaking: Destinators and percentageslenght are not equals"); uint256 total = 0; for (uint8 i = 0; i < _percentages.length; i++) { total += _percentages[i]; } require(total == 100, "AlohaStaking: Percentages sum must be 100"); feesDestinators = _destinators; feesPercentages = _percentages; } /* Internal functions */ function _existsReward(uint256 _tokenImage) internal view returns (bool) { return rewardsMap[_tokenImage] != 0; } function _existsPool(address _erc20Token, uint256 _rarity) internal view returns (bool) { return poolsMap[_erc20Token][_rarity].duration != 0; } function _getTime() internal view returns (uint256) { return block.timestamp; } /** * @dev Apply withdraw fees to the amounts. */ function _applyStakeFees( address _erc20Token, uint256 _tokenRarity ) internal view returns ( uint256 _alohaAmountAfterFees, uint256 _erc20AmountAfterFees ) { uint256 alohaAmount = poolsMap[_erc20Token][_tokenRarity].alohaAmount; uint256 alohaAmountAfterFees = alohaAmount.sub(alohaAmount.mul(fee).div(10000)); uint256 erc20AmountAfterFees = 0; if (_erc20Token != alohaERC20) { uint256 erc20Amount = poolsMap[_erc20Token][_tokenRarity].erc20Amount; erc20AmountAfterFees = erc20Amount.sub(erc20Amount.mul(fee).div(10000)); } return (alohaAmountAfterFees, erc20AmountAfterFees); } /** * @dev Transfers erc20 tokens to this contract. */ function _transferStake( address _wallet, address _erc20, uint256 _amount ) internal { require(IERC20(_erc20).transferFrom(_wallet, address(this), _amount), "Must approve the ERC20 first"); emit Transfered(_wallet, _erc20, _amount, _getTime()); } /** * @dev Transfers erc20 tokens from this contract to the wallet. */ function _transferWithdrawRewards( address _wallet, address _erc20, uint256 _amount ) internal { require(IERC20(_erc20).transfer(_wallet, _amount), "Must approve the ERC20 first"); emit Transfered(_wallet, _erc20, _amount, _getTime()); } /** * @dev Clear the stake state for a wallet and a rarity. */ function _clearStake(address wallet, address _erc20Token, uint256 _tokenRarity) internal { stakingsMap[wallet][_erc20Token][_tokenRarity].endDate = 0; stakingsMap[wallet][_erc20Token][_tokenRarity].tokenImage = 0; stakingsMap[wallet][_erc20Token][_tokenRarity].tokenBackground = 0; stakingsMap[wallet][_erc20Token][_tokenRarity].alohaAmount = 0; stakingsMap[wallet][_erc20Token][_tokenRarity].erc20Amount = 0; } /** * @dev Withdraw tokens and mints the NFT if claimed. */ function _withdraw(address _erc20Token, uint256 _tokenRarity, bool claimReward) internal { uint256 alohaAmount = poolsMap[_erc20Token][_tokenRarity].alohaAmount; uint256 erc20Amount = poolsMap[_erc20Token][_tokenRarity].erc20Amount; uint256 alohaAmountAfterFees; uint256 erc20AmountAfterFees; if (!claimReward) { alohaAmountAfterFees = alohaAmount; erc20AmountAfterFees = erc20Amount; } else { (alohaAmountAfterFees, erc20AmountAfterFees) = _applyStakeFees(_erc20Token, _tokenRarity); } _transferWithdrawRewards(msg.sender, alohaERC20, alohaAmountAfterFees); totalStaked[alohaERC20] -= alohaAmount; if (_erc20Token != alohaERC20) { _transferWithdrawRewards(msg.sender, _erc20Token, erc20AmountAfterFees); totalStaked[_erc20Token] -= erc20Amount; } uint256 tokenId = 0; uint256 image = stakingsMap[msg.sender][_erc20Token][_tokenRarity].tokenImage; if (claimReward) { uint256 background = stakingsMap[msg.sender][_erc20Token][_tokenRarity].tokenBackground; tokenId = IAlohaNFT(alohaERC721).awardItem(msg.sender, _tokenRarity, image, background); } else { totalTokensByRarityAndImage[image][_tokenRarity] -= 1; } emit Withdrawal( msg.sender, _erc20Token, _tokenRarity, alohaAmount, erc20Amount, alohaAmountAfterFees, erc20AmountAfterFees, tokenId, _getTime() ); _clearStake(msg.sender, _erc20Token, _tokenRarity); } function _getRandomImage(uint256 _rarity) internal returns (uint256) { uint256 selectedImage = rarityByImages[_rarity][_randomA(rarityByImagesTotal[_rarity]) - 1]; if (limitByRarityAndImage[selectedImage][_rarity] == 0 || totalTokensByRarityAndImage[selectedImage][_rarity] < limitByRarityAndImage[selectedImage][_rarity] ) { totalTokensByRarityAndImage[selectedImage][_rarity] += 1; return selectedImage; } for (uint256 index = 1; index <= rarityByImagesTotal[_rarity]; index++) { selectedImage = rarityByImages[_rarity][index - 1]; if (limitByRarityAndImage[selectedImage][_rarity] == 0 || totalTokensByRarityAndImage[selectedImage][_rarity] < limitByRarityAndImage[selectedImage][_rarity] ) { totalTokensByRarityAndImage[selectedImage][_rarity] += 1; return selectedImage; } } revert("AlohaStaking: All images has reached the limit"); } /** * @dev Generates a "random" number using the numbers of backgrounds that we have. */ function _randomA(uint256 _limit) internal view returns (uint8) { uint256 _gasleft = gasleft(); bytes32 _blockhash = blockhash(block.number-1); bytes32 _structHash = keccak256( abi.encode( _blockhash, backgrounds, _gasleft, _limit ) ); uint256 _randomNumber = uint256(_structHash); assembly {_randomNumber := add(mod(_randomNumber, _limit),1)} return uint8(_randomNumber); } /** * @dev Generates a "random" number using the current block timestamp. */ function _randomB(uint256 _limit) internal view returns (uint256) { uint256 _gasleft = gasleft(); bytes32 _blockhash = blockhash(block.number-1); bytes32 _structHash = keccak256( abi.encode( _blockhash, _getTime(), _gasleft, _limit ) ); uint256 _randomNumber = uint256(_structHash); assembly {_randomNumber := add(mod(_randomNumber, _limit),1)} return uint8(_randomNumber); } }
Apply withdraw fees to the amounts./
function _applyStakeFees( address _erc20Token, uint256 _tokenRarity ) internal view returns ( uint256 _alohaAmountAfterFees, uint256 _erc20AmountAfterFees ) { uint256 alohaAmount = poolsMap[_erc20Token][_tokenRarity].alohaAmount; uint256 alohaAmountAfterFees = alohaAmount.sub(alohaAmount.mul(fee).div(10000)); uint256 erc20AmountAfterFees = 0; if (_erc20Token != alohaERC20) { uint256 erc20Amount = poolsMap[_erc20Token][_tokenRarity].erc20Amount; erc20AmountAfterFees = erc20Amount.sub(erc20Amount.mul(fee).div(10000)); } return (alohaAmountAfterFees, erc20AmountAfterFees); }
147,480
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol"; import "@openzeppelin/contracts/token/ERC1155/extensions/ERC1155Burnable.sol"; import "@openzeppelin/contracts/token/ERC1155/extensions/ERC1155Pausable.sol"; import "@openzeppelin/contracts/token/ERC1155/extensions/ERC1155Supply.sol"; import "@openzeppelin/contracts/finance/PaymentSplitter.sol"; error InvalidMint(); error InvalidApproval(); error NoMaxSupply(); contract LegacyOfPolMedinaJr is Ownable, ReentrancyGuard, ERC1155Burnable, ERC1155Pausable, ERC1155Supply { using Strings for uint256; // ============ Constants ============ //royalty percent uint256 public constant ROYALTY_PERCENT = 1000; //royalty recipient PaymentSplitter public immutable ROYALTY_RECIPIENT; //bytes4(keccak256("royaltyInfo(uint256,uint256)")) == 0x2a55205a bytes4 private constant _INTERFACE_ID_ERC2981 = 0x2a55205a; // ============ Structs ============ struct Token { uint256 maxSupply; uint256 mintPrice; bool active; } // ============ Storage ============ //mapping of token id to token info (max, price) mapping(uint256 => Token) private _tokens; //the contract metadata string private _contractURI; //a flag that allows NFTs to be listed on marketplaces //this helps to prevent people from listing at a lower //price during the whitelist bool approvable = false; // ============ Modifier ============ modifier canApprove { if (!approvable) revert InvalidApproval(); _; } // ============ Deploy ============ /** * @dev Sets the base token uri */ constructor( string memory contract_uri, string memory token_uri, address[] memory payees, uint256[] memory shares ) ERC1155(token_uri) { ROYALTY_RECIPIENT = new PaymentSplitter(payees, shares); _contractURI = contract_uri; } // ============ Read Methods ============ /** * @dev Returns the contract URI */ function contractURI() external view returns(string memory) { return _contractURI; } /** * @dev Returns true if the token exists */ function exists(uint256 id) public view override returns(bool) { return _tokens[id].active; } /** * @dev Get the maximum supply for a token */ function maxSupply(uint256 id) public view returns(uint256) { return _tokens[id].maxSupply; } /** * @dev Get the mint supply for a token */ function mintPrice(uint256 id) public view returns(uint256) { return _tokens[id].mintPrice; } /** * @dev Returns the name */ function name() external pure returns(string memory) { return "The Legacy of Pol Medina Jr."; } /** * @dev Get the remaining supply for a token */ function remainingSupply(uint256 id) public view returns(uint256) { uint256 max = maxSupply(id); if (max == 0) revert NoMaxSupply(); return max - totalSupply(id); } /** * @dev implements ERC2981 `royaltyInfo()` */ function royaltyInfo(uint256, uint256 salePrice) external view returns(address receiver, uint256 royaltyAmount) { return ( payable(address(ROYALTY_RECIPIENT)), (salePrice * ROYALTY_PERCENT) / 10000 ); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns(bool) { //support ERC2981 if (interfaceId == _INTERFACE_ID_ERC2981) { return true; } return super.supportsInterface(interfaceId); } /** * @dev Returns the symbol */ function symbol() external pure returns(string memory) { return "PMJR"; } /** * @dev Returns the max and price for a token */ function tokenInfo(uint256 id) external view returns(uint256 max, uint256 price, uint256 remaining) { return ( _tokens[id].maxSupply, _tokens[id].mintPrice, remainingSupply(id) ); } /** * @dev See {IERC1155MetadataURI-uri}. * * This implementation returns the same URI for *all* token types. It relies * on the token type ID substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * Clients calling this function must replace the `\{id\}` substring with the * actual token type ID. */ function uri(uint256 id) public view virtual override returns(string memory) { if (exists(id)) { return string(abi.encodePacked(super.uri(id), "/", id.toString(), ".json")); } return string(abi.encodePacked(super.uri(id), "/{id}.json")); } // ============ Write Methods ============ /** * @dev Allows anyone to mint by purchasing */ function buy(address to, uint256 id, uint256 quantity, bytes memory proof) external payable nonReentrant { //make sure the minter signed this off if (ECDSA.recover( ECDSA.toEthSignedMessageHash( keccak256(abi.encodePacked("authorized", to)) ), proof ) != owner()) revert InvalidMint(); //get price uint256 price = mintPrice(id) * quantity; //if there is a price and the amount sent is less than if(price == 0 || msg.value < price) revert InvalidMint(); //we are okay to mint _mintSupply(to, id, quantity); } /** * @dev Check if can approve before approving */ function setApprovalForAll(address operator, bool approved) public virtual override canApprove { super.setApprovalForAll(operator, approved); } // ============ Admin Methods ============ /** * @dev Adds a token that can be minted */ function addToken(uint256 id, uint256 max, uint256 price, uint8 prizes) public onlyOwner { _tokens[id] = Token(max, price, true); if (prizes > 0) { _mintSupply(_msgSender(), id, prizes); } } /** * @dev Allows admin to mint */ function mint(address to, uint256 id, uint256 quantity) public onlyOwner { _mintSupply(to, id, quantity); } /** * @dev Allows admin to update URI */ function updateURI(string memory newuri) public onlyOwner { _setURI(newuri); } /** * @dev Sends the entire contract balance to a `recipient`. * This also enables NFTs to be listable on marketplaces. */ function withdraw(address recipient) external virtual nonReentrant onlyOwner { //now make approvable, it's only here we will //set this so it's kind of immutable (a one time deal) if (!approvable) { approvable = true; } Address.sendValue(payable(recipient), address(this).balance); } /** * @dev This contract should not hold any tokens in the first place. * This method exists to transfer out tokens funds. */ function withdraw(IERC20 erc20, address recipient, uint256 amount) external virtual nonReentrant onlyOwner { SafeERC20.safeTransfer(erc20, recipient, amount); } // ============ Internal Methods ============ /** * @dev Mint token considering max supply */ function _mintSupply(address to, uint256 id, uint256 quantity) internal { //if the id does not exists if (!exists(id)) revert InvalidMint(); //get max and calculated supply uint256 max = maxSupply(id); uint256 supply = totalSupply(id) + quantity; //if there is a max supply and it was exceeded if(max > 0 && supply > max) revert InvalidMint(); //we are okay to mint _mint(to, id, quantity, ""); } // ============ Overrides ============ /** * @dev Describes linear override for `_beforeTokenTransfer` used in * both `ERC721` and `ERC721Pausable` */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual override(ERC1155, ERC1155Pausable, ERC1155Supply) { super._beforeTokenTransfer(operator, from, to, ids, amounts, data); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (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.0 (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.0 (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.0 (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; } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/cryptography/ECDSA.sol) pragma solidity ^0.8.0; import "../Strings.sol"; /** * @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. */ library ECDSA { enum RecoverError { NoError, InvalidSignature, InvalidSignatureLength, InvalidSignatureS, InvalidSignatureV } function _throwError(RecoverError error) private pure { if (error == RecoverError.NoError) { return; // no error: do nothing } else if (error == RecoverError.InvalidSignature) { revert("ECDSA: invalid signature"); } else if (error == RecoverError.InvalidSignatureLength) { revert("ECDSA: invalid signature length"); } else if (error == RecoverError.InvalidSignatureS) { revert("ECDSA: invalid signature 's' value"); } else if (error == RecoverError.InvalidSignatureV) { revert("ECDSA: invalid signature 'v' value"); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature` or error string. 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. * * Documentation for signature generation: * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] * * _Available since v4.3._ */ function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) { // Check the signature length // - case 65: r,s,v signature (standard) // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._ if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return tryRecover(hash, v, r, s); } else if (signature.length == 64) { bytes32 r; bytes32 vs; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) vs := mload(add(signature, 0x40)) } return tryRecover(hash, r, vs); } else { return (address(0), RecoverError.InvalidSignatureLength); } } /** * @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) { (address recovered, RecoverError error) = tryRecover(hash, signature); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately. * * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] * * _Available since v4.3._ */ function tryRecover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address, RecoverError) { bytes32 s; uint8 v; assembly { s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) v := add(shr(255, vs), 27) } return tryRecover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately. * * _Available since v4.2._ */ function recover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, r, vs); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `v`, * `r` and `s` signature fields separately. * * _Available since v4.3._ */ function tryRecover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address, RecoverError) { // 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 (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): 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 (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return (address(0), RecoverError.InvalidSignatureS); } if (v != 27 && v != 28) { return (address(0), RecoverError.InvalidSignatureV); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); if (signer == address(0)) { return (address(0), RecoverError.InvalidSignature); } return (signer, RecoverError.NoError); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, * `r` and `s` signature fields separately. */ function recover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, v, r, s); _throwError(error); return recovered; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * 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)); } /** * @dev Returns an Ethereum Signed Message, created from `s`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s)); } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC1155/extensions/ERC1155Burnable.sol) pragma solidity ^0.8.0; import "../ERC1155.sol"; /** * @dev Extension of {ERC1155} that allows token holders to destroy both their * own tokens and those that they have been approved to use. * * _Available since v3.1._ */ abstract contract ERC1155Burnable is ERC1155 { function burn( address account, uint256 id, uint256 value ) public virtual { require( account == _msgSender() || isApprovedForAll(account, _msgSender()), "ERC1155: caller is not owner nor approved" ); _burn(account, id, value); } function burnBatch( address account, uint256[] memory ids, uint256[] memory values ) public virtual { require( account == _msgSender() || isApprovedForAll(account, _msgSender()), "ERC1155: caller is not owner nor approved" ); _burnBatch(account, ids, values); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC1155/extensions/ERC1155Pausable.sol) pragma solidity ^0.8.0; import "../ERC1155.sol"; import "../../../security/Pausable.sol"; /** * @dev ERC1155 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. * * _Available since v3.1._ */ abstract contract ERC1155Pausable is ERC1155, Pausable { /** * @dev See {ERC1155-_beforeTokenTransfer}. * * Requirements: * * - the contract must not be paused. */ 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); require(!paused(), "ERC1155Pausable: token transfer while paused"); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC1155/extensions/ERC1155Supply.sol) pragma solidity ^0.8.0; import "../ERC1155.sol"; /** * @dev Extension of ERC1155 that adds tracking of total supply per id. * * Useful for scenarios where Fungible and Non-fungible tokens have to be * clearly identified. Note: While a totalSupply of 1 might mean the * corresponding is an NFT, there is no guarantees that no other token with the * same id are not going to be minted. */ abstract contract ERC1155Supply is ERC1155 { mapping(uint256 => uint256) private _totalSupply; /** * @dev Total amount of tokens in with a given id. */ function totalSupply(uint256 id) public view virtual returns (uint256) { return _totalSupply[id]; } /** * @dev Indicates whether any token exist with a given id, or not. */ function exists(uint256 id) public view virtual returns (bool) { return ERC1155Supply.totalSupply(id) > 0; } /** * @dev See {ERC1155-_beforeTokenTransfer}. */ 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 == address(0)) { for (uint256 i = 0; i < ids.length; ++i) { _totalSupply[ids[i]] += amounts[i]; } } if (to == address(0)) { for (uint256 i = 0; i < ids.length; ++i) { _totalSupply[ids[i]] -= amounts[i]; } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (finance/PaymentSplitter.sol) pragma solidity ^0.8.0; import "../token/ERC20/utils/SafeERC20.sol"; import "../utils/Address.sol"; import "../utils/Context.sol"; /** * @title PaymentSplitter * @dev This contract allows to split Ether payments among a group of accounts. The sender does not need to be aware * that the Ether will be split in this way, since it is handled transparently by the contract. * * The split can be in equal parts or in any other arbitrary proportion. The way this is specified is by assigning each * account to a number of shares. Of all the Ether that this contract receives, each account will then be able to claim * an amount proportional to the percentage of total shares they were assigned. * * `PaymentSplitter` follows a _pull payment_ model. This means that payments are not automatically forwarded to the * accounts but kept in this contract, and the actual transfer is triggered as a separate step by calling the {release} * function. * * NOTE: This contract assumes that ERC20 tokens will behave similarly to native tokens (Ether). Rebasing tokens, and * tokens that apply fees during transfers, are likely to not be supported as expected. If in doubt, we encourage you * to run tests before sending real value to this contract. */ contract PaymentSplitter is Context { event PayeeAdded(address account, uint256 shares); event PaymentReleased(address to, uint256 amount); event ERC20PaymentReleased(IERC20 indexed token, address to, uint256 amount); event PaymentReceived(address from, uint256 amount); uint256 private _totalShares; uint256 private _totalReleased; mapping(address => uint256) private _shares; mapping(address => uint256) private _released; address[] private _payees; mapping(IERC20 => uint256) private _erc20TotalReleased; mapping(IERC20 => mapping(address => uint256)) private _erc20Released; /** * @dev Creates an instance of `PaymentSplitter` where each account in `payees` is assigned the number of shares at * the matching position in the `shares` array. * * All addresses in `payees` must be non-zero. Both arrays must have the same non-zero length, and there must be no * duplicates in `payees`. */ constructor(address[] memory payees, uint256[] memory shares_) payable { require(payees.length == shares_.length, "PaymentSplitter: payees and shares length mismatch"); require(payees.length > 0, "PaymentSplitter: no payees"); for (uint256 i = 0; i < payees.length; i++) { _addPayee(payees[i], shares_[i]); } } /** * @dev The Ether received will be logged with {PaymentReceived} events. Note that these events are not fully * reliable: it's possible for a contract to receive Ether without triggering this function. This only affects the * reliability of the events, and not the actual splitting of Ether. * * To learn more about this see the Solidity documentation for * https://solidity.readthedocs.io/en/latest/contracts.html#fallback-function[fallback * functions]. */ receive() external payable virtual { emit PaymentReceived(_msgSender(), msg.value); } /** * @dev Getter for the total shares held by payees. */ function totalShares() public view returns (uint256) { return _totalShares; } /** * @dev Getter for the total amount of Ether already released. */ function totalReleased() public view returns (uint256) { return _totalReleased; } /** * @dev Getter for the total amount of `token` already released. `token` should be the address of an IERC20 * contract. */ function totalReleased(IERC20 token) public view returns (uint256) { return _erc20TotalReleased[token]; } /** * @dev Getter for the amount of shares held by an account. */ function shares(address account) public view returns (uint256) { return _shares[account]; } /** * @dev Getter for the amount of Ether already released to a payee. */ function released(address account) public view returns (uint256) { return _released[account]; } /** * @dev Getter for the amount of `token` tokens already released to a payee. `token` should be the address of an * IERC20 contract. */ function released(IERC20 token, address account) public view returns (uint256) { return _erc20Released[token][account]; } /** * @dev Getter for the address of the payee number `index`. */ function payee(uint256 index) public view returns (address) { return _payees[index]; } /** * @dev Triggers a transfer to `account` of the amount of Ether they are owed, according to their percentage of the * total shares and their previous withdrawals. */ function release(address payable account) public virtual { require(_shares[account] > 0, "PaymentSplitter: account has no shares"); uint256 totalReceived = address(this).balance + totalReleased(); uint256 payment = _pendingPayment(account, totalReceived, released(account)); require(payment != 0, "PaymentSplitter: account is not due payment"); _released[account] += payment; _totalReleased += payment; Address.sendValue(account, payment); emit PaymentReleased(account, payment); } /** * @dev Triggers a transfer to `account` of the amount of `token` tokens they are owed, according to their * percentage of the total shares and their previous withdrawals. `token` must be the address of an IERC20 * contract. */ function release(IERC20 token, address account) public virtual { require(_shares[account] > 0, "PaymentSplitter: account has no shares"); uint256 totalReceived = token.balanceOf(address(this)) + totalReleased(token); uint256 payment = _pendingPayment(account, totalReceived, released(token, account)); require(payment != 0, "PaymentSplitter: account is not due payment"); _erc20Released[token][account] += payment; _erc20TotalReleased[token] += payment; SafeERC20.safeTransfer(token, account, payment); emit ERC20PaymentReleased(token, account, payment); } /** * @dev internal logic for computing the pending payment of an `account` given the token historical balances and * already released amounts. */ function _pendingPayment( address account, uint256 totalReceived, uint256 alreadyReleased ) private view returns (uint256) { return (totalReceived * _shares[account]) / _totalShares - alreadyReleased; } /** * @dev Add a new payee to the contract. * @param account The address of the payee to add. * @param shares_ The number of shares owned by the payee. */ function _addPayee(address account, uint256 shares_) private { require(account != address(0), "PaymentSplitter: account is the zero address"); require(shares_ > 0, "PaymentSplitter: shares are 0"); require(_shares[account] == 0, "PaymentSplitter: account already has shares"); _payees.push(account); _shares[account] = shares_; _totalShares = _totalShares + shares_; emit PayeeAdded(account, shares_); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (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.0 (token/ERC1155/ERC1155.sol) pragma solidity ^0.8.0; import "./IERC1155.sol"; import "./IERC1155Receiver.sol"; import "./extensions/IERC1155MetadataURI.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of the basic standard multi-token. * See https://eips.ethereum.org/EIPS/eip-1155 * Originally based on code by Enjin: https://github.com/enjin/erc-1155 * * _Available since v3.1._ */ contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI { using Address for address; // Mapping from token ID to account balances mapping(uint256 => mapping(address => uint256)) private _balances; // Mapping from account to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; // Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json string private _uri; /** * @dev See {_setURI}. */ constructor(string memory uri_) { _setURI(uri_); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC1155).interfaceId || interfaceId == type(IERC1155MetadataURI).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC1155MetadataURI-uri}. * * This implementation returns the same URI for *all* token types. It relies * on the token type ID substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * Clients calling this function must replace the `\{id\}` substring with the * actual token type ID. */ function uri(uint256) public view virtual override returns (string memory) { return _uri; } /** * @dev See {IERC1155-balanceOf}. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) public view virtual override returns (uint256) { require(account != address(0), "ERC1155: balance query for the zero address"); return _balances[id][account]; } /** * @dev See {IERC1155-balanceOfBatch}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ 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"); uint256[] memory batchBalances = new uint256[](accounts.length); for (uint256 i = 0; i < accounts.length; ++i) { batchBalances[i] = balanceOf(accounts[i], ids[i]); } return batchBalances; } /** * @dev See {IERC1155-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC1155-isApprovedForAll}. */ function isApprovedForAll(address account, address operator) public view virtual override returns (bool) { return _operatorApprovals[account][operator]; } /** * @dev See {IERC1155-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) public virtual override { require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: caller is not owner nor approved" ); _safeTransferFrom(from, to, id, amount, data); } /** * @dev See {IERC1155-safeBatchTransferFrom}. */ function safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) public virtual override { require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: transfer caller is not owner nor approved" ); _safeBatchTransferFrom(from, to, ids, amounts, data); } /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: transfer to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data); uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: insufficient balance for transfer"); unchecked { _balances[id][from] = fromBalance - amount; } _balances[id][to] += amount; emit TransferSingle(operator, from, to, id, amount); _doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function _safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); require(to != address(0), "ERC1155: transfer to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, ids, amounts, data); for (uint256 i = 0; i < ids.length; ++i) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: insufficient balance for transfer"); unchecked { _balances[id][from] = fromBalance - amount; } _balances[id][to] += amount; } emit TransferBatch(operator, from, to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data); } /** * @dev Sets a new URI for all token types, by relying on the token type ID * substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * By this mechanism, any occurrence of the `\{id\}` substring in either the * URI or any of the amounts in the JSON file at said URI will be replaced by * clients with the token type ID. * * For example, the `https://token-cdn-domain/\{id\}.json` URI would be * interpreted by clients as * `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json` * for token type ID 0x4cce0. * * See {uri}. * * Because these URIs cannot be meaningfully represented by the {URI} event, * this function emits no events. */ function _setURI(string memory newuri) internal virtual { _uri = newuri; } /** * @dev Creates `amount` tokens of token type `id`, and assigns them to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _mint( address to, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), to, _asSingletonArray(id), _asSingletonArray(amount), data); _balances[id][to] += amount; emit TransferSingle(operator, address(0), to, id, amount); _doSafeTransferAcceptanceCheck(operator, address(0), to, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function _mintBatch( address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), to, ids, amounts, data); for (uint256 i = 0; i < ids.length; i++) { _balances[ids[i]][to] += amounts[i]; } emit TransferBatch(operator, address(0), to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data); } /** * @dev Destroys `amount` tokens of token type `id` from `from` * * Requirements: * * - `from` cannot be the zero address. * - `from` must have at least `amount` tokens of token type `id`. */ function _burn( address from, uint256 id, uint256 amount ) internal virtual { require(from != address(0), "ERC1155: burn from the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, address(0), _asSingletonArray(id), _asSingletonArray(amount), ""); uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: burn amount exceeds balance"); unchecked { _balances[id][from] = fromBalance - amount; } emit TransferSingle(operator, from, address(0), id, amount); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}. * * Requirements: * * - `ids` and `amounts` must have the same length. */ function _burnBatch( address from, uint256[] memory ids, uint256[] memory amounts ) internal virtual { require(from != address(0), "ERC1155: burn from the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, address(0), ids, amounts, ""); for (uint256 i = 0; i < ids.length; i++) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: burn amount exceeds balance"); unchecked { _balances[id][from] = fromBalance - amount; } } emit TransferBatch(operator, from, address(0), ids, amounts); } /** * @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, "ERC1155: setting approval status for self"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Hook that is called before any token transfer. This includes minting * and burning, as well as batched variants. * * The same hook is called on both single and batched variants. For single * transfers, the length of the `id` and `amount` arrays will be 1. * * Calling conditions (for each `id` and `amount` pair): * * - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens * of token type `id` will be transferred to `to`. * - When `from` is zero, `amount` tokens of token type `id` will be minted * for `to`. * - when `to` is zero, `amount` of ``from``'s tokens of token type `id` * will be burned. * - `from` and `to` are never both zero. * - `ids` and `amounts` have the same, non-zero length. * * 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[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual {} 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) { if (response != IERC1155Receiver.onERC1155Received.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } 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 ) { if (response != IERC1155Receiver.onERC1155BatchReceived.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) { uint256[] memory array = new uint256[](1); array[0] = element; return array; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC1155/IERC1155.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[EIP]. * * _Available since v3.1._ */ interface IERC1155 is IERC165 { /** * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch( address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values ); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type `id` owned by `account`. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes calldata data ) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom( address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC1155/IERC1155Receiver.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev _Available since v3.1._ */ interface IERC1155Receiver is IERC165 { /** @dev Handles the receipt of a single ERC1155 token type. This function is called at the end of a `safeTransferFrom` after the balance has been updated. To accept the transfer, this must return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` (i.e. 0xf23a6e61, or its own function selector). @param operator The address which initiated the transfer (i.e. msg.sender) @param from The address which previously owned the token @param id The ID of the token being transferred @param value The amount of tokens being transferred @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed */ function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external returns (bytes4); /** @dev Handles the receipt of a multiple ERC1155 token types. This function is called at the end of a `safeBatchTransferFrom` after the balances have been updated. To accept the transfer(s), this must return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` (i.e. 0xbc197c81, or its own function selector). @param operator The address which initiated the batch transfer (i.e. msg.sender) @param from The address which previously owned the token @param ids An array containing ids of each token being transferred (order and length must match values array) @param values An array containing amounts of each token being transferred (order and length must match ids array) @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed */ function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC1155/extensions/IERC1155MetadataURI.sol) pragma solidity ^0.8.0; import "../IERC1155.sol"; /** * @dev Interface of the optional ERC1155MetadataExtension interface, as defined * in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP]. * * _Available since v3.1._ */ interface IERC1155MetadataURI is IERC1155 { /** * @dev Returns the URI for token type `id`. * * If the `\{id\}` substring is present in the URI, it must be replaced by * clients with the actual token type ID. */ function uri(uint256 id) external view returns (string memory); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/Address.sol) 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 // OpenZeppelin Contracts v4.4.0 (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.0 (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); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (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()); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC20/utils/SafeERC20.sol) 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 // OpenZeppelin Contracts v4.4.0 (token/ERC20/IERC20.sol) 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); }
Check if can approve before approving/
function setApprovalForAll(address operator, bool approved) public virtual override canApprove { super.setApprovalForAll(operator, approved); }
14,365,844
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; pragma abicoder v2; library Blake2b { function digest208(bytes memory input208) internal view returns (bytes32 ret){ // solium-disable-next-line assembly{ // reject not ckbinput // 208 = 0xD0 if iszero(eq(mload(input208), 0xD0)){ revert(0x80,0x00) } let input_ptr := add(input208,0x20) // the init vector is 0x // 08c9bc3f 67e6096a 3ba7ca84 85ae67bb // 2bf894fe 72f36e3c f1361d5f 3af54fa5 // d182e6ad 7f520e51 1f6c3e2b 8c68059b // 6bbd41fb abd9831f 79217e13 19cde05b // // the param is // let param = blake2b_param { // digest_length: out_len as u8, u8 0x20 // key_length: 0, u8 0x00 // fanout: 1, u8 0x01 // depth: 1, u8 0x01 // leaf_length: 0, u32 // node_offset: 0,u32 // xof_length: 0, u32 // node_depth: 0, u8 // inner_length: 0, u8 // reserved: [0u8; 14usize], u8[14] // salt: [0u8; blake2b_constant_BLAKE2B_SALTBYTES as usize], u8[16] // personal: [0u8; blake2b_constant_BLAKE2B_PERSONALBYTES as usize], u8[16] // }; // pub const blake2b_constant_BLAKE2B_SALTBYTES: blake2b_constant = 16; // pub const blake2b_constant_BLAKE2B_PERSONALBYTES: blake2b_constant = 16; // the PERSONALBYTES is b"ckb-default-hash"; // PERSONALBYTES = 636b622d 64656661 756c742d 68617368 // // the param is 0x // 20000101 00000000 00000000 00000000 [digest_length key_length fanout depth] leaf_length node_offset xof_length // 00000000 00000000 00000000 00000000 node_depth inner_length reserved // 00000000 00000000 00000000 00000000 salt // 636b622d 64656661 756c742d 68617368 personal // // iv ^ param is 64 bytes, which is the init h // 28c9bdf2 67e6096a 3ba7ca84 85ae67bb // 2bf894fe 72f36e3c f1361d5f 3af54fa5 // d182e6ad 7f520e51 1f6c3e2b 8c68059b // 08d623d6 cfbce57e 0c4d0a3e 71ac9333 // // param for blake2b F(): // rounds - the number of rounds - 32-bit unsigned big-endian word // h - the state vector - 8 unsigned 64-bit little-endian words // m - the message block vector - 16 unsigned 64-bit little-endian words // t_0, t_1 - offset counters - 2 unsigned 64-bit little-endian words // f - the final block indicator flag - 8-bit word // // the rounds === 12 for blake2b, 10 for blake2s // h is state vector, the first/init is iv^param as above // m, t_0, t_1 and f is initialized as 0 // the first call param is // 0000000c28c9bdf267e6096a3ba7ca8485ae67bb2bf894fe72f36e3cf1361d5f3af54fa5d182e6ad7f520e511f6c3e2b8c68059b08d623d6cfbce57e0c4d0a3e71ac933300000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 // // we don't have private/password 'key', so we can skip 'first' update loop // // 208 = 128 + 80 + 28 padding // it need 7slot * 32(256bits) = 224 bytes to cover m // due to call/staticcall/delegagecall, we have to use memory // 0x80 + 213 = 341 0x0155 // 0x80 + 0xe0 = 0x0160, we align memory to 0x20 bytes due to evm is 256-bit machine // take over memory management let memory_ptr := mload(0x40) // allocate more 0xE0 bytes temporarily mstore(0x40, add(memory_ptr,0x0E0)) // total size = E0 // offset // round h // 0x00 0000000c28c9bdf267e6096a3ba7ca84 // 0x10 85ae67bb2bf894fe72f36e3cf1361d5f // 0x20 3af54fa5d182e6ad7f520e511f6c3e2b // 0x30 8c68059b08d623d6cfbce57e0c4d0a3e // m // 0x40 71ac9333000000000000000000000000 // 0x50 00000000000000000000000000000000 // 0x60 00000000000000000000000000000000 // 0x70 00000000000000000000000000000000 // 0x80 00000000000000000000000000000000 // 0x90 00000000000000000000000000000000 // 0xA0 00000000000000000000000000000000 // 0xB0 00000000000000000000000000000000 // // t0 t1 // 0xC0 00000000000000000000000000000000 // 0xD0 0000000000PPPPPPPPPPPPPPPPPPPPPP P for placeholder // fi // populate init param mstore(memory_ptr, 0x0000000c28c9bdf267e6096a3ba7ca8485ae67bb2bf894fe72f36e3cf1361d5f) mstore(add(memory_ptr,0x20), 0x3af54fa5d182e6ad7f520e511f6c3e2b8c68059b08d623d6cfbce57e0c4d0a3e) mstore(add(memory_ptr,0x40), 0x71ac933300000000000000000000000000000000000000000000000000000000) mstore(add(memory_ptr,0x60), 0x0000000000000000000000000000000000000000000000000000000000000000) mstore(add(memory_ptr,0x80), 0x0000000000000000000000000000000000000000000000000000000000000000) mstore(add(memory_ptr,0xA0), 0x0000000000000000000000000000000000000000000000000000000000000000) mstore(add(memory_ptr,0xC0), 0x0000000000000000000000000000000000000000000000000000000000000000) /*// copy 128 0x80 bytes to m, eliminate selector and leading length of bytes calldatacopy(0xC4, 0x44, 0x80)*/ //copy 0x80 bytes in memory from input_ptr to // 0x00 mstore(add(memory_ptr,0x44),mload(input_ptr)) // 0x20 mstore(add(memory_ptr,0x64),mload(add(input_ptr,0x20))) // 0x40 mstore(add(memory_ptr,0x84),mload(add(input_ptr,0x40))) // 0x60 mstore(add(memory_ptr,0xA4),mload(add(input_ptr,0x60))) // set t0,t1 to 128 0x80 // watch that the data is Little.Endian // t0 = 0x 80 00 00 00 00 00 00 00 // t1 = 0x 00 00 00 00 00 00 00 00 mstore8(add(memory_ptr,0xC4),0x80) // not final block, leave f to 0x00 // call F() // pass memory to blake2b, get the result h at 0x80+0x04, over-writing if iszero(staticcall(not(0), 0x09, memory_ptr, 0xD5, add(memory_ptr,0x04), 0x40)) { revert(0x80, 0x00) } // the remaining 208-128=80 0x50 bytes input data // copy 208-128=80 0x50 bytes to m, need padding zero // 0x80 mstore(add(memory_ptr,0x44),mload(add(input_ptr,0x80))) // 0xA0 mstore(add(memory_ptr,0x64),mload(add(input_ptr,0xA0))) // 0xC0, the data size is 0xD0, we must truncate the low bytes mstore(add(memory_ptr,0x84),and(mload(add(input_ptr,0xC0)),0xffffffffffffffffffffffffffffffff00000000000000000000000000000000)) // 0xE0 mstore(add(memory_ptr,0xA4),0x0000000000000000000000000000000000000000000000000000000000000000) // set t0,t1 to 208 0xD0 // watch that the data is Little.Endian // t0 = 0x D0 00 00 00 00 00 00 00 // t1 = 0x 00 00 00 00 00 00 00 00 mstore8(add(memory_ptr,0xC4),0xD0) // final block, set f to 0x01 mstore8(add(memory_ptr,0xD4),0x01) // call F() // pass memory to blake2b, get the result h at 0x80+0x04, over-writing if iszero(staticcall(not(0), 0x09, memory_ptr, 0xD5, add(memory_ptr,0x04), 0x40)) { revert(0x80, 0x00) } ret := mload(add(memory_ptr,0x04)) // clear memory mstore(0x40,memory_ptr) } } function digest208Ptr(uint256 input_ptr) internal view returns (bytes32 ret){ // solium-disable-next-line assembly{ // the init vector is 0x // 08c9bc3f 67e6096a 3ba7ca84 85ae67bb // 2bf894fe 72f36e3c f1361d5f 3af54fa5 // d182e6ad 7f520e51 1f6c3e2b 8c68059b // 6bbd41fb abd9831f 79217e13 19cde05b // // the param is // let param = blake2b_param { // digest_length: out_len as u8, u8 0x20 // key_length: 0, u8 0x00 // fanout: 1, u8 0x01 // depth: 1, u8 0x01 // leaf_length: 0, u32 // node_offset: 0,u32 // xof_length: 0, u32 // node_depth: 0, u8 // inner_length: 0, u8 // reserved: [0u8; 14usize], u8[14] // salt: [0u8; blake2b_constant_BLAKE2B_SALTBYTES as usize], u8[16] // personal: [0u8; blake2b_constant_BLAKE2B_PERSONALBYTES as usize], u8[16] // }; // pub const blake2b_constant_BLAKE2B_SALTBYTES: blake2b_constant = 16; // pub const blake2b_constant_BLAKE2B_PERSONALBYTES: blake2b_constant = 16; // the PERSONALBYTES is b"ckb-default-hash"; // PERSONALBYTES = 636b622d 64656661 756c742d 68617368 // // the param is 0x // 20000101 00000000 00000000 00000000 [digest_length key_length fanout depth] leaf_length node_offset xof_length // 00000000 00000000 00000000 00000000 node_depth inner_length reserved // 00000000 00000000 00000000 00000000 salt // 636b622d 64656661 756c742d 68617368 personal // // iv ^ param is 64 bytes, which is the init h // 28c9bdf2 67e6096a 3ba7ca84 85ae67bb // 2bf894fe 72f36e3c f1361d5f 3af54fa5 // d182e6ad 7f520e51 1f6c3e2b 8c68059b // 08d623d6 cfbce57e 0c4d0a3e 71ac9333 // // param for blake2b F(): // rounds - the number of rounds - 32-bit unsigned big-endian word // h - the state vector - 8 unsigned 64-bit little-endian words // m - the message block vector - 16 unsigned 64-bit little-endian words // t_0, t_1 - offset counters - 2 unsigned 64-bit little-endian words // f - the final block indicator flag - 8-bit word // // the rounds === 12 for blake2b, 10 for blake2s // h is state vector, the first/init is iv^param as above // m, t_0, t_1 and f is initialized as 0 // the first call param is // 0000000c28c9bdf267e6096a3ba7ca8485ae67bb2bf894fe72f36e3cf1361d5f3af54fa5d182e6ad7f520e511f6c3e2b8c68059b08d623d6cfbce57e0c4d0a3e71ac933300000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 // // we don't have private/password 'key', so we can skip 'first' update loop // // 208 = 128 + 80 + 28 padding // it need 7slot * 32(256bits) = 224 bytes to cover m // due to call/staticcall/delegagecall, we have to use memory // 0x80 + 213 = 341 0x0155 // 0x80 + 0xe0 = 0x0160, we align memory to 0x20 bytes due to evm is 256-bit machine // take over memory management let memory_ptr := mload(0x40) // allocate more 0xE0 bytes temporarily mstore(0x40, add(memory_ptr,0x0E0)) // total size = E0 // offset // round h // 0x00 0000000c28c9bdf267e6096a3ba7ca84 // 0x10 85ae67bb2bf894fe72f36e3cf1361d5f // 0x20 3af54fa5d182e6ad7f520e511f6c3e2b // 0x30 8c68059b08d623d6cfbce57e0c4d0a3e // m // 0x40 71ac9333000000000000000000000000 // 0x50 00000000000000000000000000000000 // 0x60 00000000000000000000000000000000 // 0x70 00000000000000000000000000000000 // 0x80 00000000000000000000000000000000 // 0x90 00000000000000000000000000000000 // 0xA0 00000000000000000000000000000000 // 0xB0 00000000000000000000000000000000 // // t0 t1 // 0xC0 00000000000000000000000000000000 // 0xD0 0000000000PPPPPPPPPPPPPPPPPPPPPP P for placeholder // fi // populate init param mstore(memory_ptr, 0x0000000c28c9bdf267e6096a3ba7ca8485ae67bb2bf894fe72f36e3cf1361d5f) mstore(add(memory_ptr,0x20), 0x3af54fa5d182e6ad7f520e511f6c3e2b8c68059b08d623d6cfbce57e0c4d0a3e) mstore(add(memory_ptr,0x40), 0x71ac933300000000000000000000000000000000000000000000000000000000) mstore(add(memory_ptr,0x60), 0x0000000000000000000000000000000000000000000000000000000000000000) mstore(add(memory_ptr,0x80), 0x0000000000000000000000000000000000000000000000000000000000000000) mstore(add(memory_ptr,0xA0), 0x0000000000000000000000000000000000000000000000000000000000000000) mstore(add(memory_ptr,0xC0), 0x0000000000000000000000000000000000000000000000000000000000000000) /*// copy 128 0x80 bytes to m, eliminate selector and leading length of bytes calldatacopy(0xC4, 0x44, 0x80)*/ //copy 0x80 bytes in memory from input_ptr to // 0x00 mstore(add(memory_ptr,0x44),mload(input_ptr)) // 0x20 mstore(add(memory_ptr,0x64),mload(add(input_ptr,0x20))) // 0x40 mstore(add(memory_ptr,0x84),mload(add(input_ptr,0x40))) // 0x60 mstore(add(memory_ptr,0xA4),mload(add(input_ptr,0x60))) // set t0,t1 to 128 0x80 // watch that the data is Little.Endian // t0 = 0x 80 00 00 00 00 00 00 00 // t1 = 0x 00 00 00 00 00 00 00 00 mstore8(add(memory_ptr,0xC4),0x80) // not final block, leave f to 0x00 // call F() // pass memory to blake2b, get the result h at 0x80+0x04, over-writing if iszero(staticcall(not(0), 0x09, memory_ptr, 0xD5, add(memory_ptr,0x04), 0x40)) { revert(0x80, 0x00) } // the remaining 208-128=80 0x50 bytes input data // copy 208-128=80 0x50 bytes to m, need padding zero // 0x80 mstore(add(memory_ptr,0x44),mload(add(input_ptr,0x80))) // 0xA0 mstore(add(memory_ptr,0x64),mload(add(input_ptr,0xA0))) // 0xC0, the data size is 0xD0, we must truncate the low bytes mstore(add(memory_ptr,0x84),and(mload(add(input_ptr,0xC0)),0xffffffffffffffffffffffffffffffff00000000000000000000000000000000)) // 0xE0 mstore(add(memory_ptr,0xA4),0x0000000000000000000000000000000000000000000000000000000000000000) // set t0,t1 to 208 0xD0 // watch that the data is Little.Endian // t0 = 0x D0 00 00 00 00 00 00 00 // t1 = 0x 00 00 00 00 00 00 00 00 mstore8(add(memory_ptr,0xC4),0xD0) // final block, set f to 0x01 mstore8(add(memory_ptr,0xD4),0x01) // call F() // pass memory to blake2b, get the result h at 0x80+0x04, over-writing if iszero(staticcall(not(0), 0x09, memory_ptr, 0xD5, add(memory_ptr,0x04), 0x40)) { revert(0x80, 0x00) } ret := mload(add(memory_ptr,0x04)) // clear memory mstore(0x40,memory_ptr) } } function digest64(bytes memory input64) internal view returns (bytes32 ret){ // solium-disable-next-line assembly{ // reject not ckbinput // 64 = 0x40 if iszero(eq(mload(input64), 0x40)){ revert(0x80,0x00) } let input_ptr := add(input64,0x20) let memory_ptr := mload(0x40) mstore(0x40, add(memory_ptr,0x0E0)) mstore(memory_ptr, 0x0000000c28c9bdf267e6096a3ba7ca8485ae67bb2bf894fe72f36e3cf1361d5f) mstore(add(memory_ptr,0x20), 0x3af54fa5d182e6ad7f520e511f6c3e2b8c68059b08d623d6cfbce57e0c4d0a3e) mstore(add(memory_ptr,0x40), 0x71ac933300000000000000000000000000000000000000000000000000000000) mstore(add(memory_ptr,0x60), 0x0000000000000000000000000000000000000000000000000000000000000000) mstore(add(memory_ptr,0x80), 0x0000000000000000000000000000000000000000000000000000000000000000) mstore(add(memory_ptr,0xA0), 0x0000000000000000000000000000000000000000000000000000000000000000) mstore(add(memory_ptr,0xC0), 0x0000000000000000000000000000000000000000000000000000000000000000) //copy 0x40 bytes in memory from input_ptr to // 0x00 mstore(add(memory_ptr,0x44),mload(input_ptr)) // 0x20 mstore(add(memory_ptr,0x64),mload(add(input_ptr,0x20))) // 0x40 set to 0x00 mstore(add(memory_ptr,0x84),0x0000000000000000000000000000000000000000000000000000000000000000) // 0x60 set to 0x00 mstore(add(memory_ptr,0xa4),0x0000000000000000000000000000000000000000000000000000000000000000) // set t0,t1 to 128 0x80 // watch that the data is Little.Endian // t0 = 0x 80 00 00 00 00 00 00 00 // t1 = 0x 00 00 00 00 00 00 00 00 mstore8(add(memory_ptr,0xC4),0x40) // final block, set f to 0x01 mstore8(add(memory_ptr,0xD4),0x01) // call F() // pass memory to blake2b, get the result h at 0x80+0x04, over-writing if iszero(staticcall(not(0), 0x09, memory_ptr, 0xD5, add(memory_ptr,0x04), 0x40)) { revert(0x80, 0x00) } ret := mload(add(memory_ptr,0x04)) // clear memory mstore(0x40,memory_ptr) } } function digest64Merge(bytes32 left, bytes32 right) internal view returns (bytes32 ret){ // solium-disable-next-line assembly{ let memory_ptr := mload(0x40) mstore(0x40, add(memory_ptr,0x0E0)) mstore(memory_ptr, 0x0000000c28c9bdf267e6096a3ba7ca8485ae67bb2bf894fe72f36e3cf1361d5f) mstore(add(memory_ptr,0x20), 0x3af54fa5d182e6ad7f520e511f6c3e2b8c68059b08d623d6cfbce57e0c4d0a3e) mstore(add(memory_ptr,0x40), 0x71ac933300000000000000000000000000000000000000000000000000000000) mstore(add(memory_ptr,0x60), 0x0000000000000000000000000000000000000000000000000000000000000000) mstore(add(memory_ptr,0x80), 0x0000000000000000000000000000000000000000000000000000000000000000) mstore(add(memory_ptr,0xA0), 0x0000000000000000000000000000000000000000000000000000000000000000) mstore(add(memory_ptr,0xC0), 0x0000000000000000000000000000000000000000000000000000000000000000) //copy 0x40 bytes in memory from input_ptr to // 0x00 mstore(add(memory_ptr,0x44), left) // 0x20 mstore(add(memory_ptr,0x64), right) // 0x40 set to 0x00 mstore(add(memory_ptr,0x84),0x0000000000000000000000000000000000000000000000000000000000000000) // 0x60 set to 0x00 mstore(add(memory_ptr,0xa4),0x0000000000000000000000000000000000000000000000000000000000000000) // set t0,t1 to 128 0x80 // watch that the data is Little.Endian // t0 = 0x 80 00 00 00 00 00 00 00 // t1 = 0x 00 00 00 00 00 00 00 00 mstore8(add(memory_ptr,0xC4),0x40) // final block, set f to 0x01 mstore8(add(memory_ptr,0xD4),0x01) // call F() // pass memory to blake2b, get the result h at 0x80+0x04, over-writing if iszero(staticcall(not(0), 0x09, memory_ptr, 0xD5, add(memory_ptr,0x04), 0x40)) { revert(0x80, 0x00) } ret := mload(add(memory_ptr,0x04)) // clear memory mstore(0x40,memory_ptr) } } }
solium-disable-next-linecopy 0x40 bytes in memory from input_ptr to 0x00 0x20 0x40 set to 0x00 0x60 set to 0x00 set t0,t1 to 128 0x80 watch that the data is Little.Endian t0 = 0x 80 00 00 00 00 00 00 00 t1 = 0x 00 00 00 00 00 00 00 00 final block, set f to 0x01 call F() pass memory to blake2b, get the result h at 0x80+0x04, over-writing
function digest64Merge(bytes32 left, bytes32 right) internal view returns (bytes32 ret){ assembly{ let memory_ptr := mload(0x40) mstore(0x40, add(memory_ptr,0x0E0)) mstore(memory_ptr, 0x0000000c28c9bdf267e6096a3ba7ca8485ae67bb2bf894fe72f36e3cf1361d5f) mstore(add(memory_ptr,0x20), 0x3af54fa5d182e6ad7f520e511f6c3e2b8c68059b08d623d6cfbce57e0c4d0a3e) mstore(add(memory_ptr,0x40), 0x71ac933300000000000000000000000000000000000000000000000000000000) mstore(add(memory_ptr,0x60), 0x0000000000000000000000000000000000000000000000000000000000000000) mstore(add(memory_ptr,0x80), 0x0000000000000000000000000000000000000000000000000000000000000000) mstore(add(memory_ptr,0xA0), 0x0000000000000000000000000000000000000000000000000000000000000000) mstore(add(memory_ptr,0xC0), 0x0000000000000000000000000000000000000000000000000000000000000000) mstore(add(memory_ptr,0x44), left) mstore(add(memory_ptr,0x64), right) mstore(add(memory_ptr,0x84),0x0000000000000000000000000000000000000000000000000000000000000000) mstore(add(memory_ptr,0xa4),0x0000000000000000000000000000000000000000000000000000000000000000) mstore8(add(memory_ptr,0xC4),0x40) mstore8(add(memory_ptr,0xD4),0x01) if iszero(staticcall(not(0), 0x09, memory_ptr, 0xD5, add(memory_ptr,0x04), 0x40)) { revert(0x80, 0x00) } ret := mload(add(memory_ptr,0x04)) } }
12,991,454
pragma solidity >=0.4.24 <0.7.0; /// @title Ethereum marriage contract /// @author Witek Radomski /// @notice This smart contract allows for marriage and divorce on the Ethereum blockchain with a monetary incentive to /// stay married for the full term, as well as a prisoner's dilemma to update the contract if a divorce were to happen. contract Marriage { address public partner1; string public partner1Name; bool public partner1Signed = false; address private partner1UpdateAddress; address public partner2; string public partner2Name; bool public partner2Signed = false; address private partner2UpdateAddress; string public marriageContractId; uint256 public blockchainWeddingDate; uint256 public yearsToLockFunds; address payable public divorceBurnAddress; uint256 public percentToBurnOnDivorce; bool public married = true; event Married(address indexed _partner1, address indexed _partner2); event Signed(uint256 indexed _partnerNumber, address indexed _partner, string _partnerName); event UpdatedAddress(uint256 indexed _partnerNumber, address indexed _oldAddress, address indexed _newAddress); event LifeEvent(address indexed _sender, string _eventDescription); event Wishes(address indexed _sender, string _note); event Divorced(address indexed _partner1, address indexed _partner2, address _initiatedBy); uint256 constant DAYS_IN_YEAR = 365; modifier onlyPartner() { require(msg.sender == partner1 || msg.sender == partner2, "Must be one of the partners"); _; } /// @param _marriageContractId A human-readable identifier or name for this contract. /// @param _partner1 The address of the first partner. /// @param _partner2 The address of the second partner. /// @param _yearsToLockFunds How many years to lock funds for. Note: Years are 365 days, leap years are not /// considered here. /// @param _divorceBurnAddress If a divorce occurs, Ether will be sent here. I recommend supplying the public /// address of a charity that accepts Ether, such as SENS Research Foundation for the betterment of humankind. /// @param _percentToBurnOnDivorce The percentage out of 100 to burn if a divorce happens. Suggested: 90. The /// rest will be transferred to the user that initiates the divorce function as a prisoner's dilemma incentive /// to execute the function. constructor( string memory _marriageContractId, address _partner1, address _partner2, uint256 _yearsToLockFunds, address payable _divorceBurnAddress, uint256 _percentToBurnOnDivorce ) public { marriageContractId = _marriageContractId; partner1 = _partner1; partner2 = _partner2; yearsToLockFunds = _yearsToLockFunds; divorceBurnAddress = _divorceBurnAddress; percentToBurnOnDivorce = _percentToBurnOnDivorce; blockchainWeddingDate = now; emit Married(partner1, partner2); } /// @notice Each partner must sign the contract with this function. This will lock funds and also set their name. /// This function may also be called any time in the future by either partner to update their name if needed. /// @param _partnerName The full legal name or nickname of the current partner signing this contract function signPartner(string memory _partnerName) public onlyPartner { if(msg.sender == partner1) { partner1Name = _partnerName; partner1Signed = true; emit Signed(1, msg.sender, _partnerName); } else if(msg.sender == partner2) { partner2Name = _partnerName; partner2Signed = true; emit Signed(2, msg.sender, _partnerName); } } /// @notice To update a partner's Ethereum account address, they must first call this function (Step 1). /// Next, they must call the acceptUpdatePartnerAddress function from the new account address, to finalize. /// @param _partnerNumber Which partner is updating their address (1 or 2) /// @param _newAddress The new address to be updated to function updatePartnerAddress(uint256 _partnerNumber, address _newAddress) public onlyPartner { if(_partnerNumber == 1) { require(msg.sender == partner1, "Must be partner 1"); partner1UpdateAddress = _newAddress; } else if(_partnerNumber == 2) { require(msg.sender == partner2, "Must be partner 2"); partner2UpdateAddress = _newAddress; } else { revert("_partnerNumber must be 1 or 2"); } } /// @notice This will permanently change one partner's address their desired new address (Step 2). /// Run this function using the new account AFTER calling updatePartnerAddress from the original account. /// @param _partnerNumber Which partner is accepting their new address change (1 or 2) function acceptUpdatePartnerAddress(uint256 _partnerNumber) public { if(_partnerNumber == 1) { if(msg.sender == partner1UpdateAddress) { emit UpdatedAddress(_partnerNumber, partner1, partner1UpdateAddress); partner1 = partner1UpdateAddress; partner1UpdateAddress = address(0); } else { revert("Please accept from the new account you had provided in updatePartnerAddress"); } } else if(_partnerNumber == 2) { if(msg.sender == partner2UpdateAddress) { emit UpdatedAddress(_partnerNumber, partner2, partner2UpdateAddress); partner2 = partner2UpdateAddress; partner2UpdateAddress = address(0); } else { revert("Please accept from the new account you had provided in updatePartnerAddress"); } } else { revert("_partnerNumber must be 1 or 2"); } } /// @notice Warning: Executing this function will send a percentage of the Ether balance to the divorceBurnAddress /// as a penalty for not staying married through the length of the marriage contract. /// The person who initiates the divorce function will receive the remainder of funds. /// Please talk things through with your partner and work on your marriage before considering this function! /// @param _confirm Safety measure. This must be integer 1 to confirm the divorce proceeds. function divorce(uint256 _confirm) public onlyPartner returns (bool) { require(_confirm == 1, "To proceed with divorce and burn funds, pass 1 to _confirm"); require(married == true, "Already divorced, cannot divorce again!"); uint256 burnAmount = address(this).balance * percentToBurnOnDivorce / 100; uint256 divorcerAmount = address(this).balance - burnAmount; divorceBurnAddress.transfer(burnAmount); msg.sender.transfer(divorcerAmount); married = false; emit Divorced(partner1, partner2, msg.sender); } /// @notice Funds may be withdrawn by either partner after the lock period has ended /// @param _amount Amount of Ether in wei to withdraw from this contract function withdrawFunds(uint256 _amount) public onlyPartner { require(partner1Signed == false || partner2Signed == false || now >= blockchainWeddingDate + (yearsToLockFunds * DAYS_IN_YEAR * 1 days), "Lock time has not passed yet"); require(_amount <= address(this).balance, "Amount is larger than the available balance"); msg.sender.transfer(_amount); } /// @notice This function may be called by the couple to log significant life events, such as the birth of a child. /// @param _eventDescription A human-readable description string function addLifeEvent(string memory _eventDescription) public onlyPartner { emit LifeEvent(msg.sender, _eventDescription); } /// @notice This function may be called by friends or public to wish a happy marriage, happy anniversary, etc. /// @param _note A human-readable note. Please include your name so the couple may know who the wishes are from. function addWishes(string memory _note) public { emit Wishes(msg.sender, _note); } /// @notice Payable fallback function, allows this contract to receive Ether. function() external payable { } }
This will permanently change one partner's address their desired new address (Step 2). Run this function using the new account AFTER calling updatePartnerAddress from the original account. _partnerNumber Which partner is accepting their new address change (1 or 2)
function acceptUpdatePartnerAddress(uint256 _partnerNumber) public { if(_partnerNumber == 1) { if(msg.sender == partner1UpdateAddress) { emit UpdatedAddress(_partnerNumber, partner1, partner1UpdateAddress); partner1 = partner1UpdateAddress; partner1UpdateAddress = address(0); } else { revert("Please accept from the new account you had provided in updatePartnerAddress"); } } else if(_partnerNumber == 2) { if(msg.sender == partner2UpdateAddress) { emit UpdatedAddress(_partnerNumber, partner2, partner2UpdateAddress); partner2 = partner2UpdateAddress; partner2UpdateAddress = address(0); } else { revert("Please accept from the new account you had provided in updatePartnerAddress"); } } else { revert("_partnerNumber must be 1 or 2"); } }
1,086,857
/** *Submitted for verification at Etherscan.io on 2022-02-17 */ // SPDX-License-Identifier: MIT pragma solidity 0.8.0; // Part: OpenZeppelin/[email protected]/Context /* * @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; } } // Part: OpenZeppelin/[email protected]/IERC165 /** * @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); } // Part: OpenZeppelin/[email protected]/IERC20 /** * @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); } // Part: OpenZeppelin/[email protected]/IERC20Metadata /** * @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); } // Part: OpenZeppelin/[email protected]/IERC721 /** * @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; } // Part: OpenZeppelin/[email protected]/Ownable /** * @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() { _setOwner(_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 { _setOwner(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"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // Part: OpenZeppelin/[email protected]/ERC20 /** * @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 guidelines: functions revert instead * of 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 {} } // Part: OpenZeppelin/[email protected]/IERC721Enumerable /** * @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); } // Part: ISheetFighterToken interface ISheetFighterToken is IERC721Enumerable { /// @notice Update the address of the CellToken contract /// @param _contractAddress Address of the CellToken contract function setCellTokenAddress(address _contractAddress) external; /// @notice Update the address which signs the mint transactions /// @dev Used for ensuring GPT-3 values have not been altered /// @param _mintSigner New address for the mintSigner function setMintSigner(address _mintSigner) external; /// @notice Update the address of the bridge /// @dev Used for authorization /// @param _bridge New address for the bridge function setBridge(address _bridge) external; /// @dev Withdraw funds as owner function withdraw() external; /// @notice Set the sale state: options are 0 (closed), 1 (presale), 2 (public sale) -- only owner can call /// @dev Implicitly converts int argument to TokenSaleState type -- only owner can call /// @param saleStateId The id for the sale state: 0 (closed), 1 (presale), 2 (public sale) function setSaleState(uint256 saleStateId) external; /// @notice Mint up to 20 Sheet Fighters /// @param numTokens Number of Sheet Fighter tokens to mint (1 to 20) function mint(uint256 numTokens) external payable; /// @notice "Print" a Sheet. Adds GPT-3 flavor text and attributes /// @dev This function requires signature verification /// @param _tokenIds Array of tokenIds to print /// @param _flavorTexts Array of strings with flavor texts concatonated with a pipe character /// @param _signature Signature verifying _flavorTexts are unmodified function print( uint256[] memory _tokenIds, string[] memory _flavorTexts, bytes memory _signature ) external; /// @notice Bridge the Sheets /// @dev Transfers Sheets to bridge /// @param tokenOwner Address of the tokenOwner who is bridging their tokens /// @param tokenIds Array of tokenIds that tokenOwner is bridging function bridgeSheets(address tokenOwner, uint256[] calldata tokenIds) external; /// @notice Update the sheet to sync with actions that occured on otherside of bridge /// @param tokenId Id of the SheetFighter /// @param HP New HP value /// @param luck New luck value /// @param heal New heal value /// @param defense New defense value /// @param attack New attack value function syncBridgedSheet( uint256 tokenId, uint8 HP, uint8 luck, uint8 heal, uint8 defense, uint8 attack ) external; /// @notice Return true if token is printed, false otherwise /// @param _tokenId Id of the SheetFighter NFT /// @return bool indicating whether or not sheet is printed function isPrinted(uint256 _tokenId) external view returns(bool); /// @notice Returns the token metadata and SVG artwork /// @dev This generates a data URI, which contains the metadata json, encoded in base64 /// @param _tokenId The tokenId of the token whos metadata and SVG we want function tokenURI(uint256 _tokenId) external view returns (string memory); } // Part: OpenZeppelin/[email protected]/ERC20Burnable /** * @dev Extension of {ERC20} that allows token holders to destroy both their own * tokens and those that they have an allowance for, in a way that can be * recognized off-chain (via event analysis). */ abstract contract ERC20Burnable is Context, ERC20 { /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } /** * @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) public virtual { uint256 currentAllowance = allowance(account, _msgSender()); require(currentAllowance >= amount, "ERC20: burn amount exceeds allowance"); unchecked { _approve(account, _msgSender(), currentAllowance - amount); } _burn(account, amount); } } // File: CellToken.sol /// @title Contract creating fungible in-game utility tokens for the Sheet Fighter game /// @author Overlord Paper Co /// @notice This defines in-game utility tokens that are used for the Sheet Fighter game /// @notice This contract is HIGHLY adapted from the Anonymice $CHEETH contract /// @notice Thank you MouseDev for writing the original $CHEETH contract! contract CellToken is ERC20Burnable, Ownable { uint256 public constant MAX_WALLET_STAKED = 10; uint256 public constant EMISSIONS_RATE = 115_740_740_740_741; // 10 $CELL per day = (10*1e18)/(60*60*24) uint256 public constant MAX_CELL = 1e26; /// @notice Address of SheetFighterToken contract address public sheetFighterTokenAddress; /// @notice Map SheetFighter id to timestamp staked mapping(uint256 => uint256) public tokenIdToTimeStamp; /// @notice Map SheetFighter id to staker's address mapping(uint256 => address) public tokenIdToStaker; /// @notice Map staker's address to array the ids of all the SheetFighters they're staking mapping(address => uint256[]) public stakerToTokenIds; /// @notice Address of the Polygon bridge address public bridge; /// @notice Construct CellToken contract for the in-game utility token for the Sheet Fighter game /// @dev Set sheetFighterTokenAddress, ERC20 name and symbol, and implicitly execute Ownable contructor constructor(address _sheetFighterTokenAddress) ERC20('Cell', 'CELL') Ownable() { sheetFighterTokenAddress = _sheetFighterTokenAddress; } /// @notice Update the address of the SheetFighterToken contract /// @param _contractAddress Address of the SheetFighterToken contract function setSheetFighterTokenAddress(address _contractAddress) external onlyOwner { sheetFighterTokenAddress = _contractAddress; } /// @notice Update the address of the bridge /// @dev Used for authorization /// @param _bridge New address for the bridge function setBridge(address _bridge) external onlyOwner { bridge = _bridge; } /// @notice Stake multiple Sheets by providing their Ids /// @param tokenIds Array of SheetFighterToken ids to stake function stakeByIds(uint256[] calldata tokenIds) external { require( stakerToTokenIds[msg.sender].length + tokenIds.length <= MAX_WALLET_STAKED, "Must have less than 10 Sheets staked!" ); for (uint256 i = 0; i < tokenIds.length; i++) { require( ISheetFighterToken(sheetFighterTokenAddress).ownerOf(tokenIds[i]) == msg.sender, "You don't own this Sheet!" ); require(tokenIdToStaker[tokenIds[i]] == address(0), "Token is already being staked!"); // Transfer SheetFighterToken to this (CellToken) contract ISheetFighterToken(sheetFighterTokenAddress).transferFrom( msg.sender, address(this), tokenIds[i] ); // Update staking variables in storage stakerToTokenIds[msg.sender].push(tokenIds[i]); tokenIdToTimeStamp[tokenIds[i]] = block.timestamp; tokenIdToStaker[tokenIds[i]] = msg.sender; } } /// @notice Unstake all of your SheetFighterTokens and get your rewards /// @notice This function is more gas efficient than calling unstakeByIds(...) for all ids /// @dev Tokens are iterated over in REVERSE order, due to the implementation of _remove(...) function unstakeAll() external { require( stakerToTokenIds[msg.sender].length > 0, "You have no tokens staked!" ); uint256 totalRewards = 0; // Iterate over staked tokens from the BACK of the array, because // the _remove() function, which is called by _removeTokenIdFromStaker(), // is far more gas efficient when called on elements further back for (uint256 i = stakerToTokenIds[msg.sender].length; i > 0; i--) { uint256 tokenId = stakerToTokenIds[msg.sender][i - 1]; // Transfer SheetFighterToken back to staker ISheetFighterToken(sheetFighterTokenAddress).transferFrom( address(this), msg.sender, tokenId ); // Add rewards for the current token totalRewards = totalRewards + ( (block.timestamp - tokenIdToTimeStamp[tokenId]) * EMISSIONS_RATE ); // Remove the token from the staker in storage variables _removeTokenIdFromStaker(msg.sender, tokenId); delete tokenIdToStaker[tokenId]; } // Mint CellTokens to reward staker _mint(msg.sender, _getMaximumRewards(totalRewards)); } /// @notice Unstake SheetFighterTokens, given by ids, and get your rewards /// @notice Use unstakeAll(...) instead if unstaking all tokens for gas efficiency /// @param tokenIds Array of SheetFighterToken ids to unstake function unstakeByIds(uint256[] memory tokenIds) external { uint256 totalRewards = 0; for (uint256 i = 0; i < tokenIds.length; i++) { require( tokenIdToStaker[tokenIds[i]] == msg.sender, "You're not staking this Sheet!" ); // Transfer SheetFighterToken back to staker ISheetFighterToken(sheetFighterTokenAddress).transferFrom( address(this), msg.sender, tokenIds[i] ); // Add rewards for the current token totalRewards = totalRewards + ( (block.timestamp - tokenIdToTimeStamp[tokenIds[i]]) * EMISSIONS_RATE ); // Remove the token from the staker in storage variables _removeTokenIdFromStaker(msg.sender, tokenIds[i]); delete tokenIdToStaker[tokenIds[i]]; } // Mint CellTokens to reward staker _mint(msg.sender, _getMaximumRewards(totalRewards)); } /// @notice Claim $CELL tokens as reward for staking a SheetFighterTokens, given by an id /// @notice This function does not unstake your Sheets /// @param tokenId SheetFighterToken id function claimByTokenId(uint256 tokenId) external { require( tokenIdToStaker[tokenId] == msg.sender, "You're not staking this Sheet!" ); _mint( msg.sender, _getMaximumRewards((block.timestamp - tokenIdToTimeStamp[tokenId]) * EMISSIONS_RATE) ); tokenIdToTimeStamp[tokenId] = block.timestamp; } /// @notice Claim $CELL tokens as reward for all SheetFighterTokens staked /// @notice This function does not unstake your Sheets function claimAll() external { uint256[] memory tokenIds = stakerToTokenIds[msg.sender]; uint256 totalRewards = 0; for (uint256 i = 0; i < tokenIds.length; i++) { require( tokenIdToStaker[tokenIds[i]] == msg.sender, "Token is not claimable by you!" ); totalRewards = totalRewards + ((block.timestamp - tokenIdToTimeStamp[tokenIds[i]]) * EMISSIONS_RATE); tokenIdToTimeStamp[tokenIds[i]] = block.timestamp; } _mint(msg.sender, _getMaximumRewards(totalRewards)); } /// @notice Mint tokens when bridging /// @dev This function is only used for bridging to mint tokens on one end /// @param to Address to send new tokens to /// @param value Number of new tokens to mint function bridgeMint(address to, uint256 value) external { require(bridge != address(0), "Bridge is not set"); require(msg.sender == bridge, "Only bridge can do this"); _mint(to, _getMaximumRewards(value)); } /// @notice Burn tokens when bridging /// @dev This function is only used for bridging to burn tokens on one end /// @param from Address to burn tokens from /// @param value Number of tokens to burn function bridgeBurn(address from, uint256 value) external { require(bridge != address(0), "Bridge is not set"); require(msg.sender == bridge, "Only bridge can do this"); _burn(from, value); } /// @notice View all rewards claimable by a staker /// @param staker Address of the staker /// @return Number of $CELL claimable by the staker function getAllRewards(address staker) external view returns (uint256) { uint256[] memory tokenIds = stakerToTokenIds[staker]; uint256 totalRewards = 0; for (uint256 i = 0; i < tokenIds.length; i++) { totalRewards = totalRewards + ((block.timestamp - tokenIdToTimeStamp[tokenIds[i]]) * EMISSIONS_RATE); } return _getMaximumRewards(totalRewards); } /// @notice View rewards claimable for a specific SheetFighterToken /// @param tokenId Id of the SheetFightToken /// @return Number of $CELL claimable by the staker for this Sheet function getRewardsByTokenId(uint256 tokenId) external view returns (uint256) { require(tokenIdToStaker[tokenId] != address(0), "Sheet is not staked!"); uint256 rewards = (block.timestamp - tokenIdToTimeStamp[tokenId]) * EMISSIONS_RATE; return _getMaximumRewards(rewards); } /// @notice Get all the token Ids staked by a staker /// @param staker Address of the staker /// @return Array of tokens staked function getTokensStaked(address staker) external view returns (uint256[] memory) { return stakerToTokenIds[staker]; } /// @notice Remove a token, given by an index, from a staker in staking storage variables /// @dev This function is significantly more gas efficient the greater the index is /// @param staker Address of the staker /// @param index Index of the SheetFighterToken in stakeToTokenIds[staker] being removed function _remove(address staker, uint256 index) internal { if (index >= stakerToTokenIds[staker].length) return; // Reset all for (uint256 i = index; i < stakerToTokenIds[staker].length - 1; i++) { stakerToTokenIds[staker][i] = stakerToTokenIds[staker][i + 1]; } stakerToTokenIds[staker].pop(); } /// @notice Remove a token, given by an id, from a staker in staking storage variables /// @param staker Address of the staker /// @param tokenId SheetFighterToken id function _removeTokenIdFromStaker(address staker, uint256 tokenId) internal { // Find index of SheetFighterToken in stakerToTokenIds[staker] array for (uint256 i = 0; i < stakerToTokenIds[staker].length; i++) { if (stakerToTokenIds[staker][i] == tokenId) { // This is the tokenId to remove // Now, remove it _remove(staker, i); } } } /// @dev Returns the maximum amount of rewards the user can get, when considering the max token cap /// @param calculatedRewards The rewards the user would receive, if there were no token cap /// @return How much the owner can claim function _getMaximumRewards(uint256 calculatedRewards) internal view returns(uint256) { uint256 totalCellAvailable = MAX_CELL - totalSupply(); return totalCellAvailable > calculatedRewards ? calculatedRewards : totalCellAvailable; } }
Remove a token, given by an index, from a staker in staking storage variables This function is significantly more gas efficient the greater the index is staker Address of the staker index Index of the SheetFighterToken in stakeToTokenIds[staker] being removed Reset all
function _remove(address staker, uint256 index) internal { if (index >= stakerToTokenIds[staker].length) return; for (uint256 i = index; i < stakerToTokenIds[staker].length - 1; i++) { stakerToTokenIds[staker][i] = stakerToTokenIds[staker][i + 1]; } stakerToTokenIds[staker].pop(); }
2,204,232
// SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.6.8; import "./ProtoBufRuntime.sol"; import "./GoogleProtobufAny.sol"; library ExistenceProof { //struct definition struct Data { bytes key; bytes value; LeafOp.Data leaf; InnerOp.Data[] path; } // Decoder section /** * @dev The main decoder for memory * @param bs The bytes array to be decoded * @return The decoded struct */ function decode(bytes memory bs) internal pure returns (Data memory) { (Data memory x, ) = _decode(32, bs, bs.length); return x; } /** * @dev The main decoder for storage * @param self The in-storage struct * @param bs The bytes array to be decoded */ function decode(Data storage self, bytes memory bs) internal { (Data memory x, ) = _decode(32, bs, bs.length); store(x, self); } // inner decoder /** * @dev The decoder for internal usage * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param sz The number of bytes expected * @return The decoded struct * @return The number of bytes decoded */ function _decode(uint256 p, bytes memory bs, uint256 sz) internal pure returns (Data memory, uint) { Data memory r; uint[5] memory counters; uint256 fieldId; ProtoBufRuntime.WireType wireType; uint256 bytesRead; uint256 offset = p; uint256 pointer = p; while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_key(pointer, bs, r, counters); } else if (fieldId == 2) { pointer += _read_value(pointer, bs, r, counters); } else if (fieldId == 3) { pointer += _read_leaf(pointer, bs, r, counters); } else if (fieldId == 4) { pointer += _read_path(pointer, bs, nil(), counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } pointer = offset; r.path = new InnerOp.Data[](counters[4]); while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_key(pointer, bs, nil(), counters); } else if (fieldId == 2) { pointer += _read_value(pointer, bs, nil(), counters); } else if (fieldId == 3) { pointer += _read_leaf(pointer, bs, nil(), counters); } else if (fieldId == 4) { pointer += _read_path(pointer, bs, r, counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } return (r, sz); } // field readers /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_key( uint256 p, bytes memory bs, Data memory r, uint[5] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs); if (isNil(r)) { counters[1] += 1; } else { r.key = x; if (counters[1] > 0) counters[1] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_value( uint256 p, bytes memory bs, Data memory r, uint[5] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs); if (isNil(r)) { counters[2] += 1; } else { r.value = x; if (counters[2] > 0) counters[2] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_leaf( uint256 p, bytes memory bs, Data memory r, uint[5] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (LeafOp.Data memory x, uint256 sz) = _decode_LeafOp(p, bs); if (isNil(r)) { counters[3] += 1; } else { r.leaf = x; if (counters[3] > 0) counters[3] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_path( uint256 p, bytes memory bs, Data memory r, uint[5] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (InnerOp.Data memory x, uint256 sz) = _decode_InnerOp(p, bs); if (isNil(r)) { counters[4] += 1; } else { r.path[r.path.length - counters[4]] = x; if (counters[4] > 0) counters[4] -= 1; } return sz; } // struct decoder /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_LeafOp(uint256 p, bytes memory bs) internal pure returns (LeafOp.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (LeafOp.Data memory r, ) = LeafOp._decode(pointer, bs, sz); return (r, sz + bytesRead); } /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_InnerOp(uint256 p, bytes memory bs) internal pure returns (InnerOp.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (InnerOp.Data memory r, ) = InnerOp._decode(pointer, bs, sz); return (r, sz + bytesRead); } // Encoder section /** * @dev The main encoder for memory * @param r The struct to be encoded * @return The encoded byte array */ function encode(Data memory r) internal pure returns (bytes memory) { bytes memory bs = new bytes(_estimate(r)); uint256 sz = _encode(r, 32, bs); assembly { mstore(bs, sz) } return bs; } // inner encoder /** * @dev The encoder for internal usage * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { uint256 offset = p; uint256 pointer = p; uint256 i; if (r.key.length != 0) { pointer += ProtoBufRuntime._encode_key( 1, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_bytes(r.key, pointer, bs); } if (r.value.length != 0) { pointer += ProtoBufRuntime._encode_key( 2, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_bytes(r.value, pointer, bs); } pointer += ProtoBufRuntime._encode_key( 3, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += LeafOp._encode_nested(r.leaf, pointer, bs); if (r.path.length != 0) { for(i = 0; i < r.path.length; i++) { pointer += ProtoBufRuntime._encode_key( 4, ProtoBufRuntime.WireType.LengthDelim, pointer, bs) ; pointer += InnerOp._encode_nested(r.path[i], pointer, bs); } } return pointer - offset; } // nested encoder /** * @dev The encoder for inner struct * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode_nested(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { /** * First encoded `r` into a temporary array, and encode the actual size used. * Then copy the temporary array into `bs`. */ uint256 offset = p; uint256 pointer = p; bytes memory tmp = new bytes(_estimate(r)); uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp); uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs); uint256 size = _encode(r, 32, tmp); pointer += ProtoBufRuntime._encode_varint(size, pointer, bs); ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size); pointer += size; delete tmp; return pointer - offset; } // estimator /** * @dev The estimator for a struct * @param r The struct to be encoded * @return The number of bytes encoded in estimation */ function _estimate( Data memory r ) internal pure returns (uint) { uint256 e;uint256 i; e += 1 + ProtoBufRuntime._sz_lendelim(r.key.length); e += 1 + ProtoBufRuntime._sz_lendelim(r.value.length); e += 1 + ProtoBufRuntime._sz_lendelim(LeafOp._estimate(r.leaf)); for(i = 0; i < r.path.length; i++) { e += 1 + ProtoBufRuntime._sz_lendelim(InnerOp._estimate(r.path[i])); } return e; } // empty checker function _empty( Data memory r ) internal pure returns (bool) { if (r.key.length != 0) { return false; } if (r.value.length != 0) { return false; } if (r.path.length != 0) { return false; } return true; } //store function /** * @dev Store in-memory struct to storage * @param input The in-memory struct * @param output The in-storage struct */ function store(Data memory input, Data storage output) internal { output.key = input.key; output.value = input.value; LeafOp.store(input.leaf, output.leaf); for(uint256 i4 = 0; i4 < input.path.length; i4++) { output.path.push(input.path[i4]); } } //array helpers for Path /** * @dev Add value to an array * @param self The in-memory struct * @param value The value to add */ function addPath(Data memory self, InnerOp.Data memory value) internal pure { /** * First resize the array. Then add the new element to the end. */ InnerOp.Data[] memory tmp = new InnerOp.Data[](self.path.length + 1); for (uint256 i = 0; i < self.path.length; i++) { tmp[i] = self.path[i]; } tmp[self.path.length] = value; self.path = tmp; } //utility functions /** * @dev Return an empty struct * @return r The empty struct */ function nil() internal pure returns (Data memory r) { assembly { r := 0 } } /** * @dev Test whether a struct is empty * @param x The struct to be tested * @return r True if it is empty */ function isNil(Data memory x) internal pure returns (bool r) { assembly { r := iszero(x) } } } //library ExistenceProof library NonExistenceProof { //struct definition struct Data { bytes key; ExistenceProof.Data left; ExistenceProof.Data right; } // Decoder section /** * @dev The main decoder for memory * @param bs The bytes array to be decoded * @return The decoded struct */ function decode(bytes memory bs) internal pure returns (Data memory) { (Data memory x, ) = _decode(32, bs, bs.length); return x; } /** * @dev The main decoder for storage * @param self The in-storage struct * @param bs The bytes array to be decoded */ function decode(Data storage self, bytes memory bs) internal { (Data memory x, ) = _decode(32, bs, bs.length); store(x, self); } // inner decoder /** * @dev The decoder for internal usage * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param sz The number of bytes expected * @return The decoded struct * @return The number of bytes decoded */ function _decode(uint256 p, bytes memory bs, uint256 sz) internal pure returns (Data memory, uint) { Data memory r; uint[4] memory counters; uint256 fieldId; ProtoBufRuntime.WireType wireType; uint256 bytesRead; uint256 offset = p; uint256 pointer = p; while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_key(pointer, bs, r, counters); } else if (fieldId == 2) { pointer += _read_left(pointer, bs, r, counters); } else if (fieldId == 3) { pointer += _read_right(pointer, bs, r, counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } return (r, sz); } // field readers /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_key( uint256 p, bytes memory bs, Data memory r, uint[4] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs); if (isNil(r)) { counters[1] += 1; } else { r.key = x; if (counters[1] > 0) counters[1] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_left( uint256 p, bytes memory bs, Data memory r, uint[4] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (ExistenceProof.Data memory x, uint256 sz) = _decode_ExistenceProof(p, bs); if (isNil(r)) { counters[2] += 1; } else { r.left = x; if (counters[2] > 0) counters[2] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_right( uint256 p, bytes memory bs, Data memory r, uint[4] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (ExistenceProof.Data memory x, uint256 sz) = _decode_ExistenceProof(p, bs); if (isNil(r)) { counters[3] += 1; } else { r.right = x; if (counters[3] > 0) counters[3] -= 1; } return sz; } // struct decoder /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_ExistenceProof(uint256 p, bytes memory bs) internal pure returns (ExistenceProof.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (ExistenceProof.Data memory r, ) = ExistenceProof._decode(pointer, bs, sz); return (r, sz + bytesRead); } // Encoder section /** * @dev The main encoder for memory * @param r The struct to be encoded * @return The encoded byte array */ function encode(Data memory r) internal pure returns (bytes memory) { bytes memory bs = new bytes(_estimate(r)); uint256 sz = _encode(r, 32, bs); assembly { mstore(bs, sz) } return bs; } // inner encoder /** * @dev The encoder for internal usage * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { uint256 offset = p; uint256 pointer = p; if (r.key.length != 0) { pointer += ProtoBufRuntime._encode_key( 1, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_bytes(r.key, pointer, bs); } pointer += ProtoBufRuntime._encode_key( 2, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ExistenceProof._encode_nested(r.left, pointer, bs); pointer += ProtoBufRuntime._encode_key( 3, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ExistenceProof._encode_nested(r.right, pointer, bs); return pointer - offset; } // nested encoder /** * @dev The encoder for inner struct * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode_nested(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { /** * First encoded `r` into a temporary array, and encode the actual size used. * Then copy the temporary array into `bs`. */ uint256 offset = p; uint256 pointer = p; bytes memory tmp = new bytes(_estimate(r)); uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp); uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs); uint256 size = _encode(r, 32, tmp); pointer += ProtoBufRuntime._encode_varint(size, pointer, bs); ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size); pointer += size; delete tmp; return pointer - offset; } // estimator /** * @dev The estimator for a struct * @param r The struct to be encoded * @return The number of bytes encoded in estimation */ function _estimate( Data memory r ) internal pure returns (uint) { uint256 e; e += 1 + ProtoBufRuntime._sz_lendelim(r.key.length); e += 1 + ProtoBufRuntime._sz_lendelim(ExistenceProof._estimate(r.left)); e += 1 + ProtoBufRuntime._sz_lendelim(ExistenceProof._estimate(r.right)); return e; } // empty checker function _empty( Data memory r ) internal pure returns (bool) { if (r.key.length != 0) { return false; } return true; } //store function /** * @dev Store in-memory struct to storage * @param input The in-memory struct * @param output The in-storage struct */ function store(Data memory input, Data storage output) internal { output.key = input.key; ExistenceProof.store(input.left, output.left); ExistenceProof.store(input.right, output.right); } //utility functions /** * @dev Return an empty struct * @return r The empty struct */ function nil() internal pure returns (Data memory r) { assembly { r := 0 } } /** * @dev Test whether a struct is empty * @param x The struct to be tested * @return r True if it is empty */ function isNil(Data memory x) internal pure returns (bool r) { assembly { r := iszero(x) } } } //library NonExistenceProof library CommitmentProof { //struct definition struct Data { ExistenceProof.Data exist; NonExistenceProof.Data nonexist; BatchProof.Data batch; CompressedBatchProof.Data compressed; } // Decoder section /** * @dev The main decoder for memory * @param bs The bytes array to be decoded * @return The decoded struct */ function decode(bytes memory bs) internal pure returns (Data memory) { (Data memory x, ) = _decode(32, bs, bs.length); return x; } /** * @dev The main decoder for storage * @param self The in-storage struct * @param bs The bytes array to be decoded */ function decode(Data storage self, bytes memory bs) internal { (Data memory x, ) = _decode(32, bs, bs.length); store(x, self); } // inner decoder /** * @dev The decoder for internal usage * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param sz The number of bytes expected * @return The decoded struct * @return The number of bytes decoded */ function _decode(uint256 p, bytes memory bs, uint256 sz) internal pure returns (Data memory, uint) { Data memory r; uint[5] memory counters; uint256 fieldId; ProtoBufRuntime.WireType wireType; uint256 bytesRead; uint256 offset = p; uint256 pointer = p; while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_exist(pointer, bs, r, counters); } else if (fieldId == 2) { pointer += _read_nonexist(pointer, bs, r, counters); } else if (fieldId == 3) { pointer += _read_batch(pointer, bs, r, counters); } else if (fieldId == 4) { pointer += _read_compressed(pointer, bs, r, counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } return (r, sz); } // field readers /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_exist( uint256 p, bytes memory bs, Data memory r, uint[5] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (ExistenceProof.Data memory x, uint256 sz) = _decode_ExistenceProof(p, bs); if (isNil(r)) { counters[1] += 1; } else { r.exist = x; if (counters[1] > 0) counters[1] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_nonexist( uint256 p, bytes memory bs, Data memory r, uint[5] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (NonExistenceProof.Data memory x, uint256 sz) = _decode_NonExistenceProof(p, bs); if (isNil(r)) { counters[2] += 1; } else { r.nonexist = x; if (counters[2] > 0) counters[2] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_batch( uint256 p, bytes memory bs, Data memory r, uint[5] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (BatchProof.Data memory x, uint256 sz) = _decode_BatchProof(p, bs); if (isNil(r)) { counters[3] += 1; } else { r.batch = x; if (counters[3] > 0) counters[3] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_compressed( uint256 p, bytes memory bs, Data memory r, uint[5] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (CompressedBatchProof.Data memory x, uint256 sz) = _decode_CompressedBatchProof(p, bs); if (isNil(r)) { counters[4] += 1; } else { r.compressed = x; if (counters[4] > 0) counters[4] -= 1; } return sz; } // struct decoder /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_ExistenceProof(uint256 p, bytes memory bs) internal pure returns (ExistenceProof.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (ExistenceProof.Data memory r, ) = ExistenceProof._decode(pointer, bs, sz); return (r, sz + bytesRead); } /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_NonExistenceProof(uint256 p, bytes memory bs) internal pure returns (NonExistenceProof.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (NonExistenceProof.Data memory r, ) = NonExistenceProof._decode(pointer, bs, sz); return (r, sz + bytesRead); } /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_BatchProof(uint256 p, bytes memory bs) internal pure returns (BatchProof.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (BatchProof.Data memory r, ) = BatchProof._decode(pointer, bs, sz); return (r, sz + bytesRead); } /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_CompressedBatchProof(uint256 p, bytes memory bs) internal pure returns (CompressedBatchProof.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (CompressedBatchProof.Data memory r, ) = CompressedBatchProof._decode(pointer, bs, sz); return (r, sz + bytesRead); } // Encoder section /** * @dev The main encoder for memory * @param r The struct to be encoded * @return The encoded byte array */ function encode(Data memory r) internal pure returns (bytes memory) { bytes memory bs = new bytes(_estimate(r)); uint256 sz = _encode(r, 32, bs); assembly { mstore(bs, sz) } return bs; } // inner encoder /** * @dev The encoder for internal usage * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { uint256 offset = p; uint256 pointer = p; pointer += ProtoBufRuntime._encode_key( 1, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ExistenceProof._encode_nested(r.exist, pointer, bs); pointer += ProtoBufRuntime._encode_key( 2, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += NonExistenceProof._encode_nested(r.nonexist, pointer, bs); pointer += ProtoBufRuntime._encode_key( 3, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += BatchProof._encode_nested(r.batch, pointer, bs); pointer += ProtoBufRuntime._encode_key( 4, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += CompressedBatchProof._encode_nested(r.compressed, pointer, bs); return pointer - offset; } // nested encoder /** * @dev The encoder for inner struct * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode_nested(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { /** * First encoded `r` into a temporary array, and encode the actual size used. * Then copy the temporary array into `bs`. */ uint256 offset = p; uint256 pointer = p; bytes memory tmp = new bytes(_estimate(r)); uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp); uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs); uint256 size = _encode(r, 32, tmp); pointer += ProtoBufRuntime._encode_varint(size, pointer, bs); ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size); pointer += size; delete tmp; return pointer - offset; } // estimator /** * @dev The estimator for a struct * @param r The struct to be encoded * @return The number of bytes encoded in estimation */ function _estimate( Data memory r ) internal pure returns (uint) { uint256 e; e += 1 + ProtoBufRuntime._sz_lendelim(ExistenceProof._estimate(r.exist)); e += 1 + ProtoBufRuntime._sz_lendelim(NonExistenceProof._estimate(r.nonexist)); e += 1 + ProtoBufRuntime._sz_lendelim(BatchProof._estimate(r.batch)); e += 1 + ProtoBufRuntime._sz_lendelim(CompressedBatchProof._estimate(r.compressed)); return e; } // empty checker function _empty( Data memory r ) internal pure returns (bool) { return true; } //store function /** * @dev Store in-memory struct to storage * @param input The in-memory struct * @param output The in-storage struct */ function store(Data memory input, Data storage output) internal { ExistenceProof.store(input.exist, output.exist); NonExistenceProof.store(input.nonexist, output.nonexist); BatchProof.store(input.batch, output.batch); CompressedBatchProof.store(input.compressed, output.compressed); } //utility functions /** * @dev Return an empty struct * @return r The empty struct */ function nil() internal pure returns (Data memory r) { assembly { r := 0 } } /** * @dev Test whether a struct is empty * @param x The struct to be tested * @return r True if it is empty */ function isNil(Data memory x) internal pure returns (bool r) { assembly { r := iszero(x) } } } //library CommitmentProof library LeafOp { //struct definition struct Data { PROOFS_PROTO_GLOBAL_ENUMS.HashOp hash; PROOFS_PROTO_GLOBAL_ENUMS.HashOp prehash_key; PROOFS_PROTO_GLOBAL_ENUMS.HashOp prehash_value; PROOFS_PROTO_GLOBAL_ENUMS.LengthOp length; bytes prefix; } // Decoder section /** * @dev The main decoder for memory * @param bs The bytes array to be decoded * @return The decoded struct */ function decode(bytes memory bs) internal pure returns (Data memory) { (Data memory x, ) = _decode(32, bs, bs.length); return x; } /** * @dev The main decoder for storage * @param self The in-storage struct * @param bs The bytes array to be decoded */ function decode(Data storage self, bytes memory bs) internal { (Data memory x, ) = _decode(32, bs, bs.length); store(x, self); } // inner decoder /** * @dev The decoder for internal usage * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param sz The number of bytes expected * @return The decoded struct * @return The number of bytes decoded */ function _decode(uint256 p, bytes memory bs, uint256 sz) internal pure returns (Data memory, uint) { Data memory r; uint[6] memory counters; uint256 fieldId; ProtoBufRuntime.WireType wireType; uint256 bytesRead; uint256 offset = p; uint256 pointer = p; while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_hash(pointer, bs, r, counters); } else if (fieldId == 2) { pointer += _read_prehash_key(pointer, bs, r, counters); } else if (fieldId == 3) { pointer += _read_prehash_value(pointer, bs, r, counters); } else if (fieldId == 4) { pointer += _read_length(pointer, bs, r, counters); } else if (fieldId == 5) { pointer += _read_prefix(pointer, bs, r, counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } return (r, sz); } // field readers /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_hash( uint256 p, bytes memory bs, Data memory r, uint[6] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (int64 tmp, uint256 sz) = ProtoBufRuntime._decode_enum(p, bs); PROOFS_PROTO_GLOBAL_ENUMS.HashOp x = PROOFS_PROTO_GLOBAL_ENUMS.decode_HashOp(tmp); if (isNil(r)) { counters[1] += 1; } else { r.hash = x; if(counters[1] > 0) counters[1] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_prehash_key( uint256 p, bytes memory bs, Data memory r, uint[6] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (int64 tmp, uint256 sz) = ProtoBufRuntime._decode_enum(p, bs); PROOFS_PROTO_GLOBAL_ENUMS.HashOp x = PROOFS_PROTO_GLOBAL_ENUMS.decode_HashOp(tmp); if (isNil(r)) { counters[2] += 1; } else { r.prehash_key = x; if(counters[2] > 0) counters[2] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_prehash_value( uint256 p, bytes memory bs, Data memory r, uint[6] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (int64 tmp, uint256 sz) = ProtoBufRuntime._decode_enum(p, bs); PROOFS_PROTO_GLOBAL_ENUMS.HashOp x = PROOFS_PROTO_GLOBAL_ENUMS.decode_HashOp(tmp); if (isNil(r)) { counters[3] += 1; } else { r.prehash_value = x; if(counters[3] > 0) counters[3] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_length( uint256 p, bytes memory bs, Data memory r, uint[6] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (int64 tmp, uint256 sz) = ProtoBufRuntime._decode_enum(p, bs); PROOFS_PROTO_GLOBAL_ENUMS.LengthOp x = PROOFS_PROTO_GLOBAL_ENUMS.decode_LengthOp(tmp); if (isNil(r)) { counters[4] += 1; } else { r.length = x; if(counters[4] > 0) counters[4] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_prefix( uint256 p, bytes memory bs, Data memory r, uint[6] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs); if (isNil(r)) { counters[5] += 1; } else { r.prefix = x; if (counters[5] > 0) counters[5] -= 1; } return sz; } // Encoder section /** * @dev The main encoder for memory * @param r The struct to be encoded * @return The encoded byte array */ function encode(Data memory r) internal pure returns (bytes memory) { bytes memory bs = new bytes(_estimate(r)); uint256 sz = _encode(r, 32, bs); assembly { mstore(bs, sz) } return bs; } // inner encoder /** * @dev The encoder for internal usage * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { uint256 offset = p; uint256 pointer = p; if (uint(r.hash) != 0) { pointer += ProtoBufRuntime._encode_key( 1, ProtoBufRuntime.WireType.Varint, pointer, bs ); int32 _enum_hash = PROOFS_PROTO_GLOBAL_ENUMS.encode_HashOp(r.hash); pointer += ProtoBufRuntime._encode_enum(_enum_hash, pointer, bs); } if (uint(r.prehash_key) != 0) { pointer += ProtoBufRuntime._encode_key( 2, ProtoBufRuntime.WireType.Varint, pointer, bs ); int32 _enum_prehash_key = PROOFS_PROTO_GLOBAL_ENUMS.encode_HashOp(r.prehash_key); pointer += ProtoBufRuntime._encode_enum(_enum_prehash_key, pointer, bs); } if (uint(r.prehash_value) != 0) { pointer += ProtoBufRuntime._encode_key( 3, ProtoBufRuntime.WireType.Varint, pointer, bs ); int32 _enum_prehash_value = PROOFS_PROTO_GLOBAL_ENUMS.encode_HashOp(r.prehash_value); pointer += ProtoBufRuntime._encode_enum(_enum_prehash_value, pointer, bs); } if (uint(r.length) != 0) { pointer += ProtoBufRuntime._encode_key( 4, ProtoBufRuntime.WireType.Varint, pointer, bs ); int32 _enum_length = PROOFS_PROTO_GLOBAL_ENUMS.encode_LengthOp(r.length); pointer += ProtoBufRuntime._encode_enum(_enum_length, pointer, bs); } if (r.prefix.length != 0) { pointer += ProtoBufRuntime._encode_key( 5, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_bytes(r.prefix, pointer, bs); } return pointer - offset; } // nested encoder /** * @dev The encoder for inner struct * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode_nested(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { /** * First encoded `r` into a temporary array, and encode the actual size used. * Then copy the temporary array into `bs`. */ uint256 offset = p; uint256 pointer = p; bytes memory tmp = new bytes(_estimate(r)); uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp); uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs); uint256 size = _encode(r, 32, tmp); pointer += ProtoBufRuntime._encode_varint(size, pointer, bs); ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size); pointer += size; delete tmp; return pointer - offset; } // estimator /** * @dev The estimator for a struct * @param r The struct to be encoded * @return The number of bytes encoded in estimation */ function _estimate( Data memory r ) internal pure returns (uint) { uint256 e; e += 1 + ProtoBufRuntime._sz_enum(PROOFS_PROTO_GLOBAL_ENUMS.encode_HashOp(r.hash)); e += 1 + ProtoBufRuntime._sz_enum(PROOFS_PROTO_GLOBAL_ENUMS.encode_HashOp(r.prehash_key)); e += 1 + ProtoBufRuntime._sz_enum(PROOFS_PROTO_GLOBAL_ENUMS.encode_HashOp(r.prehash_value)); e += 1 + ProtoBufRuntime._sz_enum(PROOFS_PROTO_GLOBAL_ENUMS.encode_LengthOp(r.length)); e += 1 + ProtoBufRuntime._sz_lendelim(r.prefix.length); return e; } // empty checker function _empty( Data memory r ) internal pure returns (bool) { if (uint(r.hash) != 0) { return false; } if (uint(r.prehash_key) != 0) { return false; } if (uint(r.prehash_value) != 0) { return false; } if (uint(r.length) != 0) { return false; } if (r.prefix.length != 0) { return false; } return true; } //store function /** * @dev Store in-memory struct to storage * @param input The in-memory struct * @param output The in-storage struct */ function store(Data memory input, Data storage output) internal { output.hash = input.hash; output.prehash_key = input.prehash_key; output.prehash_value = input.prehash_value; output.length = input.length; output.prefix = input.prefix; } //utility functions /** * @dev Return an empty struct * @return r The empty struct */ function nil() internal pure returns (Data memory r) { assembly { r := 0 } } /** * @dev Test whether a struct is empty * @param x The struct to be tested * @return r True if it is empty */ function isNil(Data memory x) internal pure returns (bool r) { assembly { r := iszero(x) } } } //library LeafOp library InnerOp { //struct definition struct Data { PROOFS_PROTO_GLOBAL_ENUMS.HashOp hash; bytes prefix; bytes suffix; } // Decoder section /** * @dev The main decoder for memory * @param bs The bytes array to be decoded * @return The decoded struct */ function decode(bytes memory bs) internal pure returns (Data memory) { (Data memory x, ) = _decode(32, bs, bs.length); return x; } /** * @dev The main decoder for storage * @param self The in-storage struct * @param bs The bytes array to be decoded */ function decode(Data storage self, bytes memory bs) internal { (Data memory x, ) = _decode(32, bs, bs.length); store(x, self); } // inner decoder /** * @dev The decoder for internal usage * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param sz The number of bytes expected * @return The decoded struct * @return The number of bytes decoded */ function _decode(uint256 p, bytes memory bs, uint256 sz) internal pure returns (Data memory, uint) { Data memory r; uint[4] memory counters; uint256 fieldId; ProtoBufRuntime.WireType wireType; uint256 bytesRead; uint256 offset = p; uint256 pointer = p; while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_hash(pointer, bs, r, counters); } else if (fieldId == 2) { pointer += _read_prefix(pointer, bs, r, counters); } else if (fieldId == 3) { pointer += _read_suffix(pointer, bs, r, counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } return (r, sz); } // field readers /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_hash( uint256 p, bytes memory bs, Data memory r, uint[4] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (int64 tmp, uint256 sz) = ProtoBufRuntime._decode_enum(p, bs); PROOFS_PROTO_GLOBAL_ENUMS.HashOp x = PROOFS_PROTO_GLOBAL_ENUMS.decode_HashOp(tmp); if (isNil(r)) { counters[1] += 1; } else { r.hash = x; if(counters[1] > 0) counters[1] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_prefix( uint256 p, bytes memory bs, Data memory r, uint[4] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs); if (isNil(r)) { counters[2] += 1; } else { r.prefix = x; if (counters[2] > 0) counters[2] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_suffix( uint256 p, bytes memory bs, Data memory r, uint[4] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs); if (isNil(r)) { counters[3] += 1; } else { r.suffix = x; if (counters[3] > 0) counters[3] -= 1; } return sz; } // Encoder section /** * @dev The main encoder for memory * @param r The struct to be encoded * @return The encoded byte array */ function encode(Data memory r) internal pure returns (bytes memory) { bytes memory bs = new bytes(_estimate(r)); uint256 sz = _encode(r, 32, bs); assembly { mstore(bs, sz) } return bs; } // inner encoder /** * @dev The encoder for internal usage * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { uint256 offset = p; uint256 pointer = p; if (uint(r.hash) != 0) { pointer += ProtoBufRuntime._encode_key( 1, ProtoBufRuntime.WireType.Varint, pointer, bs ); int32 _enum_hash = PROOFS_PROTO_GLOBAL_ENUMS.encode_HashOp(r.hash); pointer += ProtoBufRuntime._encode_enum(_enum_hash, pointer, bs); } if (r.prefix.length != 0) { pointer += ProtoBufRuntime._encode_key( 2, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_bytes(r.prefix, pointer, bs); } if (r.suffix.length != 0) { pointer += ProtoBufRuntime._encode_key( 3, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_bytes(r.suffix, pointer, bs); } return pointer - offset; } // nested encoder /** * @dev The encoder for inner struct * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode_nested(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { /** * First encoded `r` into a temporary array, and encode the actual size used. * Then copy the temporary array into `bs`. */ uint256 offset = p; uint256 pointer = p; bytes memory tmp = new bytes(_estimate(r)); uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp); uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs); uint256 size = _encode(r, 32, tmp); pointer += ProtoBufRuntime._encode_varint(size, pointer, bs); ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size); pointer += size; delete tmp; return pointer - offset; } // estimator /** * @dev The estimator for a struct * @param r The struct to be encoded * @return The number of bytes encoded in estimation */ function _estimate( Data memory r ) internal pure returns (uint) { uint256 e; e += 1 + ProtoBufRuntime._sz_enum(PROOFS_PROTO_GLOBAL_ENUMS.encode_HashOp(r.hash)); e += 1 + ProtoBufRuntime._sz_lendelim(r.prefix.length); e += 1 + ProtoBufRuntime._sz_lendelim(r.suffix.length); return e; } // empty checker function _empty( Data memory r ) internal pure returns (bool) { if (uint(r.hash) != 0) { return false; } if (r.prefix.length != 0) { return false; } if (r.suffix.length != 0) { return false; } return true; } //store function /** * @dev Store in-memory struct to storage * @param input The in-memory struct * @param output The in-storage struct */ function store(Data memory input, Data storage output) internal { output.hash = input.hash; output.prefix = input.prefix; output.suffix = input.suffix; } //utility functions /** * @dev Return an empty struct * @return r The empty struct */ function nil() internal pure returns (Data memory r) { assembly { r := 0 } } /** * @dev Test whether a struct is empty * @param x The struct to be tested * @return r True if it is empty */ function isNil(Data memory x) internal pure returns (bool r) { assembly { r := iszero(x) } } } //library InnerOp library ProofSpec { //struct definition struct Data { LeafOp.Data leaf_spec; InnerSpec.Data inner_spec; int32 max_depth; int32 min_depth; } // Decoder section /** * @dev The main decoder for memory * @param bs The bytes array to be decoded * @return The decoded struct */ function decode(bytes memory bs) internal pure returns (Data memory) { (Data memory x, ) = _decode(32, bs, bs.length); return x; } /** * @dev The main decoder for storage * @param self The in-storage struct * @param bs The bytes array to be decoded */ function decode(Data storage self, bytes memory bs) internal { (Data memory x, ) = _decode(32, bs, bs.length); store(x, self); } // inner decoder /** * @dev The decoder for internal usage * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param sz The number of bytes expected * @return The decoded struct * @return The number of bytes decoded */ function _decode(uint256 p, bytes memory bs, uint256 sz) internal pure returns (Data memory, uint) { Data memory r; uint[5] memory counters; uint256 fieldId; ProtoBufRuntime.WireType wireType; uint256 bytesRead; uint256 offset = p; uint256 pointer = p; while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_leaf_spec(pointer, bs, r, counters); } else if (fieldId == 2) { pointer += _read_inner_spec(pointer, bs, r, counters); } else if (fieldId == 3) { pointer += _read_max_depth(pointer, bs, r, counters); } else if (fieldId == 4) { pointer += _read_min_depth(pointer, bs, r, counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } return (r, sz); } // field readers /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_leaf_spec( uint256 p, bytes memory bs, Data memory r, uint[5] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (LeafOp.Data memory x, uint256 sz) = _decode_LeafOp(p, bs); if (isNil(r)) { counters[1] += 1; } else { r.leaf_spec = x; if (counters[1] > 0) counters[1] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_inner_spec( uint256 p, bytes memory bs, Data memory r, uint[5] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (InnerSpec.Data memory x, uint256 sz) = _decode_InnerSpec(p, bs); if (isNil(r)) { counters[2] += 1; } else { r.inner_spec = x; if (counters[2] > 0) counters[2] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_max_depth( uint256 p, bytes memory bs, Data memory r, uint[5] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (int32 x, uint256 sz) = ProtoBufRuntime._decode_int32(p, bs); if (isNil(r)) { counters[3] += 1; } else { r.max_depth = x; if (counters[3] > 0) counters[3] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_min_depth( uint256 p, bytes memory bs, Data memory r, uint[5] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (int32 x, uint256 sz) = ProtoBufRuntime._decode_int32(p, bs); if (isNil(r)) { counters[4] += 1; } else { r.min_depth = x; if (counters[4] > 0) counters[4] -= 1; } return sz; } // struct decoder /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_LeafOp(uint256 p, bytes memory bs) internal pure returns (LeafOp.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (LeafOp.Data memory r, ) = LeafOp._decode(pointer, bs, sz); return (r, sz + bytesRead); } /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_InnerSpec(uint256 p, bytes memory bs) internal pure returns (InnerSpec.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (InnerSpec.Data memory r, ) = InnerSpec._decode(pointer, bs, sz); return (r, sz + bytesRead); } // Encoder section /** * @dev The main encoder for memory * @param r The struct to be encoded * @return The encoded byte array */ function encode(Data memory r) internal pure returns (bytes memory) { bytes memory bs = new bytes(_estimate(r)); uint256 sz = _encode(r, 32, bs); assembly { mstore(bs, sz) } return bs; } // inner encoder /** * @dev The encoder for internal usage * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { uint256 offset = p; uint256 pointer = p; pointer += ProtoBufRuntime._encode_key( 1, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += LeafOp._encode_nested(r.leaf_spec, pointer, bs); pointer += ProtoBufRuntime._encode_key( 2, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += InnerSpec._encode_nested(r.inner_spec, pointer, bs); if (r.max_depth != 0) { pointer += ProtoBufRuntime._encode_key( 3, ProtoBufRuntime.WireType.Varint, pointer, bs ); pointer += ProtoBufRuntime._encode_int32(r.max_depth, pointer, bs); } if (r.min_depth != 0) { pointer += ProtoBufRuntime._encode_key( 4, ProtoBufRuntime.WireType.Varint, pointer, bs ); pointer += ProtoBufRuntime._encode_int32(r.min_depth, pointer, bs); } return pointer - offset; } // nested encoder /** * @dev The encoder for inner struct * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode_nested(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { /** * First encoded `r` into a temporary array, and encode the actual size used. * Then copy the temporary array into `bs`. */ uint256 offset = p; uint256 pointer = p; bytes memory tmp = new bytes(_estimate(r)); uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp); uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs); uint256 size = _encode(r, 32, tmp); pointer += ProtoBufRuntime._encode_varint(size, pointer, bs); ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size); pointer += size; delete tmp; return pointer - offset; } // estimator /** * @dev The estimator for a struct * @param r The struct to be encoded * @return The number of bytes encoded in estimation */ function _estimate( Data memory r ) internal pure returns (uint) { uint256 e; e += 1 + ProtoBufRuntime._sz_lendelim(LeafOp._estimate(r.leaf_spec)); e += 1 + ProtoBufRuntime._sz_lendelim(InnerSpec._estimate(r.inner_spec)); e += 1 + ProtoBufRuntime._sz_int32(r.max_depth); e += 1 + ProtoBufRuntime._sz_int32(r.min_depth); return e; } // empty checker function _empty( Data memory r ) internal pure returns (bool) { if (r.max_depth != 0) { return false; } if (r.min_depth != 0) { return false; } return true; } //store function /** * @dev Store in-memory struct to storage * @param input The in-memory struct * @param output The in-storage struct */ function store(Data memory input, Data storage output) internal { LeafOp.store(input.leaf_spec, output.leaf_spec); InnerSpec.store(input.inner_spec, output.inner_spec); output.max_depth = input.max_depth; output.min_depth = input.min_depth; } //utility functions /** * @dev Return an empty struct * @return r The empty struct */ function nil() internal pure returns (Data memory r) { assembly { r := 0 } } /** * @dev Test whether a struct is empty * @param x The struct to be tested * @return r True if it is empty */ function isNil(Data memory x) internal pure returns (bool r) { assembly { r := iszero(x) } } } //library ProofSpec library InnerSpec { //struct definition struct Data { int32[] child_order; int32 child_size; int32 min_prefix_length; int32 max_prefix_length; bytes empty_child; PROOFS_PROTO_GLOBAL_ENUMS.HashOp hash; } // Decoder section /** * @dev The main decoder for memory * @param bs The bytes array to be decoded * @return The decoded struct */ function decode(bytes memory bs) internal pure returns (Data memory) { (Data memory x, ) = _decode(32, bs, bs.length); return x; } /** * @dev The main decoder for storage * @param self The in-storage struct * @param bs The bytes array to be decoded */ function decode(Data storage self, bytes memory bs) internal { (Data memory x, ) = _decode(32, bs, bs.length); store(x, self); } // inner decoder /** * @dev The decoder for internal usage * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param sz The number of bytes expected * @return The decoded struct * @return The number of bytes decoded */ function _decode(uint256 p, bytes memory bs, uint256 sz) internal pure returns (Data memory, uint) { Data memory r; uint[7] memory counters; uint256 fieldId; ProtoBufRuntime.WireType wireType; uint256 bytesRead; uint256 offset = p; uint256 pointer = p; while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_child_order(pointer, bs, nil(), counters); } else if (fieldId == 2) { pointer += _read_child_size(pointer, bs, r, counters); } else if (fieldId == 3) { pointer += _read_min_prefix_length(pointer, bs, r, counters); } else if (fieldId == 4) { pointer += _read_max_prefix_length(pointer, bs, r, counters); } else if (fieldId == 5) { pointer += _read_empty_child(pointer, bs, r, counters); } else if (fieldId == 6) { pointer += _read_hash(pointer, bs, r, counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } pointer = offset; r.child_order = new int32[](counters[1]); while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_child_order(pointer, bs, r, counters); } else if (fieldId == 2) { pointer += _read_child_size(pointer, bs, nil(), counters); } else if (fieldId == 3) { pointer += _read_min_prefix_length(pointer, bs, nil(), counters); } else if (fieldId == 4) { pointer += _read_max_prefix_length(pointer, bs, nil(), counters); } else if (fieldId == 5) { pointer += _read_empty_child(pointer, bs, nil(), counters); } else if (fieldId == 6) { pointer += _read_hash(pointer, bs, nil(), counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } return (r, sz); } // field readers /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_child_order( uint256 p, bytes memory bs, Data memory r, uint[7] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (int32 x, uint256 sz) = ProtoBufRuntime._decode_int32(p, bs); if (isNil(r)) { counters[1] += 1; } else { r.child_order[r.child_order.length - counters[1]] = x; if (counters[1] > 0) counters[1] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_child_size( uint256 p, bytes memory bs, Data memory r, uint[7] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (int32 x, uint256 sz) = ProtoBufRuntime._decode_int32(p, bs); if (isNil(r)) { counters[2] += 1; } else { r.child_size = x; if (counters[2] > 0) counters[2] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_min_prefix_length( uint256 p, bytes memory bs, Data memory r, uint[7] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (int32 x, uint256 sz) = ProtoBufRuntime._decode_int32(p, bs); if (isNil(r)) { counters[3] += 1; } else { r.min_prefix_length = x; if (counters[3] > 0) counters[3] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_max_prefix_length( uint256 p, bytes memory bs, Data memory r, uint[7] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (int32 x, uint256 sz) = ProtoBufRuntime._decode_int32(p, bs); if (isNil(r)) { counters[4] += 1; } else { r.max_prefix_length = x; if (counters[4] > 0) counters[4] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_empty_child( uint256 p, bytes memory bs, Data memory r, uint[7] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs); if (isNil(r)) { counters[5] += 1; } else { r.empty_child = x; if (counters[5] > 0) counters[5] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_hash( uint256 p, bytes memory bs, Data memory r, uint[7] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (int64 tmp, uint256 sz) = ProtoBufRuntime._decode_enum(p, bs); PROOFS_PROTO_GLOBAL_ENUMS.HashOp x = PROOFS_PROTO_GLOBAL_ENUMS.decode_HashOp(tmp); if (isNil(r)) { counters[6] += 1; } else { r.hash = x; if(counters[6] > 0) counters[6] -= 1; } return sz; } // Encoder section /** * @dev The main encoder for memory * @param r The struct to be encoded * @return The encoded byte array */ function encode(Data memory r) internal pure returns (bytes memory) { bytes memory bs = new bytes(_estimate(r)); uint256 sz = _encode(r, 32, bs); assembly { mstore(bs, sz) } return bs; } // inner encoder /** * @dev The encoder for internal usage * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { uint256 offset = p; uint256 pointer = p; uint256 i; if (r.child_order.length != 0) { for(i = 0; i < r.child_order.length; i++) { pointer += ProtoBufRuntime._encode_key( 1, ProtoBufRuntime.WireType.Varint, pointer, bs) ; pointer += ProtoBufRuntime._encode_int32(r.child_order[i], pointer, bs); } } if (r.child_size != 0) { pointer += ProtoBufRuntime._encode_key( 2, ProtoBufRuntime.WireType.Varint, pointer, bs ); pointer += ProtoBufRuntime._encode_int32(r.child_size, pointer, bs); } if (r.min_prefix_length != 0) { pointer += ProtoBufRuntime._encode_key( 3, ProtoBufRuntime.WireType.Varint, pointer, bs ); pointer += ProtoBufRuntime._encode_int32(r.min_prefix_length, pointer, bs); } if (r.max_prefix_length != 0) { pointer += ProtoBufRuntime._encode_key( 4, ProtoBufRuntime.WireType.Varint, pointer, bs ); pointer += ProtoBufRuntime._encode_int32(r.max_prefix_length, pointer, bs); } if (r.empty_child.length != 0) { pointer += ProtoBufRuntime._encode_key( 5, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_bytes(r.empty_child, pointer, bs); } if (uint(r.hash) != 0) { pointer += ProtoBufRuntime._encode_key( 6, ProtoBufRuntime.WireType.Varint, pointer, bs ); int32 _enum_hash = PROOFS_PROTO_GLOBAL_ENUMS.encode_HashOp(r.hash); pointer += ProtoBufRuntime._encode_enum(_enum_hash, pointer, bs); } return pointer - offset; } // nested encoder /** * @dev The encoder for inner struct * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode_nested(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { /** * First encoded `r` into a temporary array, and encode the actual size used. * Then copy the temporary array into `bs`. */ uint256 offset = p; uint256 pointer = p; bytes memory tmp = new bytes(_estimate(r)); uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp); uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs); uint256 size = _encode(r, 32, tmp); pointer += ProtoBufRuntime._encode_varint(size, pointer, bs); ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size); pointer += size; delete tmp; return pointer - offset; } // estimator /** * @dev The estimator for a struct * @param r The struct to be encoded * @return The number of bytes encoded in estimation */ function _estimate( Data memory r ) internal pure returns (uint) { uint256 e;uint256 i; for(i = 0; i < r.child_order.length; i++) { e += 1 + ProtoBufRuntime._sz_int32(r.child_order[i]); } e += 1 + ProtoBufRuntime._sz_int32(r.child_size); e += 1 + ProtoBufRuntime._sz_int32(r.min_prefix_length); e += 1 + ProtoBufRuntime._sz_int32(r.max_prefix_length); e += 1 + ProtoBufRuntime._sz_lendelim(r.empty_child.length); e += 1 + ProtoBufRuntime._sz_enum(PROOFS_PROTO_GLOBAL_ENUMS.encode_HashOp(r.hash)); return e; } // empty checker function _empty( Data memory r ) internal pure returns (bool) { if (r.child_order.length != 0) { return false; } if (r.child_size != 0) { return false; } if (r.min_prefix_length != 0) { return false; } if (r.max_prefix_length != 0) { return false; } if (r.empty_child.length != 0) { return false; } if (uint(r.hash) != 0) { return false; } return true; } //store function /** * @dev Store in-memory struct to storage * @param input The in-memory struct * @param output The in-storage struct */ function store(Data memory input, Data storage output) internal { output.child_order = input.child_order; output.child_size = input.child_size; output.min_prefix_length = input.min_prefix_length; output.max_prefix_length = input.max_prefix_length; output.empty_child = input.empty_child; output.hash = input.hash; } //array helpers for ChildOrder /** * @dev Add value to an array * @param self The in-memory struct * @param value The value to add */ function addChildOrder(Data memory self, int32 value) internal pure { /** * First resize the array. Then add the new element to the end. */ int32[] memory tmp = new int32[](self.child_order.length + 1); for (uint256 i = 0; i < self.child_order.length; i++) { tmp[i] = self.child_order[i]; } tmp[self.child_order.length] = value; self.child_order = tmp; } //utility functions /** * @dev Return an empty struct * @return r The empty struct */ function nil() internal pure returns (Data memory r) { assembly { r := 0 } } /** * @dev Test whether a struct is empty * @param x The struct to be tested * @return r True if it is empty */ function isNil(Data memory x) internal pure returns (bool r) { assembly { r := iszero(x) } } } //library InnerSpec library BatchProof { //struct definition struct Data { BatchEntry.Data[] entries; } // Decoder section /** * @dev The main decoder for memory * @param bs The bytes array to be decoded * @return The decoded struct */ function decode(bytes memory bs) internal pure returns (Data memory) { (Data memory x, ) = _decode(32, bs, bs.length); return x; } /** * @dev The main decoder for storage * @param self The in-storage struct * @param bs The bytes array to be decoded */ function decode(Data storage self, bytes memory bs) internal { (Data memory x, ) = _decode(32, bs, bs.length); store(x, self); } // inner decoder /** * @dev The decoder for internal usage * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param sz The number of bytes expected * @return The decoded struct * @return The number of bytes decoded */ function _decode(uint256 p, bytes memory bs, uint256 sz) internal pure returns (Data memory, uint) { Data memory r; uint[2] memory counters; uint256 fieldId; ProtoBufRuntime.WireType wireType; uint256 bytesRead; uint256 offset = p; uint256 pointer = p; while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_entries(pointer, bs, nil(), counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } pointer = offset; r.entries = new BatchEntry.Data[](counters[1]); while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_entries(pointer, bs, r, counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } return (r, sz); } // field readers /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_entries( uint256 p, bytes memory bs, Data memory r, uint[2] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (BatchEntry.Data memory x, uint256 sz) = _decode_BatchEntry(p, bs); if (isNil(r)) { counters[1] += 1; } else { r.entries[r.entries.length - counters[1]] = x; if (counters[1] > 0) counters[1] -= 1; } return sz; } // struct decoder /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_BatchEntry(uint256 p, bytes memory bs) internal pure returns (BatchEntry.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (BatchEntry.Data memory r, ) = BatchEntry._decode(pointer, bs, sz); return (r, sz + bytesRead); } // Encoder section /** * @dev The main encoder for memory * @param r The struct to be encoded * @return The encoded byte array */ function encode(Data memory r) internal pure returns (bytes memory) { bytes memory bs = new bytes(_estimate(r)); uint256 sz = _encode(r, 32, bs); assembly { mstore(bs, sz) } return bs; } // inner encoder /** * @dev The encoder for internal usage * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { uint256 offset = p; uint256 pointer = p; uint256 i; if (r.entries.length != 0) { for(i = 0; i < r.entries.length; i++) { pointer += ProtoBufRuntime._encode_key( 1, ProtoBufRuntime.WireType.LengthDelim, pointer, bs) ; pointer += BatchEntry._encode_nested(r.entries[i], pointer, bs); } } return pointer - offset; } // nested encoder /** * @dev The encoder for inner struct * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode_nested(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { /** * First encoded `r` into a temporary array, and encode the actual size used. * Then copy the temporary array into `bs`. */ uint256 offset = p; uint256 pointer = p; bytes memory tmp = new bytes(_estimate(r)); uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp); uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs); uint256 size = _encode(r, 32, tmp); pointer += ProtoBufRuntime._encode_varint(size, pointer, bs); ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size); pointer += size; delete tmp; return pointer - offset; } // estimator /** * @dev The estimator for a struct * @param r The struct to be encoded * @return The number of bytes encoded in estimation */ function _estimate( Data memory r ) internal pure returns (uint) { uint256 e;uint256 i; for(i = 0; i < r.entries.length; i++) { e += 1 + ProtoBufRuntime._sz_lendelim(BatchEntry._estimate(r.entries[i])); } return e; } // empty checker function _empty( Data memory r ) internal pure returns (bool) { if (r.entries.length != 0) { return false; } return true; } //store function /** * @dev Store in-memory struct to storage * @param input The in-memory struct * @param output The in-storage struct */ function store(Data memory input, Data storage output) internal { for(uint256 i1 = 0; i1 < input.entries.length; i1++) { output.entries.push(input.entries[i1]); } } //array helpers for Entries /** * @dev Add value to an array * @param self The in-memory struct * @param value The value to add */ function addEntries(Data memory self, BatchEntry.Data memory value) internal pure { /** * First resize the array. Then add the new element to the end. */ BatchEntry.Data[] memory tmp = new BatchEntry.Data[](self.entries.length + 1); for (uint256 i = 0; i < self.entries.length; i++) { tmp[i] = self.entries[i]; } tmp[self.entries.length] = value; self.entries = tmp; } //utility functions /** * @dev Return an empty struct * @return r The empty struct */ function nil() internal pure returns (Data memory r) { assembly { r := 0 } } /** * @dev Test whether a struct is empty * @param x The struct to be tested * @return r True if it is empty */ function isNil(Data memory x) internal pure returns (bool r) { assembly { r := iszero(x) } } } //library BatchProof library BatchEntry { //struct definition struct Data { ExistenceProof.Data exist; NonExistenceProof.Data nonexist; } // Decoder section /** * @dev The main decoder for memory * @param bs The bytes array to be decoded * @return The decoded struct */ function decode(bytes memory bs) internal pure returns (Data memory) { (Data memory x, ) = _decode(32, bs, bs.length); return x; } /** * @dev The main decoder for storage * @param self The in-storage struct * @param bs The bytes array to be decoded */ function decode(Data storage self, bytes memory bs) internal { (Data memory x, ) = _decode(32, bs, bs.length); store(x, self); } // inner decoder /** * @dev The decoder for internal usage * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param sz The number of bytes expected * @return The decoded struct * @return The number of bytes decoded */ function _decode(uint256 p, bytes memory bs, uint256 sz) internal pure returns (Data memory, uint) { Data memory r; uint[3] memory counters; uint256 fieldId; ProtoBufRuntime.WireType wireType; uint256 bytesRead; uint256 offset = p; uint256 pointer = p; while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_exist(pointer, bs, r, counters); } else if (fieldId == 2) { pointer += _read_nonexist(pointer, bs, r, counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } return (r, sz); } // field readers /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_exist( uint256 p, bytes memory bs, Data memory r, uint[3] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (ExistenceProof.Data memory x, uint256 sz) = _decode_ExistenceProof(p, bs); if (isNil(r)) { counters[1] += 1; } else { r.exist = x; if (counters[1] > 0) counters[1] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_nonexist( uint256 p, bytes memory bs, Data memory r, uint[3] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (NonExistenceProof.Data memory x, uint256 sz) = _decode_NonExistenceProof(p, bs); if (isNil(r)) { counters[2] += 1; } else { r.nonexist = x; if (counters[2] > 0) counters[2] -= 1; } return sz; } // struct decoder /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_ExistenceProof(uint256 p, bytes memory bs) internal pure returns (ExistenceProof.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (ExistenceProof.Data memory r, ) = ExistenceProof._decode(pointer, bs, sz); return (r, sz + bytesRead); } /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_NonExistenceProof(uint256 p, bytes memory bs) internal pure returns (NonExistenceProof.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (NonExistenceProof.Data memory r, ) = NonExistenceProof._decode(pointer, bs, sz); return (r, sz + bytesRead); } // Encoder section /** * @dev The main encoder for memory * @param r The struct to be encoded * @return The encoded byte array */ function encode(Data memory r) internal pure returns (bytes memory) { bytes memory bs = new bytes(_estimate(r)); uint256 sz = _encode(r, 32, bs); assembly { mstore(bs, sz) } return bs; } // inner encoder /** * @dev The encoder for internal usage * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { uint256 offset = p; uint256 pointer = p; pointer += ProtoBufRuntime._encode_key( 1, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ExistenceProof._encode_nested(r.exist, pointer, bs); pointer += ProtoBufRuntime._encode_key( 2, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += NonExistenceProof._encode_nested(r.nonexist, pointer, bs); return pointer - offset; } // nested encoder /** * @dev The encoder for inner struct * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode_nested(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { /** * First encoded `r` into a temporary array, and encode the actual size used. * Then copy the temporary array into `bs`. */ uint256 offset = p; uint256 pointer = p; bytes memory tmp = new bytes(_estimate(r)); uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp); uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs); uint256 size = _encode(r, 32, tmp); pointer += ProtoBufRuntime._encode_varint(size, pointer, bs); ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size); pointer += size; delete tmp; return pointer - offset; } // estimator /** * @dev The estimator for a struct * @param r The struct to be encoded * @return The number of bytes encoded in estimation */ function _estimate( Data memory r ) internal pure returns (uint) { uint256 e; e += 1 + ProtoBufRuntime._sz_lendelim(ExistenceProof._estimate(r.exist)); e += 1 + ProtoBufRuntime._sz_lendelim(NonExistenceProof._estimate(r.nonexist)); return e; } // empty checker function _empty( Data memory r ) internal pure returns (bool) { return true; } //store function /** * @dev Store in-memory struct to storage * @param input The in-memory struct * @param output The in-storage struct */ function store(Data memory input, Data storage output) internal { ExistenceProof.store(input.exist, output.exist); NonExistenceProof.store(input.nonexist, output.nonexist); } //utility functions /** * @dev Return an empty struct * @return r The empty struct */ function nil() internal pure returns (Data memory r) { assembly { r := 0 } } /** * @dev Test whether a struct is empty * @param x The struct to be tested * @return r True if it is empty */ function isNil(Data memory x) internal pure returns (bool r) { assembly { r := iszero(x) } } } //library BatchEntry library CompressedBatchProof { //struct definition struct Data { CompressedBatchEntry.Data[] entries; InnerOp.Data[] lookup_inners; } // Decoder section /** * @dev The main decoder for memory * @param bs The bytes array to be decoded * @return The decoded struct */ function decode(bytes memory bs) internal pure returns (Data memory) { (Data memory x, ) = _decode(32, bs, bs.length); return x; } /** * @dev The main decoder for storage * @param self The in-storage struct * @param bs The bytes array to be decoded */ function decode(Data storage self, bytes memory bs) internal { (Data memory x, ) = _decode(32, bs, bs.length); store(x, self); } // inner decoder /** * @dev The decoder for internal usage * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param sz The number of bytes expected * @return The decoded struct * @return The number of bytes decoded */ function _decode(uint256 p, bytes memory bs, uint256 sz) internal pure returns (Data memory, uint) { Data memory r; uint[3] memory counters; uint256 fieldId; ProtoBufRuntime.WireType wireType; uint256 bytesRead; uint256 offset = p; uint256 pointer = p; while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_entries(pointer, bs, nil(), counters); } else if (fieldId == 2) { pointer += _read_lookup_inners(pointer, bs, nil(), counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } pointer = offset; r.entries = new CompressedBatchEntry.Data[](counters[1]); r.lookup_inners = new InnerOp.Data[](counters[2]); while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_entries(pointer, bs, r, counters); } else if (fieldId == 2) { pointer += _read_lookup_inners(pointer, bs, r, counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } return (r, sz); } // field readers /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_entries( uint256 p, bytes memory bs, Data memory r, uint[3] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (CompressedBatchEntry.Data memory x, uint256 sz) = _decode_CompressedBatchEntry(p, bs); if (isNil(r)) { counters[1] += 1; } else { r.entries[r.entries.length - counters[1]] = x; if (counters[1] > 0) counters[1] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_lookup_inners( uint256 p, bytes memory bs, Data memory r, uint[3] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (InnerOp.Data memory x, uint256 sz) = _decode_InnerOp(p, bs); if (isNil(r)) { counters[2] += 1; } else { r.lookup_inners[r.lookup_inners.length - counters[2]] = x; if (counters[2] > 0) counters[2] -= 1; } return sz; } // struct decoder /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_CompressedBatchEntry(uint256 p, bytes memory bs) internal pure returns (CompressedBatchEntry.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (CompressedBatchEntry.Data memory r, ) = CompressedBatchEntry._decode(pointer, bs, sz); return (r, sz + bytesRead); } /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_InnerOp(uint256 p, bytes memory bs) internal pure returns (InnerOp.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (InnerOp.Data memory r, ) = InnerOp._decode(pointer, bs, sz); return (r, sz + bytesRead); } // Encoder section /** * @dev The main encoder for memory * @param r The struct to be encoded * @return The encoded byte array */ function encode(Data memory r) internal pure returns (bytes memory) { bytes memory bs = new bytes(_estimate(r)); uint256 sz = _encode(r, 32, bs); assembly { mstore(bs, sz) } return bs; } // inner encoder /** * @dev The encoder for internal usage * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { uint256 offset = p; uint256 pointer = p; uint256 i; if (r.entries.length != 0) { for(i = 0; i < r.entries.length; i++) { pointer += ProtoBufRuntime._encode_key( 1, ProtoBufRuntime.WireType.LengthDelim, pointer, bs) ; pointer += CompressedBatchEntry._encode_nested(r.entries[i], pointer, bs); } } if (r.lookup_inners.length != 0) { for(i = 0; i < r.lookup_inners.length; i++) { pointer += ProtoBufRuntime._encode_key( 2, ProtoBufRuntime.WireType.LengthDelim, pointer, bs) ; pointer += InnerOp._encode_nested(r.lookup_inners[i], pointer, bs); } } return pointer - offset; } // nested encoder /** * @dev The encoder for inner struct * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode_nested(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { /** * First encoded `r` into a temporary array, and encode the actual size used. * Then copy the temporary array into `bs`. */ uint256 offset = p; uint256 pointer = p; bytes memory tmp = new bytes(_estimate(r)); uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp); uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs); uint256 size = _encode(r, 32, tmp); pointer += ProtoBufRuntime._encode_varint(size, pointer, bs); ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size); pointer += size; delete tmp; return pointer - offset; } // estimator /** * @dev The estimator for a struct * @param r The struct to be encoded * @return The number of bytes encoded in estimation */ function _estimate( Data memory r ) internal pure returns (uint) { uint256 e;uint256 i; for(i = 0; i < r.entries.length; i++) { e += 1 + ProtoBufRuntime._sz_lendelim(CompressedBatchEntry._estimate(r.entries[i])); } for(i = 0; i < r.lookup_inners.length; i++) { e += 1 + ProtoBufRuntime._sz_lendelim(InnerOp._estimate(r.lookup_inners[i])); } return e; } // empty checker function _empty( Data memory r ) internal pure returns (bool) { if (r.entries.length != 0) { return false; } if (r.lookup_inners.length != 0) { return false; } return true; } //store function /** * @dev Store in-memory struct to storage * @param input The in-memory struct * @param output The in-storage struct */ function store(Data memory input, Data storage output) internal { for(uint256 i1 = 0; i1 < input.entries.length; i1++) { output.entries.push(input.entries[i1]); } for(uint256 i2 = 0; i2 < input.lookup_inners.length; i2++) { output.lookup_inners.push(input.lookup_inners[i2]); } } //array helpers for Entries /** * @dev Add value to an array * @param self The in-memory struct * @param value The value to add */ function addEntries(Data memory self, CompressedBatchEntry.Data memory value) internal pure { /** * First resize the array. Then add the new element to the end. */ CompressedBatchEntry.Data[] memory tmp = new CompressedBatchEntry.Data[](self.entries.length + 1); for (uint256 i = 0; i < self.entries.length; i++) { tmp[i] = self.entries[i]; } tmp[self.entries.length] = value; self.entries = tmp; } //array helpers for LookupInners /** * @dev Add value to an array * @param self The in-memory struct * @param value The value to add */ function addLookupInners(Data memory self, InnerOp.Data memory value) internal pure { /** * First resize the array. Then add the new element to the end. */ InnerOp.Data[] memory tmp = new InnerOp.Data[](self.lookup_inners.length + 1); for (uint256 i = 0; i < self.lookup_inners.length; i++) { tmp[i] = self.lookup_inners[i]; } tmp[self.lookup_inners.length] = value; self.lookup_inners = tmp; } //utility functions /** * @dev Return an empty struct * @return r The empty struct */ function nil() internal pure returns (Data memory r) { assembly { r := 0 } } /** * @dev Test whether a struct is empty * @param x The struct to be tested * @return r True if it is empty */ function isNil(Data memory x) internal pure returns (bool r) { assembly { r := iszero(x) } } } //library CompressedBatchProof library CompressedBatchEntry { //struct definition struct Data { CompressedExistenceProof.Data exist; CompressedNonExistenceProof.Data nonexist; } // Decoder section /** * @dev The main decoder for memory * @param bs The bytes array to be decoded * @return The decoded struct */ function decode(bytes memory bs) internal pure returns (Data memory) { (Data memory x, ) = _decode(32, bs, bs.length); return x; } /** * @dev The main decoder for storage * @param self The in-storage struct * @param bs The bytes array to be decoded */ function decode(Data storage self, bytes memory bs) internal { (Data memory x, ) = _decode(32, bs, bs.length); store(x, self); } // inner decoder /** * @dev The decoder for internal usage * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param sz The number of bytes expected * @return The decoded struct * @return The number of bytes decoded */ function _decode(uint256 p, bytes memory bs, uint256 sz) internal pure returns (Data memory, uint) { Data memory r; uint[3] memory counters; uint256 fieldId; ProtoBufRuntime.WireType wireType; uint256 bytesRead; uint256 offset = p; uint256 pointer = p; while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_exist(pointer, bs, r, counters); } else if (fieldId == 2) { pointer += _read_nonexist(pointer, bs, r, counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } return (r, sz); } // field readers /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_exist( uint256 p, bytes memory bs, Data memory r, uint[3] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (CompressedExistenceProof.Data memory x, uint256 sz) = _decode_CompressedExistenceProof(p, bs); if (isNil(r)) { counters[1] += 1; } else { r.exist = x; if (counters[1] > 0) counters[1] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_nonexist( uint256 p, bytes memory bs, Data memory r, uint[3] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (CompressedNonExistenceProof.Data memory x, uint256 sz) = _decode_CompressedNonExistenceProof(p, bs); if (isNil(r)) { counters[2] += 1; } else { r.nonexist = x; if (counters[2] > 0) counters[2] -= 1; } return sz; } // struct decoder /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_CompressedExistenceProof(uint256 p, bytes memory bs) internal pure returns (CompressedExistenceProof.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (CompressedExistenceProof.Data memory r, ) = CompressedExistenceProof._decode(pointer, bs, sz); return (r, sz + bytesRead); } /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_CompressedNonExistenceProof(uint256 p, bytes memory bs) internal pure returns (CompressedNonExistenceProof.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (CompressedNonExistenceProof.Data memory r, ) = CompressedNonExistenceProof._decode(pointer, bs, sz); return (r, sz + bytesRead); } // Encoder section /** * @dev The main encoder for memory * @param r The struct to be encoded * @return The encoded byte array */ function encode(Data memory r) internal pure returns (bytes memory) { bytes memory bs = new bytes(_estimate(r)); uint256 sz = _encode(r, 32, bs); assembly { mstore(bs, sz) } return bs; } // inner encoder /** * @dev The encoder for internal usage * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { uint256 offset = p; uint256 pointer = p; pointer += ProtoBufRuntime._encode_key( 1, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += CompressedExistenceProof._encode_nested(r.exist, pointer, bs); pointer += ProtoBufRuntime._encode_key( 2, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += CompressedNonExistenceProof._encode_nested(r.nonexist, pointer, bs); return pointer - offset; } // nested encoder /** * @dev The encoder for inner struct * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode_nested(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { /** * First encoded `r` into a temporary array, and encode the actual size used. * Then copy the temporary array into `bs`. */ uint256 offset = p; uint256 pointer = p; bytes memory tmp = new bytes(_estimate(r)); uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp); uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs); uint256 size = _encode(r, 32, tmp); pointer += ProtoBufRuntime._encode_varint(size, pointer, bs); ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size); pointer += size; delete tmp; return pointer - offset; } // estimator /** * @dev The estimator for a struct * @param r The struct to be encoded * @return The number of bytes encoded in estimation */ function _estimate( Data memory r ) internal pure returns (uint) { uint256 e; e += 1 + ProtoBufRuntime._sz_lendelim(CompressedExistenceProof._estimate(r.exist)); e += 1 + ProtoBufRuntime._sz_lendelim(CompressedNonExistenceProof._estimate(r.nonexist)); return e; } // empty checker function _empty( Data memory r ) internal pure returns (bool) { return true; } //store function /** * @dev Store in-memory struct to storage * @param input The in-memory struct * @param output The in-storage struct */ function store(Data memory input, Data storage output) internal { CompressedExistenceProof.store(input.exist, output.exist); CompressedNonExistenceProof.store(input.nonexist, output.nonexist); } //utility functions /** * @dev Return an empty struct * @return r The empty struct */ function nil() internal pure returns (Data memory r) { assembly { r := 0 } } /** * @dev Test whether a struct is empty * @param x The struct to be tested * @return r True if it is empty */ function isNil(Data memory x) internal pure returns (bool r) { assembly { r := iszero(x) } } } //library CompressedBatchEntry library CompressedExistenceProof { //struct definition struct Data { bytes key; bytes value; LeafOp.Data leaf; int32[] path; } // Decoder section /** * @dev The main decoder for memory * @param bs The bytes array to be decoded * @return The decoded struct */ function decode(bytes memory bs) internal pure returns (Data memory) { (Data memory x, ) = _decode(32, bs, bs.length); return x; } /** * @dev The main decoder for storage * @param self The in-storage struct * @param bs The bytes array to be decoded */ function decode(Data storage self, bytes memory bs) internal { (Data memory x, ) = _decode(32, bs, bs.length); store(x, self); } // inner decoder /** * @dev The decoder for internal usage * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param sz The number of bytes expected * @return The decoded struct * @return The number of bytes decoded */ function _decode(uint256 p, bytes memory bs, uint256 sz) internal pure returns (Data memory, uint) { Data memory r; uint[5] memory counters; uint256 fieldId; ProtoBufRuntime.WireType wireType; uint256 bytesRead; uint256 offset = p; uint256 pointer = p; while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_key(pointer, bs, r, counters); } else if (fieldId == 2) { pointer += _read_value(pointer, bs, r, counters); } else if (fieldId == 3) { pointer += _read_leaf(pointer, bs, r, counters); } else if (fieldId == 4) { pointer += _read_path(pointer, bs, nil(), counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } pointer = offset; r.path = new int32[](counters[4]); while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_key(pointer, bs, nil(), counters); } else if (fieldId == 2) { pointer += _read_value(pointer, bs, nil(), counters); } else if (fieldId == 3) { pointer += _read_leaf(pointer, bs, nil(), counters); } else if (fieldId == 4) { pointer += _read_path(pointer, bs, r, counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } return (r, sz); } // field readers /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_key( uint256 p, bytes memory bs, Data memory r, uint[5] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs); if (isNil(r)) { counters[1] += 1; } else { r.key = x; if (counters[1] > 0) counters[1] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_value( uint256 p, bytes memory bs, Data memory r, uint[5] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs); if (isNil(r)) { counters[2] += 1; } else { r.value = x; if (counters[2] > 0) counters[2] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_leaf( uint256 p, bytes memory bs, Data memory r, uint[5] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (LeafOp.Data memory x, uint256 sz) = _decode_LeafOp(p, bs); if (isNil(r)) { counters[3] += 1; } else { r.leaf = x; if (counters[3] > 0) counters[3] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_path( uint256 p, bytes memory bs, Data memory r, uint[5] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (int32 x, uint256 sz) = ProtoBufRuntime._decode_int32(p, bs); if (isNil(r)) { counters[4] += 1; } else { r.path[r.path.length - counters[4]] = x; if (counters[4] > 0) counters[4] -= 1; } return sz; } // struct decoder /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_LeafOp(uint256 p, bytes memory bs) internal pure returns (LeafOp.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (LeafOp.Data memory r, ) = LeafOp._decode(pointer, bs, sz); return (r, sz + bytesRead); } // Encoder section /** * @dev The main encoder for memory * @param r The struct to be encoded * @return The encoded byte array */ function encode(Data memory r) internal pure returns (bytes memory) { bytes memory bs = new bytes(_estimate(r)); uint256 sz = _encode(r, 32, bs); assembly { mstore(bs, sz) } return bs; } // inner encoder /** * @dev The encoder for internal usage * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { uint256 offset = p; uint256 pointer = p; uint256 i; if (r.key.length != 0) { pointer += ProtoBufRuntime._encode_key( 1, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_bytes(r.key, pointer, bs); } if (r.value.length != 0) { pointer += ProtoBufRuntime._encode_key( 2, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_bytes(r.value, pointer, bs); } pointer += ProtoBufRuntime._encode_key( 3, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += LeafOp._encode_nested(r.leaf, pointer, bs); if (r.path.length != 0) { for(i = 0; i < r.path.length; i++) { pointer += ProtoBufRuntime._encode_key( 4, ProtoBufRuntime.WireType.Varint, pointer, bs) ; pointer += ProtoBufRuntime._encode_int32(r.path[i], pointer, bs); } } return pointer - offset; } // nested encoder /** * @dev The encoder for inner struct * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode_nested(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { /** * First encoded `r` into a temporary array, and encode the actual size used. * Then copy the temporary array into `bs`. */ uint256 offset = p; uint256 pointer = p; bytes memory tmp = new bytes(_estimate(r)); uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp); uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs); uint256 size = _encode(r, 32, tmp); pointer += ProtoBufRuntime._encode_varint(size, pointer, bs); ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size); pointer += size; delete tmp; return pointer - offset; } // estimator /** * @dev The estimator for a struct * @param r The struct to be encoded * @return The number of bytes encoded in estimation */ function _estimate( Data memory r ) internal pure returns (uint) { uint256 e;uint256 i; e += 1 + ProtoBufRuntime._sz_lendelim(r.key.length); e += 1 + ProtoBufRuntime._sz_lendelim(r.value.length); e += 1 + ProtoBufRuntime._sz_lendelim(LeafOp._estimate(r.leaf)); for(i = 0; i < r.path.length; i++) { e += 1 + ProtoBufRuntime._sz_int32(r.path[i]); } return e; } // empty checker function _empty( Data memory r ) internal pure returns (bool) { if (r.key.length != 0) { return false; } if (r.value.length != 0) { return false; } if (r.path.length != 0) { return false; } return true; } //store function /** * @dev Store in-memory struct to storage * @param input The in-memory struct * @param output The in-storage struct */ function store(Data memory input, Data storage output) internal { output.key = input.key; output.value = input.value; LeafOp.store(input.leaf, output.leaf); output.path = input.path; } //array helpers for Path /** * @dev Add value to an array * @param self The in-memory struct * @param value The value to add */ function addPath(Data memory self, int32 value) internal pure { /** * First resize the array. Then add the new element to the end. */ int32[] memory tmp = new int32[](self.path.length + 1); for (uint256 i = 0; i < self.path.length; i++) { tmp[i] = self.path[i]; } tmp[self.path.length] = value; self.path = tmp; } //utility functions /** * @dev Return an empty struct * @return r The empty struct */ function nil() internal pure returns (Data memory r) { assembly { r := 0 } } /** * @dev Test whether a struct is empty * @param x The struct to be tested * @return r True if it is empty */ function isNil(Data memory x) internal pure returns (bool r) { assembly { r := iszero(x) } } } //library CompressedExistenceProof library CompressedNonExistenceProof { //struct definition struct Data { bytes key; CompressedExistenceProof.Data left; CompressedExistenceProof.Data right; } // Decoder section /** * @dev The main decoder for memory * @param bs The bytes array to be decoded * @return The decoded struct */ function decode(bytes memory bs) internal pure returns (Data memory) { (Data memory x, ) = _decode(32, bs, bs.length); return x; } /** * @dev The main decoder for storage * @param self The in-storage struct * @param bs The bytes array to be decoded */ function decode(Data storage self, bytes memory bs) internal { (Data memory x, ) = _decode(32, bs, bs.length); store(x, self); } // inner decoder /** * @dev The decoder for internal usage * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param sz The number of bytes expected * @return The decoded struct * @return The number of bytes decoded */ function _decode(uint256 p, bytes memory bs, uint256 sz) internal pure returns (Data memory, uint) { Data memory r; uint[4] memory counters; uint256 fieldId; ProtoBufRuntime.WireType wireType; uint256 bytesRead; uint256 offset = p; uint256 pointer = p; while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_key(pointer, bs, r, counters); } else if (fieldId == 2) { pointer += _read_left(pointer, bs, r, counters); } else if (fieldId == 3) { pointer += _read_right(pointer, bs, r, counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } return (r, sz); } // field readers /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_key( uint256 p, bytes memory bs, Data memory r, uint[4] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs); if (isNil(r)) { counters[1] += 1; } else { r.key = x; if (counters[1] > 0) counters[1] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_left( uint256 p, bytes memory bs, Data memory r, uint[4] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (CompressedExistenceProof.Data memory x, uint256 sz) = _decode_CompressedExistenceProof(p, bs); if (isNil(r)) { counters[2] += 1; } else { r.left = x; if (counters[2] > 0) counters[2] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_right( uint256 p, bytes memory bs, Data memory r, uint[4] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (CompressedExistenceProof.Data memory x, uint256 sz) = _decode_CompressedExistenceProof(p, bs); if (isNil(r)) { counters[3] += 1; } else { r.right = x; if (counters[3] > 0) counters[3] -= 1; } return sz; } // struct decoder /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_CompressedExistenceProof(uint256 p, bytes memory bs) internal pure returns (CompressedExistenceProof.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (CompressedExistenceProof.Data memory r, ) = CompressedExistenceProof._decode(pointer, bs, sz); return (r, sz + bytesRead); } // Encoder section /** * @dev The main encoder for memory * @param r The struct to be encoded * @return The encoded byte array */ function encode(Data memory r) internal pure returns (bytes memory) { bytes memory bs = new bytes(_estimate(r)); uint256 sz = _encode(r, 32, bs); assembly { mstore(bs, sz) } return bs; } // inner encoder /** * @dev The encoder for internal usage * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { uint256 offset = p; uint256 pointer = p; if (r.key.length != 0) { pointer += ProtoBufRuntime._encode_key( 1, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_bytes(r.key, pointer, bs); } pointer += ProtoBufRuntime._encode_key( 2, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += CompressedExistenceProof._encode_nested(r.left, pointer, bs); pointer += ProtoBufRuntime._encode_key( 3, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += CompressedExistenceProof._encode_nested(r.right, pointer, bs); return pointer - offset; } // nested encoder /** * @dev The encoder for inner struct * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode_nested(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { /** * First encoded `r` into a temporary array, and encode the actual size used. * Then copy the temporary array into `bs`. */ uint256 offset = p; uint256 pointer = p; bytes memory tmp = new bytes(_estimate(r)); uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp); uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs); uint256 size = _encode(r, 32, tmp); pointer += ProtoBufRuntime._encode_varint(size, pointer, bs); ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size); pointer += size; delete tmp; return pointer - offset; } // estimator /** * @dev The estimator for a struct * @param r The struct to be encoded * @return The number of bytes encoded in estimation */ function _estimate( Data memory r ) internal pure returns (uint) { uint256 e; e += 1 + ProtoBufRuntime._sz_lendelim(r.key.length); e += 1 + ProtoBufRuntime._sz_lendelim(CompressedExistenceProof._estimate(r.left)); e += 1 + ProtoBufRuntime._sz_lendelim(CompressedExistenceProof._estimate(r.right)); return e; } // empty checker function _empty( Data memory r ) internal pure returns (bool) { if (r.key.length != 0) { return false; } return true; } //store function /** * @dev Store in-memory struct to storage * @param input The in-memory struct * @param output The in-storage struct */ function store(Data memory input, Data storage output) internal { output.key = input.key; CompressedExistenceProof.store(input.left, output.left); CompressedExistenceProof.store(input.right, output.right); } //utility functions /** * @dev Return an empty struct * @return r The empty struct */ function nil() internal pure returns (Data memory r) { assembly { r := 0 } } /** * @dev Test whether a struct is empty * @param x The struct to be tested * @return r True if it is empty */ function isNil(Data memory x) internal pure returns (bool r) { assembly { r := iszero(x) } } } //library CompressedNonExistenceProof library PROOFS_PROTO_GLOBAL_ENUMS { //enum definition // Solidity enum definitions enum HashOp { NO_HASH, SHA256, SHA512, KECCAK, RIPEMD160, BITCOIN } // Solidity enum encoder function encode_HashOp(HashOp x) internal pure returns (int32) { if (x == HashOp.NO_HASH) { return 0; } if (x == HashOp.SHA256) { return 1; } if (x == HashOp.SHA512) { return 2; } if (x == HashOp.KECCAK) { return 3; } if (x == HashOp.RIPEMD160) { return 4; } if (x == HashOp.BITCOIN) { return 5; } revert(); } // Solidity enum decoder function decode_HashOp(int64 x) internal pure returns (HashOp) { if (x == 0) { return HashOp.NO_HASH; } if (x == 1) { return HashOp.SHA256; } if (x == 2) { return HashOp.SHA512; } if (x == 3) { return HashOp.KECCAK; } if (x == 4) { return HashOp.RIPEMD160; } if (x == 5) { return HashOp.BITCOIN; } revert(); } // Solidity enum definitions enum LengthOp { NO_PREFIX, VAR_PROTO, VAR_RLP, FIXED32_BIG, FIXED32_LITTLE, FIXED64_BIG, FIXED64_LITTLE, REQUIRE_32_BYTES, REQUIRE_64_BYTES } // Solidity enum encoder function encode_LengthOp(LengthOp x) internal pure returns (int32) { if (x == LengthOp.NO_PREFIX) { return 0; } if (x == LengthOp.VAR_PROTO) { return 1; } if (x == LengthOp.VAR_RLP) { return 2; } if (x == LengthOp.FIXED32_BIG) { return 3; } if (x == LengthOp.FIXED32_LITTLE) { return 4; } if (x == LengthOp.FIXED64_BIG) { return 5; } if (x == LengthOp.FIXED64_LITTLE) { return 6; } if (x == LengthOp.REQUIRE_32_BYTES) { return 7; } if (x == LengthOp.REQUIRE_64_BYTES) { return 8; } revert(); } // Solidity enum decoder function decode_LengthOp(int64 x) internal pure returns (LengthOp) { if (x == 0) { return LengthOp.NO_PREFIX; } if (x == 1) { return LengthOp.VAR_PROTO; } if (x == 2) { return LengthOp.VAR_RLP; } if (x == 3) { return LengthOp.FIXED32_BIG; } if (x == 4) { return LengthOp.FIXED32_LITTLE; } if (x == 5) { return LengthOp.FIXED64_BIG; } if (x == 6) { return LengthOp.FIXED64_LITTLE; } if (x == 7) { return LengthOp.REQUIRE_32_BYTES; } if (x == 8) { return LengthOp.REQUIRE_64_BYTES; } revert(); } } //library PROOFS_PROTO_GLOBAL_ENUMS
The decoder for reading a field p The offset of bytes array to start decode bs The bytes array to be decoded r The in-memory struct counters The counters for repeated fields return The number of bytes decoded/ if `r` is NULL, then only counting the number of fields./
function _read_leaf_spec( uint256 p, bytes memory bs, Data memory r, uint[5] memory counters ) internal pure returns (uint) { (LeafOp.Data memory x, uint256 sz) = _decode_LeafOp(p, bs); if (isNil(r)) { counters[1] += 1; r.leaf_spec = x; if (counters[1] > 0) counters[1] -= 1; } return sz; }
13,050,308
// SPDX-License-Identifier: Apache-2.0 pragma solidity 0.8.12; pragma experimental ABIEncoderV2; // Part: Address /** * @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); } } } } // Part: Context /** * @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; } } // Part: IBZx /// @title A proxy interface for The Protocol /// @author bZeroX /// @notice This is just an interface, not to be deployed itself. /// @dev This interface is to be used for the protocol interactions. interface IBZx { ////// Protocol ////// /// @dev adds or replaces existing proxy module /// @param target target proxy module address function replaceContract(address target) external; /// @dev updates all proxy modules addreses and function signatures. /// sigsArr and targetsArr should be of equal length /// @param sigsArr array of function signatures /// @param targetsArr array of target proxy module addresses function setTargets( string[] calldata sigsArr, address[] calldata targetsArr ) external; /// @dev returns protocol module address given a function signature /// @return module address function getTarget(string calldata sig) external view returns (address); ////// Protocol Settings ////// /// @dev sets price feed contract address. The contract on the addres should implement IPriceFeeds interface /// @param newContract module address for the IPriceFeeds implementation function setPriceFeedContract(address newContract) external; /// @dev sets swaps contract address. The contract on the addres should implement ISwapsImpl interface /// @param newContract module address for the ISwapsImpl implementation function setSwapsImplContract(address newContract) external; /// @dev sets loan pool with assets. Accepts two arrays of equal length /// @param pools array of address of pools /// @param assets array of addresses of assets function setLoanPool(address[] calldata pools, address[] calldata assets) external; /// @dev updates list of supported tokens, it can be use also to disable or enable particualr token /// @param addrs array of address of pools /// @param toggles array of addresses of assets /// @param withApprovals resets tokens to unlimited approval with the swaps integration (kyber, etc.) function setSupportedTokens( address[] calldata addrs, bool[] calldata toggles, bool withApprovals ) external; /// @dev sets approvals for any token list for any spender /// @param tokens array of tokens /// @param spender spender function setTokenApprovals( address[] calldata tokens, address spender ) external; /// @dev sets lending fee with WEI_PERCENT_PRECISION /// @param newValue lending fee percent function setLendingFeePercent(uint256 newValue) external; /// @dev sets trading fee with WEI_PERCENT_PRECISION /// @param newValue trading fee percent function setTradingFeePercent(uint256 newValue) external; /// @dev sets borrowing fee with WEI_PERCENT_PRECISION /// @param newValue borrowing fee percent function setBorrowingFeePercent(uint256 newValue) external; /// @dev sets affiliate fee with WEI_PERCENT_PRECISION /// @param newValue affiliate fee percent function setAffiliateFeePercent(uint256 newValue) external; /// @dev sets liquidation inncetive percent per loan per token. This is the profit percent /// that liquidator gets in the process of liquidating. /// @param loanTokens array list of loan tokens /// @param collateralTokens array list of collateral tokens /// @param amounts array list of liquidation inncetive amount function setLiquidationIncentivePercent( address[] calldata loanTokens, address[] calldata collateralTokens, uint256[] calldata amounts ) external; /// @dev sets max swap rate slippage percent. /// @param newAmount max swap rate slippage percent. function setMaxDisagreement(uint256 newAmount) external; /// TODO function setSourceBufferPercent(uint256 newAmount) external; /// @dev sets maximum supported swap size in ETH /// @param newAmount max swap size in ETH. function setMaxSwapSize(uint256 newAmount) external; /// @dev sets fee controller address /// @param newController address of the new fees controller function setFeesController(address newController) external; /// @dev withdraws lending fees to receiver. Only can be called by feesController address /// @param tokens array of token addresses. /// @param receiver fees receiver address /// @return amounts array of amounts withdrawn function withdrawFees( address[] calldata tokens, address receiver, FeeClaimType feeType ) external returns (uint256[] memory amounts); /// @dev withdraw protocol token (BZRX) from vesting contract vBZRX /// @param receiver address of BZRX tokens claimed /// @param amount of BZRX token to be claimed. max is claimed if amount is greater than balance. /// @return rewardToken reward token address /// @return withdrawAmount amount function withdrawProtocolToken(address receiver, uint256 amount) external returns (address rewardToken, uint256 withdrawAmount); /// @dev depozit protocol token (BZRX) /// @param amount address of BZRX tokens to deposit function depositProtocolToken(uint256 amount) external; function grantRewards(address[] calldata users, uint256[] calldata amounts) external returns (uint256 totalAmount); // NOTE: this doesn't sanitize inputs -> inaccurate values may be returned if there are duplicates tokens input function queryFees(address[] calldata tokens, FeeClaimType feeType) external view returns (uint256[] memory amountsHeld, uint256[] memory amountsPaid); function priceFeeds() external view returns (address); function swapsImpl() external view returns (address); function logicTargets(bytes4) external view returns (address); function loans(bytes32) external view returns (Loan memory); function loanParams(bytes32) external view returns (LoanParams memory); // we don't use this yet // function lenderOrders(address, bytes32) external returns (Order memory); // function borrowerOrders(address, bytes32) external returns (Order memory); function delegatedManagers(bytes32, address) external view returns (bool); function lenderInterest(address, address) external view returns (LenderInterest memory); function loanInterest(bytes32) external view returns (LoanInterest memory); function feesController() external view returns (address); function lendingFeePercent() external view returns (uint256); function lendingFeeTokensHeld(address) external view returns (uint256); function lendingFeeTokensPaid(address) external view returns (uint256); function borrowingFeePercent() external view returns (uint256); function borrowingFeeTokensHeld(address) external view returns (uint256); function borrowingFeeTokensPaid(address) external view returns (uint256); function protocolTokenHeld() external view returns (uint256); function protocolTokenPaid() external view returns (uint256); function affiliateFeePercent() external view returns (uint256); function liquidationIncentivePercent(address, address) external view returns (uint256); function loanPoolToUnderlying(address) external view returns (address); function underlyingToLoanPool(address) external view returns (address); function supportedTokens(address) external view returns (bool); function maxDisagreement() external view returns (uint256); function sourceBufferPercent() external view returns (uint256); function maxSwapSize() external view returns (uint256); /// @dev get list of loan pools in the system. Ordering is not guaranteed /// @param start start index /// @param count number of pools to return /// @return loanPoolsList array of loan pools function getLoanPoolsList(uint256 start, uint256 count) external view returns (address[] memory loanPoolsList); /// @dev checks whether addreess is a loan pool address /// @return boolean function isLoanPool(address loanPool) external view returns (bool); ////// Loan Settings ////// /// @dev creates new loan param settings /// @param loanParamsList array of LoanParams /// @return loanParamsIdList array of loan ids created function setupLoanParams(LoanParams[] calldata loanParamsList) external returns (bytes32[] memory loanParamsIdList); /// @dev Deactivates LoanParams for future loans. Active loans using it are unaffected. /// @param loanParamsIdList array of loan ids function disableLoanParams(bytes32[] calldata loanParamsIdList) external; /// @dev gets array of LoanParams by given ids /// @param loanParamsIdList array of loan ids /// @return loanParamsList array of LoanParams function getLoanParams(bytes32[] calldata loanParamsIdList) external view returns (LoanParams[] memory loanParamsList); /// @dev Enumerates LoanParams in the system by owner /// @param owner of the loan params /// @param start number of loans to return /// @param count total number of the items /// @return loanParamsList array of LoanParams function getLoanParamsList( address owner, uint256 start, uint256 count ) external view returns (bytes32[] memory loanParamsList); /// @dev returns total loan principal for token address /// @param lender address /// @param loanToken address /// @return total principal of the loan function getTotalPrincipal(address lender, address loanToken) external view returns (uint256); /// @dev returns total principal for a loan pool that was last settled /// @param pool address /// @return total stored principal of the loan function getPoolPrincipalStored(address pool) external view returns (uint256); /// @dev returns the last interest rate founnd during interest settlement /// @param pool address /// @return the last interset rate function getPoolLastInterestRate(address pool) external view returns (uint256); ////// Loan Openings ////// /// @dev This is THE function that borrows or trades on the protocol /// @param loanParamsId id of the LoanParam created beforehand by setupLoanParams function /// @param loanId id of existing loan, if 0, start a new loan /// @param isTorqueLoan boolean whether it is toreque or non torque loan /// @param initialMargin in WEI_PERCENT_PRECISION /// @param sentAddresses array of size 4: /// lender: must match loan if loanId provided /// borrower: must match loan if loanId provided /// receiver: receiver of funds (address(0) assumes borrower address) /// manager: delegated manager of loan unless address(0) /// @param sentValues array of size 5: /// newRate: new loan interest rate /// newPrincipal: new loan size (borrowAmount + any borrowed interest) /// torqueInterest: new amount of interest to escrow for Torque loan (determines initial loan length) /// loanTokenReceived: total loanToken deposit (amount not sent to borrower in the case of Torque loans) /// collateralTokenReceived: total collateralToken deposit /// @param loanDataBytes required when sending ether /// @return principal of the loan and collateral amount function borrowOrTradeFromPool( bytes32 loanParamsId, bytes32 loanId, bool isTorqueLoan, uint256 initialMargin, address[4] calldata sentAddresses, uint256[5] calldata sentValues, bytes calldata loanDataBytes ) external payable returns (LoanOpenData memory); /// @dev sets/disables/enables the delegated manager for the loan /// @param loanId id of the loan /// @param delegated delegated manager address /// @param toggle boolean set enabled or disabled function setDelegatedManager( bytes32 loanId, address delegated, bool toggle ) external; /// @dev estimates margin exposure for simulated position /// @param loanToken address of the loan token /// @param collateralToken address of collateral token /// @param loanTokenSent amout of loan token sent /// @param collateralTokenSent amount of collateral token sent /// @param interestRate yearly interest rate /// @param newPrincipal principal amount of the loan /// @return estimated margin exposure amount function getEstimatedMarginExposure( address loanToken, address collateralToken, uint256 loanTokenSent, uint256 collateralTokenSent, uint256 interestRate, uint256 newPrincipal ) external view returns (uint256); /// @dev calculates required collateral for simulated position /// @param loanToken address of loan token /// @param collateralToken address of collateral token /// @param newPrincipal principal amount of the loan /// @param marginAmount margin amount of the loan /// @param isTorqueLoan boolean torque or non torque loan /// @return collateralAmountRequired amount required function getRequiredCollateral( address loanToken, address collateralToken, uint256 newPrincipal, uint256 marginAmount, bool isTorqueLoan ) external view returns (uint256 collateralAmountRequired); function getRequiredCollateralByParams( bytes32 loanParamsId, uint256 newPrincipal ) external view returns (uint256 collateralAmountRequired); /// @dev calculates borrow amount for simulated position /// @param loanToken address of loan token /// @param collateralToken address of collateral token /// @param collateralTokenAmount amount of collateral token sent /// @param marginAmount margin amount /// @param isTorqueLoan boolean torque or non torque loan /// @return borrowAmount possible borrow amount function getBorrowAmount( address loanToken, address collateralToken, uint256 collateralTokenAmount, uint256 marginAmount, bool isTorqueLoan ) external view returns (uint256 borrowAmount); function getBorrowAmountByParams( bytes32 loanParamsId, uint256 collateralTokenAmount ) external view returns (uint256 borrowAmount); ////// Loan Closings ////// /// @dev liquidates unhealty loans /// @param loanId id of the loan /// @param receiver address receiving liquidated loan collateral /// @param closeAmount amount to close denominated in loanToken /// @return loanCloseAmount amount of the collateral token of the loan /// @return seizedAmount sezied amount in the collateral token /// @return seizedToken loan token address function liquidate( bytes32 loanId, address receiver, uint256 closeAmount ) external payable returns ( uint256 loanCloseAmount, uint256 seizedAmount, address seizedToken ); /// @dev close position with loan token deposit /// @param loanId id of the loan /// @param receiver collateral token reciever address /// @param depositAmount amount of loan token to deposit /// @return loanCloseAmount loan close amount /// @return withdrawAmount loan token withdraw amount /// @return withdrawToken loan token address function closeWithDeposit( bytes32 loanId, address receiver, uint256 depositAmount // denominated in loanToken ) external payable returns ( uint256 loanCloseAmount, uint256 withdrawAmount, address withdrawToken ); /// @dev close position with swap /// @param loanId id of the loan /// @param receiver collateral token reciever address /// @param swapAmount amount of loan token to swap /// @param returnTokenIsCollateral boolean whether to return tokens is collateral /// @param loanDataBytes custom payload for specifying swap implementation and data to pass /// @return loanCloseAmount loan close amount /// @return withdrawAmount loan token withdraw amount /// @return withdrawToken loan token address function closeWithSwap( bytes32 loanId, address receiver, uint256 swapAmount, // denominated in collateralToken bool returnTokenIsCollateral, // true: withdraws collateralToken, false: withdraws loanToken bytes calldata loanDataBytes ) external returns ( uint256 loanCloseAmount, uint256 withdrawAmount, address withdrawToken ); ////// Loan Closings With Gas Token ////// /// @dev liquidates unhealty loans by using Gas token /// @param loanId id of the loan /// @param receiver address receiving liquidated loan collateral /// @param gasTokenUser user address of the GAS token /// @param closeAmount amount to close denominated in loanToken /// @return loanCloseAmount loan close amount /// @return seizedAmount loan token withdraw amount /// @return seizedToken loan token address function liquidateWithGasToken( bytes32 loanId, address receiver, address gasTokenUser, uint256 closeAmount // denominated in loanToken ) external payable returns ( uint256 loanCloseAmount, uint256 seizedAmount, address seizedToken ); /// @dev close position with loan token deposit /// @param loanId id of the loan /// @param receiver collateral token reciever address /// @param gasTokenUser user address of the GAS token /// @param depositAmount amount of loan token to deposit denominated in loanToken /// @return loanCloseAmount loan close amount /// @return withdrawAmount loan token withdraw amount /// @return withdrawToken loan token address function closeWithDepositWithGasToken( bytes32 loanId, address receiver, address gasTokenUser, uint256 depositAmount ) external payable returns ( uint256 loanCloseAmount, uint256 withdrawAmount, address withdrawToken ); /// @dev close position with swap /// @param loanId id of the loan /// @param receiver collateral token reciever address /// @param gasTokenUser user address of the GAS token /// @param swapAmount amount of loan token to swap denominated in collateralToken /// @param returnTokenIsCollateral true: withdraws collateralToken, false: withdraws loanToken /// @return loanCloseAmount loan close amount /// @return withdrawAmount loan token withdraw amount /// @return withdrawToken loan token address function closeWithSwapWithGasToken( bytes32 loanId, address receiver, address gasTokenUser, uint256 swapAmount, bool returnTokenIsCollateral, bytes calldata loanDataBytes ) external returns ( uint256 loanCloseAmount, uint256 withdrawAmount, address withdrawToken ); ////// Loan Maintenance ////// /// @dev deposit collateral to existing loan /// @param loanId existing loan id /// @param depositAmount amount to deposit which must match msg.value if ether is sent function depositCollateral(bytes32 loanId, uint256 depositAmount) external payable; /// @dev withdraw collateral from existing loan /// @param loanId existing loan id /// @param receiver address of withdrawn tokens /// @param withdrawAmount amount to withdraw /// @return actualWithdrawAmount actual amount withdrawn function withdrawCollateral( bytes32 loanId, address receiver, uint256 withdrawAmount ) external returns (uint256 actualWithdrawAmount); /// @dev settles accrued interest for all active loans from a loan pool /// @param loanId existing loan id function settleInterest(bytes32 loanId) external; /*/// @dev withdraw accrued interest rate for a loan given token address /// @param loanToken loan token address function withdrawAccruedInterest(address loanToken) external;*/ /*/// @dev extends loan duration by depositing more collateral /// @param loanId id of the existing loan /// @param depositAmount amount to deposit /// @param useCollateral boolean whether to extend using collateral or deposit amount /// @return secondsExtended by that number of seconds loan duration was extended function extendLoanDuration( bytes32 loanId, uint256 depositAmount, bool useCollateral, bytes calldata // for future use loanDataBytes ) external payable returns (uint256 secondsExtended);*/ /*/// @dev reduces loan duration by withdrawing collateral /// @param loanId id of the existing loan /// @param receiver address to receive tokens /// @param withdrawAmount amount to withdraw /// @return secondsReduced by that number of seconds loan duration was extended function reduceLoanDuration( bytes32 loanId, address receiver, uint256 withdrawAmount ) external returns (uint256 secondsReduced);*/ function setDepositAmount( bytes32 loanId, uint256 depositValueAsLoanToken, uint256 depositValueAsCollateralToken ) external; function claimRewards(address receiver) external returns (uint256 claimAmount); function transferLoan(bytes32 loanId, address newOwner) external; function rewardsBalanceOf(address user) external view returns (uint256 rewardsBalance); function getInterestModelValues( address pool, bytes32 loanId) external view returns ( uint256 _poolLastUpdateTime, uint256 _poolPrincipalTotal, uint256 _poolInterestTotal, uint256 _poolRatePerTokenStored, uint256 _poolLastInterestRate, uint256 _loanPrincipalTotal, uint256 _loanInterestTotal, uint256 _loanRatePerTokenPaid ); /*/// @dev Gets current lender interest data totals for all loans with a specific oracle and interest token /// @param lender The lender address /// @param loanToken The loan token address /// @return interestPaid The total amount of interest that has been paid to a lender so far /// @return interestPaidDate The date of the last interest pay out, or 0 if no interest has been withdrawn yet /// @return interestOwedPerDay The amount of interest the lender is earning per day /// @return interestUnPaid The total amount of interest the lender is owned and not yet withdrawn /// @return interestFeePercent The fee retained by the protocol before interest is paid to the lender /// @return principalTotal The total amount of outstading principal the lender has loaned function getLenderInterestData(address lender, address loanToken) external view returns ( uint256 interestPaid, uint256 interestPaidDate, uint256 interestOwedPerDay, uint256 interestUnPaid, uint256 interestFeePercent, uint256 principalTotal ); /// @dev Gets current interest data for a loan /// @param loanId A unique id representing the loan /// @return loanToken The loan token that interest is paid in /// @return interestOwedPerDay The amount of interest the borrower is paying per day /// @return interestDepositTotal The total amount of interest the borrower has deposited /// @return interestDepositRemaining The amount of deposited interest that is not yet owed to a lender function getLoanInterestData(bytes32 loanId) external view returns ( address loanToken, uint256 interestOwedPerDay, uint256 interestDepositTotal, uint256 interestDepositRemaining );*/ /// @dev gets list of loans of particular user address /// @param user address of the loans /// @param start of the index /// @param count number of loans to return /// @param loanType type of the loan: All(0), Margin(1), NonMargin(2) /// @param isLender whether to list lender loans or borrower loans /// @param unsafeOnly booleat if true return only unsafe loans that are open for liquidation /// @return loansData LoanReturnData array of loans function getUserLoans( address user, uint256 start, uint256 count, LoanType loanType, bool isLender, bool unsafeOnly ) external view returns (LoanReturnData[] memory loansData); function getUserLoansCount(address user, bool isLender) external view returns (uint256); /// @dev gets existing loan /// @param loanId id of existing loan /// @return loanData array of loans function getLoan(bytes32 loanId) external view returns (LoanReturnData memory loanData); /// @dev gets loan principal including interest /// @param loanId id of existing loan /// @return principal function getLoanPrincipal(bytes32 loanId) external view returns (uint256 principal); /// @dev gets loan outstanding interest /// @param loanId id of existing loan /// @return interest function getLoanInterestOutstanding(bytes32 loanId) external view returns (uint256 interest); /// @dev get current active loans in the system /// @param start of the index /// @param count number of loans to return /// @param unsafeOnly boolean if true return unsafe loan only (open for liquidation) function getActiveLoans( uint256 start, uint256 count, bool unsafeOnly ) external view returns (LoanReturnData[] memory loansData); /// @dev get current active loans in the system /// @param start of the index /// @param count number of loans to return /// @param unsafeOnly boolean if true return unsafe loan only (open for liquidation) /// @param isLiquidatable boolean if true return liquidatable loans only function getActiveLoansAdvanced( uint256 start, uint256 count, bool unsafeOnly, bool isLiquidatable ) external view returns (LoanReturnData[] memory loansData); function getActiveLoansCount() external view returns (uint256); ////// Swap External ////// /// @dev swap thru external integration /// @param sourceToken source token address /// @param destToken destintaion token address /// @param receiver address to receive tokens /// @param returnToSender TODO /// @param sourceTokenAmount source token amount /// @param requiredDestTokenAmount destination token amount /// @param swapData TODO /// @return destTokenAmountReceived destination token received /// @return sourceTokenAmountUsed source token amount used function swapExternal( address sourceToken, address destToken, address receiver, address returnToSender, uint256 sourceTokenAmount, uint256 requiredDestTokenAmount, bytes calldata swapData ) external payable returns ( uint256 destTokenAmountReceived, uint256 sourceTokenAmountUsed ); /// @dev swap thru external integration using GAS /// @param sourceToken source token address /// @param destToken destintaion token address /// @param receiver address to receive tokens /// @param returnToSender TODO /// @param gasTokenUser user address of the GAS token /// @param sourceTokenAmount source token amount /// @param requiredDestTokenAmount destination token amount /// @param swapData TODO /// @return destTokenAmountReceived destination token received /// @return sourceTokenAmountUsed source token amount used function swapExternalWithGasToken( address sourceToken, address destToken, address receiver, address returnToSender, address gasTokenUser, uint256 sourceTokenAmount, uint256 requiredDestTokenAmount, bytes calldata swapData ) external payable returns ( uint256 destTokenAmountReceived, uint256 sourceTokenAmountUsed ); /// @dev calculate simulated return of swap /// @param sourceToken source token address /// @param destToken destination token address /// @param sourceTokenAmount source token amount /// @return amoun denominated in destination token function getSwapExpectedReturn( address sourceToken, address destToken, uint256 sourceTokenAmount, bytes calldata swapData ) external view returns (uint256); function owner() external view returns (address); function transferOwnership(address newOwner) external; /// Guardian Interface function _isPaused(bytes4 sig) external view returns (bool isPaused); function toggleFunctionPause(bytes4 sig) external; function toggleFunctionUnPause(bytes4 sig) external; function changeGuardian(address newGuardian) external; function getGuardian() external view returns (address guardian); /// Loan Cleanup Interface function cleanupLoans( address loanToken, bytes32[] calldata loanIds) external payable returns (uint256 totalPrincipalIn); struct LoanParams { bytes32 id; bool active; address owner; address loanToken; address collateralToken; uint256 minInitialMargin; uint256 maintenanceMargin; uint256 maxLoanTerm; } struct LoanOpenData { bytes32 loanId; uint256 principal; uint256 collateral; } enum LoanType { All, Margin, NonMargin } struct LoanReturnData { bytes32 loanId; uint96 endTimestamp; address loanToken; address collateralToken; uint256 principal; uint256 collateral; uint256 interestOwedPerDay; uint256 interestDepositRemaining; uint256 startRate; uint256 startMargin; uint256 maintenanceMargin; uint256 currentMargin; uint256 maxLoanTerm; uint256 maxLiquidatable; uint256 maxSeizable; uint256 depositValueAsLoanToken; uint256 depositValueAsCollateralToken; } enum FeeClaimType { All, Lending, Trading, Borrowing } struct Loan { bytes32 id; // id of the loan bytes32 loanParamsId; // the linked loan params id bytes32 pendingTradesId; // the linked pending trades id uint256 principal; // total borrowed amount outstanding uint256 collateral; // total collateral escrowed for the loan uint256 startTimestamp; // loan start time uint256 endTimestamp; // for active loans, this is the expected loan end time, for in-active loans, is the actual (past) end time uint256 startMargin; // initial margin when the loan opened uint256 startRate; // reference rate when the loan opened for converting collateralToken to loanToken address borrower; // borrower of this loan address lender; // lender of this loan bool active; // if false, the loan has been fully closed } struct LenderInterest { uint256 principalTotal; // total borrowed amount outstanding of asset uint256 owedPerDay; // interest owed per day for all loans of asset uint256 owedTotal; // total interest owed for all loans of asset (assuming they go to full term) uint256 paidTotal; // total interest paid so far for asset uint256 updatedTimestamp; // last update } struct LoanInterest { uint256 owedPerDay; // interest owed per day for loan uint256 depositTotal; // total escrowed interest for loan uint256 updatedTimestamp; // last update } ////// Flash Borrow Fees ////// function payFlashBorrowFees( address user, uint256 borrowAmount, uint256 flashBorrowFeePercent) external; } // Part: IBridge interface IBridge { function send( address _receiver, address _token, uint256 _amount, uint64 _dstChainId, uint64 _nonce, uint32 _maxSlippage ) external; function relay( bytes calldata _relayRequest, bytes[] calldata _sigs, address[] calldata _signers, uint256[] calldata _powers ) external; function transfers(bytes32 transferId) external view returns (bool); function withdraws(bytes32 withdrawId) external view returns (bool); function withdraw( bytes calldata _wdmsg, bytes[] calldata _sigs, address[] calldata _signers, uint256[] calldata _powers ) external; /** * @notice Verifies that a message is signed by a quorum among the signers. * @param _msg signed message * @param _sigs list of signatures sorted by signer addresses in ascending order * @param _signers sorted list of current signers * @param _powers powers of current signers */ function verifySigs( bytes memory _msg, bytes[] calldata _sigs, address[] calldata _signers, uint256[] calldata _powers ) external view; } // Part: ICurve3Pool interface ICurve3Pool { function add_liquidity( uint256[3] calldata amounts, uint256 min_mint_amount) external; function remove_liquidity_one_coin( uint256 token_amount, int128 i, uint256 min_amount ) external; function get_virtual_price() external view returns (uint256); } // Part: IERC20 /** * @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); } // Part: IPriceFeeds interface IPriceFeeds { function queryRate( address sourceToken, address destToken) external view returns (uint256 rate, uint256 precision); function queryReturn( address sourceToken, address destToken, uint256 sourceAmount) external view returns (uint256 destAmount); } // Part: IStakingV2 interface IStakingV2 { struct ProposalState { uint256 proposalTime; uint256 iOOKIWeight; uint256 lpOOKIBalance; uint256 lpTotalSupply; } struct AltRewardsUserInfo { uint256 rewardsPerShare; uint256 pendingRewards; } function getCurrentFeeTokens() external view returns (address[] memory); function maxUniswapDisagreement() external view returns (uint256); function fundsWallet() external view returns (address); function callerRewardDivisor() external view returns (uint256); function maxCurveDisagreement() external view returns (uint256); function rewardPercent() external view returns (uint256); function addRewards(uint256 newOOKI, uint256 newStableCoin) external; function stake(address[] calldata tokens, uint256[] calldata values) external; function unstake(address[] calldata tokens, uint256[] calldata values) external; function earned(address account) external view returns ( uint256 bzrxRewardsEarned, uint256 stableCoinRewardsEarned, uint256 bzrxRewardsVesting, uint256 stableCoinRewardsVesting, uint256 sushiRewardsEarned ); function pendingCrvRewards(address account) external view returns ( uint256 bzrxRewardsEarned, uint256 stableCoinRewardsEarned, uint256 bzrxRewardsVesting, uint256 stableCoinRewardsVesting, uint256 sushiRewardsEarned ); function getVariableWeights() external view returns ( uint256 vBZRXWeight, uint256 iOOKIWeight, uint256 LPTokenWeight ); function balanceOfByAsset(address token, address account) external view returns (uint256 balance); function balanceOfByAssets(address account) external view returns ( uint256 bzrxBalance, uint256 iOOKIBalance, uint256 vBZRXBalance, uint256 LPTokenBalance ); function balanceOfStored(address account) external view returns (uint256 vestedBalance, uint256 vestingBalance); function totalSupplyStored() external view returns (uint256 supply); function vestedBalanceForAmount( uint256 tokenBalance, uint256 lastUpdate, uint256 vestingEndTime ) external view returns (uint256 vested); function votingBalanceOf(address account, uint256 proposalId) external view returns (uint256 totalVotes); function votingBalanceOfNow(address account) external view returns (uint256 totalVotes); function votingFromStakedBalanceOf(address account) external view returns (uint256 totalVotes); function _setProposalVals(address account, uint256 proposalId) external returns (uint256); function exit() external; function addAltRewards(address token, uint256 amount) external; function governor() external view returns (address); function owner() external view returns (address); function transferOwnership(address newOwner) external; function claim(bool restake) external; function claimAltRewards() external; function _totalSupplyPerToken(address) external view returns(uint256); /// Guardian Interface function _isPaused(bytes4 sig) external view returns (bool isPaused); function toggleFunctionPause(bytes4 sig) external; function toggleFunctionUnPause(bytes4 sig) external; function changeGuardian(address newGuardian) external; function getGuardian() external view returns (address guardian); // Admin functions // Withdraw all from sushi masterchef function exitSushi() external; function setGovernor(address _governor) external; function setApprovals( address _token, address _spender, uint256 _value ) external; function setVoteDelegator(address stakingGovernance) external; function updateSettings(address settingsTarget, bytes calldata callData) external; function claimSushi() external returns (uint256 sushiRewardsEarned); function totalSupplyByAsset(address token) external view returns (uint256); function vestingLastSync(address user) external view returns(uint256); } // Part: IUniswapV2Router interface IUniswapV2Router { // 0x38ed1739 function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline) external returns (uint256[] memory amounts); // 0x8803dbee function swapTokensForExactTokens( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline) external returns (uint256[] memory amounts); // 0x1f00ca74 function getAmountsIn( uint256 amountOut, address[] calldata path) external view returns (uint256[] memory amounts); // 0xd06ca61f function getAmountsOut( uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts); } // Part: Ownable /** * @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); } } // Part: SafeERC20 /** * @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"); } } } // Part: PausableGuardian_0_8 contract PausableGuardian_0_8 is Ownable { // keccak256("Pausable_FunctionPause") bytes32 internal constant Pausable_FunctionPause = 0xa7143c84d793a15503da6f19bf9119a2dac94448ca45d77c8bf08f57b2e91047; // keccak256("Pausable_GuardianAddress") bytes32 internal constant Pausable_GuardianAddress = 0x80e6706973d0c59541550537fd6a33b971efad732635e6c3b99fb01006803cdf; modifier pausable() { require(!_isPaused(msg.sig) || msg.sender == getGuardian(), "paused"); _; } function _isPaused(bytes4 sig) public view returns (bool isPaused) { bytes32 slot = keccak256(abi.encodePacked(sig, Pausable_FunctionPause)); assembly { isPaused := sload(slot) } } function toggleFunctionPause(bytes4 sig) public { require(msg.sender == getGuardian() || msg.sender == owner(), "unauthorized"); bytes32 slot = keccak256(abi.encodePacked(sig, Pausable_FunctionPause)); assembly { sstore(slot, 1) } } function toggleFunctionUnPause(bytes4 sig) public { // only DAO can unpause, and adding guardian temporarily require(msg.sender == getGuardian() || msg.sender == owner(), "unauthorized"); bytes32 slot = keccak256(abi.encodePacked(sig, Pausable_FunctionPause)); assembly { sstore(slot, 0) } } function changeGuardian(address newGuardian) public { require(msg.sender == getGuardian() || msg.sender == owner(), "unauthorized"); assembly { sstore(Pausable_GuardianAddress, newGuardian) } } function getGuardian() public view returns (address guardian) { assembly { guardian := sload(Pausable_GuardianAddress) } } } // File: FeeExtractAndDistribute_ETH.sol contract FeeExtractAndDistribute_ETH is PausableGuardian_0_8 { using SafeERC20 for IERC20; address public implementation; IStakingV2 public constant STAKING = IStakingV2(0x16f179f5C344cc29672A58Ea327A26F64B941a63); address public constant OOKI = 0x0De05F6447ab4D22c8827449EE4bA2D5C288379B; IERC20 public constant CURVE_3CRV = IERC20(0x6c3F90f043a72FA612cbac8115EE7e52BDe6E490); address public constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant DAI = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address public constant USDC = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48; address public constant USDT = 0xdAC17F958D2ee523a2206206994597C13D831ec7; address public constant BUYBACK = 0x12EBd8263A54751Aaf9d8C2c74740A8e62C0AfBe; address public constant BRIDGE = 0x5427FEFA711Eff984124bFBB1AB6fbf5E3DA1820; uint64 public constant DEST_CHAINID = 137; //polygon IUniswapV2Router public constant UNISWAP_ROUTER = IUniswapV2Router(0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F); // sushiswap ICurve3Pool public constant CURVE_3POOL = ICurve3Pool(0xbEbc44782C7dB0a1A60Cb6fe97d0b483032FF1C7); IBZx public constant BZX = IBZx(0xD8Ee69652E4e4838f2531732a46d1f7F584F0b7f); mapping(address => address[]) public swapPaths; mapping(address => uint256) public stakingRewards; address[] public feeTokens; uint256 public buybackPercent; event ExtractAndDistribute(); event WithdrawFees(address indexed sender); event DistributeFees( address indexed sender, uint256 bzrxRewards, uint256 stableCoinRewards ); event ConvertFees( address indexed sender, uint256 bzrxOutput, uint256 stableCoinOutput ); // Fee Conversion Logic // function sweepFees() public pausable returns (uint256 bzrxRewards, uint256 crv3Rewards) { uint256[] memory amounts = _withdrawFees(feeTokens); _convertFees(feeTokens, amounts); (bzrxRewards, crv3Rewards) = _distributeFees(); } function sweepFees(address[] memory assets) public pausable returns (uint256 bzrxRewards, uint256 crv3Rewards) { uint256[] memory amounts = _withdrawFees(assets); _convertFees(assets, amounts); (bzrxRewards, crv3Rewards) = _distributeFees(); } function _withdrawFees(address[] memory assets) internal returns (uint256[] memory) { uint256[] memory amounts = BZX.withdrawFees( assets, address(this), IBZx.FeeClaimType.All ); for (uint256 i = 0; i < assets.length; i++) { stakingRewards[assets[i]] += amounts[i]; } emit WithdrawFees(msg.sender); return amounts; } function _convertFees(address[] memory assets, uint256[] memory amounts) internal returns (uint256 bzrxOutput, uint256 crv3Output) { require(assets.length == amounts.length, "count mismatch"); IPriceFeeds priceFeeds = IPriceFeeds(BZX.priceFeeds()); //(uint256 bzrxRate, ) = priceFeeds.queryRate(OOKI, WETH); uint256 maxDisagreement = 1e18; address asset; uint256 daiAmount; uint256 usdcAmount; uint256 usdtAmount; for (uint256 i = 0; i < assets.length; i++) { asset = assets[i]; if (asset == OOKI) { continue; } else if (asset == DAI) { daiAmount += amounts[i]; continue; } else if (asset == USDC) { usdcAmount += amounts[i]; continue; } else if (asset == USDT) { usdtAmount += amounts[i]; continue; } if (amounts[i] != 0) { bzrxOutput += _convertFeeWithUniswap( asset, amounts[i], priceFeeds, 0, /*bzrxRate*/ maxDisagreement ); } } if (bzrxOutput != 0) { stakingRewards[OOKI] += bzrxOutput; } if (daiAmount != 0 || usdcAmount != 0 || usdtAmount != 0) { crv3Output = _convertFeesWithCurve( daiAmount, usdcAmount, usdtAmount ); stakingRewards[address(CURVE_3CRV)] += crv3Output; } emit ConvertFees(msg.sender, bzrxOutput, crv3Output); } function _distributeFees() internal returns (uint256 bzrxRewards, uint256 crv3Rewards) { bzrxRewards = stakingRewards[OOKI]; crv3Rewards = stakingRewards[address(CURVE_3CRV)]; uint256 USDCBridge = 0; if (bzrxRewards != 0 || crv3Rewards != 0) { address _fundsWallet = 0xfedC4dD5247B93feb41e899A09C44cFaBec29Cbc; uint256 rewardAmount; uint256 callerReward; uint256 bridgeRewards; if (bzrxRewards != 0) { stakingRewards[OOKI] = 0; callerReward = bzrxRewards / 100; IERC20(OOKI).transfer(msg.sender, callerReward); bzrxRewards = bzrxRewards - (callerReward); bridgeRewards = (bzrxRewards * (buybackPercent)) / (1e20); USDCBridge = _convertToUSDCUniswap(bridgeRewards); rewardAmount = (bzrxRewards * (50e18)) / (1e20); IERC20(OOKI).transfer( _fundsWallet, bzrxRewards - rewardAmount - bridgeRewards ); bzrxRewards = rewardAmount; } if (crv3Rewards != 0) { stakingRewards[address(CURVE_3CRV)] = 0; callerReward = crv3Rewards / 100; CURVE_3CRV.transfer(msg.sender, callerReward); crv3Rewards = crv3Rewards - (callerReward); bridgeRewards = (crv3Rewards * (buybackPercent)) / (1e20); USDCBridge += _convertToUSDCCurve(bridgeRewards); rewardAmount = (crv3Rewards * (50e18)) / (1e20); CURVE_3CRV.transfer( _fundsWallet, crv3Rewards - rewardAmount - bridgeRewards ); crv3Rewards = rewardAmount; } STAKING.addRewards(bzrxRewards, crv3Rewards); _bridgeFeesToPolygon(USDCBridge); } emit DistributeFees(msg.sender, bzrxRewards, crv3Rewards); } function _bridgeFeesToPolygon(uint256 bridgeAmount) internal { IBridge(BRIDGE).send( BUYBACK, USDC, bridgeAmount, DEST_CHAINID, uint64(block.timestamp), 10000 ); } function _convertToUSDCUniswap(uint256 amount) internal returns (uint256 returnAmount) { address[] memory path = new address[](3); path[0] = OOKI; path[1] = WETH; path[2] = USDC; uint256[] memory amounts = UNISWAP_ROUTER.swapExactTokensForTokens( amount, 1, // amountOutMin path, address(this), block.timestamp ); returnAmount = amounts[amounts.length - 1]; IPriceFeeds priceFeeds = IPriceFeeds(BZX.priceFeeds()); //(uint256 bzrxRate, ) = priceFeeds.queryRate(OOKI, WETH); /*_checkUniDisagreement( OOKI, USDC, amount, returnAmount, STAKING.maxUniswapDisagreement() );*/ } function _convertFeeWithUniswap( address asset, uint256 amount, IPriceFeeds priceFeeds, uint256 bzrxRate, uint256 maxDisagreement ) internal returns (uint256 returnAmount) { uint256 stakingReward = stakingRewards[asset]; if (stakingReward != 0) { if (amount > stakingReward) { amount = stakingReward; } stakingRewards[asset] = stakingReward - (amount); uint256[] memory amounts = UNISWAP_ROUTER.swapExactTokensForTokens( amount, 1, // amountOutMin swapPaths[asset], address(this), block.timestamp ); returnAmount = amounts[amounts.length - 1]; // will revert if disagreement found /*_checkUniDisagreement( asset, OOKI, amount, returnAmount, maxDisagreement );*/ } } function _convertToUSDCCurve(uint256 amount) internal returns (uint256 returnAmount) { uint256 beforeBalance = IERC20(USDC).balanceOf(address(this)); CURVE_3POOL.remove_liquidity_one_coin(amount, 1, 1); //does not need to be checked for disagreement as liquidity add handles that returnAmount = IERC20(USDC).balanceOf(address(this)) - beforeBalance; //does not underflow as USDC is not being transferred out } function _convertFeesWithCurve( uint256 daiAmount, uint256 usdcAmount, uint256 usdtAmount ) internal returns (uint256 returnAmount) { uint256[3] memory curveAmounts; uint256 curveTotal; uint256 stakingReward; if (daiAmount != 0) { stakingReward = stakingRewards[DAI]; if (stakingReward != 0) { if (daiAmount > stakingReward) { daiAmount = stakingReward; } stakingRewards[DAI] = stakingReward - (daiAmount); curveAmounts[0] = daiAmount; curveTotal = daiAmount; } } if (usdcAmount != 0) { stakingReward = stakingRewards[USDC]; if (stakingReward != 0) { if (usdcAmount > stakingReward) { usdcAmount = stakingReward; } stakingRewards[USDC] = stakingReward - (usdcAmount); curveAmounts[1] = usdcAmount; curveTotal += usdcAmount * 1e12; // normalize to 18 decimals } } if (usdtAmount != 0) { stakingReward = stakingRewards[USDT]; if (stakingReward != 0) { if (usdtAmount > stakingReward) { usdtAmount = stakingReward; } stakingRewards[USDT] = stakingReward - (usdtAmount); curveAmounts[2] = usdtAmount; curveTotal += usdtAmount * 1e12; // normalize to 18 decimals } } uint256 beforeBalance = CURVE_3CRV.balanceOf(address(this)); CURVE_3POOL.add_liquidity( curveAmounts, (curveTotal * 1e18 / CURVE_3POOL.get_virtual_price())*995/1000 ); returnAmount = CURVE_3CRV.balanceOf(address(this)) - beforeBalance; } function _checkUniDisagreement( address asset, address recvAsset, uint256 assetAmount, uint256 recvAmount, uint256 maxDisagreement ) internal view { uint256 estAmountOut = IPriceFeeds(BZX.priceFeeds()).queryReturn( asset, recvAsset, assetAmount ); uint256 spreadValue = estAmountOut > recvAmount ? estAmountOut - recvAmount : recvAmount - estAmountOut; if (spreadValue != 0) { spreadValue = (spreadValue * 1e20) / estAmountOut; require( spreadValue <= maxDisagreement, "uniswap price disagreement" ); } } function setApprovals() external onlyOwner { IERC20(DAI).safeApprove(address(CURVE_3POOL), type(uint256).max); IERC20(USDC).safeApprove(address(CURVE_3POOL), type(uint256).max); IERC20(USDC).safeApprove(BRIDGE, type(uint256).max); IERC20(USDT).safeApprove(address(CURVE_3POOL), 0); IERC20(USDT).safeApprove(address(CURVE_3POOL), type(uint256).max); IERC20(OOKI).safeApprove(address(STAKING), type(uint256).max); IERC20(OOKI).safeApprove(address(UNISWAP_ROUTER), type(uint256).max); CURVE_3CRV.safeApprove(address(STAKING), type(uint256).max); } // path should start with the asset to swap and end with OOKI // only one path allowed per asset // ex: asset -> WETH -> OOKI function setPaths(address[][] calldata paths) external onlyOwner { address[] memory path; for (uint256 i = 0; i < paths.length; i++) { path = paths[i]; require( path.length >= 2 && path[0] != path[path.length - 1] && path[path.length - 1] == OOKI, "invalid path" ); // check that the path exists uint256[] memory amountsOut = UNISWAP_ROUTER.getAmountsOut( 1e10, path ); require( amountsOut[amountsOut.length - 1] != 0, "path does not exist" ); swapPaths[path[0]] = path; IERC20(path[0]).safeApprove(address(UNISWAP_ROUTER), 0); IERC20(path[0]).safeApprove(address(UNISWAP_ROUTER), type(uint256).max); } } function setBuybackSettings(uint256 amount) external onlyOwner { buybackPercent = amount; } function setFeeTokens(address[] calldata tokens) external onlyOwner { feeTokens = tokens; } }
Verifies that a message is signed by a quorum among the signers. _msg signed message _sigs list of signatures sorted by signer addresses in ascending order _signers sorted list of current signers _powers powers of current signers/ Part: ICurve3Pool
interface ICurve3Pool { function add_liquidity( uint256[3] calldata amounts, uint256 min_mint_amount) external; function remove_liquidity_one_coin( uint256 token_amount, int128 i, uint256 min_amount ) external; function get_virtual_price() external view returns (uint256); }
11,721,618
./full_match/42220/0x6ea01ea80FeB4313C3329e6e9fcA751CCb2cF323/sources/out/ManagedPoolFactory_flat.sol
The Vault only requires the token list to be ordered for the Two Token Pools specialization. However, to make the developer experience consistent, we are requiring this condition for all the native pools. Note that for Pools which can register and deregister tokens after deployment, this property may not hold as tokens which are added to the Pool after deployment are always added to the end of the array. We insert the Pool's BPT address into the first position. This allows us to know the position of the BPT token in the tokens array without explicitly tracking it. When deregistering a token, the token at the end of the array is moved into the index of the deregistered token, changing its index. By placing BPT at the beginning of the tokens array we can be sure that its index will never change unless it is deregistered itself (something which composable pools must prevent anyway).
function registerComposablePool( IVault vault, IVault.PoolSpecialization specialization, IERC20[] memory tokens, address[] memory assetManagers ) internal returns (bytes32) { InputHelpers.ensureArrayIsSorted(tokens); IERC20[] memory composableTokens = new IERC20[](tokens.length + 1); composableTokens[0] = IERC20(address(this)); for (uint256 i = 0; i < tokens.length; i++) { composableTokens[i + 1] = tokens[i]; } address[] memory composableAssetManagers = new address[](assetManagers.length + 1); for (uint256 i = 0; i < assetManagers.length; i++) { composableAssetManagers[i + 1] = assetManagers[i]; } return _registerPool(vault, specialization, composableTokens, composableAssetManagers); }
16,352,811